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>
71 #include "path-util.h"
72 #include "exit-status.h"
76 #include "device-nodes.h"
79 char **saved_argv = NULL;
81 static volatile unsigned cached_columns = 0;
82 static volatile unsigned cached_lines = 0;
84 size_t page_size(void) {
85 static __thread size_t pgsz = 0;
88 if (_likely_(pgsz > 0))
91 r = sysconf(_SC_PAGESIZE);
98 bool streq_ptr(const char *a, const char *b) {
100 /* Like streq(), but tries to make sense of NULL pointers */
111 char* endswith(const char *s, const char *postfix) {
118 pl = strlen(postfix);
121 return (char*) s + sl;
126 if (memcmp(s + sl - pl, postfix, pl) != 0)
129 return (char*) s + sl - pl;
132 bool first_word(const char *s, const char *word) {
147 if (memcmp(s, word, wl) != 0)
151 strchr(WHITESPACE, s[wl]);
154 int close_nointr(int fd) {
160 /* Just ignore EINTR; a retry loop is the wrong
161 * thing to do on Linux.
163 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
164 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
165 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
166 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
168 if (_unlikely_(r < 0 && errno == EINTR))
176 void close_nointr_nofail(int fd) {
179 /* like close_nointr() but cannot fail, and guarantees errno
182 assert_se(close_nointr(fd) == 0);
185 void close_many(const int fds[], unsigned n_fd) {
188 assert(fds || n_fd <= 0);
190 for (i = 0; i < n_fd; i++)
191 close_nointr_nofail(fds[i]);
194 int unlink_noerrno(const char *path) {
205 int parse_boolean(const char *v) {
208 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
210 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
216 int parse_pid(const char *s, pid_t* ret_pid) {
217 unsigned long ul = 0;
224 r = safe_atolu(s, &ul);
230 if ((unsigned long) pid != ul)
240 int parse_uid(const char *s, uid_t* ret_uid) {
241 unsigned long ul = 0;
248 r = safe_atolu(s, &ul);
254 if ((unsigned long) uid != ul)
261 int safe_atou(const char *s, unsigned *ret_u) {
269 l = strtoul(s, &x, 0);
271 if (!x || x == s || *x || errno)
272 return errno > 0 ? -errno : -EINVAL;
274 if ((unsigned long) (unsigned) l != l)
277 *ret_u = (unsigned) l;
281 int safe_atoi(const char *s, int *ret_i) {
289 l = strtol(s, &x, 0);
291 if (!x || x == s || *x || errno)
292 return errno > 0 ? -errno : -EINVAL;
294 if ((long) (int) l != l)
301 int safe_atollu(const char *s, long long unsigned *ret_llu) {
303 unsigned long long l;
309 l = strtoull(s, &x, 0);
311 if (!x || x == s || *x || errno)
312 return errno ? -errno : -EINVAL;
318 int safe_atolli(const char *s, long long int *ret_lli) {
326 l = strtoll(s, &x, 0);
328 if (!x || x == s || *x || errno)
329 return errno ? -errno : -EINVAL;
335 int safe_atod(const char *s, double *ret_d) {
342 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
347 if (!x || x == s || *x || errno)
348 return errno ? -errno : -EINVAL;
354 /* Split a string into words. */
355 char *split(const char *c, size_t *l, const char *separator, char **state) {
358 current = *state ? *state : (char*) c;
360 if (!*current || *c == 0)
363 current += strspn(current, separator);
364 *l = strcspn(current, separator);
367 return (char*) current;
370 /* Split a string into words, but consider strings enclosed in '' and
371 * "" as words even if they include spaces. */
372 char *split_quoted(const char *c, size_t *l, char **state) {
374 bool escaped = false;
376 current = *state ? *state : (char*) c;
378 if (!*current || *c == 0)
381 current += strspn(current, WHITESPACE);
383 if (*current == '\'') {
386 for (e = current; *e; e++) {
396 *state = *e == 0 ? e : e+1;
397 } else if (*current == '\"') {
400 for (e = current; *e; e++) {
410 *state = *e == 0 ? e : e+1;
412 for (e = current; *e; e++) {
417 else if (strchr(WHITESPACE, *e))
424 return (char*) current;
427 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
429 _cleanup_fclose_ FILE *f = NULL;
442 p = procfs_file_alloca(pid, "stat");
447 if (!fgets(line, sizeof(line), f)) {
448 r = feof(f) ? -EIO : -errno;
452 /* Let's skip the pid and comm fields. The latter is enclosed
453 * in () but does not escape any () in its value, so let's
454 * skip over it manually */
456 p = strrchr(line, ')');
468 if ((long unsigned) (pid_t) ppid != ppid)
471 *_ppid = (pid_t) ppid;
476 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
477 _cleanup_fclose_ FILE *f = NULL;
485 p = "/proc/self/stat";
487 p = procfs_file_alloca(pid, "stat");
493 if (!fgets(line, sizeof(line), f)) {
500 /* Let's skip the pid and comm fields. The latter is enclosed
501 * in () but does not escape any () in its value, so let's
502 * skip over it manually */
504 p = strrchr(line, ')');
526 "%*d " /* priority */
528 "%*d " /* num_threads */
529 "%*d " /* itrealvalue */
530 "%llu " /* starttime */,
537 int fchmod_umask(int fd, mode_t m) {
542 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
548 char *truncate_nl(char *s) {
551 s[strcspn(s, NEWLINE)] = 0;
555 int get_process_comm(pid_t pid, char **name) {
562 p = "/proc/self/comm";
564 p = procfs_file_alloca(pid, "comm");
566 return read_one_line_file(p, name);
569 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
570 _cleanup_fclose_ FILE *f = NULL;
579 p = "/proc/self/cmdline";
581 p = procfs_file_alloca(pid, "cmdline");
587 if (max_length == 0) {
588 size_t len = 0, allocated = 0;
590 while ((c = getc(f)) != EOF) {
592 if (!GREEDY_REALLOC(r, allocated, len+2)) {
597 r[len++] = isprint(c) ? c : ' ';
607 r = new(char, max_length);
613 while ((c = getc(f)) != EOF) {
635 size_t n = MIN(left-1, 3U);
642 /* Kernel threads have no argv[] */
643 if (r == NULL || r[0] == 0) {
652 h = get_process_comm(pid, &t);
656 r = strjoin("[", t, "]", NULL);
667 int is_kernel_thread(pid_t pid) {
679 p = procfs_file_alloca(pid, "cmdline");
684 count = fread(&c, 1, 1, f);
688 /* Kernel threads have an empty cmdline */
691 return eof ? 1 : -errno;
696 int get_process_capeff(pid_t pid, char **capeff) {
703 p = "/proc/self/status";
705 p = procfs_file_alloca(pid, "status");
707 return get_status_field(p, "\nCapEff:", capeff);
710 int get_process_exe(pid_t pid, char **name) {
719 p = "/proc/self/exe";
721 p = procfs_file_alloca(pid, "exe");
723 r = readlink_malloc(p, name);
727 d = endswith(*name, " (deleted)");
734 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
735 _cleanup_fclose_ FILE *f = NULL;
745 p = procfs_file_alloca(pid, "status");
750 FOREACH_LINE(line, f, return -errno) {
755 if (startswith(l, field)) {
757 l += strspn(l, WHITESPACE);
759 l[strcspn(l, WHITESPACE)] = 0;
761 return parse_uid(l, uid);
768 int get_process_uid(pid_t pid, uid_t *uid) {
769 return get_process_id(pid, "Uid:", uid);
772 int get_process_gid(pid_t pid, gid_t *gid) {
773 assert_cc(sizeof(uid_t) == sizeof(gid_t));
774 return get_process_id(pid, "Gid:", gid);
777 char *strnappend(const char *s, const char *suffix, size_t b) {
785 return strndup(suffix, b);
794 if (b > ((size_t) -1) - a)
797 r = new(char, a+b+1);
802 memcpy(r+a, suffix, b);
808 char *strappend(const char *s, const char *suffix) {
809 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
812 int readlink_malloc(const char *p, char **r) {
822 if (!(c = new(char, l)))
825 if ((n = readlink(p, c, l-1)) < 0) {
831 if ((size_t) n < l-1) {
842 int readlink_and_make_absolute(const char *p, char **r) {
843 _cleanup_free_ char *target = NULL;
850 j = readlink_malloc(p, &target);
854 k = file_in_same_dir(p, target);
862 int readlink_and_canonicalize(const char *p, char **r) {
869 j = readlink_and_make_absolute(p, &t);
873 s = canonicalize_file_name(t);
880 path_kill_slashes(*r);
885 int reset_all_signal_handlers(void) {
888 for (sig = 1; sig < _NSIG; sig++) {
889 struct sigaction sa = {
890 .sa_handler = SIG_DFL,
891 .sa_flags = SA_RESTART,
894 if (sig == SIGKILL || sig == SIGSTOP)
897 /* On Linux the first two RT signals are reserved by
898 * glibc, and sigaction() will return EINVAL for them. */
899 if ((sigaction(sig, &sa, NULL) < 0))
907 char *strstrip(char *s) {
910 /* Drops trailing whitespace. Modifies the string in
911 * place. Returns pointer to first non-space character */
913 s += strspn(s, WHITESPACE);
915 for (e = strchr(s, 0); e > s; e --)
916 if (!strchr(WHITESPACE, e[-1]))
924 char *delete_chars(char *s, const char *bad) {
927 /* Drops all whitespace, regardless where in the string */
929 for (f = s, t = s; *f; f++) {
941 bool in_charset(const char *s, const char* charset) {
948 if (!strchr(charset, *i))
954 char *file_in_same_dir(const char *path, const char *filename) {
961 /* This removes the last component of path and appends
962 * filename, unless the latter is absolute anyway or the
965 if (path_is_absolute(filename))
966 return strdup(filename);
968 if (!(e = strrchr(path, '/')))
969 return strdup(filename);
971 k = strlen(filename);
972 if (!(r = new(char, e-path+1+k+1)))
975 memcpy(r, path, e-path+1);
976 memcpy(r+(e-path)+1, filename, k+1);
981 int rmdir_parents(const char *path, const char *stop) {
990 /* Skip trailing slashes */
991 while (l > 0 && path[l-1] == '/')
997 /* Skip last component */
998 while (l > 0 && path[l-1] != '/')
1001 /* Skip trailing slashes */
1002 while (l > 0 && path[l-1] == '/')
1008 if (!(t = strndup(path, l)))
1011 if (path_startswith(stop, t)) {
1020 if (errno != ENOENT)
1027 char hexchar(int x) {
1028 static const char table[16] = "0123456789abcdef";
1030 return table[x & 15];
1033 int unhexchar(char c) {
1035 if (c >= '0' && c <= '9')
1038 if (c >= 'a' && c <= 'f')
1039 return c - 'a' + 10;
1041 if (c >= 'A' && c <= 'F')
1042 return c - 'A' + 10;
1047 char *hexmem(const void *p, size_t l) {
1051 z = r = malloc(l * 2 + 1);
1055 for (x = p; x < (const uint8_t*) p + l; x++) {
1056 *(z++) = hexchar(*x >> 4);
1057 *(z++) = hexchar(*x & 15);
1064 void *unhexmem(const char *p, size_t l) {
1070 z = r = malloc((l + 1) / 2 + 1);
1074 for (x = p; x < p + l; x += 2) {
1077 a = unhexchar(x[0]);
1079 b = unhexchar(x[1]);
1083 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1090 char octchar(int x) {
1091 return '0' + (x & 7);
1094 int unoctchar(char c) {
1096 if (c >= '0' && c <= '7')
1102 char decchar(int x) {
1103 return '0' + (x % 10);
1106 int undecchar(char c) {
1108 if (c >= '0' && c <= '9')
1114 char *cescape(const char *s) {
1120 /* Does C style string escaping. */
1122 r = new(char, strlen(s)*4 + 1);
1126 for (f = s, t = r; *f; f++)
1172 /* For special chars we prefer octal over
1173 * hexadecimal encoding, simply because glib's
1174 * g_strescape() does the same */
1175 if ((*f < ' ') || (*f >= 127)) {
1177 *(t++) = octchar((unsigned char) *f >> 6);
1178 *(t++) = octchar((unsigned char) *f >> 3);
1179 *(t++) = octchar((unsigned char) *f);
1190 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1197 /* Undoes C style string escaping, and optionally prefixes it. */
1199 pl = prefix ? strlen(prefix) : 0;
1201 r = new(char, pl+length+1);
1206 memcpy(r, prefix, pl);
1208 for (f = s, t = r + pl; f < s + length; f++) {
1251 /* This is an extension of the XDG syntax files */
1256 /* hexadecimal encoding */
1259 a = unhexchar(f[1]);
1260 b = unhexchar(f[2]);
1262 if (a < 0 || b < 0) {
1263 /* Invalid escape code, let's take it literal then */
1267 *(t++) = (char) ((a << 4) | b);
1282 /* octal encoding */
1285 a = unoctchar(f[0]);
1286 b = unoctchar(f[1]);
1287 c = unoctchar(f[2]);
1289 if (a < 0 || b < 0 || c < 0) {
1290 /* Invalid escape code, let's take it literal then */
1294 *(t++) = (char) ((a << 6) | (b << 3) | c);
1302 /* premature end of string.*/
1307 /* Invalid escape code, let's take it literal then */
1319 char *cunescape_length(const char *s, size_t length) {
1320 return cunescape_length_with_prefix(s, length, NULL);
1323 char *cunescape(const char *s) {
1326 return cunescape_length(s, strlen(s));
1329 char *xescape(const char *s, const char *bad) {
1333 /* Escapes all chars in bad, in addition to \ and all special
1334 * chars, in \xFF style escaping. May be reversed with
1337 r = new(char, strlen(s) * 4 + 1);
1341 for (f = s, t = r; *f; f++) {
1343 if ((*f < ' ') || (*f >= 127) ||
1344 (*f == '\\') || strchr(bad, *f)) {
1347 *(t++) = hexchar(*f >> 4);
1348 *(t++) = hexchar(*f);
1358 char *bus_path_escape(const char *s) {
1364 /* Escapes all chars that D-Bus' object path cannot deal
1365 * with. Can be reverse with bus_path_unescape(). We special
1366 * case the empty string. */
1371 r = new(char, strlen(s)*3 + 1);
1375 for (f = s, t = r; *f; f++) {
1377 /* Escape everything that is not a-zA-Z0-9. We also
1378 * escape 0-9 if it's the first character */
1380 if (!(*f >= 'A' && *f <= 'Z') &&
1381 !(*f >= 'a' && *f <= 'z') &&
1382 !(f > s && *f >= '0' && *f <= '9')) {
1384 *(t++) = hexchar(*f >> 4);
1385 *(t++) = hexchar(*f);
1395 char *bus_path_unescape(const char *f) {
1400 /* Special case for the empty string */
1404 r = new(char, strlen(f) + 1);
1408 for (t = r; *f; f++) {
1413 if ((a = unhexchar(f[1])) < 0 ||
1414 (b = unhexchar(f[2])) < 0) {
1415 /* Invalid escape code, let's take it literal then */
1418 *(t++) = (char) ((a << 4) | b);
1430 char *ascii_strlower(char *t) {
1435 for (p = t; *p; p++)
1436 if (*p >= 'A' && *p <= 'Z')
1437 *p = *p - 'A' + 'a';
1442 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1446 filename[0] == '.' ||
1447 streq(filename, "lost+found") ||
1448 streq(filename, "aquota.user") ||
1449 streq(filename, "aquota.group") ||
1450 endswith(filename, ".rpmnew") ||
1451 endswith(filename, ".rpmsave") ||
1452 endswith(filename, ".rpmorig") ||
1453 endswith(filename, ".dpkg-old") ||
1454 endswith(filename, ".dpkg-new") ||
1455 endswith(filename, ".swp");
1458 bool ignore_file(const char *filename) {
1461 if (endswith(filename, "~"))
1464 return ignore_file_allow_backup(filename);
1467 int fd_nonblock(int fd, bool nonblock) {
1472 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1476 flags |= O_NONBLOCK;
1478 flags &= ~O_NONBLOCK;
1480 if (fcntl(fd, F_SETFL, flags) < 0)
1486 int fd_cloexec(int fd, bool cloexec) {
1491 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1495 flags |= FD_CLOEXEC;
1497 flags &= ~FD_CLOEXEC;
1499 if (fcntl(fd, F_SETFD, flags) < 0)
1505 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1508 assert(n_fdset == 0 || fdset);
1510 for (i = 0; i < n_fdset; i++)
1517 int close_all_fds(const int except[], unsigned n_except) {
1522 assert(n_except == 0 || except);
1524 d = opendir("/proc/self/fd");
1529 /* When /proc isn't available (for example in chroots)
1530 * the fallback is brute forcing through the fd
1533 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1534 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1536 if (fd_in_set(fd, except, n_except))
1539 if (close_nointr(fd) < 0)
1540 if (errno != EBADF && r == 0)
1547 while ((de = readdir(d))) {
1550 if (ignore_file(de->d_name))
1553 if (safe_atoi(de->d_name, &fd) < 0)
1554 /* Let's better ignore this, just in case */
1563 if (fd_in_set(fd, except, n_except))
1566 if (close_nointr(fd) < 0) {
1567 /* Valgrind has its own FD and doesn't want to have it closed */
1568 if (errno != EBADF && r == 0)
1577 bool chars_intersect(const char *a, const char *b) {
1580 /* Returns true if any of the chars in a are in b. */
1581 for (p = a; *p; p++)
1588 bool fstype_is_network(const char *fstype) {
1589 static const char table[] =
1599 return nulstr_contains(table, fstype);
1603 _cleanup_close_ int fd;
1605 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1611 TIOCL_GETKMSGREDIRECT,
1615 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1618 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1621 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1627 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1628 struct termios old_termios, new_termios;
1630 char line[LINE_MAX];
1635 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1636 new_termios = old_termios;
1638 new_termios.c_lflag &= ~ICANON;
1639 new_termios.c_cc[VMIN] = 1;
1640 new_termios.c_cc[VTIME] = 0;
1642 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1645 if (t != (usec_t) -1) {
1646 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1647 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1652 k = fread(&c, 1, 1, f);
1654 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1660 *need_nl = c != '\n';
1667 if (t != (usec_t) -1)
1668 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1671 if (!fgets(line, sizeof(line), f))
1676 if (strlen(line) != 1)
1686 int ask(char *ret, const char *replies, const char *text, ...) {
1696 bool need_nl = true;
1699 fputs(ANSI_HIGHLIGHT_ON, stdout);
1706 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1710 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1713 if (r == -EBADMSG) {
1714 puts("Bad input, please try again.");
1725 if (strchr(replies, c)) {
1730 puts("Read unexpected character, please try again.");
1734 int reset_terminal_fd(int fd, bool switch_to_text) {
1735 struct termios termios;
1738 /* Set terminal to some sane defaults */
1742 /* We leave locked terminal attributes untouched, so that
1743 * Plymouth may set whatever it wants to set, and we don't
1744 * interfere with that. */
1746 /* Disable exclusive mode, just in case */
1747 ioctl(fd, TIOCNXCL);
1749 /* Switch to text mode */
1751 ioctl(fd, KDSETMODE, KD_TEXT);
1753 /* Enable console unicode mode */
1754 ioctl(fd, KDSKBMODE, K_UNICODE);
1756 if (tcgetattr(fd, &termios) < 0) {
1761 /* We only reset the stuff that matters to the software. How
1762 * hardware is set up we don't touch assuming that somebody
1763 * else will do that for us */
1765 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1766 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1767 termios.c_oflag |= ONLCR;
1768 termios.c_cflag |= CREAD;
1769 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1771 termios.c_cc[VINTR] = 03; /* ^C */
1772 termios.c_cc[VQUIT] = 034; /* ^\ */
1773 termios.c_cc[VERASE] = 0177;
1774 termios.c_cc[VKILL] = 025; /* ^X */
1775 termios.c_cc[VEOF] = 04; /* ^D */
1776 termios.c_cc[VSTART] = 021; /* ^Q */
1777 termios.c_cc[VSTOP] = 023; /* ^S */
1778 termios.c_cc[VSUSP] = 032; /* ^Z */
1779 termios.c_cc[VLNEXT] = 026; /* ^V */
1780 termios.c_cc[VWERASE] = 027; /* ^W */
1781 termios.c_cc[VREPRINT] = 022; /* ^R */
1782 termios.c_cc[VEOL] = 0;
1783 termios.c_cc[VEOL2] = 0;
1785 termios.c_cc[VTIME] = 0;
1786 termios.c_cc[VMIN] = 1;
1788 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1792 /* Just in case, flush all crap out */
1793 tcflush(fd, TCIOFLUSH);
1798 int reset_terminal(const char *name) {
1801 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1805 r = reset_terminal_fd(fd, true);
1806 close_nointr_nofail(fd);
1811 int open_terminal(const char *name, int mode) {
1816 * If a TTY is in the process of being closed opening it might
1817 * cause EIO. This is horribly awful, but unlikely to be
1818 * changed in the kernel. Hence we work around this problem by
1819 * retrying a couple of times.
1821 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1824 assert(!(mode & O_CREAT));
1827 fd = open(name, mode, 0);
1834 /* Max 1s in total */
1838 usleep(50 * USEC_PER_MSEC);
1847 close_nointr_nofail(fd);
1852 close_nointr_nofail(fd);
1859 int flush_fd(int fd) {
1860 struct pollfd pollfd = {
1870 r = poll(&pollfd, 1, 0);
1880 l = read(fd, buf, sizeof(buf));
1886 if (errno == EAGAIN)
1895 int acquire_terminal(
1899 bool ignore_tiocstty_eperm,
1902 int fd = -1, notify = -1, r = 0, wd = -1;
1907 /* We use inotify to be notified when the tty is closed. We
1908 * create the watch before checking if we can actually acquire
1909 * it, so that we don't lose any event.
1911 * Note: strictly speaking this actually watches for the
1912 * device being closed, it does *not* really watch whether a
1913 * tty loses its controlling process. However, unless some
1914 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1915 * its tty otherwise this will not become a problem. As long
1916 * as the administrator makes sure not configure any service
1917 * on the same tty as an untrusted user this should not be a
1918 * problem. (Which he probably should not do anyway.) */
1920 if (timeout != (usec_t) -1)
1921 ts = now(CLOCK_MONOTONIC);
1923 if (!fail && !force) {
1924 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1930 wd = inotify_add_watch(notify, name, IN_CLOSE);
1938 struct sigaction sa_old, sa_new = {
1939 .sa_handler = SIG_IGN,
1940 .sa_flags = SA_RESTART,
1944 r = flush_fd(notify);
1949 /* We pass here O_NOCTTY only so that we can check the return
1950 * value TIOCSCTTY and have a reliable way to figure out if we
1951 * successfully became the controlling process of the tty */
1952 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1956 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1957 * if we already own the tty. */
1958 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1960 /* First, try to get the tty */
1961 if (ioctl(fd, TIOCSCTTY, force) < 0)
1964 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1966 /* Sometimes it makes sense to ignore TIOCSCTTY
1967 * returning EPERM, i.e. when very likely we already
1968 * are have this controlling terminal. */
1969 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1972 if (r < 0 && (force || fail || r != -EPERM)) {
1981 assert(notify >= 0);
1984 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1986 struct inotify_event *e;
1988 if (timeout != (usec_t) -1) {
1991 n = now(CLOCK_MONOTONIC);
1992 if (ts + timeout < n) {
1997 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2007 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2010 if (errno == EINTR || errno == EAGAIN)
2017 e = (struct inotify_event*) inotify_buffer;
2022 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2027 step = sizeof(struct inotify_event) + e->len;
2028 assert(step <= (size_t) l);
2030 e = (struct inotify_event*) ((uint8_t*) e + step);
2037 /* We close the tty fd here since if the old session
2038 * ended our handle will be dead. It's important that
2039 * we do this after sleeping, so that we don't enter
2040 * an endless loop. */
2041 close_nointr_nofail(fd);
2045 close_nointr_nofail(notify);
2047 r = reset_terminal_fd(fd, true);
2049 log_warning("Failed to reset terminal: %s", strerror(-r));
2055 close_nointr_nofail(fd);
2058 close_nointr_nofail(notify);
2063 int release_terminal(void) {
2065 struct sigaction sa_old, sa_new = {
2066 .sa_handler = SIG_IGN,
2067 .sa_flags = SA_RESTART,
2069 _cleanup_close_ int fd;
2071 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2075 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2076 * by our own TIOCNOTTY */
2077 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2079 if (ioctl(fd, TIOCNOTTY) < 0)
2082 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2087 int sigaction_many(const struct sigaction *sa, ...) {
2092 while ((sig = va_arg(ap, int)) > 0)
2093 if (sigaction(sig, sa, NULL) < 0)
2100 int ignore_signals(int sig, ...) {
2101 struct sigaction sa = {
2102 .sa_handler = SIG_IGN,
2103 .sa_flags = SA_RESTART,
2109 if (sigaction(sig, &sa, NULL) < 0)
2113 while ((sig = va_arg(ap, int)) > 0)
2114 if (sigaction(sig, &sa, NULL) < 0)
2121 int default_signals(int sig, ...) {
2122 struct sigaction sa = {
2123 .sa_handler = SIG_DFL,
2124 .sa_flags = SA_RESTART,
2129 if (sigaction(sig, &sa, NULL) < 0)
2133 while ((sig = va_arg(ap, int)) > 0)
2134 if (sigaction(sig, &sa, NULL) < 0)
2141 int close_pipe(int p[]) {
2147 a = close_nointr(p[0]);
2152 b = close_nointr(p[1]);
2156 return a < 0 ? a : b;
2159 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2168 while (nbytes > 0) {
2171 if ((k = read(fd, p, nbytes)) <= 0) {
2173 if (k < 0 && errno == EINTR)
2176 if (k < 0 && errno == EAGAIN && do_poll) {
2177 struct pollfd pollfd = {
2182 if (poll(&pollfd, 1, -1) < 0) {
2186 return n > 0 ? n : -errno;
2189 /* We knowingly ignore the revents value here,
2190 * and expect that any error/EOF is reported
2191 * via read()/write()
2197 return n > 0 ? n : (k < 0 ? -errno : 0);
2208 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2217 while (nbytes > 0) {
2220 k = write(fd, p, nbytes);
2223 if (k < 0 && errno == EINTR)
2226 if (k < 0 && errno == EAGAIN && do_poll) {
2227 struct pollfd pollfd = {
2232 if (poll(&pollfd, 1, -1) < 0) {
2236 return n > 0 ? n : -errno;
2239 /* We knowingly ignore the revents value here,
2240 * and expect that any error/EOF is reported
2241 * via read()/write()
2247 return n > 0 ? n : (k < 0 ? -errno : 0);
2258 int parse_bytes(const char *t, off_t *bytes) {
2259 static const struct {
2261 unsigned long long factor;
2265 { "M", 1024ULL*1024ULL },
2266 { "G", 1024ULL*1024ULL*1024ULL },
2267 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2268 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2269 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2274 unsigned long long r = 0;
2286 l = strtoll(p, &e, 10);
2297 e += strspn(e, WHITESPACE);
2299 for (i = 0; i < ELEMENTSOF(table); i++)
2300 if (startswith(e, table[i].suffix)) {
2301 unsigned long long tmp;
2302 if ((unsigned long long) l > ULLONG_MAX / table[i].factor)
2304 tmp = l * table[i].factor;
2305 if (tmp > ULLONG_MAX - r)
2309 if ((unsigned long long) (off_t) r != r)
2312 p = e + strlen(table[i].suffix);
2316 if (i >= ELEMENTSOF(table))
2326 int make_stdio(int fd) {
2331 r = dup3(fd, STDIN_FILENO, 0);
2332 s = dup3(fd, STDOUT_FILENO, 0);
2333 t = dup3(fd, STDERR_FILENO, 0);
2336 close_nointr_nofail(fd);
2338 if (r < 0 || s < 0 || t < 0)
2341 /* We rely here that the new fd has O_CLOEXEC not set */
2346 int make_null_stdio(void) {
2349 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2353 return make_stdio(null_fd);
2356 bool is_device_path(const char *path) {
2358 /* Returns true on paths that refer to a device, either in
2359 * sysfs or in /dev */
2362 path_startswith(path, "/dev/") ||
2363 path_startswith(path, "/sys/");
2366 int dir_is_empty(const char *path) {
2367 _cleanup_closedir_ DIR *d;
2376 union dirent_storage buf;
2378 r = readdir_r(d, &buf.de, &de);
2385 if (!ignore_file(de->d_name))
2390 char* dirname_malloc(const char *path) {
2391 char *d, *dir, *dir2;
2408 unsigned long long random_ull(void) {
2409 _cleanup_close_ int fd;
2413 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2417 r = loop_read(fd, &ull, sizeof(ull), true);
2418 if (r != sizeof(ull))
2424 return random() * RAND_MAX + random();
2427 void rename_process(const char name[8]) {
2430 /* This is a like a poor man's setproctitle(). It changes the
2431 * comm field, argv[0], and also the glibc's internally used
2432 * name of the process. For the first one a limit of 16 chars
2433 * applies, to the second one usually one of 10 (i.e. length
2434 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2435 * "systemd"). If you pass a longer string it will be
2438 prctl(PR_SET_NAME, name);
2440 if (program_invocation_name)
2441 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2443 if (saved_argc > 0) {
2447 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2449 for (i = 1; i < saved_argc; i++) {
2453 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2458 void sigset_add_many(sigset_t *ss, ...) {
2465 while ((sig = va_arg(ap, int)) > 0)
2466 assert_se(sigaddset(ss, sig) == 0);
2470 char* gethostname_malloc(void) {
2473 assert_se(uname(&u) >= 0);
2475 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2476 return strdup(u.nodename);
2478 return strdup(u.sysname);
2481 bool hostname_is_set(void) {
2484 assert_se(uname(&u) >= 0);
2486 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2489 static char *lookup_uid(uid_t uid) {
2492 _cleanup_free_ char *buf = NULL;
2493 struct passwd pwbuf, *pw = NULL;
2495 /* Shortcut things to avoid NSS lookups */
2497 return strdup("root");
2499 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2503 buf = malloc(bufsize);
2507 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2508 return strdup(pw->pw_name);
2510 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2516 char* getlogname_malloc(void) {
2520 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2525 return lookup_uid(uid);
2528 char *getusername_malloc(void) {
2535 return lookup_uid(getuid());
2538 int getttyname_malloc(int fd, char **r) {
2539 char path[PATH_MAX], *c;
2544 k = ttyname_r(fd, path, sizeof(path));
2550 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2558 int getttyname_harder(int fd, char **r) {
2562 k = getttyname_malloc(fd, &s);
2566 if (streq(s, "tty")) {
2568 return get_ctty(0, NULL, r);
2575 int get_ctty_devnr(pid_t pid, dev_t *d) {
2576 _cleanup_fclose_ FILE *f = NULL;
2577 char line[LINE_MAX], *p;
2578 unsigned long ttynr;
2586 fn = "/proc/self/stat";
2588 fn = procfs_file_alloca(pid, "stat");
2590 f = fopen(fn, "re");
2594 if (!fgets(line, sizeof(line), f)) {
2595 k = feof(f) ? -EIO : -errno;
2599 p = strrchr(line, ')');
2609 "%*d " /* session */
2614 if (major(ttynr) == 0 && minor(ttynr) == 0)
2621 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2623 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2628 k = get_ctty_devnr(pid, &devnr);
2632 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2634 k = readlink_malloc(fn, &s);
2640 /* This is an ugly hack */
2641 if (major(devnr) == 136) {
2642 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2652 /* Probably something like the ptys which have no
2653 * symlink in /dev/char. Let's return something
2654 * vaguely useful. */
2667 if (startswith(s, "/dev/"))
2669 else if (startswith(s, "../"))
2687 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2693 /* This returns the first error we run into, but nevertheless
2694 * tries to go on. This closes the passed fd. */
2698 close_nointr_nofail(fd);
2700 return errno == ENOENT ? 0 : -errno;
2705 union dirent_storage buf;
2706 bool is_dir, keep_around;
2710 r = readdir_r(d, &buf.de, &de);
2711 if (r != 0 && ret == 0) {
2719 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2722 if (de->d_type == DT_UNKNOWN ||
2724 (de->d_type == DT_DIR && root_dev)) {
2725 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2726 if (ret == 0 && errno != ENOENT)
2731 is_dir = S_ISDIR(st.st_mode);
2734 (st.st_uid == 0 || st.st_uid == getuid()) &&
2735 (st.st_mode & S_ISVTX);
2737 is_dir = de->d_type == DT_DIR;
2738 keep_around = false;
2744 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2745 if (root_dev && st.st_dev != root_dev->st_dev)
2748 subdir_fd = openat(fd, de->d_name,
2749 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2750 if (subdir_fd < 0) {
2751 if (ret == 0 && errno != ENOENT)
2756 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2757 if (r < 0 && ret == 0)
2761 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2762 if (ret == 0 && errno != ENOENT)
2766 } else if (!only_dirs && !keep_around) {
2768 if (unlinkat(fd, de->d_name, 0) < 0) {
2769 if (ret == 0 && errno != ENOENT)
2780 _pure_ static int is_temporary_fs(struct statfs *s) {
2783 F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2784 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2787 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2792 if (fstatfs(fd, &s) < 0) {
2793 close_nointr_nofail(fd);
2797 /* We refuse to clean disk file systems with this call. This
2798 * is extra paranoia just to be sure we never ever remove
2800 if (!is_temporary_fs(&s)) {
2801 log_error("Attempted to remove disk file system, and we can't allow that.");
2802 close_nointr_nofail(fd);
2806 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2809 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2815 /* We refuse to clean the root file system with this
2816 * call. This is extra paranoia to never cause a really
2817 * seriously broken system. */
2818 if (path_equal(path, "/")) {
2819 log_error("Attempted to remove entire root file system, and we can't allow that.");
2823 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2826 if (errno != ENOTDIR)
2830 if (statfs(path, &s) < 0)
2833 if (!is_temporary_fs(&s)) {
2834 log_error("Attempted to remove disk file system, and we can't allow that.");
2839 if (delete_root && !only_dirs)
2840 if (unlink(path) < 0 && errno != ENOENT)
2847 if (fstatfs(fd, &s) < 0) {
2848 close_nointr_nofail(fd);
2852 if (!is_temporary_fs(&s)) {
2853 log_error("Attempted to remove disk file system, and we can't allow that.");
2854 close_nointr_nofail(fd);
2859 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2862 if (honour_sticky && file_is_priv_sticky(path) > 0)
2865 if (rmdir(path) < 0 && errno != ENOENT) {
2874 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2875 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2878 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2879 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2882 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2885 /* Under the assumption that we are running privileged we
2886 * first change the access mode and only then hand out
2887 * ownership to avoid a window where access is too open. */
2889 if (mode != (mode_t) -1)
2890 if (chmod(path, mode) < 0)
2893 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2894 if (chown(path, uid, gid) < 0)
2900 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2903 /* Under the assumption that we are running privileged we
2904 * first change the access mode and only then hand out
2905 * ownership to avoid a window where access is too open. */
2907 if (fchmod(fd, mode) < 0)
2910 if (fchown(fd, uid, gid) < 0)
2916 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2920 /* Allocates the cpuset in the right size */
2923 if (!(r = CPU_ALLOC(n)))
2926 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2927 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2937 if (errno != EINVAL)
2944 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2945 static const char status_indent[] = " "; /* "[" STATUS "] " */
2946 _cleanup_free_ char *s = NULL;
2947 _cleanup_close_ int fd = -1;
2948 struct iovec iovec[6] = {};
2950 static bool prev_ephemeral;
2954 /* This is independent of logging, as status messages are
2955 * optional and go exclusively to the console. */
2957 if (vasprintf(&s, format, ap) < 0)
2960 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2973 sl = status ? sizeof(status_indent)-1 : 0;
2979 e = ellipsize(s, emax, 75);
2987 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2988 prev_ephemeral = ephemeral;
2991 if (!isempty(status)) {
2992 IOVEC_SET_STRING(iovec[n++], "[");
2993 IOVEC_SET_STRING(iovec[n++], status);
2994 IOVEC_SET_STRING(iovec[n++], "] ");
2996 IOVEC_SET_STRING(iovec[n++], status_indent);
2999 IOVEC_SET_STRING(iovec[n++], s);
3001 IOVEC_SET_STRING(iovec[n++], "\n");
3003 if (writev(fd, iovec, n) < 0)
3009 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3015 va_start(ap, format);
3016 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3022 int status_welcome(void) {
3024 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3026 r = parse_env_file("/etc/os-release", NEWLINE,
3027 "PRETTY_NAME", &pretty_name,
3028 "ANSI_COLOR", &ansi_color,
3030 if (r < 0 && r != -ENOENT)
3031 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3033 return status_printf(NULL, false, false,
3034 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3035 isempty(ansi_color) ? "1" : ansi_color,
3036 isempty(pretty_name) ? "Linux" : pretty_name);
3039 char *replace_env(const char *format, char **env) {
3046 const char *e, *word = format;
3051 for (e = format; *e; e ++) {
3062 if (!(k = strnappend(r, word, e-word-1)))
3071 } else if (*e == '$') {
3072 if (!(k = strnappend(r, word, e-word)))
3088 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3090 k = strappend(r, t);
3104 if (!(k = strnappend(r, word, e-word)))
3115 char **replace_env_argv(char **argv, char **env) {
3117 unsigned k = 0, l = 0;
3119 l = strv_length(argv);
3121 if (!(r = new(char*, l+1)))
3124 STRV_FOREACH(i, argv) {
3126 /* If $FOO appears as single word, replace it by the split up variable */
3127 if ((*i)[0] == '$' && (*i)[1] != '{') {
3132 e = strv_env_get(env, *i+1);
3135 if (!(m = strv_split_quoted(e))) {
3146 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3155 memcpy(r + k, m, q * sizeof(char*));
3163 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3164 if (!(r[k++] = replace_env(*i, env))) {
3174 int fd_columns(int fd) {
3175 struct winsize ws = {};
3177 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3186 unsigned columns(void) {
3190 if (_likely_(cached_columns > 0))
3191 return cached_columns;
3194 e = getenv("COLUMNS");
3199 c = fd_columns(STDOUT_FILENO);
3208 int fd_lines(int fd) {
3209 struct winsize ws = {};
3211 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3220 unsigned lines(void) {
3224 if (_likely_(cached_lines > 0))
3225 return cached_lines;
3228 e = getenv("LINES");
3233 l = fd_lines(STDOUT_FILENO);
3239 return cached_lines;
3242 /* intended to be used as a SIGWINCH sighandler */
3243 void columns_lines_cache_reset(int signum) {
3249 static int cached_on_tty = -1;
3251 if (_unlikely_(cached_on_tty < 0))
3252 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3254 return cached_on_tty;
3257 int running_in_chroot(void) {
3258 struct stat a = {}, b = {};
3260 /* Only works as root */
3261 if (stat("/proc/1/root", &a) < 0)
3264 if (stat("/", &b) < 0)
3268 a.st_dev != b.st_dev ||
3269 a.st_ino != b.st_ino;
3272 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3277 assert(percent <= 100);
3278 assert(new_length >= 3);
3280 if (old_length <= 3 || old_length <= new_length)
3281 return strndup(s, old_length);
3283 r = new0(char, new_length+1);
3287 x = (new_length * percent) / 100;
3289 if (x > new_length - 3)
3297 s + old_length - (new_length - x - 3),
3298 new_length - x - 3);
3303 char *ellipsize(const char *s, size_t length, unsigned percent) {
3304 return ellipsize_mem(s, strlen(s), length, percent);
3307 int touch(const char *path) {
3312 /* This just opens the file for writing, ensuring it
3313 * exists. It doesn't call utimensat() the way /usr/bin/touch
3316 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3320 close_nointr_nofail(fd);
3324 char *unquote(const char *s, const char* quotes) {
3328 /* This is rather stupid, simply removes the heading and
3329 * trailing quotes if there is one. Doesn't care about
3330 * escaping or anything. We should make this smarter one
3337 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3338 return strndup(s+1, l-2);
3343 char *normalize_env_assignment(const char *s) {
3344 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3347 eq = strchr(s, '=');
3359 memmove(r, t, strlen(t) + 1);
3363 name = strndup(s, eq - s);
3371 value = unquote(strstrip(p), QUOTES);
3375 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3381 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3392 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3404 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3411 r = wait_for_terminate(pid, &status);
3413 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3417 if (status.si_code == CLD_EXITED) {
3418 if (status.si_status != 0) {
3419 log_warning("%s failed with error code %i.", name, status.si_status);
3420 return status.si_status;
3423 log_debug("%s succeeded.", name);
3426 } else if (status.si_code == CLD_KILLED ||
3427 status.si_code == CLD_DUMPED) {
3429 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3433 log_warning("%s failed due to unknown reason.", name);
3437 _noreturn_ void freeze(void) {
3439 /* Make sure nobody waits for us on a socket anymore */
3440 close_all_fds(NULL, 0);
3448 bool null_or_empty(struct stat *st) {
3451 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3454 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3460 int null_or_empty_path(const char *fn) {
3465 if (stat(fn, &st) < 0)
3468 return null_or_empty(&st);
3471 DIR *xopendirat(int fd, const char *name, int flags) {
3475 assert(!(flags & O_CREAT));
3477 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3483 close_nointr_nofail(nfd);
3490 int signal_from_string_try_harder(const char *s) {
3494 signo = signal_from_string(s);
3496 if (startswith(s, "SIG"))
3497 return signal_from_string(s+3);
3502 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3503 _cleanup_free_ char *t = NULL, *u = NULL;
3507 u = unquote(tagvalue, "\"\'");
3511 enc_len = strlen(u) * 4;
3512 t = new(char, enc_len);
3516 if (encode_devnode_name(u, t, enc_len) < 0)
3519 if (asprintf(&dn, "/dev/disk/by-%s/%s", by, t) < 0)
3525 char *fstab_node_to_udev_node(const char *p) {
3528 if (startswith(p, "LABEL="))
3529 return tag_to_udev_node(p+6, "label");
3531 if (startswith(p, "UUID="))
3532 return tag_to_udev_node(p+5, "uuid");
3534 if (startswith(p, "PARTUUID="))
3535 return tag_to_udev_node(p+9, "partuuid");
3537 if (startswith(p, "PARTLABEL="))
3538 return tag_to_udev_node(p+10, "partlabel");
3543 bool tty_is_vc(const char *tty) {
3546 if (startswith(tty, "/dev/"))
3549 return vtnr_from_tty(tty) >= 0;
3552 bool tty_is_console(const char *tty) {
3555 if (startswith(tty, "/dev/"))
3558 return streq(tty, "console");
3561 int vtnr_from_tty(const char *tty) {
3566 if (startswith(tty, "/dev/"))
3569 if (!startswith(tty, "tty") )
3572 if (tty[3] < '0' || tty[3] > '9')
3575 r = safe_atoi(tty+3, &i);
3579 if (i < 0 || i > 63)
3585 char *resolve_dev_console(char **active) {
3588 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3589 * (i.e. not read-only-mounted which is a sign for container setups) */
3591 if (path_is_read_only_fs("/sys") > 0)
3594 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3597 /* If multiple log outputs are configured the last one is what
3598 * /dev/console points to */
3599 tty = strrchr(*active, ' ');
3608 bool tty_is_vc_resolve(const char *tty) {
3609 char *active = NULL;
3614 if (startswith(tty, "/dev/"))
3617 if (streq(tty, "console")) {
3618 tty = resolve_dev_console(&active);
3629 const char *default_term_for_tty(const char *tty) {
3632 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3635 bool dirent_is_file(const struct dirent *de) {
3638 if (ignore_file(de->d_name))
3641 if (de->d_type != DT_REG &&
3642 de->d_type != DT_LNK &&
3643 de->d_type != DT_UNKNOWN)
3649 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3652 if (de->d_type != DT_REG &&
3653 de->d_type != DT_LNK &&
3654 de->d_type != DT_UNKNOWN)
3657 if (ignore_file_allow_backup(de->d_name))
3660 return endswith(de->d_name, suffix);
3663 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3666 Hashmap *pids = NULL;
3670 /* Executes all binaries in a directory in parallel and
3671 * waits for them to finish. */
3674 if (!(_d = opendir(directory))) {
3676 if (errno == ENOENT)
3679 log_error("Failed to enumerate directory %s: %m", directory);
3686 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3687 log_error("Failed to allocate set.");
3691 while ((de = readdir(d))) {
3696 if (!dirent_is_file(de))
3699 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3704 if ((pid = fork()) < 0) {
3705 log_error("Failed to fork: %m");
3723 log_error("Failed to execute %s: %m", path);
3724 _exit(EXIT_FAILURE);
3727 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3729 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3730 log_error("Failed to add PID to set: %s", strerror(-k));
3735 while (!hashmap_isempty(pids)) {
3736 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3740 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3745 log_error("waitid() failed: %m");
3749 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3750 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3751 if (si.si_code == CLD_EXITED)
3752 log_error("%s exited with exit status %i.", path, si.si_status);
3754 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3756 log_debug("%s exited successfully.", path);
3767 hashmap_free_free(pids);
3770 int kill_and_sigcont(pid_t pid, int sig) {
3773 r = kill(pid, sig) < 0 ? -errno : 0;
3781 bool nulstr_contains(const char*nulstr, const char *needle) {
3787 NULSTR_FOREACH(i, nulstr)
3788 if (streq(i, needle))
3794 bool plymouth_running(void) {
3795 return access("/run/plymouth/pid", F_OK) >= 0;
3798 char* strshorten(char *s, size_t l) {
3807 static bool hostname_valid_char(char c) {
3809 (c >= 'a' && c <= 'z') ||
3810 (c >= 'A' && c <= 'Z') ||
3811 (c >= '0' && c <= '9') ||
3817 bool hostname_is_valid(const char *s) {
3824 for (p = s, dot = true; *p; p++) {
3831 if (!hostname_valid_char(*p))
3841 if (p-s > HOST_NAME_MAX)
3847 char* hostname_cleanup(char *s, bool lowercase) {
3851 for (p = s, d = s, dot = true; *p; p++) {
3858 } else if (hostname_valid_char(*p)) {
3859 *(d++) = lowercase ? tolower(*p) : *p;
3870 strshorten(s, HOST_NAME_MAX);
3875 int pipe_eof(int fd) {
3877 struct pollfd pollfd = {
3879 .events = POLLIN|POLLHUP,
3882 r = poll(&pollfd, 1, 0);
3889 return pollfd.revents & POLLHUP;
3892 int fd_wait_for_event(int fd, int event, usec_t t) {
3894 struct pollfd pollfd = {
3899 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3906 return pollfd.revents;
3909 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3920 t = new(char, strlen(path) + 1 + 6 + 1);
3924 fn = path_get_file_name(path);
3928 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3930 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3936 f = fdopen(fd, "we");
3949 int terminal_vhangup_fd(int fd) {
3952 if (ioctl(fd, TIOCVHANGUP) < 0)
3958 int terminal_vhangup(const char *name) {
3961 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3965 r = terminal_vhangup_fd(fd);
3966 close_nointr_nofail(fd);
3971 int vt_disallocate(const char *name) {
3975 /* Deallocate the VT if possible. If not possible
3976 * (i.e. because it is the active one), at least clear it
3977 * entirely (including the scrollback buffer) */
3979 if (!startswith(name, "/dev/"))
3982 if (!tty_is_vc(name)) {
3983 /* So this is not a VT. I guess we cannot deallocate
3984 * it then. But let's at least clear the screen */
3986 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3991 "\033[r" /* clear scrolling region */
3992 "\033[H" /* move home */
3993 "\033[2J", /* clear screen */
3995 close_nointr_nofail(fd);
4000 if (!startswith(name, "/dev/tty"))
4003 r = safe_atou(name+8, &u);
4010 /* Try to deallocate */
4011 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4015 r = ioctl(fd, VT_DISALLOCATE, u);
4016 close_nointr_nofail(fd);
4024 /* Couldn't deallocate, so let's clear it fully with
4026 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4031 "\033[r" /* clear scrolling region */
4032 "\033[H" /* move home */
4033 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4035 close_nointr_nofail(fd);
4040 int copy_file(const char *from, const char *to) {
4046 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4050 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4052 close_nointr_nofail(fdf);
4060 n = read(fdf, buf, sizeof(buf));
4064 close_nointr_nofail(fdf);
4075 k = loop_write(fdt, buf, n, false);
4077 r = k < 0 ? k : (errno ? -errno : -EIO);
4079 close_nointr_nofail(fdf);
4087 close_nointr_nofail(fdf);
4088 r = close_nointr(fdt);
4098 int symlink_atomic(const char *from, const char *to) {
4100 _cleanup_free_ char *t;
4103 unsigned long long ull;
4110 t = new(char, strlen(to) + 1 + 16 + 1);
4114 fn = path_get_file_name(to);
4118 x = stpcpy(t+k+1, fn);
4121 for (i = 0; i < 16; i++) {
4122 *(x++) = hexchar(ull & 0xF);
4128 if (symlink(from, t) < 0)
4131 if (rename(t, to) < 0) {
4140 bool display_is_local(const char *display) {
4144 display[0] == ':' &&
4145 display[1] >= '0' &&
4149 int socket_from_display(const char *display, char **path) {
4156 if (!display_is_local(display))
4159 k = strspn(display+1, "0123456789");
4161 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4165 c = stpcpy(f, "/tmp/.X11-unix/X");
4166 memcpy(c, display+1, k);
4175 const char **username,
4176 uid_t *uid, gid_t *gid,
4178 const char **shell) {
4186 /* We enforce some special rules for uid=0: in order to avoid
4187 * NSS lookups for root we hardcode its data. */
4189 if (streq(*username, "root") || streq(*username, "0")) {
4207 if (parse_uid(*username, &u) >= 0) {
4211 /* If there are multiple users with the same id, make
4212 * sure to leave $USER to the configured value instead
4213 * of the first occurrence in the database. However if
4214 * the uid was configured by a numeric uid, then let's
4215 * pick the real username from /etc/passwd. */
4217 *username = p->pw_name;
4220 p = getpwnam(*username);
4224 return errno > 0 ? -errno : -ESRCH;
4236 *shell = p->pw_shell;
4241 char* uid_to_name(uid_t uid) {
4246 return strdup("root");
4250 return strdup(p->pw_name);
4252 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4258 char* gid_to_name(gid_t gid) {
4263 return strdup("root");
4267 return strdup(p->gr_name);
4269 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4275 int get_group_creds(const char **groupname, gid_t *gid) {
4281 /* We enforce some special rules for gid=0: in order to avoid
4282 * NSS lookups for root we hardcode its data. */
4284 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4285 *groupname = "root";
4293 if (parse_gid(*groupname, &id) >= 0) {
4298 *groupname = g->gr_name;
4301 g = getgrnam(*groupname);
4305 return errno > 0 ? -errno : -ESRCH;
4313 int in_gid(gid_t gid) {
4315 int ngroups_max, r, i;
4317 if (getgid() == gid)
4320 if (getegid() == gid)
4323 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4324 assert(ngroups_max > 0);
4326 gids = alloca(sizeof(gid_t) * ngroups_max);
4328 r = getgroups(ngroups_max, gids);
4332 for (i = 0; i < r; i++)
4339 int in_group(const char *name) {
4343 r = get_group_creds(&name, &gid);
4350 int glob_exists(const char *path) {
4351 _cleanup_globfree_ glob_t g = {};
4357 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4359 if (k == GLOB_NOMATCH)
4361 else if (k == GLOB_NOSPACE)
4364 return !strv_isempty(g.gl_pathv);
4366 return errno ? -errno : -EIO;
4369 int glob_extend(char ***strv, const char *path) {
4370 _cleanup_globfree_ glob_t g = {};
4375 k = glob(optarg, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4377 if (k == GLOB_NOMATCH)
4379 else if (k == GLOB_NOSPACE)
4381 else if (k != 0 || strv_isempty(g.gl_pathv))
4382 return errno ? -errno : -EIO;
4384 STRV_FOREACH(p, g.gl_pathv) {
4385 k = strv_extend(strv, *p);
4393 int dirent_ensure_type(DIR *d, struct dirent *de) {
4399 if (de->d_type != DT_UNKNOWN)
4402 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4406 S_ISREG(st.st_mode) ? DT_REG :
4407 S_ISDIR(st.st_mode) ? DT_DIR :
4408 S_ISLNK(st.st_mode) ? DT_LNK :
4409 S_ISFIFO(st.st_mode) ? DT_FIFO :
4410 S_ISSOCK(st.st_mode) ? DT_SOCK :
4411 S_ISCHR(st.st_mode) ? DT_CHR :
4412 S_ISBLK(st.st_mode) ? DT_BLK :
4418 int in_search_path(const char *path, char **search) {
4420 _cleanup_free_ char *parent = NULL;
4423 r = path_get_parent(path, &parent);
4427 STRV_FOREACH(i, search)
4428 if (path_equal(parent, *i))
4434 int get_files_in_directory(const char *path, char ***list) {
4435 _cleanup_closedir_ DIR *d = NULL;
4436 size_t bufsize = 0, n = 0;
4437 _cleanup_strv_free_ char **l = NULL;
4441 /* Returns all files in a directory in *list, and the number
4442 * of files as return value. If list is NULL returns only the
4451 union dirent_storage buf;
4454 k = readdir_r(d, &buf.de, &de);
4461 dirent_ensure_type(d, de);
4463 if (!dirent_is_file(de))
4467 /* one extra slot is needed for the terminating NULL */
4468 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4471 l[n] = strdup(de->d_name);
4482 l = NULL; /* avoid freeing */
4488 char *strjoin(const char *x, ...) {
4502 t = va_arg(ap, const char *);
4507 if (n > ((size_t) -1) - l) {
4531 t = va_arg(ap, const char *);
4545 bool is_main_thread(void) {
4546 static __thread int cached = 0;
4548 if (_unlikely_(cached == 0))
4549 cached = getpid() == gettid() ? 1 : -1;
4554 int block_get_whole_disk(dev_t d, dev_t *ret) {
4561 /* If it has a queue this is good enough for us */
4562 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4565 r = access(p, F_OK);
4573 /* If it is a partition find the originating device */
4574 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4577 r = access(p, F_OK);
4583 /* Get parent dev_t */
4584 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4587 r = read_one_line_file(p, &s);
4593 r = sscanf(s, "%u:%u", &m, &n);
4599 /* Only return this if it is really good enough for us. */
4600 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4603 r = access(p, F_OK);
4607 *ret = makedev(m, n);
4614 int file_is_priv_sticky(const char *p) {
4619 if (lstat(p, &st) < 0)
4623 (st.st_uid == 0 || st.st_uid == getuid()) &&
4624 (st.st_mode & S_ISVTX);
4627 static const char *const ioprio_class_table[] = {
4628 [IOPRIO_CLASS_NONE] = "none",
4629 [IOPRIO_CLASS_RT] = "realtime",
4630 [IOPRIO_CLASS_BE] = "best-effort",
4631 [IOPRIO_CLASS_IDLE] = "idle"
4634 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4636 static const char *const sigchld_code_table[] = {
4637 [CLD_EXITED] = "exited",
4638 [CLD_KILLED] = "killed",
4639 [CLD_DUMPED] = "dumped",
4640 [CLD_TRAPPED] = "trapped",
4641 [CLD_STOPPED] = "stopped",
4642 [CLD_CONTINUED] = "continued",
4645 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4647 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4648 [LOG_FAC(LOG_KERN)] = "kern",
4649 [LOG_FAC(LOG_USER)] = "user",
4650 [LOG_FAC(LOG_MAIL)] = "mail",
4651 [LOG_FAC(LOG_DAEMON)] = "daemon",
4652 [LOG_FAC(LOG_AUTH)] = "auth",
4653 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4654 [LOG_FAC(LOG_LPR)] = "lpr",
4655 [LOG_FAC(LOG_NEWS)] = "news",
4656 [LOG_FAC(LOG_UUCP)] = "uucp",
4657 [LOG_FAC(LOG_CRON)] = "cron",
4658 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4659 [LOG_FAC(LOG_FTP)] = "ftp",
4660 [LOG_FAC(LOG_LOCAL0)] = "local0",
4661 [LOG_FAC(LOG_LOCAL1)] = "local1",
4662 [LOG_FAC(LOG_LOCAL2)] = "local2",
4663 [LOG_FAC(LOG_LOCAL3)] = "local3",
4664 [LOG_FAC(LOG_LOCAL4)] = "local4",
4665 [LOG_FAC(LOG_LOCAL5)] = "local5",
4666 [LOG_FAC(LOG_LOCAL6)] = "local6",
4667 [LOG_FAC(LOG_LOCAL7)] = "local7"
4670 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4672 static const char *const log_level_table[] = {
4673 [LOG_EMERG] = "emerg",
4674 [LOG_ALERT] = "alert",
4675 [LOG_CRIT] = "crit",
4677 [LOG_WARNING] = "warning",
4678 [LOG_NOTICE] = "notice",
4679 [LOG_INFO] = "info",
4680 [LOG_DEBUG] = "debug"
4683 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4685 static const char* const sched_policy_table[] = {
4686 [SCHED_OTHER] = "other",
4687 [SCHED_BATCH] = "batch",
4688 [SCHED_IDLE] = "idle",
4689 [SCHED_FIFO] = "fifo",
4693 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4695 static const char* const rlimit_table[] = {
4696 [RLIMIT_CPU] = "LimitCPU",
4697 [RLIMIT_FSIZE] = "LimitFSIZE",
4698 [RLIMIT_DATA] = "LimitDATA",
4699 [RLIMIT_STACK] = "LimitSTACK",
4700 [RLIMIT_CORE] = "LimitCORE",
4701 [RLIMIT_RSS] = "LimitRSS",
4702 [RLIMIT_NOFILE] = "LimitNOFILE",
4703 [RLIMIT_AS] = "LimitAS",
4704 [RLIMIT_NPROC] = "LimitNPROC",
4705 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4706 [RLIMIT_LOCKS] = "LimitLOCKS",
4707 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4708 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4709 [RLIMIT_NICE] = "LimitNICE",
4710 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4711 [RLIMIT_RTTIME] = "LimitRTTIME"
4714 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4716 static const char* const ip_tos_table[] = {
4717 [IPTOS_LOWDELAY] = "low-delay",
4718 [IPTOS_THROUGHPUT] = "throughput",
4719 [IPTOS_RELIABILITY] = "reliability",
4720 [IPTOS_LOWCOST] = "low-cost",
4723 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4725 static const char *const __signal_table[] = {
4742 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4753 [SIGVTALRM] = "VTALRM",
4755 [SIGWINCH] = "WINCH",
4761 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4763 const char *signal_to_string(int signo) {
4764 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4767 name = __signal_to_string(signo);
4771 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4772 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4774 snprintf(buf, sizeof(buf), "%d", signo);
4779 int signal_from_string(const char *s) {
4784 signo = __signal_from_string(s);
4788 if (startswith(s, "RTMIN+")) {
4792 if (safe_atou(s, &u) >= 0) {
4793 signo = (int) u + offset;
4794 if (signo > 0 && signo < _NSIG)
4800 bool kexec_loaded(void) {
4801 bool loaded = false;
4804 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4812 int strdup_or_null(const char *a, char **b) {
4830 int prot_from_flags(int flags) {
4832 switch (flags & O_ACCMODE) {
4841 return PROT_READ|PROT_WRITE;
4848 char *format_bytes(char *buf, size_t l, off_t t) {
4851 static const struct {
4855 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4856 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4857 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4858 { "G", 1024ULL*1024ULL*1024ULL },
4859 { "M", 1024ULL*1024ULL },
4863 for (i = 0; i < ELEMENTSOF(table); i++) {
4865 if (t >= table[i].factor) {
4868 (unsigned long long) (t / table[i].factor),
4869 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4876 snprintf(buf, l, "%lluB", (unsigned long long) t);
4884 void* memdup(const void *p, size_t l) {
4897 int fd_inc_sndbuf(int fd, size_t n) {
4899 socklen_t l = sizeof(value);
4901 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4903 l == sizeof(value) &&
4904 (size_t) value >= n*2)
4908 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4915 int fd_inc_rcvbuf(int fd, size_t n) {
4917 socklen_t l = sizeof(value);
4919 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4921 l == sizeof(value) &&
4922 (size_t) value >= n*2)
4926 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4933 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4934 pid_t parent_pid, agent_pid;
4936 bool stdout_is_tty, stderr_is_tty;
4944 parent_pid = getpid();
4946 /* Spawns a temporary TTY agent, making sure it goes away when
4953 if (agent_pid != 0) {
4960 * Make sure the agent goes away when the parent dies */
4961 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4962 _exit(EXIT_FAILURE);
4964 /* Check whether our parent died before we were able
4965 * to set the death signal */
4966 if (getppid() != parent_pid)
4967 _exit(EXIT_SUCCESS);
4969 /* Don't leak fds to the agent */
4970 close_all_fds(except, n_except);
4972 stdout_is_tty = isatty(STDOUT_FILENO);
4973 stderr_is_tty = isatty(STDERR_FILENO);
4975 if (!stdout_is_tty || !stderr_is_tty) {
4976 /* Detach from stdout/stderr. and reopen
4977 * /dev/tty for them. This is important to
4978 * ensure that when systemctl is started via
4979 * popen() or a similar call that expects to
4980 * read EOF we actually do generate EOF and
4981 * not delay this indefinitely by because we
4982 * keep an unused copy of stdin around. */
4983 fd = open("/dev/tty", O_WRONLY);
4985 log_error("Failed to open /dev/tty: %m");
4986 _exit(EXIT_FAILURE);
4990 dup2(fd, STDOUT_FILENO);
4993 dup2(fd, STDERR_FILENO);
4999 /* Count arguments */
5001 for (n = 0; va_arg(ap, char*); n++)
5006 l = alloca(sizeof(char *) * (n + 1));
5008 /* Fill in arguments */
5010 for (i = 0; i <= n; i++)
5011 l[i] = va_arg(ap, char*);
5015 _exit(EXIT_FAILURE);
5018 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5019 struct rlimit highest, fixed;
5023 if (setrlimit(resource, rlim) >= 0)
5029 /* So we failed to set the desired setrlimit, then let's try
5030 * to get as close as we can */
5031 assert_se(getrlimit(resource, &highest) == 0);
5033 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5034 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5036 if (setrlimit(resource, &fixed) < 0)
5042 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5043 _cleanup_fclose_ FILE *f = NULL;
5055 path = "/proc/self/environ";
5057 path = procfs_file_alloca(pid, "environ");
5059 f = fopen(path, "re");
5067 char line[LINE_MAX];
5070 for (i = 0; i < sizeof(line)-1; i++) {
5074 if (_unlikely_(c == EOF)) {
5084 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5085 value = strdup(line + l + 1);
5099 bool is_valid_documentation_url(const char *url) {
5102 if (startswith(url, "http://") && url[7])
5105 if (startswith(url, "https://") && url[8])
5108 if (startswith(url, "file:") && url[5])
5111 if (startswith(url, "info:") && url[5])
5114 if (startswith(url, "man:") && url[4])
5120 bool in_initrd(void) {
5121 static __thread int saved = -1;
5127 /* We make two checks here:
5129 * 1. the flag file /etc/initrd-release must exist
5130 * 2. the root file system must be a memory file system
5132 * The second check is extra paranoia, since misdetecting an
5133 * initrd can have bad bad consequences due the initrd
5134 * emptying when transititioning to the main systemd.
5137 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5138 statfs("/", &s) >= 0 &&
5139 is_temporary_fs(&s);
5144 void warn_melody(void) {
5145 _cleanup_close_ int fd = -1;
5147 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5151 /* Yeah, this is synchronous. Kinda sucks. But well... */
5153 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5154 usleep(125*USEC_PER_MSEC);
5156 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5157 usleep(125*USEC_PER_MSEC);
5159 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5160 usleep(125*USEC_PER_MSEC);
5162 ioctl(fd, KIOCSOUND, 0);
5165 int make_console_stdio(void) {
5168 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5170 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5172 log_error("Failed to acquire terminal: %s", strerror(-fd));
5178 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5185 int get_home_dir(char **_h) {
5193 /* Take the user specified one */
5204 /* Hardcode home directory for root to avoid NSS */
5207 h = strdup("/root");
5215 /* Check the database... */
5219 return errno > 0 ? -errno : -ESRCH;
5221 if (!path_is_absolute(p->pw_dir))
5224 h = strdup(p->pw_dir);
5232 bool filename_is_safe(const char *p) {
5246 if (strlen(p) > FILENAME_MAX)
5252 bool string_is_safe(const char *p) {
5257 for (t = p; *t; t++) {
5258 if (*t > 0 && *t < ' ')
5261 if (strchr("\\\"\'", *t))
5269 * Check if a string contains control characters.
5270 * Spaces and tabs are not considered control characters.
5272 bool string_has_cc(const char *p) {
5277 for (t = p; *t; t++)
5278 if (*t > 0 && *t < ' ' && *t != '\t')
5284 bool path_is_safe(const char *p) {
5289 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5292 if (strlen(p) > PATH_MAX)
5295 /* The following two checks are not really dangerous, but hey, they still are confusing */
5296 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5299 if (strstr(p, "//"))
5305 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5306 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5307 int (*compar) (const void *, const void *, void *), void *arg) {
5316 p = (void *)(((const char *) base) + (idx * size));
5317 comparison = compar(key, p, arg);
5320 else if (comparison > 0)
5328 bool is_locale_utf8(void) {
5330 static int cached_answer = -1;
5332 if (cached_answer >= 0)
5335 if (!setlocale(LC_ALL, "")) {
5336 cached_answer = true;
5340 set = nl_langinfo(CODESET);
5342 cached_answer = true;
5346 if(streq(set, "UTF-8")) {
5347 cached_answer = true;
5351 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5352 * unset and everything can do to UTF-8 nowadays. */
5353 set = setlocale(LC_CTYPE, NULL);
5355 cached_answer = true;
5359 /* Check result, but ignore the result if C was set
5363 !getenv("LC_ALL") &&
5364 !getenv("LC_CTYPE") &&
5368 return (bool) cached_answer;
5371 const char *draw_special_char(DrawSpecialChar ch) {
5372 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5374 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5375 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5376 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5377 [DRAW_TREE_SPACE] = " ", /* */
5378 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5380 /* ASCII fallback */ {
5381 [DRAW_TREE_VERT] = "| ",
5382 [DRAW_TREE_BRANCH] = "|-",
5383 [DRAW_TREE_RIGHT] = "`-",
5384 [DRAW_TREE_SPACE] = " ",
5385 [DRAW_TRIANGULAR_BULLET] = "> ",
5389 return draw_table[!is_locale_utf8()][ch];
5392 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5395 size_t l, old_len, new_len;
5401 old_len = strlen(old_string);
5402 new_len = strlen(new_string);
5415 if (!startswith(f, old_string)) {
5421 nl = l - old_len + new_len;
5422 a = realloc(r, nl + 1);
5430 t = stpcpy(t, new_string);
5442 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5443 const char *i, *begin = NULL;
5448 } state = STATE_OTHER;
5450 size_t osz = 0, isz;
5456 /* Strips ANSI color and replaces TABs by 8 spaces */
5458 isz = _isz ? *_isz : strlen(*ibuf);
5460 f = open_memstream(&obuf, &osz);
5464 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5469 if (i >= *ibuf + isz) /* EOT */
5471 else if (*i == '\x1B')
5472 state = STATE_ESCAPE;
5473 else if (*i == '\t')
5480 if (i >= *ibuf + isz) { /* EOT */
5483 } else if (*i == '[') {
5484 state = STATE_BRACKET;
5489 state = STATE_OTHER;
5496 if (i >= *ibuf + isz || /* EOT */
5497 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5500 state = STATE_OTHER;
5502 } else if (*i == 'm')
5503 state = STATE_OTHER;
5525 int on_ac_power(void) {
5526 bool found_offline = false, found_online = false;
5527 _cleanup_closedir_ DIR *d = NULL;
5529 d = opendir("/sys/class/power_supply");
5535 union dirent_storage buf;
5536 _cleanup_close_ int fd = -1, device = -1;
5541 k = readdir_r(d, &buf.de, &de);
5548 if (ignore_file(de->d_name))
5551 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5553 if (errno == ENOENT || errno == ENOTDIR)
5559 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5561 if (errno == ENOENT)
5567 n = read(fd, contents, sizeof(contents));
5571 if (n != 6 || memcmp(contents, "Mains\n", 6))
5574 close_nointr_nofail(fd);
5575 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5577 if (errno == ENOENT)
5583 n = read(fd, contents, sizeof(contents));
5587 if (n != 2 || contents[1] != '\n')
5590 if (contents[0] == '1') {
5591 found_online = true;
5593 } else if (contents[0] == '0')
5594 found_offline = true;
5599 return found_online || !found_offline;
5602 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5609 if (!path_strv_canonicalize_uniq(search))
5612 STRV_FOREACH(i, search) {
5613 _cleanup_free_ char *p = NULL;
5616 p = strjoin(*i, "/", path, NULL);
5626 if (errno != ENOENT)
5633 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5634 _cleanup_strv_free_ char **copy = NULL;
5640 if (path_is_absolute(path)) {
5643 f = fopen(path, mode);
5652 copy = strv_copy((char**) search);
5656 return search_and_fopen_internal(path, mode, copy, _f);
5659 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5660 _cleanup_strv_free_ char **s = NULL;
5662 if (path_is_absolute(path)) {
5665 f = fopen(path, mode);
5674 s = strv_split_nulstr(search);
5678 return search_and_fopen_internal(path, mode, s, _f);
5681 int create_tmp_dir(char template[], char** dir_name) {
5683 char *d = NULL, *dt;
5687 RUN_WITH_UMASK(0077) {
5688 d = mkdtemp(template);
5691 log_error("Can't create directory %s: %m", template);
5695 dt = strjoin(d, "/tmp", NULL);
5701 RUN_WITH_UMASK(0000) {
5702 r = mkdir(dt, 0777);
5705 log_error("Can't create directory %s: %m", dt);
5709 log_debug("Created temporary directory %s", dt);
5711 r = chmod(dt, 0777 | S_ISVTX);
5713 log_error("Failed to chmod %s: %m", dt);
5717 log_debug("Set sticky bit on %s", dt);
5731 char *strextend(char **x, ...) {
5738 l = f = *x ? strlen(*x) : 0;
5745 t = va_arg(ap, const char *);
5750 if (n > ((size_t) -1) - l) {
5759 r = realloc(*x, l+1);
5769 t = va_arg(ap, const char *);
5783 char *strrep(const char *s, unsigned n) {
5791 p = r = malloc(l * n + 1);
5795 for (i = 0; i < n; i++)
5802 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5806 if (*allocated >= need)
5809 a = MAX(64u, need * 2);
5819 bool id128_is_valid(const char *s) {
5825 /* Simple formatted 128bit hex string */
5827 for (i = 0; i < l; i++) {
5830 if (!(c >= '0' && c <= '9') &&
5831 !(c >= 'a' && c <= 'z') &&
5832 !(c >= 'A' && c <= 'Z'))
5836 } else if (l == 36) {
5838 /* Formatted UUID */
5840 for (i = 0; i < l; i++) {
5843 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5847 if (!(c >= '0' && c <= '9') &&
5848 !(c >= 'a' && c <= 'z') &&
5849 !(c >= 'A' && c <= 'Z'))
5860 void parse_user_at_host(char *arg, char **user, char **host) {
5865 *host = strchr(arg, '@');
5874 int split_pair(const char *s, const char *sep, char **l, char **r) {
5889 a = strndup(s, x - s);
5893 b = strdup(x + strlen(sep));