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>
45 #include <sys/prctl.h>
46 #include <sys/utsname.h>
48 #include <netinet/ip.h>
57 #include <linux/magic.h>
64 #ifdef HAVE_SYS_AUXV_H
75 #include "path-util.h"
76 #include "exit-status.h"
80 #include "device-nodes.h"
87 char **saved_argv = NULL;
89 static volatile unsigned cached_columns = 0;
90 static volatile unsigned cached_lines = 0;
92 size_t page_size(void) {
93 static thread_local size_t pgsz = 0;
96 if (_likely_(pgsz > 0))
99 r = sysconf(_SC_PAGESIZE);
106 bool streq_ptr(const char *a, const char *b) {
108 /* Like streq(), but tries to make sense of NULL pointers */
119 char* endswith(const char *s, const char *postfix) {
126 pl = strlen(postfix);
129 return (char*) s + sl;
134 if (memcmp(s + sl - pl, postfix, pl) != 0)
137 return (char*) s + sl - pl;
140 bool first_word(const char *s, const char *word) {
155 if (memcmp(s, word, wl) != 0)
159 strchr(WHITESPACE, s[wl]);
162 int close_nointr(int fd) {
168 /* Just ignore EINTR; a retry loop is the wrong
169 * thing to do on Linux.
171 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
172 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
173 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
174 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
176 if (_unlikely_(r < 0 && errno == EINTR))
184 void close_nointr_nofail(int fd) {
187 /* like close_nointr() but cannot fail, and guarantees errno
190 assert_se(close_nointr(fd) == 0);
193 void close_many(const int fds[], unsigned n_fd) {
196 assert(fds || n_fd <= 0);
198 for (i = 0; i < n_fd; i++)
199 close_nointr_nofail(fds[i]);
202 int unlink_noerrno(const char *path) {
213 int parse_boolean(const char *v) {
216 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
218 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
224 int parse_pid(const char *s, pid_t* ret_pid) {
225 unsigned long ul = 0;
232 r = safe_atolu(s, &ul);
238 if ((unsigned long) pid != ul)
248 int parse_uid(const char *s, uid_t* ret_uid) {
249 unsigned long ul = 0;
256 r = safe_atolu(s, &ul);
262 if ((unsigned long) uid != ul)
269 int safe_atou(const char *s, unsigned *ret_u) {
277 l = strtoul(s, &x, 0);
279 if (!x || x == s || *x || errno)
280 return errno > 0 ? -errno : -EINVAL;
282 if ((unsigned long) (unsigned) l != l)
285 *ret_u = (unsigned) l;
289 int safe_atoi(const char *s, int *ret_i) {
297 l = strtol(s, &x, 0);
299 if (!x || x == s || *x || errno)
300 return errno > 0 ? -errno : -EINVAL;
302 if ((long) (int) l != l)
309 int safe_atollu(const char *s, long long unsigned *ret_llu) {
311 unsigned long long l;
317 l = strtoull(s, &x, 0);
319 if (!x || x == s || *x || errno)
320 return errno ? -errno : -EINVAL;
326 int safe_atolli(const char *s, long long int *ret_lli) {
334 l = strtoll(s, &x, 0);
336 if (!x || x == s || *x || errno)
337 return errno ? -errno : -EINVAL;
343 int safe_atod(const char *s, double *ret_d) {
350 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
355 if (!x || x == s || *x || errno)
356 return errno ? -errno : -EINVAL;
362 static size_t strcspn_escaped(const char *s, const char *reject) {
363 bool escaped = false;
366 for (n=0; s[n]; n++) {
369 else if (s[n] == '\\')
371 else if (strchr(reject, s[n]))
377 /* Split a string into words. */
378 char *split(const char *c, size_t *l, const char *separator, bool quoted, char **state) {
381 current = *state ? *state : (char*) c;
383 if (!*current || *c == 0)
386 current += strspn(current, separator);
390 if (quoted && strchr("\'\"", *current)) {
391 char quotechar = *(current++);
392 *l = strcspn_escaped(current, (char[]){quotechar, '\0'});
393 *state = current+*l+1;
395 *l = strcspn_escaped(current, separator);
398 *l = strcspn(current, separator);
402 return (char*) current;
405 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
407 _cleanup_free_ char *line = NULL;
419 p = procfs_file_alloca(pid, "stat");
420 r = read_one_line_file(p, &line);
424 /* Let's skip the pid and comm fields. The latter is enclosed
425 * in () but does not escape any () in its value, so let's
426 * skip over it manually */
428 p = strrchr(line, ')');
440 if ((long unsigned) (pid_t) ppid != ppid)
443 *_ppid = (pid_t) ppid;
448 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
450 _cleanup_free_ char *line = NULL;
456 p = procfs_file_alloca(pid, "stat");
457 r = read_one_line_file(p, &line);
461 /* Let's skip the pid and comm fields. The latter is enclosed
462 * in () but does not escape any () in its value, so let's
463 * skip over it manually */
465 p = strrchr(line, ')');
487 "%*d " /* priority */
489 "%*d " /* num_threads */
490 "%*d " /* itrealvalue */
491 "%llu " /* starttime */,
498 int fchmod_umask(int fd, mode_t m) {
503 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
509 char *truncate_nl(char *s) {
512 s[strcspn(s, NEWLINE)] = 0;
516 int get_process_comm(pid_t pid, char **name) {
523 p = procfs_file_alloca(pid, "comm");
525 r = read_one_line_file(p, name);
532 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
533 _cleanup_fclose_ FILE *f = NULL;
541 p = procfs_file_alloca(pid, "cmdline");
547 if (max_length == 0) {
548 size_t len = 0, allocated = 0;
550 while ((c = getc(f)) != EOF) {
552 if (!GREEDY_REALLOC(r, allocated, len+2)) {
557 r[len++] = isprint(c) ? c : ' ';
567 r = new(char, max_length);
573 while ((c = getc(f)) != EOF) {
595 size_t n = MIN(left-1, 3U);
602 /* Kernel threads have no argv[] */
603 if (r == NULL || r[0] == 0) {
604 _cleanup_free_ char *t = NULL;
612 h = get_process_comm(pid, &t);
616 r = strjoin("[", t, "]", NULL);
625 int is_kernel_thread(pid_t pid) {
637 p = procfs_file_alloca(pid, "cmdline");
642 count = fread(&c, 1, 1, f);
646 /* Kernel threads have an empty cmdline */
649 return eof ? 1 : -errno;
654 int get_process_capeff(pid_t pid, char **capeff) {
660 p = procfs_file_alloca(pid, "status");
662 return get_status_field(p, "\nCapEff:", capeff);
665 int get_process_exe(pid_t pid, char **name) {
673 p = procfs_file_alloca(pid, "exe");
675 r = readlink_malloc(p, name);
677 return r == -ENOENT ? -ESRCH : r;
679 d = endswith(*name, " (deleted)");
686 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
687 _cleanup_fclose_ FILE *f = NULL;
697 p = procfs_file_alloca(pid, "status");
702 FOREACH_LINE(line, f, return -errno) {
707 if (startswith(l, field)) {
709 l += strspn(l, WHITESPACE);
711 l[strcspn(l, WHITESPACE)] = 0;
713 return parse_uid(l, uid);
720 int get_process_uid(pid_t pid, uid_t *uid) {
721 return get_process_id(pid, "Uid:", uid);
724 int get_process_gid(pid_t pid, gid_t *gid) {
725 assert_cc(sizeof(uid_t) == sizeof(gid_t));
726 return get_process_id(pid, "Gid:", gid);
729 char *strnappend(const char *s, const char *suffix, size_t b) {
737 return strndup(suffix, b);
746 if (b > ((size_t) -1) - a)
749 r = new(char, a+b+1);
754 memcpy(r+a, suffix, b);
760 char *strappend(const char *s, const char *suffix) {
761 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
764 int readlink_malloc(const char *p, char **ret) {
779 n = readlink(p, c, l-1);
786 if ((size_t) n < l-1) {
797 int readlink_and_make_absolute(const char *p, char **r) {
798 _cleanup_free_ char *target = NULL;
805 j = readlink_malloc(p, &target);
809 k = file_in_same_dir(p, target);
817 int readlink_and_canonicalize(const char *p, char **r) {
824 j = readlink_and_make_absolute(p, &t);
828 s = canonicalize_file_name(t);
835 path_kill_slashes(*r);
840 int reset_all_signal_handlers(void) {
843 for (sig = 1; sig < _NSIG; sig++) {
844 struct sigaction sa = {
845 .sa_handler = SIG_DFL,
846 .sa_flags = SA_RESTART,
849 if (sig == SIGKILL || sig == SIGSTOP)
852 /* On Linux the first two RT signals are reserved by
853 * glibc, and sigaction() will return EINVAL for them. */
854 if ((sigaction(sig, &sa, NULL) < 0))
862 char *strstrip(char *s) {
865 /* Drops trailing whitespace. Modifies the string in
866 * place. Returns pointer to first non-space character */
868 s += strspn(s, WHITESPACE);
870 for (e = strchr(s, 0); e > s; e --)
871 if (!strchr(WHITESPACE, e[-1]))
879 char *delete_chars(char *s, const char *bad) {
882 /* Drops all whitespace, regardless where in the string */
884 for (f = s, t = s; *f; f++) {
896 bool in_charset(const char *s, const char* charset) {
903 if (!strchr(charset, *i))
909 char *file_in_same_dir(const char *path, const char *filename) {
916 /* This removes the last component of path and appends
917 * filename, unless the latter is absolute anyway or the
920 if (path_is_absolute(filename))
921 return strdup(filename);
923 if (!(e = strrchr(path, '/')))
924 return strdup(filename);
926 k = strlen(filename);
927 if (!(r = new(char, e-path+1+k+1)))
930 memcpy(r, path, e-path+1);
931 memcpy(r+(e-path)+1, filename, k+1);
936 int rmdir_parents(const char *path, const char *stop) {
945 /* Skip trailing slashes */
946 while (l > 0 && path[l-1] == '/')
952 /* Skip last component */
953 while (l > 0 && path[l-1] != '/')
956 /* Skip trailing slashes */
957 while (l > 0 && path[l-1] == '/')
963 if (!(t = strndup(path, l)))
966 if (path_startswith(stop, t)) {
982 char hexchar(int x) {
983 static const char table[16] = "0123456789abcdef";
985 return table[x & 15];
988 int unhexchar(char c) {
990 if (c >= '0' && c <= '9')
993 if (c >= 'a' && c <= 'f')
996 if (c >= 'A' && c <= 'F')
1002 char *hexmem(const void *p, size_t l) {
1006 z = r = malloc(l * 2 + 1);
1010 for (x = p; x < (const uint8_t*) p + l; x++) {
1011 *(z++) = hexchar(*x >> 4);
1012 *(z++) = hexchar(*x & 15);
1019 void *unhexmem(const char *p, size_t l) {
1025 z = r = malloc((l + 1) / 2 + 1);
1029 for (x = p; x < p + l; x += 2) {
1032 a = unhexchar(x[0]);
1034 b = unhexchar(x[1]);
1038 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1045 char octchar(int x) {
1046 return '0' + (x & 7);
1049 int unoctchar(char c) {
1051 if (c >= '0' && c <= '7')
1057 char decchar(int x) {
1058 return '0' + (x % 10);
1061 int undecchar(char c) {
1063 if (c >= '0' && c <= '9')
1069 char *cescape(const char *s) {
1075 /* Does C style string escaping. */
1077 r = new(char, strlen(s)*4 + 1);
1081 for (f = s, t = r; *f; f++)
1127 /* For special chars we prefer octal over
1128 * hexadecimal encoding, simply because glib's
1129 * g_strescape() does the same */
1130 if ((*f < ' ') || (*f >= 127)) {
1132 *(t++) = octchar((unsigned char) *f >> 6);
1133 *(t++) = octchar((unsigned char) *f >> 3);
1134 *(t++) = octchar((unsigned char) *f);
1145 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1152 /* Undoes C style string escaping, and optionally prefixes it. */
1154 pl = prefix ? strlen(prefix) : 0;
1156 r = new(char, pl+length+1);
1161 memcpy(r, prefix, pl);
1163 for (f = s, t = r + pl; f < s + length; f++) {
1206 /* This is an extension of the XDG syntax files */
1211 /* hexadecimal encoding */
1214 a = unhexchar(f[1]);
1215 b = unhexchar(f[2]);
1217 if (a < 0 || b < 0) {
1218 /* Invalid escape code, let's take it literal then */
1222 *(t++) = (char) ((a << 4) | b);
1237 /* octal encoding */
1240 a = unoctchar(f[0]);
1241 b = unoctchar(f[1]);
1242 c = unoctchar(f[2]);
1244 if (a < 0 || b < 0 || c < 0) {
1245 /* Invalid escape code, let's take it literal then */
1249 *(t++) = (char) ((a << 6) | (b << 3) | c);
1257 /* premature end of string.*/
1262 /* Invalid escape code, let's take it literal then */
1274 char *cunescape_length(const char *s, size_t length) {
1275 return cunescape_length_with_prefix(s, length, NULL);
1278 char *cunescape(const char *s) {
1281 return cunescape_length(s, strlen(s));
1284 char *xescape(const char *s, const char *bad) {
1288 /* Escapes all chars in bad, in addition to \ and all special
1289 * chars, in \xFF style escaping. May be reversed with
1292 r = new(char, strlen(s) * 4 + 1);
1296 for (f = s, t = r; *f; f++) {
1298 if ((*f < ' ') || (*f >= 127) ||
1299 (*f == '\\') || strchr(bad, *f)) {
1302 *(t++) = hexchar(*f >> 4);
1303 *(t++) = hexchar(*f);
1313 char *ascii_strlower(char *t) {
1318 for (p = t; *p; p++)
1319 if (*p >= 'A' && *p <= 'Z')
1320 *p = *p - 'A' + 'a';
1325 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1329 filename[0] == '.' ||
1330 streq(filename, "lost+found") ||
1331 streq(filename, "aquota.user") ||
1332 streq(filename, "aquota.group") ||
1333 endswith(filename, ".rpmnew") ||
1334 endswith(filename, ".rpmsave") ||
1335 endswith(filename, ".rpmorig") ||
1336 endswith(filename, ".dpkg-old") ||
1337 endswith(filename, ".dpkg-new") ||
1338 endswith(filename, ".swp");
1341 bool ignore_file(const char *filename) {
1344 if (endswith(filename, "~"))
1347 return ignore_file_allow_backup(filename);
1350 int fd_nonblock(int fd, bool nonblock) {
1355 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1359 flags |= O_NONBLOCK;
1361 flags &= ~O_NONBLOCK;
1363 if (fcntl(fd, F_SETFL, flags) < 0)
1369 int fd_cloexec(int fd, bool cloexec) {
1374 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1378 flags |= FD_CLOEXEC;
1380 flags &= ~FD_CLOEXEC;
1382 if (fcntl(fd, F_SETFD, flags) < 0)
1388 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1391 assert(n_fdset == 0 || fdset);
1393 for (i = 0; i < n_fdset; i++)
1400 int close_all_fds(const int except[], unsigned n_except) {
1405 assert(n_except == 0 || except);
1407 d = opendir("/proc/self/fd");
1412 /* When /proc isn't available (for example in chroots)
1413 * the fallback is brute forcing through the fd
1416 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1417 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1419 if (fd_in_set(fd, except, n_except))
1422 if (close_nointr(fd) < 0)
1423 if (errno != EBADF && r == 0)
1430 while ((de = readdir(d))) {
1433 if (ignore_file(de->d_name))
1436 if (safe_atoi(de->d_name, &fd) < 0)
1437 /* Let's better ignore this, just in case */
1446 if (fd_in_set(fd, except, n_except))
1449 if (close_nointr(fd) < 0) {
1450 /* Valgrind has its own FD and doesn't want to have it closed */
1451 if (errno != EBADF && r == 0)
1460 bool chars_intersect(const char *a, const char *b) {
1463 /* Returns true if any of the chars in a are in b. */
1464 for (p = a; *p; p++)
1471 bool fstype_is_network(const char *fstype) {
1472 static const char table[] =
1482 return nulstr_contains(table, fstype);
1486 _cleanup_close_ int fd;
1488 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1494 TIOCL_GETKMSGREDIRECT,
1498 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1501 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1504 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1510 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1511 struct termios old_termios, new_termios;
1513 char line[LINE_MAX];
1518 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1519 new_termios = old_termios;
1521 new_termios.c_lflag &= ~ICANON;
1522 new_termios.c_cc[VMIN] = 1;
1523 new_termios.c_cc[VTIME] = 0;
1525 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1528 if (t != (usec_t) -1) {
1529 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1530 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1535 k = fread(&c, 1, 1, f);
1537 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1543 *need_nl = c != '\n';
1550 if (t != (usec_t) -1)
1551 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1554 if (!fgets(line, sizeof(line), f))
1559 if (strlen(line) != 1)
1569 int ask(char *ret, const char *replies, const char *text, ...) {
1579 bool need_nl = true;
1582 fputs(ANSI_HIGHLIGHT_ON, stdout);
1589 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1593 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1596 if (r == -EBADMSG) {
1597 puts("Bad input, please try again.");
1608 if (strchr(replies, c)) {
1613 puts("Read unexpected character, please try again.");
1617 int reset_terminal_fd(int fd, bool switch_to_text) {
1618 struct termios termios;
1621 /* Set terminal to some sane defaults */
1625 /* We leave locked terminal attributes untouched, so that
1626 * Plymouth may set whatever it wants to set, and we don't
1627 * interfere with that. */
1629 /* Disable exclusive mode, just in case */
1630 ioctl(fd, TIOCNXCL);
1632 /* Switch to text mode */
1634 ioctl(fd, KDSETMODE, KD_TEXT);
1636 /* Enable console unicode mode */
1637 ioctl(fd, KDSKBMODE, K_UNICODE);
1639 if (tcgetattr(fd, &termios) < 0) {
1644 /* We only reset the stuff that matters to the software. How
1645 * hardware is set up we don't touch assuming that somebody
1646 * else will do that for us */
1648 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1649 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1650 termios.c_oflag |= ONLCR;
1651 termios.c_cflag |= CREAD;
1652 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1654 termios.c_cc[VINTR] = 03; /* ^C */
1655 termios.c_cc[VQUIT] = 034; /* ^\ */
1656 termios.c_cc[VERASE] = 0177;
1657 termios.c_cc[VKILL] = 025; /* ^X */
1658 termios.c_cc[VEOF] = 04; /* ^D */
1659 termios.c_cc[VSTART] = 021; /* ^Q */
1660 termios.c_cc[VSTOP] = 023; /* ^S */
1661 termios.c_cc[VSUSP] = 032; /* ^Z */
1662 termios.c_cc[VLNEXT] = 026; /* ^V */
1663 termios.c_cc[VWERASE] = 027; /* ^W */
1664 termios.c_cc[VREPRINT] = 022; /* ^R */
1665 termios.c_cc[VEOL] = 0;
1666 termios.c_cc[VEOL2] = 0;
1668 termios.c_cc[VTIME] = 0;
1669 termios.c_cc[VMIN] = 1;
1671 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1675 /* Just in case, flush all crap out */
1676 tcflush(fd, TCIOFLUSH);
1681 int reset_terminal(const char *name) {
1684 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1688 r = reset_terminal_fd(fd, true);
1689 close_nointr_nofail(fd);
1694 int open_terminal(const char *name, int mode) {
1699 * If a TTY is in the process of being closed opening it might
1700 * cause EIO. This is horribly awful, but unlikely to be
1701 * changed in the kernel. Hence we work around this problem by
1702 * retrying a couple of times.
1704 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1707 assert(!(mode & O_CREAT));
1710 fd = open(name, mode, 0);
1717 /* Max 1s in total */
1721 usleep(50 * USEC_PER_MSEC);
1730 close_nointr_nofail(fd);
1735 close_nointr_nofail(fd);
1742 int flush_fd(int fd) {
1743 struct pollfd pollfd = {
1753 r = poll(&pollfd, 1, 0);
1763 l = read(fd, buf, sizeof(buf));
1769 if (errno == EAGAIN)
1778 int acquire_terminal(
1782 bool ignore_tiocstty_eperm,
1785 int fd = -1, notify = -1, r = 0, wd = -1;
1790 /* We use inotify to be notified when the tty is closed. We
1791 * create the watch before checking if we can actually acquire
1792 * it, so that we don't lose any event.
1794 * Note: strictly speaking this actually watches for the
1795 * device being closed, it does *not* really watch whether a
1796 * tty loses its controlling process. However, unless some
1797 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1798 * its tty otherwise this will not become a problem. As long
1799 * as the administrator makes sure not configure any service
1800 * on the same tty as an untrusted user this should not be a
1801 * problem. (Which he probably should not do anyway.) */
1803 if (timeout != (usec_t) -1)
1804 ts = now(CLOCK_MONOTONIC);
1806 if (!fail && !force) {
1807 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1813 wd = inotify_add_watch(notify, name, IN_CLOSE);
1821 struct sigaction sa_old, sa_new = {
1822 .sa_handler = SIG_IGN,
1823 .sa_flags = SA_RESTART,
1827 r = flush_fd(notify);
1832 /* We pass here O_NOCTTY only so that we can check the return
1833 * value TIOCSCTTY and have a reliable way to figure out if we
1834 * successfully became the controlling process of the tty */
1835 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1839 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1840 * if we already own the tty. */
1841 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1843 /* First, try to get the tty */
1844 if (ioctl(fd, TIOCSCTTY, force) < 0)
1847 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1849 /* Sometimes it makes sense to ignore TIOCSCTTY
1850 * returning EPERM, i.e. when very likely we already
1851 * are have this controlling terminal. */
1852 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1855 if (r < 0 && (force || fail || r != -EPERM)) {
1864 assert(notify >= 0);
1867 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1869 struct inotify_event *e;
1871 if (timeout != (usec_t) -1) {
1874 n = now(CLOCK_MONOTONIC);
1875 if (ts + timeout < n) {
1880 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1890 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1893 if (errno == EINTR || errno == EAGAIN)
1900 e = (struct inotify_event*) inotify_buffer;
1905 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1910 step = sizeof(struct inotify_event) + e->len;
1911 assert(step <= (size_t) l);
1913 e = (struct inotify_event*) ((uint8_t*) e + step);
1920 /* We close the tty fd here since if the old session
1921 * ended our handle will be dead. It's important that
1922 * we do this after sleeping, so that we don't enter
1923 * an endless loop. */
1924 close_nointr_nofail(fd);
1928 close_nointr_nofail(notify);
1930 r = reset_terminal_fd(fd, true);
1932 log_warning("Failed to reset terminal: %s", strerror(-r));
1938 close_nointr_nofail(fd);
1941 close_nointr_nofail(notify);
1946 int release_terminal(void) {
1948 struct sigaction sa_old, sa_new = {
1949 .sa_handler = SIG_IGN,
1950 .sa_flags = SA_RESTART,
1952 _cleanup_close_ int fd;
1954 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
1958 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1959 * by our own TIOCNOTTY */
1960 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1962 if (ioctl(fd, TIOCNOTTY) < 0)
1965 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1970 int sigaction_many(const struct sigaction *sa, ...) {
1975 while ((sig = va_arg(ap, int)) > 0)
1976 if (sigaction(sig, sa, NULL) < 0)
1983 int ignore_signals(int sig, ...) {
1984 struct sigaction sa = {
1985 .sa_handler = SIG_IGN,
1986 .sa_flags = SA_RESTART,
1992 if (sigaction(sig, &sa, NULL) < 0)
1996 while ((sig = va_arg(ap, int)) > 0)
1997 if (sigaction(sig, &sa, NULL) < 0)
2004 int default_signals(int sig, ...) {
2005 struct sigaction sa = {
2006 .sa_handler = SIG_DFL,
2007 .sa_flags = SA_RESTART,
2012 if (sigaction(sig, &sa, NULL) < 0)
2016 while ((sig = va_arg(ap, int)) > 0)
2017 if (sigaction(sig, &sa, NULL) < 0)
2024 int close_pipe(int p[]) {
2030 a = close_nointr(p[0]);
2035 b = close_nointr(p[1]);
2039 return a < 0 ? a : b;
2042 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2049 while (nbytes > 0) {
2052 k = read(fd, p, nbytes);
2053 if (k < 0 && errno == EINTR)
2056 if (k < 0 && errno == EAGAIN && do_poll) {
2058 /* We knowingly ignore any return value here,
2059 * and expect that any error/EOF is reported
2062 fd_wait_for_event(fd, POLLIN, (usec_t) -1);
2067 return n > 0 ? n : (k < 0 ? -errno : 0);
2077 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2078 const uint8_t *p = buf;
2084 while (nbytes > 0) {
2087 k = write(fd, p, nbytes);
2088 if (k < 0 && errno == EINTR)
2091 if (k < 0 && errno == EAGAIN && do_poll) {
2093 /* We knowingly ignore any return value here,
2094 * and expect that any error/EOF is reported
2097 fd_wait_for_event(fd, POLLOUT, (usec_t) -1);
2102 return n > 0 ? n : (k < 0 ? -errno : 0);
2112 int parse_bytes(const char *t, off_t *bytes) {
2113 static const struct {
2115 unsigned long long factor;
2119 { "M", 1024ULL*1024ULL },
2120 { "G", 1024ULL*1024ULL*1024ULL },
2121 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2122 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2123 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2128 unsigned long long r = 0;
2140 l = strtoll(p, &e, 10);
2151 e += strspn(e, WHITESPACE);
2153 for (i = 0; i < ELEMENTSOF(table); i++)
2154 if (startswith(e, table[i].suffix)) {
2155 unsigned long long tmp;
2156 if ((unsigned long long) l > ULLONG_MAX / table[i].factor)
2158 tmp = l * table[i].factor;
2159 if (tmp > ULLONG_MAX - r)
2163 if ((unsigned long long) (off_t) r != r)
2166 p = e + strlen(table[i].suffix);
2170 if (i >= ELEMENTSOF(table))
2180 int make_stdio(int fd) {
2185 r = dup3(fd, STDIN_FILENO, 0);
2186 s = dup3(fd, STDOUT_FILENO, 0);
2187 t = dup3(fd, STDERR_FILENO, 0);
2190 close_nointr_nofail(fd);
2192 if (r < 0 || s < 0 || t < 0)
2195 /* We rely here that the new fd has O_CLOEXEC not set */
2200 int make_null_stdio(void) {
2203 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2207 return make_stdio(null_fd);
2210 bool is_device_path(const char *path) {
2212 /* Returns true on paths that refer to a device, either in
2213 * sysfs or in /dev */
2216 path_startswith(path, "/dev/") ||
2217 path_startswith(path, "/sys/");
2220 int dir_is_empty(const char *path) {
2221 _cleanup_closedir_ DIR *d;
2232 if (!de && errno != 0)
2238 if (!ignore_file(de->d_name))
2243 char* dirname_malloc(const char *path) {
2244 char *d, *dir, *dir2;
2261 int dev_urandom(void *p, size_t n) {
2262 _cleanup_close_ int fd;
2265 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2267 return errno == ENOENT ? -ENOSYS : -errno;
2269 k = loop_read(fd, p, n, true);
2272 if ((size_t) k != n)
2278 void random_bytes(void *p, size_t n) {
2279 static bool srand_called = false;
2283 r = dev_urandom(p, n);
2287 /* If some idiot made /dev/urandom unavailable to us, he'll
2288 * get a PRNG instead. */
2290 if (!srand_called) {
2293 #ifdef HAVE_SYS_AUXV_H
2294 /* The kernel provides us with a bit of entropy in
2295 * auxv, so let's try to make use of that to seed the
2296 * pseudo-random generator. It's better than
2301 auxv = (void*) getauxval(AT_RANDOM);
2303 x ^= *(unsigned*) auxv;
2306 x ^= (unsigned) now(CLOCK_REALTIME);
2307 x ^= (unsigned) gettid();
2310 srand_called = true;
2313 for (q = p; q < (uint8_t*) p + n; q ++)
2317 void rename_process(const char name[8]) {
2320 /* This is a like a poor man's setproctitle(). It changes the
2321 * comm field, argv[0], and also the glibc's internally used
2322 * name of the process. For the first one a limit of 16 chars
2323 * applies, to the second one usually one of 10 (i.e. length
2324 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2325 * "systemd"). If you pass a longer string it will be
2328 prctl(PR_SET_NAME, name);
2330 if (program_invocation_name)
2331 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2333 if (saved_argc > 0) {
2337 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2339 for (i = 1; i < saved_argc; i++) {
2343 memzero(saved_argv[i], strlen(saved_argv[i]));
2348 void sigset_add_many(sigset_t *ss, ...) {
2355 while ((sig = va_arg(ap, int)) > 0)
2356 assert_se(sigaddset(ss, sig) == 0);
2360 char* gethostname_malloc(void) {
2363 assert_se(uname(&u) >= 0);
2365 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2366 return strdup(u.nodename);
2368 return strdup(u.sysname);
2371 bool hostname_is_set(void) {
2374 assert_se(uname(&u) >= 0);
2376 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2379 static char *lookup_uid(uid_t uid) {
2382 _cleanup_free_ char *buf = NULL;
2383 struct passwd pwbuf, *pw = NULL;
2385 /* Shortcut things to avoid NSS lookups */
2387 return strdup("root");
2389 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2393 buf = malloc(bufsize);
2397 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2398 return strdup(pw->pw_name);
2400 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2406 char* getlogname_malloc(void) {
2410 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2415 return lookup_uid(uid);
2418 char *getusername_malloc(void) {
2425 return lookup_uid(getuid());
2428 int getttyname_malloc(int fd, char **r) {
2429 char path[PATH_MAX], *c;
2434 k = ttyname_r(fd, path, sizeof(path));
2440 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2448 int getttyname_harder(int fd, char **r) {
2452 k = getttyname_malloc(fd, &s);
2456 if (streq(s, "tty")) {
2458 return get_ctty(0, NULL, r);
2465 int get_ctty_devnr(pid_t pid, dev_t *d) {
2467 _cleanup_free_ char *line = NULL;
2469 unsigned long ttynr;
2473 p = procfs_file_alloca(pid, "stat");
2474 r = read_one_line_file(p, &line);
2478 p = strrchr(line, ')');
2488 "%*d " /* session */
2493 if (major(ttynr) == 0 && minor(ttynr) == 0)
2502 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2504 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2509 k = get_ctty_devnr(pid, &devnr);
2513 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2515 k = readlink_malloc(fn, &s);
2521 /* This is an ugly hack */
2522 if (major(devnr) == 136) {
2523 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2533 /* Probably something like the ptys which have no
2534 * symlink in /dev/char. Let's return something
2535 * vaguely useful. */
2548 if (startswith(s, "/dev/"))
2550 else if (startswith(s, "../"))
2568 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2574 /* This returns the first error we run into, but nevertheless
2575 * tries to go on. This closes the passed fd. */
2579 close_nointr_nofail(fd);
2581 return errno == ENOENT ? 0 : -errno;
2586 bool is_dir, keep_around;
2592 if (!de && errno != 0) {
2601 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2604 if (de->d_type == DT_UNKNOWN ||
2606 (de->d_type == DT_DIR && root_dev)) {
2607 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2608 if (ret == 0 && errno != ENOENT)
2613 is_dir = S_ISDIR(st.st_mode);
2616 (st.st_uid == 0 || st.st_uid == getuid()) &&
2617 (st.st_mode & S_ISVTX);
2619 is_dir = de->d_type == DT_DIR;
2620 keep_around = false;
2626 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2627 if (root_dev && st.st_dev != root_dev->st_dev)
2630 subdir_fd = openat(fd, de->d_name,
2631 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2632 if (subdir_fd < 0) {
2633 if (ret == 0 && errno != ENOENT)
2638 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2639 if (r < 0 && ret == 0)
2643 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2644 if (ret == 0 && errno != ENOENT)
2648 } else if (!only_dirs && !keep_around) {
2650 if (unlinkat(fd, de->d_name, 0) < 0) {
2651 if (ret == 0 && errno != ENOENT)
2662 _pure_ static int is_temporary_fs(struct statfs *s) {
2665 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2666 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2669 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2674 if (fstatfs(fd, &s) < 0) {
2675 close_nointr_nofail(fd);
2679 /* We refuse to clean disk file systems with this call. This
2680 * is extra paranoia just to be sure we never ever remove
2682 if (!is_temporary_fs(&s)) {
2683 log_error("Attempted to remove disk file system, and we can't allow that.");
2684 close_nointr_nofail(fd);
2688 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2691 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2697 /* We refuse to clean the root file system with this
2698 * call. This is extra paranoia to never cause a really
2699 * seriously broken system. */
2700 if (path_equal(path, "/")) {
2701 log_error("Attempted to remove entire root file system, and we can't allow that.");
2705 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2708 if (errno != ENOTDIR)
2712 if (statfs(path, &s) < 0)
2715 if (!is_temporary_fs(&s)) {
2716 log_error("Attempted to remove disk file system, and we can't allow that.");
2721 if (delete_root && !only_dirs)
2722 if (unlink(path) < 0 && errno != ENOENT)
2729 if (fstatfs(fd, &s) < 0) {
2730 close_nointr_nofail(fd);
2734 if (!is_temporary_fs(&s)) {
2735 log_error("Attempted to remove disk file system, and we can't allow that.");
2736 close_nointr_nofail(fd);
2741 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2744 if (honour_sticky && file_is_priv_sticky(path) > 0)
2747 if (rmdir(path) < 0 && errno != ENOENT) {
2756 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2757 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2760 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2761 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2764 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2767 /* Under the assumption that we are running privileged we
2768 * first change the access mode and only then hand out
2769 * ownership to avoid a window where access is too open. */
2771 if (mode != (mode_t) -1)
2772 if (chmod(path, mode) < 0)
2775 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2776 if (chown(path, uid, gid) < 0)
2782 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2785 /* Under the assumption that we are running privileged we
2786 * first change the access mode and only then hand out
2787 * ownership to avoid a window where access is too open. */
2789 if (mode != (mode_t) -1)
2790 if (fchmod(fd, mode) < 0)
2793 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2794 if (fchown(fd, uid, gid) < 0)
2800 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2804 /* Allocates the cpuset in the right size */
2807 if (!(r = CPU_ALLOC(n)))
2810 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2811 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2821 if (errno != EINVAL)
2828 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2829 static const char status_indent[] = " "; /* "[" STATUS "] " */
2830 _cleanup_free_ char *s = NULL;
2831 _cleanup_close_ int fd = -1;
2832 struct iovec iovec[6] = {};
2834 static bool prev_ephemeral;
2838 /* This is independent of logging, as status messages are
2839 * optional and go exclusively to the console. */
2841 if (vasprintf(&s, format, ap) < 0)
2844 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2857 sl = status ? sizeof(status_indent)-1 : 0;
2863 e = ellipsize(s, emax, 75);
2871 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2872 prev_ephemeral = ephemeral;
2875 if (!isempty(status)) {
2876 IOVEC_SET_STRING(iovec[n++], "[");
2877 IOVEC_SET_STRING(iovec[n++], status);
2878 IOVEC_SET_STRING(iovec[n++], "] ");
2880 IOVEC_SET_STRING(iovec[n++], status_indent);
2883 IOVEC_SET_STRING(iovec[n++], s);
2885 IOVEC_SET_STRING(iovec[n++], "\n");
2887 if (writev(fd, iovec, n) < 0)
2893 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2899 va_start(ap, format);
2900 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2906 int status_welcome(void) {
2907 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2910 r = parse_env_file("/etc/os-release", NEWLINE,
2911 "PRETTY_NAME", &pretty_name,
2912 "ANSI_COLOR", &ansi_color,
2915 if (r < 0 && r != -ENOENT)
2916 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2918 return status_printf(NULL, false, false,
2919 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2920 isempty(ansi_color) ? "1" : ansi_color,
2921 isempty(pretty_name) ? "Linux" : pretty_name);
2924 char *replace_env(const char *format, char **env) {
2931 const char *e, *word = format;
2936 for (e = format; *e; e ++) {
2947 if (!(k = strnappend(r, word, e-word-1)))
2956 } else if (*e == '$') {
2957 if (!(k = strnappend(r, word, e-word)))
2973 t = strempty(strv_env_get_n(env, word+2, e-word-2));
2975 k = strappend(r, t);
2989 if (!(k = strnappend(r, word, e-word)))
3000 char **replace_env_argv(char **argv, char **env) {
3002 unsigned k = 0, l = 0;
3004 l = strv_length(argv);
3006 if (!(r = new(char*, l+1)))
3009 STRV_FOREACH(i, argv) {
3011 /* If $FOO appears as single word, replace it by the split up variable */
3012 if ((*i)[0] == '$' && (*i)[1] != '{') {
3017 e = strv_env_get(env, *i+1);
3020 if (!(m = strv_split_quoted(e))) {
3031 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3040 memcpy(r + k, m, q * sizeof(char*));
3048 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3049 if (!(r[k++] = replace_env(*i, env))) {
3059 int fd_columns(int fd) {
3060 struct winsize ws = {};
3062 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3071 unsigned columns(void) {
3075 if (_likely_(cached_columns > 0))
3076 return cached_columns;
3079 e = getenv("COLUMNS");
3084 c = fd_columns(STDOUT_FILENO);
3093 int fd_lines(int fd) {
3094 struct winsize ws = {};
3096 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3105 unsigned lines(void) {
3109 if (_likely_(cached_lines > 0))
3110 return cached_lines;
3113 e = getenv("LINES");
3118 l = fd_lines(STDOUT_FILENO);
3124 return cached_lines;
3127 /* intended to be used as a SIGWINCH sighandler */
3128 void columns_lines_cache_reset(int signum) {
3134 static int cached_on_tty = -1;
3136 if (_unlikely_(cached_on_tty < 0))
3137 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3139 return cached_on_tty;
3142 int running_in_chroot(void) {
3143 struct stat a = {}, b = {};
3145 /* Only works as root */
3146 if (stat("/proc/1/root", &a) < 0)
3149 if (stat("/", &b) < 0)
3153 a.st_dev != b.st_dev ||
3154 a.st_ino != b.st_ino;
3157 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3162 assert(percent <= 100);
3163 assert(new_length >= 3);
3165 if (old_length <= 3 || old_length <= new_length)
3166 return strndup(s, old_length);
3168 r = new0(char, new_length+1);
3172 x = (new_length * percent) / 100;
3174 if (x > new_length - 3)
3182 s + old_length - (new_length - x - 3),
3183 new_length - x - 3);
3188 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3192 unsigned k, len, len2;
3195 assert(percent <= 100);
3196 assert(new_length >= 3);
3198 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3199 if (ascii_is_valid(s))
3200 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3202 if (old_length <= 3 || old_length <= new_length)
3203 return strndup(s, old_length);
3205 x = (new_length * percent) / 100;
3207 if (x > new_length - 3)
3211 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3214 c = utf8_encoded_to_unichar(i);
3217 k += unichar_iswide(c) ? 2 : 1;
3220 if (k > x) /* last character was wide and went over quota */
3223 for (j = s + old_length; k < new_length && j > i; ) {
3226 j = utf8_prev_char(j);
3227 c = utf8_encoded_to_unichar(j);
3230 k += unichar_iswide(c) ? 2 : 1;
3234 /* we don't actually need to ellipsize */
3236 return memdup(s, old_length + 1);
3238 /* make space for ellipsis */
3239 j = utf8_next_char(j);
3242 len2 = s + old_length - j;
3243 e = new(char, len + 3 + len2 + 1);
3248 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3249 old_length, new_length, x, len, len2, k);
3253 e[len] = 0xe2; /* tri-dot ellipsis: … */
3257 memcpy(e + len + 3, j, len2 + 1);
3262 char *ellipsize(const char *s, size_t length, unsigned percent) {
3263 return ellipsize_mem(s, strlen(s), length, percent);
3266 int touch(const char *path) {
3271 /* This just opens the file for writing, ensuring it
3272 * exists. It doesn't call utimensat() the way /usr/bin/touch
3275 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3279 close_nointr_nofail(fd);
3283 char *unquote(const char *s, const char* quotes) {
3287 /* This is rather stupid, simply removes the heading and
3288 * trailing quotes if there is one. Doesn't care about
3289 * escaping or anything. We should make this smarter one
3296 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3297 return strndup(s+1, l-2);
3302 char *normalize_env_assignment(const char *s) {
3303 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3306 eq = strchr(s, '=');
3318 memmove(r, t, strlen(t) + 1);
3322 name = strndup(s, eq - s);
3330 value = unquote(strstrip(p), QUOTES);
3334 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3340 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3351 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3363 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3370 r = wait_for_terminate(pid, &status);
3372 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3376 if (status.si_code == CLD_EXITED) {
3377 if (status.si_status != 0) {
3378 log_warning("%s failed with error code %i.", name, status.si_status);
3379 return status.si_status;
3382 log_debug("%s succeeded.", name);
3385 } else if (status.si_code == CLD_KILLED ||
3386 status.si_code == CLD_DUMPED) {
3388 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3392 log_warning("%s failed due to unknown reason.", name);
3396 noreturn void freeze(void) {
3398 /* Make sure nobody waits for us on a socket anymore */
3399 close_all_fds(NULL, 0);
3407 bool null_or_empty(struct stat *st) {
3410 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3413 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3419 int null_or_empty_path(const char *fn) {
3424 if (stat(fn, &st) < 0)
3427 return null_or_empty(&st);
3430 DIR *xopendirat(int fd, const char *name, int flags) {
3434 assert(!(flags & O_CREAT));
3436 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3442 close_nointr_nofail(nfd);
3449 int signal_from_string_try_harder(const char *s) {
3453 signo = signal_from_string(s);
3455 if (startswith(s, "SIG"))
3456 return signal_from_string(s+3);
3461 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3462 _cleanup_free_ char *t = NULL, *u = NULL;
3466 u = unquote(tagvalue, "\"\'");
3470 enc_len = strlen(u) * 4 + 1;
3471 t = new(char, enc_len);
3475 if (encode_devnode_name(u, t, enc_len) < 0)
3478 if (asprintf(&dn, "/dev/disk/by-%s/%s", by, t) < 0)
3484 char *fstab_node_to_udev_node(const char *p) {
3487 if (startswith(p, "LABEL="))
3488 return tag_to_udev_node(p+6, "label");
3490 if (startswith(p, "UUID="))
3491 return tag_to_udev_node(p+5, "uuid");
3493 if (startswith(p, "PARTUUID="))
3494 return tag_to_udev_node(p+9, "partuuid");
3496 if (startswith(p, "PARTLABEL="))
3497 return tag_to_udev_node(p+10, "partlabel");
3502 bool tty_is_vc(const char *tty) {
3505 if (startswith(tty, "/dev/"))
3508 return vtnr_from_tty(tty) >= 0;
3511 bool tty_is_console(const char *tty) {
3514 if (startswith(tty, "/dev/"))
3517 return streq(tty, "console");
3520 int vtnr_from_tty(const char *tty) {
3525 if (startswith(tty, "/dev/"))
3528 if (!startswith(tty, "tty") )
3531 if (tty[3] < '0' || tty[3] > '9')
3534 r = safe_atoi(tty+3, &i);
3538 if (i < 0 || i > 63)
3544 char *resolve_dev_console(char **active) {
3547 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3548 * (i.e. not read-only-mounted which is a sign for container setups) */
3550 if (path_is_read_only_fs("/sys") > 0)
3553 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3556 /* If multiple log outputs are configured the last one is what
3557 * /dev/console points to */
3558 tty = strrchr(*active, ' ');
3564 if (streq(tty, "tty0")) {
3567 /* Get the active VC (e.g. tty1) */
3568 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3570 tty = *active = tmp;
3577 bool tty_is_vc_resolve(const char *tty) {
3578 _cleanup_free_ char *active = NULL;
3582 if (startswith(tty, "/dev/"))
3585 if (streq(tty, "console")) {
3586 tty = resolve_dev_console(&active);
3591 return tty_is_vc(tty);
3594 const char *default_term_for_tty(const char *tty) {
3597 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3600 bool dirent_is_file(const struct dirent *de) {
3603 if (ignore_file(de->d_name))
3606 if (de->d_type != DT_REG &&
3607 de->d_type != DT_LNK &&
3608 de->d_type != DT_UNKNOWN)
3614 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3617 if (de->d_type != DT_REG &&
3618 de->d_type != DT_LNK &&
3619 de->d_type != DT_UNKNOWN)
3622 if (ignore_file_allow_backup(de->d_name))
3625 return endswith(de->d_name, suffix);
3628 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3631 Hashmap *pids = NULL;
3635 /* Executes all binaries in a directory in parallel and
3636 * waits for them to finish. */
3639 if (!(_d = opendir(directory))) {
3641 if (errno == ENOENT)
3644 log_error("Failed to enumerate directory %s: %m", directory);
3651 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3652 log_error("Failed to allocate set.");
3656 while ((de = readdir(d))) {
3661 if (!dirent_is_file(de))
3664 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3669 if ((pid = fork()) < 0) {
3670 log_error("Failed to fork: %m");
3688 log_error("Failed to execute %s: %m", path);
3689 _exit(EXIT_FAILURE);
3692 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3694 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3695 log_error("Failed to add PID to set: %s", strerror(-k));
3700 while (!hashmap_isempty(pids)) {
3701 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3705 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3710 log_error("waitid() failed: %m");
3714 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3715 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3716 if (si.si_code == CLD_EXITED)
3717 log_error("%s exited with exit status %i.", path, si.si_status);
3719 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3721 log_debug("%s exited successfully.", path);
3732 hashmap_free_free(pids);
3735 int kill_and_sigcont(pid_t pid, int sig) {
3738 r = kill(pid, sig) < 0 ? -errno : 0;
3746 bool nulstr_contains(const char*nulstr, const char *needle) {
3752 NULSTR_FOREACH(i, nulstr)
3753 if (streq(i, needle))
3759 bool plymouth_running(void) {
3760 return access("/run/plymouth/pid", F_OK) >= 0;
3763 char* strshorten(char *s, size_t l) {
3772 static bool hostname_valid_char(char c) {
3774 (c >= 'a' && c <= 'z') ||
3775 (c >= 'A' && c <= 'Z') ||
3776 (c >= '0' && c <= '9') ||
3782 bool hostname_is_valid(const char *s) {
3789 for (p = s, dot = true; *p; p++) {
3796 if (!hostname_valid_char(*p))
3806 if (p-s > HOST_NAME_MAX)
3812 char* hostname_cleanup(char *s, bool lowercase) {
3816 for (p = s, d = s, dot = true; *p; p++) {
3823 } else if (hostname_valid_char(*p)) {
3824 *(d++) = lowercase ? tolower(*p) : *p;
3835 strshorten(s, HOST_NAME_MAX);
3840 int pipe_eof(int fd) {
3841 struct pollfd pollfd = {
3843 .events = POLLIN|POLLHUP,
3848 r = poll(&pollfd, 1, 0);
3855 return pollfd.revents & POLLHUP;
3858 int fd_wait_for_event(int fd, int event, usec_t t) {
3860 struct pollfd pollfd = {
3868 r = ppoll(&pollfd, 1, t == (usec_t) -1 ? NULL : timespec_store(&ts, t), NULL);
3875 return pollfd.revents;
3878 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3889 t = new(char, strlen(path) + 1 + 6 + 1);
3893 fn = basename(path);
3897 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3899 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
3905 f = fdopen(fd, "we");
3918 int terminal_vhangup_fd(int fd) {
3921 if (ioctl(fd, TIOCVHANGUP) < 0)
3927 int terminal_vhangup(const char *name) {
3930 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3934 r = terminal_vhangup_fd(fd);
3935 close_nointr_nofail(fd);
3940 int vt_disallocate(const char *name) {
3944 /* Deallocate the VT if possible. If not possible
3945 * (i.e. because it is the active one), at least clear it
3946 * entirely (including the scrollback buffer) */
3948 if (!startswith(name, "/dev/"))
3951 if (!tty_is_vc(name)) {
3952 /* So this is not a VT. I guess we cannot deallocate
3953 * it then. But let's at least clear the screen */
3955 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3960 "\033[r" /* clear scrolling region */
3961 "\033[H" /* move home */
3962 "\033[2J", /* clear screen */
3964 close_nointr_nofail(fd);
3969 if (!startswith(name, "/dev/tty"))
3972 r = safe_atou(name+8, &u);
3979 /* Try to deallocate */
3980 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3984 r = ioctl(fd, VT_DISALLOCATE, u);
3985 close_nointr_nofail(fd);
3993 /* Couldn't deallocate, so let's clear it fully with
3995 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4000 "\033[r" /* clear scrolling region */
4001 "\033[H" /* move home */
4002 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4004 close_nointr_nofail(fd);
4009 int copy_file(const char *from, const char *to, int flags) {
4010 _cleanup_close_ int fdf = -1;
4016 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4020 fdt = open(to, flags|O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
4028 n = read(fdf, buf, sizeof(buf));
4042 k = loop_write(fdt, buf, n, false);
4044 r = k < 0 ? k : (errno ? -errno : -EIO);
4053 r = close_nointr(fdt);
4063 int symlink_atomic(const char *from, const char *to) {
4065 _cleanup_free_ char *t;
4075 t = new(char, strlen(to) + 1 + 16 + 1);
4083 x = stpcpy(t+k+1, fn);
4086 for (i = 0; i < 16; i++) {
4087 *(x++) = hexchar(u & 0xF);
4093 if (symlink(from, t) < 0)
4096 if (rename(t, to) < 0) {
4105 bool display_is_local(const char *display) {
4109 display[0] == ':' &&
4110 display[1] >= '0' &&
4114 int socket_from_display(const char *display, char **path) {
4121 if (!display_is_local(display))
4124 k = strspn(display+1, "0123456789");
4126 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4130 c = stpcpy(f, "/tmp/.X11-unix/X");
4131 memcpy(c, display+1, k);
4140 const char **username,
4141 uid_t *uid, gid_t *gid,
4143 const char **shell) {
4151 /* We enforce some special rules for uid=0: in order to avoid
4152 * NSS lookups for root we hardcode its data. */
4154 if (streq(*username, "root") || streq(*username, "0")) {
4172 if (parse_uid(*username, &u) >= 0) {
4176 /* If there are multiple users with the same id, make
4177 * sure to leave $USER to the configured value instead
4178 * of the first occurrence in the database. However if
4179 * the uid was configured by a numeric uid, then let's
4180 * pick the real username from /etc/passwd. */
4182 *username = p->pw_name;
4185 p = getpwnam(*username);
4189 return errno > 0 ? -errno : -ESRCH;
4201 *shell = p->pw_shell;
4206 char* uid_to_name(uid_t uid) {
4211 return strdup("root");
4215 return strdup(p->pw_name);
4217 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4223 char* gid_to_name(gid_t gid) {
4228 return strdup("root");
4232 return strdup(p->gr_name);
4234 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4240 int get_group_creds(const char **groupname, gid_t *gid) {
4246 /* We enforce some special rules for gid=0: in order to avoid
4247 * NSS lookups for root we hardcode its data. */
4249 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4250 *groupname = "root";
4258 if (parse_gid(*groupname, &id) >= 0) {
4263 *groupname = g->gr_name;
4266 g = getgrnam(*groupname);
4270 return errno > 0 ? -errno : -ESRCH;
4278 int in_gid(gid_t gid) {
4280 int ngroups_max, r, i;
4282 if (getgid() == gid)
4285 if (getegid() == gid)
4288 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4289 assert(ngroups_max > 0);
4291 gids = alloca(sizeof(gid_t) * ngroups_max);
4293 r = getgroups(ngroups_max, gids);
4297 for (i = 0; i < r; i++)
4304 int in_group(const char *name) {
4308 r = get_group_creds(&name, &gid);
4315 int glob_exists(const char *path) {
4316 _cleanup_globfree_ glob_t g = {};
4322 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4324 if (k == GLOB_NOMATCH)
4326 else if (k == GLOB_NOSPACE)
4329 return !strv_isempty(g.gl_pathv);
4331 return errno ? -errno : -EIO;
4334 int glob_extend(char ***strv, const char *path) {
4335 _cleanup_globfree_ glob_t g = {};
4340 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4342 if (k == GLOB_NOMATCH)
4344 else if (k == GLOB_NOSPACE)
4346 else if (k != 0 || strv_isempty(g.gl_pathv))
4347 return errno ? -errno : -EIO;
4349 STRV_FOREACH(p, g.gl_pathv) {
4350 k = strv_extend(strv, *p);
4358 int dirent_ensure_type(DIR *d, struct dirent *de) {
4364 if (de->d_type != DT_UNKNOWN)
4367 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4371 S_ISREG(st.st_mode) ? DT_REG :
4372 S_ISDIR(st.st_mode) ? DT_DIR :
4373 S_ISLNK(st.st_mode) ? DT_LNK :
4374 S_ISFIFO(st.st_mode) ? DT_FIFO :
4375 S_ISSOCK(st.st_mode) ? DT_SOCK :
4376 S_ISCHR(st.st_mode) ? DT_CHR :
4377 S_ISBLK(st.st_mode) ? DT_BLK :
4383 int in_search_path(const char *path, char **search) {
4385 _cleanup_free_ char *parent = NULL;
4388 r = path_get_parent(path, &parent);
4392 STRV_FOREACH(i, search)
4393 if (path_equal(parent, *i))
4399 int get_files_in_directory(const char *path, char ***list) {
4400 _cleanup_closedir_ DIR *d = NULL;
4401 size_t bufsize = 0, n = 0;
4402 _cleanup_strv_free_ char **l = NULL;
4406 /* Returns all files in a directory in *list, and the number
4407 * of files as return value. If list is NULL returns only the
4419 if (!de && errno != 0)
4424 dirent_ensure_type(d, de);
4426 if (!dirent_is_file(de))
4430 /* one extra slot is needed for the terminating NULL */
4431 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4434 l[n] = strdup(de->d_name);
4445 l = NULL; /* avoid freeing */
4451 char *strjoin(const char *x, ...) {
4465 t = va_arg(ap, const char *);
4470 if (n > ((size_t) -1) - l) {
4494 t = va_arg(ap, const char *);
4508 bool is_main_thread(void) {
4509 static thread_local int cached = 0;
4511 if (_unlikely_(cached == 0))
4512 cached = getpid() == gettid() ? 1 : -1;
4517 int block_get_whole_disk(dev_t d, dev_t *ret) {
4524 /* If it has a queue this is good enough for us */
4525 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4528 r = access(p, F_OK);
4536 /* If it is a partition find the originating device */
4537 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4540 r = access(p, F_OK);
4546 /* Get parent dev_t */
4547 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4550 r = read_one_line_file(p, &s);
4556 r = sscanf(s, "%u:%u", &m, &n);
4562 /* Only return this if it is really good enough for us. */
4563 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4566 r = access(p, F_OK);
4570 *ret = makedev(m, n);
4577 int file_is_priv_sticky(const char *p) {
4582 if (lstat(p, &st) < 0)
4586 (st.st_uid == 0 || st.st_uid == getuid()) &&
4587 (st.st_mode & S_ISVTX);
4590 static const char *const ioprio_class_table[] = {
4591 [IOPRIO_CLASS_NONE] = "none",
4592 [IOPRIO_CLASS_RT] = "realtime",
4593 [IOPRIO_CLASS_BE] = "best-effort",
4594 [IOPRIO_CLASS_IDLE] = "idle"
4597 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4599 static const char *const sigchld_code_table[] = {
4600 [CLD_EXITED] = "exited",
4601 [CLD_KILLED] = "killed",
4602 [CLD_DUMPED] = "dumped",
4603 [CLD_TRAPPED] = "trapped",
4604 [CLD_STOPPED] = "stopped",
4605 [CLD_CONTINUED] = "continued",
4608 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4610 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4611 [LOG_FAC(LOG_KERN)] = "kern",
4612 [LOG_FAC(LOG_USER)] = "user",
4613 [LOG_FAC(LOG_MAIL)] = "mail",
4614 [LOG_FAC(LOG_DAEMON)] = "daemon",
4615 [LOG_FAC(LOG_AUTH)] = "auth",
4616 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4617 [LOG_FAC(LOG_LPR)] = "lpr",
4618 [LOG_FAC(LOG_NEWS)] = "news",
4619 [LOG_FAC(LOG_UUCP)] = "uucp",
4620 [LOG_FAC(LOG_CRON)] = "cron",
4621 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4622 [LOG_FAC(LOG_FTP)] = "ftp",
4623 [LOG_FAC(LOG_LOCAL0)] = "local0",
4624 [LOG_FAC(LOG_LOCAL1)] = "local1",
4625 [LOG_FAC(LOG_LOCAL2)] = "local2",
4626 [LOG_FAC(LOG_LOCAL3)] = "local3",
4627 [LOG_FAC(LOG_LOCAL4)] = "local4",
4628 [LOG_FAC(LOG_LOCAL5)] = "local5",
4629 [LOG_FAC(LOG_LOCAL6)] = "local6",
4630 [LOG_FAC(LOG_LOCAL7)] = "local7"
4633 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4635 static const char *const log_level_table[] = {
4636 [LOG_EMERG] = "emerg",
4637 [LOG_ALERT] = "alert",
4638 [LOG_CRIT] = "crit",
4640 [LOG_WARNING] = "warning",
4641 [LOG_NOTICE] = "notice",
4642 [LOG_INFO] = "info",
4643 [LOG_DEBUG] = "debug"
4646 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4648 static const char* const sched_policy_table[] = {
4649 [SCHED_OTHER] = "other",
4650 [SCHED_BATCH] = "batch",
4651 [SCHED_IDLE] = "idle",
4652 [SCHED_FIFO] = "fifo",
4656 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4658 static const char* const rlimit_table[] = {
4659 [RLIMIT_CPU] = "LimitCPU",
4660 [RLIMIT_FSIZE] = "LimitFSIZE",
4661 [RLIMIT_DATA] = "LimitDATA",
4662 [RLIMIT_STACK] = "LimitSTACK",
4663 [RLIMIT_CORE] = "LimitCORE",
4664 [RLIMIT_RSS] = "LimitRSS",
4665 [RLIMIT_NOFILE] = "LimitNOFILE",
4666 [RLIMIT_AS] = "LimitAS",
4667 [RLIMIT_NPROC] = "LimitNPROC",
4668 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4669 [RLIMIT_LOCKS] = "LimitLOCKS",
4670 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4671 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4672 [RLIMIT_NICE] = "LimitNICE",
4673 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4674 [RLIMIT_RTTIME] = "LimitRTTIME"
4677 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4679 static const char* const ip_tos_table[] = {
4680 [IPTOS_LOWDELAY] = "low-delay",
4681 [IPTOS_THROUGHPUT] = "throughput",
4682 [IPTOS_RELIABILITY] = "reliability",
4683 [IPTOS_LOWCOST] = "low-cost",
4686 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4688 static const char *const __signal_table[] = {
4705 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4716 [SIGVTALRM] = "VTALRM",
4718 [SIGWINCH] = "WINCH",
4724 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4726 const char *signal_to_string(int signo) {
4727 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4730 name = __signal_to_string(signo);
4734 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4735 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4737 snprintf(buf, sizeof(buf), "%d", signo);
4742 int signal_from_string(const char *s) {
4747 signo = __signal_from_string(s);
4751 if (startswith(s, "RTMIN+")) {
4755 if (safe_atou(s, &u) >= 0) {
4756 signo = (int) u + offset;
4757 if (signo > 0 && signo < _NSIG)
4763 bool kexec_loaded(void) {
4764 bool loaded = false;
4767 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4775 int strdup_or_null(const char *a, char **b) {
4793 int prot_from_flags(int flags) {
4795 switch (flags & O_ACCMODE) {
4804 return PROT_READ|PROT_WRITE;
4811 char *format_bytes(char *buf, size_t l, off_t t) {
4814 static const struct {
4818 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4819 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4820 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4821 { "G", 1024ULL*1024ULL*1024ULL },
4822 { "M", 1024ULL*1024ULL },
4826 for (i = 0; i < ELEMENTSOF(table); i++) {
4828 if (t >= table[i].factor) {
4831 (unsigned long long) (t / table[i].factor),
4832 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4839 snprintf(buf, l, "%lluB", (unsigned long long) t);
4847 void* memdup(const void *p, size_t l) {
4860 int fd_inc_sndbuf(int fd, size_t n) {
4862 socklen_t l = sizeof(value);
4864 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4865 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4868 /* If we have the privileges we will ignore the kernel limit. */
4871 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
4872 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
4878 int fd_inc_rcvbuf(int fd, size_t n) {
4880 socklen_t l = sizeof(value);
4882 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4883 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4886 /* If we have the privileges we will ignore the kernel limit. */
4889 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
4890 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
4895 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4896 pid_t parent_pid, agent_pid;
4898 bool stdout_is_tty, stderr_is_tty;
4906 parent_pid = getpid();
4908 /* Spawns a temporary TTY agent, making sure it goes away when
4915 if (agent_pid != 0) {
4922 * Make sure the agent goes away when the parent dies */
4923 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4924 _exit(EXIT_FAILURE);
4926 /* Check whether our parent died before we were able
4927 * to set the death signal */
4928 if (getppid() != parent_pid)
4929 _exit(EXIT_SUCCESS);
4931 /* Don't leak fds to the agent */
4932 close_all_fds(except, n_except);
4934 stdout_is_tty = isatty(STDOUT_FILENO);
4935 stderr_is_tty = isatty(STDERR_FILENO);
4937 if (!stdout_is_tty || !stderr_is_tty) {
4938 /* Detach from stdout/stderr. and reopen
4939 * /dev/tty for them. This is important to
4940 * ensure that when systemctl is started via
4941 * popen() or a similar call that expects to
4942 * read EOF we actually do generate EOF and
4943 * not delay this indefinitely by because we
4944 * keep an unused copy of stdin around. */
4945 fd = open("/dev/tty", O_WRONLY);
4947 log_error("Failed to open /dev/tty: %m");
4948 _exit(EXIT_FAILURE);
4952 dup2(fd, STDOUT_FILENO);
4955 dup2(fd, STDERR_FILENO);
4961 /* Count arguments */
4963 for (n = 0; va_arg(ap, char*); n++)
4968 l = alloca(sizeof(char *) * (n + 1));
4970 /* Fill in arguments */
4972 for (i = 0; i <= n; i++)
4973 l[i] = va_arg(ap, char*);
4977 _exit(EXIT_FAILURE);
4980 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4981 struct rlimit highest, fixed;
4985 if (setrlimit(resource, rlim) >= 0)
4991 /* So we failed to set the desired setrlimit, then let's try
4992 * to get as close as we can */
4993 assert_se(getrlimit(resource, &highest) == 0);
4995 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4996 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4998 if (setrlimit(resource, &fixed) < 0)
5004 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5005 _cleanup_fclose_ FILE *f = NULL;
5016 path = procfs_file_alloca(pid, "environ");
5018 f = fopen(path, "re");
5026 char line[LINE_MAX];
5029 for (i = 0; i < sizeof(line)-1; i++) {
5033 if (_unlikely_(c == EOF)) {
5043 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5044 value = strdup(line + l + 1);
5058 bool is_valid_documentation_url(const char *url) {
5061 if (startswith(url, "http://") && url[7])
5064 if (startswith(url, "https://") && url[8])
5067 if (startswith(url, "file:") && url[5])
5070 if (startswith(url, "info:") && url[5])
5073 if (startswith(url, "man:") && url[4])
5079 bool in_initrd(void) {
5080 static int saved = -1;
5086 /* We make two checks here:
5088 * 1. the flag file /etc/initrd-release must exist
5089 * 2. the root file system must be a memory file system
5091 * The second check is extra paranoia, since misdetecting an
5092 * initrd can have bad bad consequences due the initrd
5093 * emptying when transititioning to the main systemd.
5096 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5097 statfs("/", &s) >= 0 &&
5098 is_temporary_fs(&s);
5103 void warn_melody(void) {
5104 _cleanup_close_ int fd = -1;
5106 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5110 /* Yeah, this is synchronous. Kinda sucks. But well... */
5112 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5113 usleep(125*USEC_PER_MSEC);
5115 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5116 usleep(125*USEC_PER_MSEC);
5118 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5119 usleep(125*USEC_PER_MSEC);
5121 ioctl(fd, KIOCSOUND, 0);
5124 int make_console_stdio(void) {
5127 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5129 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5131 log_error("Failed to acquire terminal: %s", strerror(-fd));
5137 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5144 int get_home_dir(char **_h) {
5152 /* Take the user specified one */
5163 /* Hardcode home directory for root to avoid NSS */
5166 h = strdup("/root");
5174 /* Check the database... */
5178 return errno > 0 ? -errno : -ESRCH;
5180 if (!path_is_absolute(p->pw_dir))
5183 h = strdup(p->pw_dir);
5191 int get_shell(char **_s) {
5199 /* Take the user specified one */
5200 e = getenv("SHELL");
5210 /* Hardcode home directory for root to avoid NSS */
5213 s = strdup("/bin/sh");
5221 /* Check the database... */
5225 return errno > 0 ? -errno : -ESRCH;
5227 if (!path_is_absolute(p->pw_shell))
5230 s = strdup(p->pw_shell);
5238 bool filename_is_safe(const char *p) {
5252 if (strlen(p) > FILENAME_MAX)
5258 bool string_is_safe(const char *p) {
5263 for (t = p; *t; t++) {
5264 if (*t > 0 && *t < ' ')
5267 if (strchr("\\\"\'", *t))
5275 * Check if a string contains control characters.
5276 * Spaces and tabs are not considered control characters.
5278 bool string_has_cc(const char *p) {
5283 for (t = p; *t; t++)
5284 if (*t > 0 && *t < ' ' && *t != '\t')
5290 bool path_is_safe(const char *p) {
5295 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5298 if (strlen(p) > PATH_MAX)
5301 /* The following two checks are not really dangerous, but hey, they still are confusing */
5302 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5305 if (strstr(p, "//"))
5311 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5312 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5313 int (*compar) (const void *, const void *, void *), void *arg) {
5322 p = (void *)(((const char *) base) + (idx * size));
5323 comparison = compar(key, p, arg);
5326 else if (comparison > 0)
5334 bool is_locale_utf8(void) {
5336 static int cached_answer = -1;
5338 if (cached_answer >= 0)
5341 if (!setlocale(LC_ALL, "")) {
5342 cached_answer = true;
5346 set = nl_langinfo(CODESET);
5348 cached_answer = true;
5352 if (streq(set, "UTF-8")) {
5353 cached_answer = true;
5357 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5358 * unset and everything can do to UTF-8 nowadays. */
5359 set = setlocale(LC_CTYPE, NULL);
5361 cached_answer = true;
5365 /* Check result, but ignore the result if C was set
5369 !getenv("LC_ALL") &&
5370 !getenv("LC_CTYPE") &&
5374 return (bool) cached_answer;
5377 const char *draw_special_char(DrawSpecialChar ch) {
5378 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5380 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5381 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5382 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5383 [DRAW_TREE_SPACE] = " ", /* */
5384 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5385 [DRAW_BLACK_CIRCLE] = "\342\227\217 ", /* ● */
5387 /* ASCII fallback */ {
5388 [DRAW_TREE_VERT] = "| ",
5389 [DRAW_TREE_BRANCH] = "|-",
5390 [DRAW_TREE_RIGHT] = "`-",
5391 [DRAW_TREE_SPACE] = " ",
5392 [DRAW_TRIANGULAR_BULLET] = "> ",
5393 [DRAW_BLACK_CIRCLE] = "* ",
5397 return draw_table[!is_locale_utf8()][ch];
5400 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5403 size_t l, old_len, new_len;
5409 old_len = strlen(old_string);
5410 new_len = strlen(new_string);
5423 if (!startswith(f, old_string)) {
5429 nl = l - old_len + new_len;
5430 a = realloc(r, nl + 1);
5438 t = stpcpy(t, new_string);
5450 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5451 const char *i, *begin = NULL;
5456 } state = STATE_OTHER;
5458 size_t osz = 0, isz;
5464 /* Strips ANSI color and replaces TABs by 8 spaces */
5466 isz = _isz ? *_isz : strlen(*ibuf);
5468 f = open_memstream(&obuf, &osz);
5472 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5477 if (i >= *ibuf + isz) /* EOT */
5479 else if (*i == '\x1B')
5480 state = STATE_ESCAPE;
5481 else if (*i == '\t')
5488 if (i >= *ibuf + isz) { /* EOT */
5491 } else if (*i == '[') {
5492 state = STATE_BRACKET;
5497 state = STATE_OTHER;
5504 if (i >= *ibuf + isz || /* EOT */
5505 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5508 state = STATE_OTHER;
5510 } else if (*i == 'm')
5511 state = STATE_OTHER;
5533 int on_ac_power(void) {
5534 bool found_offline = false, found_online = false;
5535 _cleanup_closedir_ DIR *d = NULL;
5537 d = opendir("/sys/class/power_supply");
5543 _cleanup_close_ int fd = -1, device = -1;
5549 if (!de && errno != 0)
5555 if (ignore_file(de->d_name))
5558 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5560 if (errno == ENOENT || errno == ENOTDIR)
5566 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5568 if (errno == ENOENT)
5574 n = read(fd, contents, sizeof(contents));
5578 if (n != 6 || memcmp(contents, "Mains\n", 6))
5581 close_nointr_nofail(fd);
5582 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5584 if (errno == ENOENT)
5590 n = read(fd, contents, sizeof(contents));
5594 if (n != 2 || contents[1] != '\n')
5597 if (contents[0] == '1') {
5598 found_online = true;
5600 } else if (contents[0] == '0')
5601 found_offline = true;
5606 return found_online || !found_offline;
5609 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5616 if (!path_strv_canonicalize_uniq(search))
5619 STRV_FOREACH(i, search) {
5620 _cleanup_free_ char *p = NULL;
5623 p = strjoin(*i, "/", path, NULL);
5633 if (errno != ENOENT)
5640 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5641 _cleanup_strv_free_ char **copy = NULL;
5647 if (path_is_absolute(path)) {
5650 f = fopen(path, mode);
5659 copy = strv_copy((char**) search);
5663 return search_and_fopen_internal(path, mode, copy, _f);
5666 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5667 _cleanup_strv_free_ char **s = NULL;
5669 if (path_is_absolute(path)) {
5672 f = fopen(path, mode);
5681 s = strv_split_nulstr(search);
5685 return search_and_fopen_internal(path, mode, s, _f);
5688 char *strextend(char **x, ...) {
5695 l = f = *x ? strlen(*x) : 0;
5702 t = va_arg(ap, const char *);
5707 if (n > ((size_t) -1) - l) {
5716 r = realloc(*x, l+1);
5726 t = va_arg(ap, const char *);
5740 char *strrep(const char *s, unsigned n) {
5748 p = r = malloc(l * n + 1);
5752 for (i = 0; i < n; i++)
5759 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5766 if (*allocated >= need)
5769 a = MAX(64u, need * 2);
5771 /* check for overflows */
5784 void* greedy_realloc0(void **p, size_t *allocated, size_t need) {
5793 q = greedy_realloc(p, allocated, need);
5797 if (*allocated > prev)
5798 memzero(&q[prev], *allocated - prev);
5803 bool id128_is_valid(const char *s) {
5809 /* Simple formatted 128bit hex string */
5811 for (i = 0; i < l; i++) {
5814 if (!(c >= '0' && c <= '9') &&
5815 !(c >= 'a' && c <= 'z') &&
5816 !(c >= 'A' && c <= 'Z'))
5820 } else if (l == 36) {
5822 /* Formatted UUID */
5824 for (i = 0; i < l; i++) {
5827 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5831 if (!(c >= '0' && c <= '9') &&
5832 !(c >= 'a' && c <= 'z') &&
5833 !(c >= 'A' && c <= 'Z'))
5844 int split_pair(const char *s, const char *sep, char **l, char **r) {
5859 a = strndup(s, x - s);
5863 b = strdup(x + strlen(sep));
5875 int shall_restore_state(void) {
5876 _cleanup_free_ char *line;
5881 r = proc_cmdline(&line);
5884 if (r == 0) /* Container ... */
5887 FOREACH_WORD_QUOTED(w, l, line, state)
5888 if (l == 23 && strneq(w, "systemd.restore_state=0", 23))
5894 int proc_cmdline(char **ret) {
5897 if (detect_container(NULL) > 0) {
5901 r = read_full_file("/proc/1/cmdline", &buf, &sz);
5905 for (p = buf; p + 1 < buf + sz; p++)
5914 r = read_one_line_file("/proc/cmdline", ret);
5921 int container_get_leader(const char *machine, pid_t *pid) {
5922 _cleanup_free_ char *s = NULL, *class = NULL;
5930 p = strappenda("/run/systemd/machines/", machine);
5931 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
5939 if (!streq_ptr(class, "container"))
5942 r = parse_pid(s, &leader);
5952 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *root_fd) {
5953 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1;
5954 const char *pidns, *mntns, *root;
5962 mntns = procfs_file_alloca(pid, "ns/mnt");
5963 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5967 pidns = procfs_file_alloca(pid, "ns/pid");
5968 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5972 root = procfs_file_alloca(pid, "root");
5973 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
5977 *pidns_fd = pidnsfd;
5978 *mntns_fd = mntnsfd;
5986 int namespace_enter(int pidns_fd, int mntns_fd, int root_fd) {
5987 assert(pidns_fd >= 0);
5988 assert(mntns_fd >= 0);
5989 assert(root_fd >= 0);
5991 if (setns(pidns_fd, CLONE_NEWPID) < 0)
5994 if (setns(mntns_fd, CLONE_NEWNS) < 0)
5997 if (fchdir(root_fd) < 0)
6000 if (chroot(".") < 0)
6003 if (setresgid(0, 0, 0) < 0)
6006 if (setresuid(0, 0, 0) < 0)
6012 bool pid_valid(pid_t pid) {
6016 if (kill(pid, 0) >= 0)
6019 return errno != ESRCH;
6022 int getpeercred(int fd, struct ucred *ucred) {
6023 socklen_t n = sizeof(struct ucred);
6030 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6034 if (n != sizeof(struct ucred))
6037 /* Check if the data is actually useful and not suppressed due
6038 * to namespacing issues */
6046 int getpeersec(int fd, char **ret) {
6058 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6062 if (errno != ERANGE)
6069 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6085 /* This is much like like mkostemp() but is subject to umask(). */
6086 int mkostemp_safe(char *pattern, int flags) {
6087 _cleanup_umask_ mode_t u;
6094 fd = mkostemp(pattern, flags);
6101 int open_tmpfile(const char *path, int flags) {
6108 /* Try O_TMPFILE first, if it is supported */
6109 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6114 /* Fall back to unguessable name + unlinking */
6115 p = strappenda(path, "/systemd-tmp-XXXXXX");
6117 fd = mkostemp_safe(p, flags);
6125 int fd_warn_permissions(const char *path, int fd) {
6128 if (fstat(fd, &st) < 0)
6131 if (st.st_mode & 0111)
6132 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6134 if (st.st_mode & 0002)
6135 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6137 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6138 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);