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>
70 #include "path-util.h"
71 #include "exit-status.h"
75 #include "device-nodes.h"
82 char **saved_argv = NULL;
84 static volatile unsigned cached_columns = 0;
85 static volatile unsigned cached_lines = 0;
87 size_t page_size(void) {
88 static __thread size_t pgsz = 0;
91 if (_likely_(pgsz > 0))
94 r = sysconf(_SC_PAGESIZE);
101 bool streq_ptr(const char *a, const char *b) {
103 /* Like streq(), but tries to make sense of NULL pointers */
114 char* endswith(const char *s, const char *postfix) {
121 pl = strlen(postfix);
124 return (char*) s + sl;
129 if (memcmp(s + sl - pl, postfix, pl) != 0)
132 return (char*) s + sl - pl;
135 bool first_word(const char *s, const char *word) {
150 if (memcmp(s, word, wl) != 0)
154 strchr(WHITESPACE, s[wl]);
157 int close_nointr(int fd) {
163 /* Just ignore EINTR; a retry loop is the wrong
164 * thing to do on Linux.
166 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
167 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
168 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
169 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
171 if (_unlikely_(r < 0 && errno == EINTR))
179 void close_nointr_nofail(int fd) {
182 /* like close_nointr() but cannot fail, and guarantees errno
185 assert_se(close_nointr(fd) == 0);
188 void close_many(const int fds[], unsigned n_fd) {
191 assert(fds || n_fd <= 0);
193 for (i = 0; i < n_fd; i++)
194 close_nointr_nofail(fds[i]);
197 int unlink_noerrno(const char *path) {
208 int parse_boolean(const char *v) {
211 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
213 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
219 int parse_pid(const char *s, pid_t* ret_pid) {
220 unsigned long ul = 0;
227 r = safe_atolu(s, &ul);
233 if ((unsigned long) pid != ul)
243 int parse_uid(const char *s, uid_t* ret_uid) {
244 unsigned long ul = 0;
251 r = safe_atolu(s, &ul);
257 if ((unsigned long) uid != ul)
264 int safe_atou(const char *s, unsigned *ret_u) {
272 l = strtoul(s, &x, 0);
274 if (!x || x == s || *x || errno)
275 return errno > 0 ? -errno : -EINVAL;
277 if ((unsigned long) (unsigned) l != l)
280 *ret_u = (unsigned) l;
284 int safe_atoi(const char *s, int *ret_i) {
292 l = strtol(s, &x, 0);
294 if (!x || x == s || *x || errno)
295 return errno > 0 ? -errno : -EINVAL;
297 if ((long) (int) l != l)
304 int safe_atollu(const char *s, long long unsigned *ret_llu) {
306 unsigned long long l;
312 l = strtoull(s, &x, 0);
314 if (!x || x == s || *x || errno)
315 return errno ? -errno : -EINVAL;
321 int safe_atolli(const char *s, long long int *ret_lli) {
329 l = strtoll(s, &x, 0);
331 if (!x || x == s || *x || errno)
332 return errno ? -errno : -EINVAL;
338 int safe_atod(const char *s, double *ret_d) {
345 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
350 if (!x || x == s || *x || errno)
351 return errno ? -errno : -EINVAL;
357 /* Split a string into words. */
358 char *split(const char *c, size_t *l, const char *separator, char **state) {
361 current = *state ? *state : (char*) c;
363 if (!*current || *c == 0)
366 current += strspn(current, separator);
367 *l = strcspn(current, separator);
370 return (char*) current;
373 /* Split a string into words, but consider strings enclosed in '' and
374 * "" as words even if they include spaces. */
375 char *split_quoted(const char *c, size_t *l, char **state) {
376 const char *current, *e;
377 bool escaped = false;
383 current = *state ? *state : c;
385 current += strspn(current, WHITESPACE);
390 else if (*current == '\'') {
393 for (e = current; *e; e++) {
403 *state = (char*) (*e == 0 ? e : e+1);
405 } else if (*current == '\"') {
408 for (e = current; *e; e++) {
418 *state = (char*) (*e == 0 ? e : e+1);
421 for (e = current; *e; e++) {
426 else if (strchr(WHITESPACE, *e))
433 return (char*) current;
436 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
438 _cleanup_fclose_ FILE *f = NULL;
451 p = procfs_file_alloca(pid, "stat");
456 if (!fgets(line, sizeof(line), f)) {
457 r = feof(f) ? -EIO : -errno;
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, ')');
477 if ((long unsigned) (pid_t) ppid != ppid)
480 *_ppid = (pid_t) ppid;
485 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
486 _cleanup_fclose_ FILE *f = NULL;
494 p = "/proc/self/stat";
496 p = procfs_file_alloca(pid, "stat");
500 return errno == ENOENT ? -ESRCH : -errno;
502 if (!fgets(line, sizeof(line), f)) {
509 /* Let's skip the pid and comm fields. The latter is enclosed
510 * in () but does not escape any () in its value, so let's
511 * skip over it manually */
513 p = strrchr(line, ')');
535 "%*d " /* priority */
537 "%*d " /* num_threads */
538 "%*d " /* itrealvalue */
539 "%llu " /* starttime */,
546 int fchmod_umask(int fd, mode_t m) {
551 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
557 char *truncate_nl(char *s) {
560 s[strcspn(s, NEWLINE)] = 0;
564 int get_process_comm(pid_t pid, char **name) {
572 p = "/proc/self/comm";
574 p = procfs_file_alloca(pid, "comm");
576 r = read_one_line_file(p, name);
583 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
584 _cleanup_fclose_ FILE *f = NULL;
593 p = "/proc/self/cmdline";
595 p = procfs_file_alloca(pid, "cmdline");
601 if (max_length == 0) {
602 size_t len = 0, allocated = 0;
604 while ((c = getc(f)) != EOF) {
606 if (!GREEDY_REALLOC(r, allocated, len+2)) {
611 r[len++] = isprint(c) ? c : ' ';
621 r = new(char, max_length);
627 while ((c = getc(f)) != EOF) {
649 size_t n = MIN(left-1, 3U);
656 /* Kernel threads have no argv[] */
657 if (r == NULL || r[0] == 0) {
658 _cleanup_free_ char *t = NULL;
666 h = get_process_comm(pid, &t);
670 r = strjoin("[", t, "]", NULL);
679 int is_kernel_thread(pid_t pid) {
691 p = procfs_file_alloca(pid, "cmdline");
696 count = fread(&c, 1, 1, f);
700 /* Kernel threads have an empty cmdline */
703 return eof ? 1 : -errno;
708 int get_process_capeff(pid_t pid, char **capeff) {
715 p = "/proc/self/status";
717 p = procfs_file_alloca(pid, "status");
719 return get_status_field(p, "\nCapEff:", capeff);
722 int get_process_exe(pid_t pid, char **name) {
731 p = "/proc/self/exe";
733 p = procfs_file_alloca(pid, "exe");
735 r = readlink_malloc(p, name);
737 return r == -ENOENT ? -ESRCH : r;
739 d = endswith(*name, " (deleted)");
746 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
747 _cleanup_fclose_ FILE *f = NULL;
757 p = procfs_file_alloca(pid, "status");
762 FOREACH_LINE(line, f, return -errno) {
767 if (startswith(l, field)) {
769 l += strspn(l, WHITESPACE);
771 l[strcspn(l, WHITESPACE)] = 0;
773 return parse_uid(l, uid);
780 int get_process_uid(pid_t pid, uid_t *uid) {
781 return get_process_id(pid, "Uid:", uid);
784 int get_process_gid(pid_t pid, gid_t *gid) {
785 assert_cc(sizeof(uid_t) == sizeof(gid_t));
786 return get_process_id(pid, "Gid:", gid);
789 char *strnappend(const char *s, const char *suffix, size_t b) {
797 return strndup(suffix, b);
806 if (b > ((size_t) -1) - a)
809 r = new(char, a+b+1);
814 memcpy(r+a, suffix, b);
820 char *strappend(const char *s, const char *suffix) {
821 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
824 int readlink_malloc(const char *p, char **r) {
834 if (!(c = new(char, l)))
837 if ((n = readlink(p, c, l-1)) < 0) {
843 if ((size_t) n < l-1) {
854 int readlink_and_make_absolute(const char *p, char **r) {
855 _cleanup_free_ char *target = NULL;
862 j = readlink_malloc(p, &target);
866 k = file_in_same_dir(p, target);
874 int readlink_and_canonicalize(const char *p, char **r) {
881 j = readlink_and_make_absolute(p, &t);
885 s = canonicalize_file_name(t);
892 path_kill_slashes(*r);
897 int reset_all_signal_handlers(void) {
900 for (sig = 1; sig < _NSIG; sig++) {
901 struct sigaction sa = {
902 .sa_handler = SIG_DFL,
903 .sa_flags = SA_RESTART,
906 if (sig == SIGKILL || sig == SIGSTOP)
909 /* On Linux the first two RT signals are reserved by
910 * glibc, and sigaction() will return EINVAL for them. */
911 if ((sigaction(sig, &sa, NULL) < 0))
919 char *strstrip(char *s) {
922 /* Drops trailing whitespace. Modifies the string in
923 * place. Returns pointer to first non-space character */
925 s += strspn(s, WHITESPACE);
927 for (e = strchr(s, 0); e > s; e --)
928 if (!strchr(WHITESPACE, e[-1]))
936 char *delete_chars(char *s, const char *bad) {
939 /* Drops all whitespace, regardless where in the string */
941 for (f = s, t = s; *f; f++) {
953 bool in_charset(const char *s, const char* charset) {
960 if (!strchr(charset, *i))
966 char *file_in_same_dir(const char *path, const char *filename) {
973 /* This removes the last component of path and appends
974 * filename, unless the latter is absolute anyway or the
977 if (path_is_absolute(filename))
978 return strdup(filename);
980 if (!(e = strrchr(path, '/')))
981 return strdup(filename);
983 k = strlen(filename);
984 if (!(r = new(char, e-path+1+k+1)))
987 memcpy(r, path, e-path+1);
988 memcpy(r+(e-path)+1, filename, k+1);
993 int rmdir_parents(const char *path, const char *stop) {
1002 /* Skip trailing slashes */
1003 while (l > 0 && path[l-1] == '/')
1009 /* Skip last component */
1010 while (l > 0 && path[l-1] != '/')
1013 /* Skip trailing slashes */
1014 while (l > 0 && path[l-1] == '/')
1020 if (!(t = strndup(path, l)))
1023 if (path_startswith(stop, t)) {
1032 if (errno != ENOENT)
1039 char hexchar(int x) {
1040 static const char table[16] = "0123456789abcdef";
1042 return table[x & 15];
1045 int unhexchar(char c) {
1047 if (c >= '0' && c <= '9')
1050 if (c >= 'a' && c <= 'f')
1051 return c - 'a' + 10;
1053 if (c >= 'A' && c <= 'F')
1054 return c - 'A' + 10;
1059 char *hexmem(const void *p, size_t l) {
1063 z = r = malloc(l * 2 + 1);
1067 for (x = p; x < (const uint8_t*) p + l; x++) {
1068 *(z++) = hexchar(*x >> 4);
1069 *(z++) = hexchar(*x & 15);
1076 void *unhexmem(const char *p, size_t l) {
1082 z = r = malloc((l + 1) / 2 + 1);
1086 for (x = p; x < p + l; x += 2) {
1089 a = unhexchar(x[0]);
1091 b = unhexchar(x[1]);
1095 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1102 char octchar(int x) {
1103 return '0' + (x & 7);
1106 int unoctchar(char c) {
1108 if (c >= '0' && c <= '7')
1114 char decchar(int x) {
1115 return '0' + (x % 10);
1118 int undecchar(char c) {
1120 if (c >= '0' && c <= '9')
1126 char *cescape(const char *s) {
1132 /* Does C style string escaping. */
1134 r = new(char, strlen(s)*4 + 1);
1138 for (f = s, t = r; *f; f++)
1184 /* For special chars we prefer octal over
1185 * hexadecimal encoding, simply because glib's
1186 * g_strescape() does the same */
1187 if ((*f < ' ') || (*f >= 127)) {
1189 *(t++) = octchar((unsigned char) *f >> 6);
1190 *(t++) = octchar((unsigned char) *f >> 3);
1191 *(t++) = octchar((unsigned char) *f);
1202 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1209 /* Undoes C style string escaping, and optionally prefixes it. */
1211 pl = prefix ? strlen(prefix) : 0;
1213 r = new(char, pl+length+1);
1218 memcpy(r, prefix, pl);
1220 for (f = s, t = r + pl; f < s + length; f++) {
1263 /* This is an extension of the XDG syntax files */
1268 /* hexadecimal encoding */
1271 a = unhexchar(f[1]);
1272 b = unhexchar(f[2]);
1274 if (a < 0 || b < 0) {
1275 /* Invalid escape code, let's take it literal then */
1279 *(t++) = (char) ((a << 4) | b);
1294 /* octal encoding */
1297 a = unoctchar(f[0]);
1298 b = unoctchar(f[1]);
1299 c = unoctchar(f[2]);
1301 if (a < 0 || b < 0 || c < 0) {
1302 /* Invalid escape code, let's take it literal then */
1306 *(t++) = (char) ((a << 6) | (b << 3) | c);
1314 /* premature end of string.*/
1319 /* Invalid escape code, let's take it literal then */
1331 char *cunescape_length(const char *s, size_t length) {
1332 return cunescape_length_with_prefix(s, length, NULL);
1335 char *cunescape(const char *s) {
1338 return cunescape_length(s, strlen(s));
1341 char *xescape(const char *s, const char *bad) {
1345 /* Escapes all chars in bad, in addition to \ and all special
1346 * chars, in \xFF style escaping. May be reversed with
1349 r = new(char, strlen(s) * 4 + 1);
1353 for (f = s, t = r; *f; f++) {
1355 if ((*f < ' ') || (*f >= 127) ||
1356 (*f == '\\') || strchr(bad, *f)) {
1359 *(t++) = hexchar(*f >> 4);
1360 *(t++) = hexchar(*f);
1370 char *ascii_strlower(char *t) {
1375 for (p = t; *p; p++)
1376 if (*p >= 'A' && *p <= 'Z')
1377 *p = *p - 'A' + 'a';
1382 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1386 filename[0] == '.' ||
1387 streq(filename, "lost+found") ||
1388 streq(filename, "aquota.user") ||
1389 streq(filename, "aquota.group") ||
1390 endswith(filename, ".rpmnew") ||
1391 endswith(filename, ".rpmsave") ||
1392 endswith(filename, ".rpmorig") ||
1393 endswith(filename, ".dpkg-old") ||
1394 endswith(filename, ".dpkg-new") ||
1395 endswith(filename, ".swp");
1398 bool ignore_file(const char *filename) {
1401 if (endswith(filename, "~"))
1404 return ignore_file_allow_backup(filename);
1407 int fd_nonblock(int fd, bool nonblock) {
1412 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1416 flags |= O_NONBLOCK;
1418 flags &= ~O_NONBLOCK;
1420 if (fcntl(fd, F_SETFL, flags) < 0)
1426 int fd_cloexec(int fd, bool cloexec) {
1431 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1435 flags |= FD_CLOEXEC;
1437 flags &= ~FD_CLOEXEC;
1439 if (fcntl(fd, F_SETFD, flags) < 0)
1445 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1448 assert(n_fdset == 0 || fdset);
1450 for (i = 0; i < n_fdset; i++)
1457 int close_all_fds(const int except[], unsigned n_except) {
1462 assert(n_except == 0 || except);
1464 d = opendir("/proc/self/fd");
1469 /* When /proc isn't available (for example in chroots)
1470 * the fallback is brute forcing through the fd
1473 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1474 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1476 if (fd_in_set(fd, except, n_except))
1479 if (close_nointr(fd) < 0)
1480 if (errno != EBADF && r == 0)
1487 while ((de = readdir(d))) {
1490 if (ignore_file(de->d_name))
1493 if (safe_atoi(de->d_name, &fd) < 0)
1494 /* Let's better ignore this, just in case */
1503 if (fd_in_set(fd, except, n_except))
1506 if (close_nointr(fd) < 0) {
1507 /* Valgrind has its own FD and doesn't want to have it closed */
1508 if (errno != EBADF && r == 0)
1517 bool chars_intersect(const char *a, const char *b) {
1520 /* Returns true if any of the chars in a are in b. */
1521 for (p = a; *p; p++)
1528 bool fstype_is_network(const char *fstype) {
1529 static const char table[] =
1539 return nulstr_contains(table, fstype);
1543 _cleanup_close_ int fd;
1545 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1551 TIOCL_GETKMSGREDIRECT,
1555 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1558 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1561 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1567 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1568 struct termios old_termios, new_termios;
1570 char line[LINE_MAX];
1575 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1576 new_termios = old_termios;
1578 new_termios.c_lflag &= ~ICANON;
1579 new_termios.c_cc[VMIN] = 1;
1580 new_termios.c_cc[VTIME] = 0;
1582 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1585 if (t != (usec_t) -1) {
1586 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1587 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1592 k = fread(&c, 1, 1, f);
1594 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1600 *need_nl = c != '\n';
1607 if (t != (usec_t) -1)
1608 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1611 if (!fgets(line, sizeof(line), f))
1616 if (strlen(line) != 1)
1626 int ask(char *ret, const char *replies, const char *text, ...) {
1636 bool need_nl = true;
1639 fputs(ANSI_HIGHLIGHT_ON, stdout);
1646 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1650 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1653 if (r == -EBADMSG) {
1654 puts("Bad input, please try again.");
1665 if (strchr(replies, c)) {
1670 puts("Read unexpected character, please try again.");
1674 int reset_terminal_fd(int fd, bool switch_to_text) {
1675 struct termios termios;
1678 /* Set terminal to some sane defaults */
1682 /* We leave locked terminal attributes untouched, so that
1683 * Plymouth may set whatever it wants to set, and we don't
1684 * interfere with that. */
1686 /* Disable exclusive mode, just in case */
1687 ioctl(fd, TIOCNXCL);
1689 /* Switch to text mode */
1691 ioctl(fd, KDSETMODE, KD_TEXT);
1693 /* Enable console unicode mode */
1694 ioctl(fd, KDSKBMODE, K_UNICODE);
1696 if (tcgetattr(fd, &termios) < 0) {
1701 /* We only reset the stuff that matters to the software. How
1702 * hardware is set up we don't touch assuming that somebody
1703 * else will do that for us */
1705 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1706 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1707 termios.c_oflag |= ONLCR;
1708 termios.c_cflag |= CREAD;
1709 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1711 termios.c_cc[VINTR] = 03; /* ^C */
1712 termios.c_cc[VQUIT] = 034; /* ^\ */
1713 termios.c_cc[VERASE] = 0177;
1714 termios.c_cc[VKILL] = 025; /* ^X */
1715 termios.c_cc[VEOF] = 04; /* ^D */
1716 termios.c_cc[VSTART] = 021; /* ^Q */
1717 termios.c_cc[VSTOP] = 023; /* ^S */
1718 termios.c_cc[VSUSP] = 032; /* ^Z */
1719 termios.c_cc[VLNEXT] = 026; /* ^V */
1720 termios.c_cc[VWERASE] = 027; /* ^W */
1721 termios.c_cc[VREPRINT] = 022; /* ^R */
1722 termios.c_cc[VEOL] = 0;
1723 termios.c_cc[VEOL2] = 0;
1725 termios.c_cc[VTIME] = 0;
1726 termios.c_cc[VMIN] = 1;
1728 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1732 /* Just in case, flush all crap out */
1733 tcflush(fd, TCIOFLUSH);
1738 int reset_terminal(const char *name) {
1741 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1745 r = reset_terminal_fd(fd, true);
1746 close_nointr_nofail(fd);
1751 int open_terminal(const char *name, int mode) {
1756 * If a TTY is in the process of being closed opening it might
1757 * cause EIO. This is horribly awful, but unlikely to be
1758 * changed in the kernel. Hence we work around this problem by
1759 * retrying a couple of times.
1761 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1764 assert(!(mode & O_CREAT));
1767 fd = open(name, mode, 0);
1774 /* Max 1s in total */
1778 usleep(50 * USEC_PER_MSEC);
1787 close_nointr_nofail(fd);
1792 close_nointr_nofail(fd);
1799 int flush_fd(int fd) {
1800 struct pollfd pollfd = {
1810 r = poll(&pollfd, 1, 0);
1820 l = read(fd, buf, sizeof(buf));
1826 if (errno == EAGAIN)
1835 int acquire_terminal(
1839 bool ignore_tiocstty_eperm,
1842 int fd = -1, notify = -1, r = 0, wd = -1;
1847 /* We use inotify to be notified when the tty is closed. We
1848 * create the watch before checking if we can actually acquire
1849 * it, so that we don't lose any event.
1851 * Note: strictly speaking this actually watches for the
1852 * device being closed, it does *not* really watch whether a
1853 * tty loses its controlling process. However, unless some
1854 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1855 * its tty otherwise this will not become a problem. As long
1856 * as the administrator makes sure not configure any service
1857 * on the same tty as an untrusted user this should not be a
1858 * problem. (Which he probably should not do anyway.) */
1860 if (timeout != (usec_t) -1)
1861 ts = now(CLOCK_MONOTONIC);
1863 if (!fail && !force) {
1864 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1870 wd = inotify_add_watch(notify, name, IN_CLOSE);
1878 struct sigaction sa_old, sa_new = {
1879 .sa_handler = SIG_IGN,
1880 .sa_flags = SA_RESTART,
1884 r = flush_fd(notify);
1889 /* We pass here O_NOCTTY only so that we can check the return
1890 * value TIOCSCTTY and have a reliable way to figure out if we
1891 * successfully became the controlling process of the tty */
1892 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1896 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1897 * if we already own the tty. */
1898 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1900 /* First, try to get the tty */
1901 if (ioctl(fd, TIOCSCTTY, force) < 0)
1904 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1906 /* Sometimes it makes sense to ignore TIOCSCTTY
1907 * returning EPERM, i.e. when very likely we already
1908 * are have this controlling terminal. */
1909 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1912 if (r < 0 && (force || fail || r != -EPERM)) {
1921 assert(notify >= 0);
1924 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1926 struct inotify_event *e;
1928 if (timeout != (usec_t) -1) {
1931 n = now(CLOCK_MONOTONIC);
1932 if (ts + timeout < n) {
1937 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1947 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1950 if (errno == EINTR || errno == EAGAIN)
1957 e = (struct inotify_event*) inotify_buffer;
1962 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1967 step = sizeof(struct inotify_event) + e->len;
1968 assert(step <= (size_t) l);
1970 e = (struct inotify_event*) ((uint8_t*) e + step);
1977 /* We close the tty fd here since if the old session
1978 * ended our handle will be dead. It's important that
1979 * we do this after sleeping, so that we don't enter
1980 * an endless loop. */
1981 close_nointr_nofail(fd);
1985 close_nointr_nofail(notify);
1987 r = reset_terminal_fd(fd, true);
1989 log_warning("Failed to reset terminal: %s", strerror(-r));
1995 close_nointr_nofail(fd);
1998 close_nointr_nofail(notify);
2003 int release_terminal(void) {
2005 struct sigaction sa_old, sa_new = {
2006 .sa_handler = SIG_IGN,
2007 .sa_flags = SA_RESTART,
2009 _cleanup_close_ int fd;
2011 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2015 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2016 * by our own TIOCNOTTY */
2017 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2019 if (ioctl(fd, TIOCNOTTY) < 0)
2022 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2027 int sigaction_many(const struct sigaction *sa, ...) {
2032 while ((sig = va_arg(ap, int)) > 0)
2033 if (sigaction(sig, sa, NULL) < 0)
2040 int ignore_signals(int sig, ...) {
2041 struct sigaction sa = {
2042 .sa_handler = SIG_IGN,
2043 .sa_flags = SA_RESTART,
2049 if (sigaction(sig, &sa, NULL) < 0)
2053 while ((sig = va_arg(ap, int)) > 0)
2054 if (sigaction(sig, &sa, NULL) < 0)
2061 int default_signals(int sig, ...) {
2062 struct sigaction sa = {
2063 .sa_handler = SIG_DFL,
2064 .sa_flags = SA_RESTART,
2069 if (sigaction(sig, &sa, NULL) < 0)
2073 while ((sig = va_arg(ap, int)) > 0)
2074 if (sigaction(sig, &sa, NULL) < 0)
2081 int close_pipe(int p[]) {
2087 a = close_nointr(p[0]);
2092 b = close_nointr(p[1]);
2096 return a < 0 ? a : b;
2099 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2108 while (nbytes > 0) {
2111 if ((k = read(fd, p, nbytes)) <= 0) {
2113 if (k < 0 && errno == EINTR)
2116 if (k < 0 && errno == EAGAIN && do_poll) {
2117 struct pollfd pollfd = {
2122 if (poll(&pollfd, 1, -1) < 0) {
2126 return n > 0 ? n : -errno;
2129 /* We knowingly ignore the revents value here,
2130 * and expect that any error/EOF is reported
2131 * via read()/write()
2137 return n > 0 ? n : (k < 0 ? -errno : 0);
2148 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2157 while (nbytes > 0) {
2160 k = write(fd, p, nbytes);
2163 if (k < 0 && errno == EINTR)
2166 if (k < 0 && errno == EAGAIN && do_poll) {
2167 struct pollfd pollfd = {
2172 if (poll(&pollfd, 1, -1) < 0) {
2176 return n > 0 ? n : -errno;
2179 /* We knowingly ignore the revents value here,
2180 * and expect that any error/EOF is reported
2181 * via read()/write()
2187 return n > 0 ? n : (k < 0 ? -errno : 0);
2198 int parse_bytes(const char *t, off_t *bytes) {
2199 static const struct {
2201 unsigned long long factor;
2205 { "M", 1024ULL*1024ULL },
2206 { "G", 1024ULL*1024ULL*1024ULL },
2207 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2208 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2209 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2214 unsigned long long r = 0;
2226 l = strtoll(p, &e, 10);
2237 e += strspn(e, WHITESPACE);
2239 for (i = 0; i < ELEMENTSOF(table); i++)
2240 if (startswith(e, table[i].suffix)) {
2241 unsigned long long tmp;
2242 if ((unsigned long long) l > ULLONG_MAX / table[i].factor)
2244 tmp = l * table[i].factor;
2245 if (tmp > ULLONG_MAX - r)
2249 if ((unsigned long long) (off_t) r != r)
2252 p = e + strlen(table[i].suffix);
2256 if (i >= ELEMENTSOF(table))
2266 int make_stdio(int fd) {
2271 r = dup3(fd, STDIN_FILENO, 0);
2272 s = dup3(fd, STDOUT_FILENO, 0);
2273 t = dup3(fd, STDERR_FILENO, 0);
2276 close_nointr_nofail(fd);
2278 if (r < 0 || s < 0 || t < 0)
2281 /* We rely here that the new fd has O_CLOEXEC not set */
2286 int make_null_stdio(void) {
2289 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2293 return make_stdio(null_fd);
2296 bool is_device_path(const char *path) {
2298 /* Returns true on paths that refer to a device, either in
2299 * sysfs or in /dev */
2302 path_startswith(path, "/dev/") ||
2303 path_startswith(path, "/sys/");
2306 int dir_is_empty(const char *path) {
2307 _cleanup_closedir_ DIR *d;
2316 union dirent_storage buf;
2318 r = readdir_r(d, &buf.de, &de);
2325 if (!ignore_file(de->d_name))
2330 char* dirname_malloc(const char *path) {
2331 char *d, *dir, *dir2;
2348 unsigned long long random_ull(void) {
2349 _cleanup_close_ int fd;
2353 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2357 r = loop_read(fd, &ull, sizeof(ull), true);
2358 if (r != sizeof(ull))
2364 return random() * RAND_MAX + random();
2367 unsigned random_u(void) {
2368 _cleanup_close_ int fd;
2372 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2376 r = loop_read(fd, &u, sizeof(u), true);
2383 return random() * RAND_MAX + random();
2386 void rename_process(const char name[8]) {
2389 /* This is a like a poor man's setproctitle(). It changes the
2390 * comm field, argv[0], and also the glibc's internally used
2391 * name of the process. For the first one a limit of 16 chars
2392 * applies, to the second one usually one of 10 (i.e. length
2393 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2394 * "systemd"). If you pass a longer string it will be
2397 prctl(PR_SET_NAME, name);
2399 if (program_invocation_name)
2400 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2402 if (saved_argc > 0) {
2406 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2408 for (i = 1; i < saved_argc; i++) {
2412 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2417 void sigset_add_many(sigset_t *ss, ...) {
2424 while ((sig = va_arg(ap, int)) > 0)
2425 assert_se(sigaddset(ss, sig) == 0);
2429 char* gethostname_malloc(void) {
2432 assert_se(uname(&u) >= 0);
2434 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2435 return strdup(u.nodename);
2437 return strdup(u.sysname);
2440 bool hostname_is_set(void) {
2443 assert_se(uname(&u) >= 0);
2445 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2448 static char *lookup_uid(uid_t uid) {
2451 _cleanup_free_ char *buf = NULL;
2452 struct passwd pwbuf, *pw = NULL;
2454 /* Shortcut things to avoid NSS lookups */
2456 return strdup("root");
2458 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2462 buf = malloc(bufsize);
2466 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2467 return strdup(pw->pw_name);
2469 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2475 char* getlogname_malloc(void) {
2479 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2484 return lookup_uid(uid);
2487 char *getusername_malloc(void) {
2494 return lookup_uid(getuid());
2497 int getttyname_malloc(int fd, char **r) {
2498 char path[PATH_MAX], *c;
2503 k = ttyname_r(fd, path, sizeof(path));
2509 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2517 int getttyname_harder(int fd, char **r) {
2521 k = getttyname_malloc(fd, &s);
2525 if (streq(s, "tty")) {
2527 return get_ctty(0, NULL, r);
2534 int get_ctty_devnr(pid_t pid, dev_t *d) {
2535 _cleanup_fclose_ FILE *f = NULL;
2536 char line[LINE_MAX], *p;
2537 unsigned long ttynr;
2543 fn = "/proc/self/stat";
2545 fn = procfs_file_alloca(pid, "stat");
2547 f = fopen(fn, "re");
2551 if (!fgets(line, sizeof(line), f))
2552 return feof(f) ? -EIO : -errno;
2554 p = strrchr(line, ')');
2564 "%*d " /* session */
2569 if (major(ttynr) == 0 && minor(ttynr) == 0)
2578 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2580 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2585 k = get_ctty_devnr(pid, &devnr);
2589 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2591 k = readlink_malloc(fn, &s);
2597 /* This is an ugly hack */
2598 if (major(devnr) == 136) {
2599 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2609 /* Probably something like the ptys which have no
2610 * symlink in /dev/char. Let's return something
2611 * vaguely useful. */
2624 if (startswith(s, "/dev/"))
2626 else if (startswith(s, "../"))
2644 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2650 /* This returns the first error we run into, but nevertheless
2651 * tries to go on. This closes the passed fd. */
2655 close_nointr_nofail(fd);
2657 return errno == ENOENT ? 0 : -errno;
2662 union dirent_storage buf;
2663 bool is_dir, keep_around;
2667 r = readdir_r(d, &buf.de, &de);
2668 if (r != 0 && ret == 0) {
2676 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2679 if (de->d_type == DT_UNKNOWN ||
2681 (de->d_type == DT_DIR && root_dev)) {
2682 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2683 if (ret == 0 && errno != ENOENT)
2688 is_dir = S_ISDIR(st.st_mode);
2691 (st.st_uid == 0 || st.st_uid == getuid()) &&
2692 (st.st_mode & S_ISVTX);
2694 is_dir = de->d_type == DT_DIR;
2695 keep_around = false;
2701 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2702 if (root_dev && st.st_dev != root_dev->st_dev)
2705 subdir_fd = openat(fd, de->d_name,
2706 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2707 if (subdir_fd < 0) {
2708 if (ret == 0 && errno != ENOENT)
2713 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2714 if (r < 0 && ret == 0)
2718 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2719 if (ret == 0 && errno != ENOENT)
2723 } else if (!only_dirs && !keep_around) {
2725 if (unlinkat(fd, de->d_name, 0) < 0) {
2726 if (ret == 0 && errno != ENOENT)
2737 _pure_ static int is_temporary_fs(struct statfs *s) {
2740 F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2741 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2744 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2749 if (fstatfs(fd, &s) < 0) {
2750 close_nointr_nofail(fd);
2754 /* We refuse to clean disk file systems with this call. This
2755 * is extra paranoia just to be sure we never ever remove
2757 if (!is_temporary_fs(&s)) {
2758 log_error("Attempted to remove disk file system, and we can't allow that.");
2759 close_nointr_nofail(fd);
2763 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2766 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2772 /* We refuse to clean the root file system with this
2773 * call. This is extra paranoia to never cause a really
2774 * seriously broken system. */
2775 if (path_equal(path, "/")) {
2776 log_error("Attempted to remove entire root file system, and we can't allow that.");
2780 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2783 if (errno != ENOTDIR)
2787 if (statfs(path, &s) < 0)
2790 if (!is_temporary_fs(&s)) {
2791 log_error("Attempted to remove disk file system, and we can't allow that.");
2796 if (delete_root && !only_dirs)
2797 if (unlink(path) < 0 && errno != ENOENT)
2804 if (fstatfs(fd, &s) < 0) {
2805 close_nointr_nofail(fd);
2809 if (!is_temporary_fs(&s)) {
2810 log_error("Attempted to remove disk file system, and we can't allow that.");
2811 close_nointr_nofail(fd);
2816 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2819 if (honour_sticky && file_is_priv_sticky(path) > 0)
2822 if (rmdir(path) < 0 && errno != ENOENT) {
2831 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2832 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2835 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2836 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2839 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2842 /* Under the assumption that we are running privileged we
2843 * first change the access mode and only then hand out
2844 * ownership to avoid a window where access is too open. */
2846 if (mode != (mode_t) -1)
2847 if (chmod(path, mode) < 0)
2850 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2851 if (chown(path, uid, gid) < 0)
2857 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2860 /* Under the assumption that we are running privileged we
2861 * first change the access mode and only then hand out
2862 * ownership to avoid a window where access is too open. */
2864 if (mode != (mode_t) -1)
2865 if (fchmod(fd, mode) < 0)
2868 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2869 if (fchown(fd, uid, gid) < 0)
2875 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2879 /* Allocates the cpuset in the right size */
2882 if (!(r = CPU_ALLOC(n)))
2885 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2886 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2896 if (errno != EINVAL)
2903 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2904 static const char status_indent[] = " "; /* "[" STATUS "] " */
2905 _cleanup_free_ char *s = NULL;
2906 _cleanup_close_ int fd = -1;
2907 struct iovec iovec[6] = {};
2909 static bool prev_ephemeral;
2913 /* This is independent of logging, as status messages are
2914 * optional and go exclusively to the console. */
2916 if (vasprintf(&s, format, ap) < 0)
2919 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2932 sl = status ? sizeof(status_indent)-1 : 0;
2938 e = ellipsize(s, emax, 75);
2946 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2947 prev_ephemeral = ephemeral;
2950 if (!isempty(status)) {
2951 IOVEC_SET_STRING(iovec[n++], "[");
2952 IOVEC_SET_STRING(iovec[n++], status);
2953 IOVEC_SET_STRING(iovec[n++], "] ");
2955 IOVEC_SET_STRING(iovec[n++], status_indent);
2958 IOVEC_SET_STRING(iovec[n++], s);
2960 IOVEC_SET_STRING(iovec[n++], "\n");
2962 if (writev(fd, iovec, n) < 0)
2968 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2974 va_start(ap, format);
2975 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2981 int status_welcome(void) {
2982 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2985 r = parse_env_file("/etc/os-release", NEWLINE,
2986 "PRETTY_NAME", &pretty_name,
2987 "ANSI_COLOR", &ansi_color,
2990 if (r < 0 && r != -ENOENT)
2991 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2993 return status_printf(NULL, false, false,
2994 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2995 isempty(ansi_color) ? "1" : ansi_color,
2996 isempty(pretty_name) ? "Linux" : pretty_name);
2999 char *replace_env(const char *format, char **env) {
3006 const char *e, *word = format;
3011 for (e = format; *e; e ++) {
3022 if (!(k = strnappend(r, word, e-word-1)))
3031 } else if (*e == '$') {
3032 if (!(k = strnappend(r, word, e-word)))
3048 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3050 k = strappend(r, t);
3064 if (!(k = strnappend(r, word, e-word)))
3075 char **replace_env_argv(char **argv, char **env) {
3077 unsigned k = 0, l = 0;
3079 l = strv_length(argv);
3081 if (!(r = new(char*, l+1)))
3084 STRV_FOREACH(i, argv) {
3086 /* If $FOO appears as single word, replace it by the split up variable */
3087 if ((*i)[0] == '$' && (*i)[1] != '{') {
3092 e = strv_env_get(env, *i+1);
3095 if (!(m = strv_split_quoted(e))) {
3106 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3115 memcpy(r + k, m, q * sizeof(char*));
3123 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3124 if (!(r[k++] = replace_env(*i, env))) {
3134 int fd_columns(int fd) {
3135 struct winsize ws = {};
3137 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3146 unsigned columns(void) {
3150 if (_likely_(cached_columns > 0))
3151 return cached_columns;
3154 e = getenv("COLUMNS");
3159 c = fd_columns(STDOUT_FILENO);
3168 int fd_lines(int fd) {
3169 struct winsize ws = {};
3171 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3180 unsigned lines(void) {
3184 if (_likely_(cached_lines > 0))
3185 return cached_lines;
3188 e = getenv("LINES");
3193 l = fd_lines(STDOUT_FILENO);
3199 return cached_lines;
3202 /* intended to be used as a SIGWINCH sighandler */
3203 void columns_lines_cache_reset(int signum) {
3209 static int cached_on_tty = -1;
3211 if (_unlikely_(cached_on_tty < 0))
3212 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3214 return cached_on_tty;
3217 int running_in_chroot(void) {
3218 struct stat a = {}, b = {};
3220 /* Only works as root */
3221 if (stat("/proc/1/root", &a) < 0)
3224 if (stat("/", &b) < 0)
3228 a.st_dev != b.st_dev ||
3229 a.st_ino != b.st_ino;
3232 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3237 assert(percent <= 100);
3238 assert(new_length >= 3);
3240 if (old_length <= 3 || old_length <= new_length)
3241 return strndup(s, old_length);
3243 r = new0(char, new_length+1);
3247 x = (new_length * percent) / 100;
3249 if (x > new_length - 3)
3257 s + old_length - (new_length - x - 3),
3258 new_length - x - 3);
3263 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3267 unsigned k, len, len2;
3270 assert(percent <= 100);
3271 assert(new_length >= 3);
3273 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3274 if (ascii_is_valid(s))
3275 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3277 if (old_length <= 3 || old_length <= new_length)
3278 return strndup(s, old_length);
3280 x = (new_length * percent) / 100;
3282 if (x > new_length - 3)
3286 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3289 c = utf8_encoded_to_unichar(i);
3292 k += unichar_iswide(c) ? 2 : 1;
3295 if (k > x) /* last character was wide and went over quota */
3298 for (j = s + old_length; k < new_length && j > i; ) {
3301 j = utf8_prev_char(j);
3302 c = utf8_encoded_to_unichar(j);
3305 k += unichar_iswide(c) ? 2 : 1;
3309 /* we don't actually need to ellipsize */
3311 return memdup(s, old_length + 1);
3313 /* make space for ellipsis */
3314 j = utf8_next_char(j);
3317 len2 = s + old_length - j;
3318 e = new(char, len + 3 + len2 + 1);
3323 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3324 old_length, new_length, x, len, len2, k);
3328 e[len] = 0xe2; /* tri-dot ellipsis: … */
3332 memcpy(e + len + 3, j, len2 + 1);
3337 char *ellipsize(const char *s, size_t length, unsigned percent) {
3338 return ellipsize_mem(s, strlen(s), length, percent);
3341 int touch(const char *path) {
3346 /* This just opens the file for writing, ensuring it
3347 * exists. It doesn't call utimensat() the way /usr/bin/touch
3350 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3354 close_nointr_nofail(fd);
3358 char *unquote(const char *s, const char* quotes) {
3362 /* This is rather stupid, simply removes the heading and
3363 * trailing quotes if there is one. Doesn't care about
3364 * escaping or anything. We should make this smarter one
3371 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3372 return strndup(s+1, l-2);
3377 char *normalize_env_assignment(const char *s) {
3378 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3381 eq = strchr(s, '=');
3393 memmove(r, t, strlen(t) + 1);
3397 name = strndup(s, eq - s);
3405 value = unquote(strstrip(p), QUOTES);
3409 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3415 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3426 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3438 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3445 r = wait_for_terminate(pid, &status);
3447 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3451 if (status.si_code == CLD_EXITED) {
3452 if (status.si_status != 0) {
3453 log_warning("%s failed with error code %i.", name, status.si_status);
3454 return status.si_status;
3457 log_debug("%s succeeded.", name);
3460 } else if (status.si_code == CLD_KILLED ||
3461 status.si_code == CLD_DUMPED) {
3463 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3467 log_warning("%s failed due to unknown reason.", name);
3471 _noreturn_ void freeze(void) {
3473 /* Make sure nobody waits for us on a socket anymore */
3474 close_all_fds(NULL, 0);
3482 bool null_or_empty(struct stat *st) {
3485 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3488 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3494 int null_or_empty_path(const char *fn) {
3499 if (stat(fn, &st) < 0)
3502 return null_or_empty(&st);
3505 DIR *xopendirat(int fd, const char *name, int flags) {
3509 assert(!(flags & O_CREAT));
3511 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3517 close_nointr_nofail(nfd);
3524 int signal_from_string_try_harder(const char *s) {
3528 signo = signal_from_string(s);
3530 if (startswith(s, "SIG"))
3531 return signal_from_string(s+3);
3536 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3537 _cleanup_free_ char *t = NULL, *u = NULL;
3541 u = unquote(tagvalue, "\"\'");
3545 enc_len = strlen(u) * 4 + 1;
3546 t = new(char, enc_len);
3550 if (encode_devnode_name(u, t, enc_len) < 0)
3553 if (asprintf(&dn, "/dev/disk/by-%s/%s", by, t) < 0)
3559 char *fstab_node_to_udev_node(const char *p) {
3562 if (startswith(p, "LABEL="))
3563 return tag_to_udev_node(p+6, "label");
3565 if (startswith(p, "UUID="))
3566 return tag_to_udev_node(p+5, "uuid");
3568 if (startswith(p, "PARTUUID="))
3569 return tag_to_udev_node(p+9, "partuuid");
3571 if (startswith(p, "PARTLABEL="))
3572 return tag_to_udev_node(p+10, "partlabel");
3577 bool tty_is_vc(const char *tty) {
3580 if (startswith(tty, "/dev/"))
3583 return vtnr_from_tty(tty) >= 0;
3586 bool tty_is_console(const char *tty) {
3589 if (startswith(tty, "/dev/"))
3592 return streq(tty, "console");
3595 int vtnr_from_tty(const char *tty) {
3600 if (startswith(tty, "/dev/"))
3603 if (!startswith(tty, "tty") )
3606 if (tty[3] < '0' || tty[3] > '9')
3609 r = safe_atoi(tty+3, &i);
3613 if (i < 0 || i > 63)
3619 char *resolve_dev_console(char **active) {
3622 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3623 * (i.e. not read-only-mounted which is a sign for container setups) */
3625 if (path_is_read_only_fs("/sys") > 0)
3628 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3631 /* If multiple log outputs are configured the last one is what
3632 * /dev/console points to */
3633 tty = strrchr(*active, ' ');
3639 if (streq(tty, "tty0")) {
3642 /* Get the active VC (e.g. tty1) */
3643 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3645 tty = *active = tmp;
3652 bool tty_is_vc_resolve(const char *tty) {
3653 _cleanup_free_ char *active = NULL;
3657 if (startswith(tty, "/dev/"))
3660 if (streq(tty, "console")) {
3661 tty = resolve_dev_console(&active);
3666 return tty_is_vc(tty);
3669 const char *default_term_for_tty(const char *tty) {
3672 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3675 bool dirent_is_file(const struct dirent *de) {
3678 if (ignore_file(de->d_name))
3681 if (de->d_type != DT_REG &&
3682 de->d_type != DT_LNK &&
3683 de->d_type != DT_UNKNOWN)
3689 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3692 if (de->d_type != DT_REG &&
3693 de->d_type != DT_LNK &&
3694 de->d_type != DT_UNKNOWN)
3697 if (ignore_file_allow_backup(de->d_name))
3700 return endswith(de->d_name, suffix);
3703 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3706 Hashmap *pids = NULL;
3710 /* Executes all binaries in a directory in parallel and
3711 * waits for them to finish. */
3714 if (!(_d = opendir(directory))) {
3716 if (errno == ENOENT)
3719 log_error("Failed to enumerate directory %s: %m", directory);
3726 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3727 log_error("Failed to allocate set.");
3731 while ((de = readdir(d))) {
3736 if (!dirent_is_file(de))
3739 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3744 if ((pid = fork()) < 0) {
3745 log_error("Failed to fork: %m");
3763 log_error("Failed to execute %s: %m", path);
3764 _exit(EXIT_FAILURE);
3767 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3769 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3770 log_error("Failed to add PID to set: %s", strerror(-k));
3775 while (!hashmap_isempty(pids)) {
3776 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3780 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3785 log_error("waitid() failed: %m");
3789 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3790 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3791 if (si.si_code == CLD_EXITED)
3792 log_error("%s exited with exit status %i.", path, si.si_status);
3794 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3796 log_debug("%s exited successfully.", path);
3807 hashmap_free_free(pids);
3810 int kill_and_sigcont(pid_t pid, int sig) {
3813 r = kill(pid, sig) < 0 ? -errno : 0;
3821 bool nulstr_contains(const char*nulstr, const char *needle) {
3827 NULSTR_FOREACH(i, nulstr)
3828 if (streq(i, needle))
3834 bool plymouth_running(void) {
3835 return access("/run/plymouth/pid", F_OK) >= 0;
3838 char* strshorten(char *s, size_t l) {
3847 static bool hostname_valid_char(char c) {
3849 (c >= 'a' && c <= 'z') ||
3850 (c >= 'A' && c <= 'Z') ||
3851 (c >= '0' && c <= '9') ||
3857 bool hostname_is_valid(const char *s) {
3864 for (p = s, dot = true; *p; p++) {
3871 if (!hostname_valid_char(*p))
3881 if (p-s > HOST_NAME_MAX)
3887 char* hostname_cleanup(char *s, bool lowercase) {
3891 for (p = s, d = s, dot = true; *p; p++) {
3898 } else if (hostname_valid_char(*p)) {
3899 *(d++) = lowercase ? tolower(*p) : *p;
3910 strshorten(s, HOST_NAME_MAX);
3915 int pipe_eof(int fd) {
3917 struct pollfd pollfd = {
3919 .events = POLLIN|POLLHUP,
3922 r = poll(&pollfd, 1, 0);
3929 return pollfd.revents & POLLHUP;
3932 int fd_wait_for_event(int fd, int event, usec_t t) {
3934 struct pollfd pollfd = {
3939 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3946 return pollfd.revents;
3949 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3960 t = new(char, strlen(path) + 1 + 6 + 1);
3964 fn = path_get_file_name(path);
3968 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3970 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3976 f = fdopen(fd, "we");
3989 int terminal_vhangup_fd(int fd) {
3992 if (ioctl(fd, TIOCVHANGUP) < 0)
3998 int terminal_vhangup(const char *name) {
4001 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4005 r = terminal_vhangup_fd(fd);
4006 close_nointr_nofail(fd);
4011 int vt_disallocate(const char *name) {
4015 /* Deallocate the VT if possible. If not possible
4016 * (i.e. because it is the active one), at least clear it
4017 * entirely (including the scrollback buffer) */
4019 if (!startswith(name, "/dev/"))
4022 if (!tty_is_vc(name)) {
4023 /* So this is not a VT. I guess we cannot deallocate
4024 * it then. But let's at least clear the screen */
4026 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4031 "\033[r" /* clear scrolling region */
4032 "\033[H" /* move home */
4033 "\033[2J", /* clear screen */
4035 close_nointr_nofail(fd);
4040 if (!startswith(name, "/dev/tty"))
4043 r = safe_atou(name+8, &u);
4050 /* Try to deallocate */
4051 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4055 r = ioctl(fd, VT_DISALLOCATE, u);
4056 close_nointr_nofail(fd);
4064 /* Couldn't deallocate, so let's clear it fully with
4066 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4071 "\033[r" /* clear scrolling region */
4072 "\033[H" /* move home */
4073 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4075 close_nointr_nofail(fd);
4080 int copy_file(const char *from, const char *to, int flags) {
4081 _cleanup_close_ int fdf = -1;
4087 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4091 fdt = open(to, flags|O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
4099 n = read(fdf, buf, sizeof(buf));
4113 k = loop_write(fdt, buf, n, false);
4115 r = k < 0 ? k : (errno ? -errno : -EIO);
4124 r = close_nointr(fdt);
4134 int symlink_atomic(const char *from, const char *to) {
4136 _cleanup_free_ char *t;
4139 unsigned long long ull;
4146 t = new(char, strlen(to) + 1 + 16 + 1);
4150 fn = path_get_file_name(to);
4154 x = stpcpy(t+k+1, fn);
4157 for (i = 0; i < 16; i++) {
4158 *(x++) = hexchar(ull & 0xF);
4164 if (symlink(from, t) < 0)
4167 if (rename(t, to) < 0) {
4176 bool display_is_local(const char *display) {
4180 display[0] == ':' &&
4181 display[1] >= '0' &&
4185 int socket_from_display(const char *display, char **path) {
4192 if (!display_is_local(display))
4195 k = strspn(display+1, "0123456789");
4197 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4201 c = stpcpy(f, "/tmp/.X11-unix/X");
4202 memcpy(c, display+1, k);
4211 const char **username,
4212 uid_t *uid, gid_t *gid,
4214 const char **shell) {
4222 /* We enforce some special rules for uid=0: in order to avoid
4223 * NSS lookups for root we hardcode its data. */
4225 if (streq(*username, "root") || streq(*username, "0")) {
4243 if (parse_uid(*username, &u) >= 0) {
4247 /* If there are multiple users with the same id, make
4248 * sure to leave $USER to the configured value instead
4249 * of the first occurrence in the database. However if
4250 * the uid was configured by a numeric uid, then let's
4251 * pick the real username from /etc/passwd. */
4253 *username = p->pw_name;
4256 p = getpwnam(*username);
4260 return errno > 0 ? -errno : -ESRCH;
4272 *shell = p->pw_shell;
4277 char* uid_to_name(uid_t uid) {
4282 return strdup("root");
4286 return strdup(p->pw_name);
4288 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4294 char* gid_to_name(gid_t gid) {
4299 return strdup("root");
4303 return strdup(p->gr_name);
4305 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4311 int get_group_creds(const char **groupname, gid_t *gid) {
4317 /* We enforce some special rules for gid=0: in order to avoid
4318 * NSS lookups for root we hardcode its data. */
4320 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4321 *groupname = "root";
4329 if (parse_gid(*groupname, &id) >= 0) {
4334 *groupname = g->gr_name;
4337 g = getgrnam(*groupname);
4341 return errno > 0 ? -errno : -ESRCH;
4349 int in_gid(gid_t gid) {
4351 int ngroups_max, r, i;
4353 if (getgid() == gid)
4356 if (getegid() == gid)
4359 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4360 assert(ngroups_max > 0);
4362 gids = alloca(sizeof(gid_t) * ngroups_max);
4364 r = getgroups(ngroups_max, gids);
4368 for (i = 0; i < r; i++)
4375 int in_group(const char *name) {
4379 r = get_group_creds(&name, &gid);
4386 int glob_exists(const char *path) {
4387 _cleanup_globfree_ glob_t g = {};
4393 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4395 if (k == GLOB_NOMATCH)
4397 else if (k == GLOB_NOSPACE)
4400 return !strv_isempty(g.gl_pathv);
4402 return errno ? -errno : -EIO;
4405 int glob_extend(char ***strv, const char *path) {
4406 _cleanup_globfree_ glob_t g = {};
4411 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4413 if (k == GLOB_NOMATCH)
4415 else if (k == GLOB_NOSPACE)
4417 else if (k != 0 || strv_isempty(g.gl_pathv))
4418 return errno ? -errno : -EIO;
4420 STRV_FOREACH(p, g.gl_pathv) {
4421 k = strv_extend(strv, *p);
4429 int dirent_ensure_type(DIR *d, struct dirent *de) {
4435 if (de->d_type != DT_UNKNOWN)
4438 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4442 S_ISREG(st.st_mode) ? DT_REG :
4443 S_ISDIR(st.st_mode) ? DT_DIR :
4444 S_ISLNK(st.st_mode) ? DT_LNK :
4445 S_ISFIFO(st.st_mode) ? DT_FIFO :
4446 S_ISSOCK(st.st_mode) ? DT_SOCK :
4447 S_ISCHR(st.st_mode) ? DT_CHR :
4448 S_ISBLK(st.st_mode) ? DT_BLK :
4454 int in_search_path(const char *path, char **search) {
4456 _cleanup_free_ char *parent = NULL;
4459 r = path_get_parent(path, &parent);
4463 STRV_FOREACH(i, search)
4464 if (path_equal(parent, *i))
4470 int get_files_in_directory(const char *path, char ***list) {
4471 _cleanup_closedir_ DIR *d = NULL;
4472 size_t bufsize = 0, n = 0;
4473 _cleanup_strv_free_ char **l = NULL;
4477 /* Returns all files in a directory in *list, and the number
4478 * of files as return value. If list is NULL returns only the
4487 union dirent_storage buf;
4490 k = readdir_r(d, &buf.de, &de);
4497 dirent_ensure_type(d, de);
4499 if (!dirent_is_file(de))
4503 /* one extra slot is needed for the terminating NULL */
4504 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4507 l[n] = strdup(de->d_name);
4518 l = NULL; /* avoid freeing */
4524 char *strjoin(const char *x, ...) {
4538 t = va_arg(ap, const char *);
4543 if (n > ((size_t) -1) - l) {
4567 t = va_arg(ap, const char *);
4581 bool is_main_thread(void) {
4582 static __thread int cached = 0;
4584 if (_unlikely_(cached == 0))
4585 cached = getpid() == gettid() ? 1 : -1;
4590 int block_get_whole_disk(dev_t d, dev_t *ret) {
4597 /* If it has a queue this is good enough for us */
4598 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4601 r = access(p, F_OK);
4609 /* If it is a partition find the originating device */
4610 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4613 r = access(p, F_OK);
4619 /* Get parent dev_t */
4620 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4623 r = read_one_line_file(p, &s);
4629 r = sscanf(s, "%u:%u", &m, &n);
4635 /* Only return this if it is really good enough for us. */
4636 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4639 r = access(p, F_OK);
4643 *ret = makedev(m, n);
4650 int file_is_priv_sticky(const char *p) {
4655 if (lstat(p, &st) < 0)
4659 (st.st_uid == 0 || st.st_uid == getuid()) &&
4660 (st.st_mode & S_ISVTX);
4663 static const char *const ioprio_class_table[] = {
4664 [IOPRIO_CLASS_NONE] = "none",
4665 [IOPRIO_CLASS_RT] = "realtime",
4666 [IOPRIO_CLASS_BE] = "best-effort",
4667 [IOPRIO_CLASS_IDLE] = "idle"
4670 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4672 static const char *const sigchld_code_table[] = {
4673 [CLD_EXITED] = "exited",
4674 [CLD_KILLED] = "killed",
4675 [CLD_DUMPED] = "dumped",
4676 [CLD_TRAPPED] = "trapped",
4677 [CLD_STOPPED] = "stopped",
4678 [CLD_CONTINUED] = "continued",
4681 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4683 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4684 [LOG_FAC(LOG_KERN)] = "kern",
4685 [LOG_FAC(LOG_USER)] = "user",
4686 [LOG_FAC(LOG_MAIL)] = "mail",
4687 [LOG_FAC(LOG_DAEMON)] = "daemon",
4688 [LOG_FAC(LOG_AUTH)] = "auth",
4689 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4690 [LOG_FAC(LOG_LPR)] = "lpr",
4691 [LOG_FAC(LOG_NEWS)] = "news",
4692 [LOG_FAC(LOG_UUCP)] = "uucp",
4693 [LOG_FAC(LOG_CRON)] = "cron",
4694 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4695 [LOG_FAC(LOG_FTP)] = "ftp",
4696 [LOG_FAC(LOG_LOCAL0)] = "local0",
4697 [LOG_FAC(LOG_LOCAL1)] = "local1",
4698 [LOG_FAC(LOG_LOCAL2)] = "local2",
4699 [LOG_FAC(LOG_LOCAL3)] = "local3",
4700 [LOG_FAC(LOG_LOCAL4)] = "local4",
4701 [LOG_FAC(LOG_LOCAL5)] = "local5",
4702 [LOG_FAC(LOG_LOCAL6)] = "local6",
4703 [LOG_FAC(LOG_LOCAL7)] = "local7"
4706 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4708 static const char *const log_level_table[] = {
4709 [LOG_EMERG] = "emerg",
4710 [LOG_ALERT] = "alert",
4711 [LOG_CRIT] = "crit",
4713 [LOG_WARNING] = "warning",
4714 [LOG_NOTICE] = "notice",
4715 [LOG_INFO] = "info",
4716 [LOG_DEBUG] = "debug"
4719 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4721 static const char* const sched_policy_table[] = {
4722 [SCHED_OTHER] = "other",
4723 [SCHED_BATCH] = "batch",
4724 [SCHED_IDLE] = "idle",
4725 [SCHED_FIFO] = "fifo",
4729 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4731 static const char* const rlimit_table[] = {
4732 [RLIMIT_CPU] = "LimitCPU",
4733 [RLIMIT_FSIZE] = "LimitFSIZE",
4734 [RLIMIT_DATA] = "LimitDATA",
4735 [RLIMIT_STACK] = "LimitSTACK",
4736 [RLIMIT_CORE] = "LimitCORE",
4737 [RLIMIT_RSS] = "LimitRSS",
4738 [RLIMIT_NOFILE] = "LimitNOFILE",
4739 [RLIMIT_AS] = "LimitAS",
4740 [RLIMIT_NPROC] = "LimitNPROC",
4741 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4742 [RLIMIT_LOCKS] = "LimitLOCKS",
4743 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4744 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4745 [RLIMIT_NICE] = "LimitNICE",
4746 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4747 [RLIMIT_RTTIME] = "LimitRTTIME"
4750 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4752 static const char* const ip_tos_table[] = {
4753 [IPTOS_LOWDELAY] = "low-delay",
4754 [IPTOS_THROUGHPUT] = "throughput",
4755 [IPTOS_RELIABILITY] = "reliability",
4756 [IPTOS_LOWCOST] = "low-cost",
4759 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4761 static const char *const __signal_table[] = {
4778 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4789 [SIGVTALRM] = "VTALRM",
4791 [SIGWINCH] = "WINCH",
4797 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4799 const char *signal_to_string(int signo) {
4800 static __thread char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4803 name = __signal_to_string(signo);
4807 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4808 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4810 snprintf(buf, sizeof(buf), "%d", signo);
4815 int signal_from_string(const char *s) {
4820 signo = __signal_from_string(s);
4824 if (startswith(s, "RTMIN+")) {
4828 if (safe_atou(s, &u) >= 0) {
4829 signo = (int) u + offset;
4830 if (signo > 0 && signo < _NSIG)
4836 bool kexec_loaded(void) {
4837 bool loaded = false;
4840 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4848 int strdup_or_null(const char *a, char **b) {
4866 int prot_from_flags(int flags) {
4868 switch (flags & O_ACCMODE) {
4877 return PROT_READ|PROT_WRITE;
4884 char *format_bytes(char *buf, size_t l, off_t t) {
4887 static const struct {
4891 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4892 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4893 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4894 { "G", 1024ULL*1024ULL*1024ULL },
4895 { "M", 1024ULL*1024ULL },
4899 for (i = 0; i < ELEMENTSOF(table); i++) {
4901 if (t >= table[i].factor) {
4904 (unsigned long long) (t / table[i].factor),
4905 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4912 snprintf(buf, l, "%lluB", (unsigned long long) t);
4920 void* memdup(const void *p, size_t l) {
4933 int fd_inc_sndbuf(int fd, size_t n) {
4935 socklen_t l = sizeof(value);
4937 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4939 l == sizeof(value) &&
4940 (size_t) value >= n*2)
4944 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4951 int fd_inc_rcvbuf(int fd, size_t n) {
4953 socklen_t l = sizeof(value);
4955 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4957 l == sizeof(value) &&
4958 (size_t) value >= n*2)
4962 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4969 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4970 pid_t parent_pid, agent_pid;
4972 bool stdout_is_tty, stderr_is_tty;
4980 parent_pid = getpid();
4982 /* Spawns a temporary TTY agent, making sure it goes away when
4989 if (agent_pid != 0) {
4996 * Make sure the agent goes away when the parent dies */
4997 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4998 _exit(EXIT_FAILURE);
5000 /* Check whether our parent died before we were able
5001 * to set the death signal */
5002 if (getppid() != parent_pid)
5003 _exit(EXIT_SUCCESS);
5005 /* Don't leak fds to the agent */
5006 close_all_fds(except, n_except);
5008 stdout_is_tty = isatty(STDOUT_FILENO);
5009 stderr_is_tty = isatty(STDERR_FILENO);
5011 if (!stdout_is_tty || !stderr_is_tty) {
5012 /* Detach from stdout/stderr. and reopen
5013 * /dev/tty for them. This is important to
5014 * ensure that when systemctl is started via
5015 * popen() or a similar call that expects to
5016 * read EOF we actually do generate EOF and
5017 * not delay this indefinitely by because we
5018 * keep an unused copy of stdin around. */
5019 fd = open("/dev/tty", O_WRONLY);
5021 log_error("Failed to open /dev/tty: %m");
5022 _exit(EXIT_FAILURE);
5026 dup2(fd, STDOUT_FILENO);
5029 dup2(fd, STDERR_FILENO);
5035 /* Count arguments */
5037 for (n = 0; va_arg(ap, char*); n++)
5042 l = alloca(sizeof(char *) * (n + 1));
5044 /* Fill in arguments */
5046 for (i = 0; i <= n; i++)
5047 l[i] = va_arg(ap, char*);
5051 _exit(EXIT_FAILURE);
5054 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5055 struct rlimit highest, fixed;
5059 if (setrlimit(resource, rlim) >= 0)
5065 /* So we failed to set the desired setrlimit, then let's try
5066 * to get as close as we can */
5067 assert_se(getrlimit(resource, &highest) == 0);
5069 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5070 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5072 if (setrlimit(resource, &fixed) < 0)
5078 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5079 _cleanup_fclose_ FILE *f = NULL;
5091 path = "/proc/self/environ";
5093 path = procfs_file_alloca(pid, "environ");
5095 f = fopen(path, "re");
5103 char line[LINE_MAX];
5106 for (i = 0; i < sizeof(line)-1; i++) {
5110 if (_unlikely_(c == EOF)) {
5120 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5121 value = strdup(line + l + 1);
5135 bool is_valid_documentation_url(const char *url) {
5138 if (startswith(url, "http://") && url[7])
5141 if (startswith(url, "https://") && url[8])
5144 if (startswith(url, "file:") && url[5])
5147 if (startswith(url, "info:") && url[5])
5150 if (startswith(url, "man:") && url[4])
5156 bool in_initrd(void) {
5157 static __thread int saved = -1;
5163 /* We make two checks here:
5165 * 1. the flag file /etc/initrd-release must exist
5166 * 2. the root file system must be a memory file system
5168 * The second check is extra paranoia, since misdetecting an
5169 * initrd can have bad bad consequences due the initrd
5170 * emptying when transititioning to the main systemd.
5173 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5174 statfs("/", &s) >= 0 &&
5175 is_temporary_fs(&s);
5180 void warn_melody(void) {
5181 _cleanup_close_ int fd = -1;
5183 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5187 /* Yeah, this is synchronous. Kinda sucks. But well... */
5189 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5190 usleep(125*USEC_PER_MSEC);
5192 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5193 usleep(125*USEC_PER_MSEC);
5195 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5196 usleep(125*USEC_PER_MSEC);
5198 ioctl(fd, KIOCSOUND, 0);
5201 int make_console_stdio(void) {
5204 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5206 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5208 log_error("Failed to acquire terminal: %s", strerror(-fd));
5214 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5221 int get_home_dir(char **_h) {
5229 /* Take the user specified one */
5240 /* Hardcode home directory for root to avoid NSS */
5243 h = strdup("/root");
5251 /* Check the database... */
5255 return errno > 0 ? -errno : -ESRCH;
5257 if (!path_is_absolute(p->pw_dir))
5260 h = strdup(p->pw_dir);
5268 bool filename_is_safe(const char *p) {
5282 if (strlen(p) > FILENAME_MAX)
5288 bool string_is_safe(const char *p) {
5293 for (t = p; *t; t++) {
5294 if (*t > 0 && *t < ' ')
5297 if (strchr("\\\"\'", *t))
5305 * Check if a string contains control characters.
5306 * Spaces and tabs are not considered control characters.
5308 bool string_has_cc(const char *p) {
5313 for (t = p; *t; t++)
5314 if (*t > 0 && *t < ' ' && *t != '\t')
5320 bool path_is_safe(const char *p) {
5325 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5328 if (strlen(p) > PATH_MAX)
5331 /* The following two checks are not really dangerous, but hey, they still are confusing */
5332 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5335 if (strstr(p, "//"))
5341 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5342 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5343 int (*compar) (const void *, const void *, void *), void *arg) {
5352 p = (void *)(((const char *) base) + (idx * size));
5353 comparison = compar(key, p, arg);
5356 else if (comparison > 0)
5364 bool is_locale_utf8(void) {
5366 static int cached_answer = -1;
5368 if (cached_answer >= 0)
5371 if (!setlocale(LC_ALL, "")) {
5372 cached_answer = true;
5376 set = nl_langinfo(CODESET);
5378 cached_answer = true;
5382 if (streq(set, "UTF-8")) {
5383 cached_answer = true;
5387 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5388 * unset and everything can do to UTF-8 nowadays. */
5389 set = setlocale(LC_CTYPE, NULL);
5391 cached_answer = true;
5395 /* Check result, but ignore the result if C was set
5399 !getenv("LC_ALL") &&
5400 !getenv("LC_CTYPE") &&
5404 return (bool) cached_answer;
5407 const char *draw_special_char(DrawSpecialChar ch) {
5408 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5410 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5411 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5412 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5413 [DRAW_TREE_SPACE] = " ", /* */
5414 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5415 [DRAW_BLACK_CIRCLE] = "\342\227\217 ", /* ● */
5417 /* ASCII fallback */ {
5418 [DRAW_TREE_VERT] = "| ",
5419 [DRAW_TREE_BRANCH] = "|-",
5420 [DRAW_TREE_RIGHT] = "`-",
5421 [DRAW_TREE_SPACE] = " ",
5422 [DRAW_TRIANGULAR_BULLET] = "> ",
5423 [DRAW_BLACK_CIRCLE] = "* ",
5427 return draw_table[!is_locale_utf8()][ch];
5430 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5433 size_t l, old_len, new_len;
5439 old_len = strlen(old_string);
5440 new_len = strlen(new_string);
5453 if (!startswith(f, old_string)) {
5459 nl = l - old_len + new_len;
5460 a = realloc(r, nl + 1);
5468 t = stpcpy(t, new_string);
5480 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5481 const char *i, *begin = NULL;
5486 } state = STATE_OTHER;
5488 size_t osz = 0, isz;
5494 /* Strips ANSI color and replaces TABs by 8 spaces */
5496 isz = _isz ? *_isz : strlen(*ibuf);
5498 f = open_memstream(&obuf, &osz);
5502 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5507 if (i >= *ibuf + isz) /* EOT */
5509 else if (*i == '\x1B')
5510 state = STATE_ESCAPE;
5511 else if (*i == '\t')
5518 if (i >= *ibuf + isz) { /* EOT */
5521 } else if (*i == '[') {
5522 state = STATE_BRACKET;
5527 state = STATE_OTHER;
5534 if (i >= *ibuf + isz || /* EOT */
5535 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5538 state = STATE_OTHER;
5540 } else if (*i == 'm')
5541 state = STATE_OTHER;
5563 int on_ac_power(void) {
5564 bool found_offline = false, found_online = false;
5565 _cleanup_closedir_ DIR *d = NULL;
5567 d = opendir("/sys/class/power_supply");
5573 union dirent_storage buf;
5574 _cleanup_close_ int fd = -1, device = -1;
5579 k = readdir_r(d, &buf.de, &de);
5586 if (ignore_file(de->d_name))
5589 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5591 if (errno == ENOENT || errno == ENOTDIR)
5597 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5599 if (errno == ENOENT)
5605 n = read(fd, contents, sizeof(contents));
5609 if (n != 6 || memcmp(contents, "Mains\n", 6))
5612 close_nointr_nofail(fd);
5613 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5615 if (errno == ENOENT)
5621 n = read(fd, contents, sizeof(contents));
5625 if (n != 2 || contents[1] != '\n')
5628 if (contents[0] == '1') {
5629 found_online = true;
5631 } else if (contents[0] == '0')
5632 found_offline = true;
5637 return found_online || !found_offline;
5640 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5647 if (!path_strv_canonicalize_uniq(search))
5650 STRV_FOREACH(i, search) {
5651 _cleanup_free_ char *p = NULL;
5654 p = strjoin(*i, "/", path, NULL);
5664 if (errno != ENOENT)
5671 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5672 _cleanup_strv_free_ char **copy = NULL;
5678 if (path_is_absolute(path)) {
5681 f = fopen(path, mode);
5690 copy = strv_copy((char**) search);
5694 return search_and_fopen_internal(path, mode, copy, _f);
5697 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5698 _cleanup_strv_free_ char **s = NULL;
5700 if (path_is_absolute(path)) {
5703 f = fopen(path, mode);
5712 s = strv_split_nulstr(search);
5716 return search_and_fopen_internal(path, mode, s, _f);
5719 char *strextend(char **x, ...) {
5726 l = f = *x ? strlen(*x) : 0;
5733 t = va_arg(ap, const char *);
5738 if (n > ((size_t) -1) - l) {
5747 r = realloc(*x, l+1);
5757 t = va_arg(ap, const char *);
5771 char *strrep(const char *s, unsigned n) {
5779 p = r = malloc(l * n + 1);
5783 for (i = 0; i < n; i++)
5790 void* greedy_realloc(void **p, size_t *allocated, size_t need) {
5796 if (*allocated >= need)
5799 a = MAX(64u, need * 2);
5809 void* greedy_realloc0(void **p, size_t *allocated, size_t need) {
5810 size_t prev = *allocated;
5813 q = greedy_realloc(p, allocated, need);
5817 if (*allocated > prev)
5818 memset(&q[prev], 0, *allocated - prev);
5823 bool id128_is_valid(const char *s) {
5829 /* Simple formatted 128bit hex string */
5831 for (i = 0; i < l; i++) {
5834 if (!(c >= '0' && c <= '9') &&
5835 !(c >= 'a' && c <= 'z') &&
5836 !(c >= 'A' && c <= 'Z'))
5840 } else if (l == 36) {
5842 /* Formatted UUID */
5844 for (i = 0; i < l; i++) {
5847 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5851 if (!(c >= '0' && c <= '9') &&
5852 !(c >= 'a' && c <= 'z') &&
5853 !(c >= 'A' && c <= 'Z'))
5864 void parse_user_at_host(char *arg, char **user, char **host) {
5869 *host = strchr(arg, '@');
5878 int split_pair(const char *s, const char *sep, char **l, char **r) {
5893 a = strndup(s, x - s);
5897 b = strdup(x + strlen(sep));
5909 int shall_restore_state(void) {
5910 _cleanup_free_ char *line;
5915 r = proc_cmdline(&line);
5918 if (r == 0) /* Container ... */
5921 FOREACH_WORD_QUOTED(w, l, line, state)
5922 if (l == 23 && memcmp(w, "systemd.restore_state=0", 23))
5928 int proc_cmdline(char **ret) {
5931 if (detect_container(NULL) > 0) {
5936 r = read_one_line_file("/proc/cmdline", ret);