1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
71 #include "path-util.h"
72 #include "exit-status.h"
78 char **saved_argv = NULL;
80 static volatile unsigned cached_columns = 0;
81 static volatile unsigned cached_lines = 0;
83 size_t page_size(void) {
84 static __thread size_t pgsz = 0;
87 if (_likely_(pgsz > 0))
90 r = sysconf(_SC_PAGESIZE);
97 bool streq_ptr(const char *a, const char *b) {
99 /* Like streq(), but tries to make sense of NULL pointers */
110 char* endswith(const char *s, const char *postfix) {
117 pl = strlen(postfix);
120 return (char*) s + sl;
125 if (memcmp(s + sl - pl, postfix, pl) != 0)
128 return (char*) s + sl - pl;
131 char* startswith(const char *s, const char *prefix) {
148 char* startswith_no_case(const char *s, const char *prefix) {
158 if (tolower(*a) != tolower(*b))
165 bool first_word(const char *s, const char *word) {
180 if (memcmp(s, word, wl) != 0)
184 strchr(WHITESPACE, s[wl]);
187 int close_nointr(int fd) {
193 /* Just ignore EINTR; a retry loop is the wrong
194 * thing to do on Linux.
196 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
197 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
198 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
199 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
201 if (_unlikely_(r < 0 && errno == EINTR))
209 void close_nointr_nofail(int fd) {
210 int saved_errno = errno;
212 /* like close_nointr() but cannot fail, and guarantees errno
215 assert_se(close_nointr(fd) == 0);
220 void close_many(const int fds[], unsigned n_fd) {
223 assert(fds || n_fd <= 0);
225 for (i = 0; i < n_fd; i++)
226 close_nointr_nofail(fds[i]);
229 int parse_boolean(const char *v) {
232 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
234 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
240 int parse_pid(const char *s, pid_t* ret_pid) {
241 unsigned long ul = 0;
248 r = safe_atolu(s, &ul);
254 if ((unsigned long) pid != ul)
264 int parse_uid(const char *s, uid_t* ret_uid) {
265 unsigned long ul = 0;
272 r = safe_atolu(s, &ul);
278 if ((unsigned long) uid != ul)
285 int safe_atou(const char *s, unsigned *ret_u) {
293 l = strtoul(s, &x, 0);
295 if (!x || x == s || *x || errno)
296 return errno > 0 ? -errno : -EINVAL;
298 if ((unsigned long) (unsigned) l != l)
301 *ret_u = (unsigned) l;
305 int safe_atoi(const char *s, int *ret_i) {
313 l = strtol(s, &x, 0);
315 if (!x || x == s || *x || errno)
316 return errno > 0 ? -errno : -EINVAL;
318 if ((long) (int) l != l)
325 int safe_atollu(const char *s, long long unsigned *ret_llu) {
327 unsigned long long l;
333 l = strtoull(s, &x, 0);
335 if (!x || x == s || *x || errno)
336 return errno ? -errno : -EINVAL;
342 int safe_atolli(const char *s, long long int *ret_lli) {
350 l = strtoll(s, &x, 0);
352 if (!x || x == s || *x || errno)
353 return errno ? -errno : -EINVAL;
359 int safe_atod(const char *s, double *ret_d) {
369 if (!x || x == s || *x || errno)
370 return errno ? -errno : -EINVAL;
376 /* Split a string into words. */
377 char *split(const char *c, size_t *l, const char *separator, char **state) {
380 current = *state ? *state : (char*) c;
382 if (!*current || *c == 0)
385 current += strspn(current, separator);
386 *l = strcspn(current, separator);
389 return (char*) current;
392 /* Split a string into words, but consider strings enclosed in '' and
393 * "" as words even if they include spaces. */
394 char *split_quoted(const char *c, size_t *l, char **state) {
396 bool escaped = false;
398 current = *state ? *state : (char*) c;
400 if (!*current || *c == 0)
403 current += strspn(current, WHITESPACE);
405 if (*current == '\'') {
408 for (e = current; *e; e++) {
418 *state = *e == 0 ? e : e+1;
419 } else if (*current == '\"') {
422 for (e = current; *e; e++) {
432 *state = *e == 0 ? e : e+1;
434 for (e = current; *e; e++) {
439 else if (strchr(WHITESPACE, *e))
446 return (char*) current;
449 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
451 _cleanup_fclose_ FILE *f = NULL;
452 char fn[PATH_MAX], line[LINE_MAX], *p;
458 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
465 if (!fgets(line, sizeof(line), f)) {
466 r = feof(f) ? -EIO : -errno;
470 /* Let's skip the pid and comm fields. The latter is enclosed
471 * in () but does not escape any () in its value, so let's
472 * skip over it manually */
474 p = strrchr(line, ')');
486 if ((long unsigned) (pid_t) ppid != ppid)
489 *_ppid = (pid_t) ppid;
494 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
495 _cleanup_fclose_ FILE *f = NULL;
496 char fn[PATH_MAX], line[LINE_MAX], *p;
501 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
508 if (!fgets(line, sizeof(line), f)) {
515 /* Let's skip the pid and comm fields. The latter is enclosed
516 * in () but does not escape any () in its value, so let's
517 * skip over it manually */
519 p = strrchr(line, ')');
541 "%*d " /* priority */
543 "%*d " /* num_threads */
544 "%*d " /* itrealvalue */
545 "%llu " /* starttime */,
552 int fchmod_umask(int fd, mode_t m) {
557 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
563 char *truncate_nl(char *s) {
566 s[strcspn(s, NEWLINE)] = 0;
570 int get_process_comm(pid_t pid, char **name) {
576 r = read_one_line_file("/proc/self/comm", name);
579 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
582 r = read_one_line_file(p, name);
589 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
597 f = fopen("/proc/self/cmdline", "re");
600 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
609 if (max_length == 0) {
611 while ((c = getc(f)) != EOF) {
612 k = realloc(r, len+1);
619 r[len-1] = isprint(c) ? c : ' ';
626 r = new(char, max_length);
634 while ((c = getc(f)) != EOF) {
656 size_t n = MIN(left-1, 3U);
665 /* Kernel threads have no argv[] */
666 if (r == NULL || r[0] == 0) {
675 h = get_process_comm(pid, &t);
679 r = strjoin("[", t, "]", NULL);
690 int is_kernel_thread(pid_t pid) {
700 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
709 count = fread(&c, 1, 1, f);
713 /* Kernel threads have an empty cmdline */
716 return eof ? 1 : -errno;
721 int get_process_exe(pid_t pid, char **name) {
727 r = readlink_malloc("/proc/self/exe", name);
730 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
733 r = readlink_malloc(p, name);
740 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
741 _cleanup_fclose_ FILE *f = NULL;
742 _cleanup_free_ char *p = NULL;
751 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
758 FOREACH_LINE(line, f, return -errno) {
763 if (startswith(l, field)) {
765 l += strspn(l, WHITESPACE);
767 l[strcspn(l, WHITESPACE)] = 0;
769 return parse_uid(l, uid);
776 int get_process_uid(pid_t pid, uid_t *uid) {
777 return get_process_id(pid, "Uid:", uid);
780 int get_process_gid(pid_t pid, gid_t *gid) {
781 return get_process_id(pid, "Gid:", gid);
784 char *strnappend(const char *s, const char *suffix, size_t b) {
792 return strndup(suffix, b);
801 if (b > ((size_t) -1) - a)
804 r = new(char, a+b+1);
809 memcpy(r+a, suffix, b);
815 char *strappend(const char *s, const char *suffix) {
816 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
819 int readlink_malloc(const char *p, char **r) {
829 if (!(c = new(char, l)))
832 if ((n = readlink(p, c, l-1)) < 0) {
838 if ((size_t) n < l-1) {
849 int readlink_and_make_absolute(const char *p, char **r) {
856 if ((j = readlink_malloc(p, &target)) < 0)
859 k = file_in_same_dir(p, target);
869 int readlink_and_canonicalize(const char *p, char **r) {
876 j = readlink_and_make_absolute(p, &t);
880 s = canonicalize_file_name(t);
887 path_kill_slashes(*r);
892 int reset_all_signal_handlers(void) {
895 for (sig = 1; sig < _NSIG; sig++) {
898 if (sig == SIGKILL || sig == SIGSTOP)
902 sa.sa_handler = SIG_DFL;
903 sa.sa_flags = SA_RESTART;
905 /* On Linux the first two RT signals are reserved by
906 * glibc, and sigaction() will return EINVAL for them. */
907 if ((sigaction(sig, &sa, NULL) < 0))
915 char *strstrip(char *s) {
918 /* Drops trailing whitespace. Modifies the string in
919 * place. Returns pointer to first non-space character */
921 s += strspn(s, WHITESPACE);
923 for (e = strchr(s, 0); e > s; e --)
924 if (!strchr(WHITESPACE, e[-1]))
932 char *delete_chars(char *s, const char *bad) {
935 /* Drops all whitespace, regardless where in the string */
937 for (f = s, t = s; *f; f++) {
949 bool in_charset(const char *s, const char* charset) {
956 if (!strchr(charset, *i))
962 char *file_in_same_dir(const char *path, const char *filename) {
969 /* This removes the last component of path and appends
970 * filename, unless the latter is absolute anyway or the
973 if (path_is_absolute(filename))
974 return strdup(filename);
976 if (!(e = strrchr(path, '/')))
977 return strdup(filename);
979 k = strlen(filename);
980 if (!(r = new(char, e-path+1+k+1)))
983 memcpy(r, path, e-path+1);
984 memcpy(r+(e-path)+1, filename, k+1);
989 int rmdir_parents(const char *path, const char *stop) {
998 /* Skip trailing slashes */
999 while (l > 0 && path[l-1] == '/')
1005 /* Skip last component */
1006 while (l > 0 && path[l-1] != '/')
1009 /* Skip trailing slashes */
1010 while (l > 0 && path[l-1] == '/')
1016 if (!(t = strndup(path, l)))
1019 if (path_startswith(stop, t)) {
1028 if (errno != ENOENT)
1035 char hexchar(int x) {
1036 static const char table[16] = "0123456789abcdef";
1038 return table[x & 15];
1041 int unhexchar(char c) {
1043 if (c >= '0' && c <= '9')
1046 if (c >= 'a' && c <= 'f')
1047 return c - 'a' + 10;
1049 if (c >= 'A' && c <= 'F')
1050 return c - 'A' + 10;
1055 char *hexmem(const void *p, size_t l) {
1059 z = r = malloc(l * 2 + 1);
1063 for (x = p; x < (const uint8_t*) p + l; x++) {
1064 *(z++) = hexchar(*x >> 4);
1065 *(z++) = hexchar(*x & 15);
1072 char octchar(int x) {
1073 return '0' + (x & 7);
1076 int unoctchar(char c) {
1078 if (c >= '0' && c <= '7')
1084 char decchar(int x) {
1085 return '0' + (x % 10);
1088 int undecchar(char c) {
1090 if (c >= '0' && c <= '9')
1096 char *cescape(const char *s) {
1102 /* Does C style string escaping. */
1104 r = new(char, strlen(s)*4 + 1);
1108 for (f = s, t = r; *f; f++)
1154 /* For special chars we prefer octal over
1155 * hexadecimal encoding, simply because glib's
1156 * g_strescape() does the same */
1157 if ((*f < ' ') || (*f >= 127)) {
1159 *(t++) = octchar((unsigned char) *f >> 6);
1160 *(t++) = octchar((unsigned char) *f >> 3);
1161 *(t++) = octchar((unsigned char) *f);
1172 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1179 /* Undoes C style string escaping, and optionally prefixes it. */
1181 pl = prefix ? strlen(prefix) : 0;
1183 r = new(char, pl+length+1);
1188 memcpy(r, prefix, pl);
1190 for (f = s, t = r + pl; f < s + length; f++) {
1233 /* This is an extension of the XDG syntax files */
1238 /* hexadecimal encoding */
1241 a = unhexchar(f[1]);
1242 b = unhexchar(f[2]);
1244 if (a < 0 || b < 0) {
1245 /* Invalid escape code, let's take it literal then */
1249 *(t++) = (char) ((a << 4) | b);
1264 /* octal encoding */
1267 a = unoctchar(f[0]);
1268 b = unoctchar(f[1]);
1269 c = unoctchar(f[2]);
1271 if (a < 0 || b < 0 || c < 0) {
1272 /* Invalid escape code, let's take it literal then */
1276 *(t++) = (char) ((a << 6) | (b << 3) | c);
1284 /* premature end of string.*/
1289 /* Invalid escape code, let's take it literal then */
1301 char *cunescape_length(const char *s, size_t length) {
1302 return cunescape_length_with_prefix(s, length, NULL);
1305 char *cunescape(const char *s) {
1308 return cunescape_length(s, strlen(s));
1311 char *xescape(const char *s, const char *bad) {
1315 /* Escapes all chars in bad, in addition to \ and all special
1316 * chars, in \xFF style escaping. May be reversed with
1319 r = new(char, strlen(s) * 4 + 1);
1323 for (f = s, t = r; *f; f++) {
1325 if ((*f < ' ') || (*f >= 127) ||
1326 (*f == '\\') || strchr(bad, *f)) {
1329 *(t++) = hexchar(*f >> 4);
1330 *(t++) = hexchar(*f);
1340 char *bus_path_escape(const char *s) {
1346 /* Escapes all chars that D-Bus' object path cannot deal
1347 * with. Can be reverse with bus_path_unescape(). We special
1348 * case the empty string. */
1353 r = new(char, strlen(s)*3 + 1);
1357 for (f = s, t = r; *f; f++) {
1359 /* Escape everything that is not a-zA-Z0-9. We also
1360 * escape 0-9 if it's the first character */
1362 if (!(*f >= 'A' && *f <= 'Z') &&
1363 !(*f >= 'a' && *f <= 'z') &&
1364 !(f > s && *f >= '0' && *f <= '9')) {
1366 *(t++) = hexchar(*f >> 4);
1367 *(t++) = hexchar(*f);
1377 char *bus_path_unescape(const char *f) {
1382 /* Special case for the empty string */
1386 r = new(char, strlen(f) + 1);
1390 for (t = r; *f; f++) {
1395 if ((a = unhexchar(f[1])) < 0 ||
1396 (b = unhexchar(f[2])) < 0) {
1397 /* Invalid escape code, let's take it literal then */
1400 *(t++) = (char) ((a << 4) | b);
1412 char *ascii_strlower(char *t) {
1417 for (p = t; *p; p++)
1418 if (*p >= 'A' && *p <= 'Z')
1419 *p = *p - 'A' + 'a';
1424 static bool ignore_file_allow_backup(const char *filename) {
1428 filename[0] == '.' ||
1429 streq(filename, "lost+found") ||
1430 streq(filename, "aquota.user") ||
1431 streq(filename, "aquota.group") ||
1432 endswith(filename, ".rpmnew") ||
1433 endswith(filename, ".rpmsave") ||
1434 endswith(filename, ".rpmorig") ||
1435 endswith(filename, ".dpkg-old") ||
1436 endswith(filename, ".dpkg-new") ||
1437 endswith(filename, ".swp");
1440 bool ignore_file(const char *filename) {
1443 if (endswith(filename, "~"))
1446 return ignore_file_allow_backup(filename);
1449 int fd_nonblock(int fd, bool nonblock) {
1454 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1458 flags |= O_NONBLOCK;
1460 flags &= ~O_NONBLOCK;
1462 if (fcntl(fd, F_SETFL, flags) < 0)
1468 int fd_cloexec(int fd, bool cloexec) {
1473 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1477 flags |= FD_CLOEXEC;
1479 flags &= ~FD_CLOEXEC;
1481 if (fcntl(fd, F_SETFD, flags) < 0)
1487 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1490 assert(n_fdset == 0 || fdset);
1492 for (i = 0; i < n_fdset; i++)
1499 int close_all_fds(const int except[], unsigned n_except) {
1504 assert(n_except == 0 || except);
1506 d = opendir("/proc/self/fd");
1511 /* When /proc isn't available (for example in chroots)
1512 * the fallback is brute forcing through the fd
1515 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1516 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1518 if (fd_in_set(fd, except, n_except))
1521 if (close_nointr(fd) < 0)
1522 if (errno != EBADF && r == 0)
1529 while ((de = readdir(d))) {
1532 if (ignore_file(de->d_name))
1535 if (safe_atoi(de->d_name, &fd) < 0)
1536 /* Let's better ignore this, just in case */
1545 if (fd_in_set(fd, except, n_except))
1548 if (close_nointr(fd) < 0) {
1549 /* Valgrind has its own FD and doesn't want to have it closed */
1550 if (errno != EBADF && r == 0)
1559 bool chars_intersect(const char *a, const char *b) {
1562 /* Returns true if any of the chars in a are in b. */
1563 for (p = a; *p; p++)
1570 bool fstype_is_network(const char *fstype) {
1571 static const char table[] =
1580 return nulstr_contains(table, fstype);
1584 _cleanup_close_ int fd;
1586 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1592 TIOCL_GETKMSGREDIRECT,
1596 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1599 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1602 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1608 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1609 struct termios old_termios, new_termios;
1611 char line[LINE_MAX];
1616 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1617 new_termios = old_termios;
1619 new_termios.c_lflag &= ~ICANON;
1620 new_termios.c_cc[VMIN] = 1;
1621 new_termios.c_cc[VTIME] = 0;
1623 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1626 if (t != (usec_t) -1) {
1627 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1628 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1633 k = fread(&c, 1, 1, f);
1635 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1641 *need_nl = c != '\n';
1648 if (t != (usec_t) -1)
1649 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1652 if (!fgets(line, sizeof(line), f))
1657 if (strlen(line) != 1)
1667 int ask(char *ret, const char *replies, const char *text, ...) {
1677 bool need_nl = true;
1680 fputs(ANSI_HIGHLIGHT_ON, stdout);
1687 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1691 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1694 if (r == -EBADMSG) {
1695 puts("Bad input, please try again.");
1706 if (strchr(replies, c)) {
1711 puts("Read unexpected character, please try again.");
1715 int reset_terminal_fd(int fd, bool switch_to_text) {
1716 struct termios termios;
1719 /* Set terminal to some sane defaults */
1723 /* We leave locked terminal attributes untouched, so that
1724 * Plymouth may set whatever it wants to set, and we don't
1725 * interfere with that. */
1727 /* Disable exclusive mode, just in case */
1728 ioctl(fd, TIOCNXCL);
1730 /* Switch to text mode */
1732 ioctl(fd, KDSETMODE, KD_TEXT);
1734 /* Enable console unicode mode */
1735 ioctl(fd, KDSKBMODE, K_UNICODE);
1737 if (tcgetattr(fd, &termios) < 0) {
1742 /* We only reset the stuff that matters to the software. How
1743 * hardware is set up we don't touch assuming that somebody
1744 * else will do that for us */
1746 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1747 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1748 termios.c_oflag |= ONLCR;
1749 termios.c_cflag |= CREAD;
1750 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1752 termios.c_cc[VINTR] = 03; /* ^C */
1753 termios.c_cc[VQUIT] = 034; /* ^\ */
1754 termios.c_cc[VERASE] = 0177;
1755 termios.c_cc[VKILL] = 025; /* ^X */
1756 termios.c_cc[VEOF] = 04; /* ^D */
1757 termios.c_cc[VSTART] = 021; /* ^Q */
1758 termios.c_cc[VSTOP] = 023; /* ^S */
1759 termios.c_cc[VSUSP] = 032; /* ^Z */
1760 termios.c_cc[VLNEXT] = 026; /* ^V */
1761 termios.c_cc[VWERASE] = 027; /* ^W */
1762 termios.c_cc[VREPRINT] = 022; /* ^R */
1763 termios.c_cc[VEOL] = 0;
1764 termios.c_cc[VEOL2] = 0;
1766 termios.c_cc[VTIME] = 0;
1767 termios.c_cc[VMIN] = 1;
1769 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1773 /* Just in case, flush all crap out */
1774 tcflush(fd, TCIOFLUSH);
1779 int reset_terminal(const char *name) {
1782 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1786 r = reset_terminal_fd(fd, true);
1787 close_nointr_nofail(fd);
1792 int open_terminal(const char *name, int mode) {
1797 * If a TTY is in the process of being closed opening it might
1798 * cause EIO. This is horribly awful, but unlikely to be
1799 * changed in the kernel. Hence we work around this problem by
1800 * retrying a couple of times.
1802 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1806 fd = open(name, mode);
1813 /* Max 1s in total */
1817 usleep(50 * USEC_PER_MSEC);
1826 close_nointr_nofail(fd);
1831 close_nointr_nofail(fd);
1838 int flush_fd(int fd) {
1839 struct pollfd pollfd;
1843 pollfd.events = POLLIN;
1850 if ((r = poll(&pollfd, 1, 0)) < 0) {
1861 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1866 if (errno == EAGAIN)
1877 int acquire_terminal(
1881 bool ignore_tiocstty_eperm,
1884 int fd = -1, notify = -1, r = 0, wd = -1;
1886 struct sigaction sa_old, sa_new;
1890 /* We use inotify to be notified when the tty is closed. We
1891 * create the watch before checking if we can actually acquire
1892 * it, so that we don't lose any event.
1894 * Note: strictly speaking this actually watches for the
1895 * device being closed, it does *not* really watch whether a
1896 * tty loses its controlling process. However, unless some
1897 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1898 * its tty otherwise this will not become a problem. As long
1899 * as the administrator makes sure not configure any service
1900 * on the same tty as an untrusted user this should not be a
1901 * problem. (Which he probably should not do anyway.) */
1903 if (timeout != (usec_t) -1)
1904 ts = now(CLOCK_MONOTONIC);
1906 if (!fail && !force) {
1907 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1913 wd = inotify_add_watch(notify, name, IN_CLOSE);
1922 r = flush_fd(notify);
1927 /* We pass here O_NOCTTY only so that we can check the return
1928 * value TIOCSCTTY and have a reliable way to figure out if we
1929 * successfully became the controlling process of the tty */
1930 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1934 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1935 * if we already own the tty. */
1937 sa_new.sa_handler = SIG_IGN;
1938 sa_new.sa_flags = SA_RESTART;
1939 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1941 /* First, try to get the tty */
1942 if (ioctl(fd, TIOCSCTTY, force) < 0)
1945 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1947 /* Sometimes it makes sense to ignore TIOCSCTTY
1948 * returning EPERM, i.e. when very likely we already
1949 * are have this controlling terminal. */
1950 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1953 if (r < 0 && (force || fail || r != -EPERM)) {
1962 assert(notify >= 0);
1965 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1967 struct inotify_event *e;
1969 if (timeout != (usec_t) -1) {
1972 n = now(CLOCK_MONOTONIC);
1973 if (ts + timeout < n) {
1978 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1988 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1991 if (errno == EINTR || errno == EAGAIN)
1998 e = (struct inotify_event*) inotify_buffer;
2003 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2008 step = sizeof(struct inotify_event) + e->len;
2009 assert(step <= (size_t) l);
2011 e = (struct inotify_event*) ((uint8_t*) e + step);
2018 /* We close the tty fd here since if the old session
2019 * ended our handle will be dead. It's important that
2020 * we do this after sleeping, so that we don't enter
2021 * an endless loop. */
2022 close_nointr_nofail(fd);
2026 close_nointr_nofail(notify);
2028 r = reset_terminal_fd(fd, true);
2030 log_warning("Failed to reset terminal: %s", strerror(-r));
2036 close_nointr_nofail(fd);
2039 close_nointr_nofail(notify);
2044 int release_terminal(void) {
2046 struct sigaction sa_old, sa_new;
2048 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2051 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2052 * by our own TIOCNOTTY */
2055 sa_new.sa_handler = SIG_IGN;
2056 sa_new.sa_flags = SA_RESTART;
2057 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2059 if (ioctl(fd, TIOCNOTTY) < 0)
2062 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2064 close_nointr_nofail(fd);
2068 int sigaction_many(const struct sigaction *sa, ...) {
2073 while ((sig = va_arg(ap, int)) > 0)
2074 if (sigaction(sig, sa, NULL) < 0)
2081 int ignore_signals(int sig, ...) {
2082 struct sigaction sa;
2087 sa.sa_handler = SIG_IGN;
2088 sa.sa_flags = SA_RESTART;
2090 if (sigaction(sig, &sa, NULL) < 0)
2094 while ((sig = va_arg(ap, int)) > 0)
2095 if (sigaction(sig, &sa, NULL) < 0)
2102 int default_signals(int sig, ...) {
2103 struct sigaction sa;
2108 sa.sa_handler = SIG_DFL;
2109 sa.sa_flags = SA_RESTART;
2111 if (sigaction(sig, &sa, NULL) < 0)
2115 while ((sig = va_arg(ap, int)) > 0)
2116 if (sigaction(sig, &sa, NULL) < 0)
2123 int close_pipe(int p[]) {
2129 a = close_nointr(p[0]);
2134 b = close_nointr(p[1]);
2138 return a < 0 ? a : b;
2141 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2150 while (nbytes > 0) {
2153 if ((k = read(fd, p, nbytes)) <= 0) {
2155 if (k < 0 && errno == EINTR)
2158 if (k < 0 && errno == EAGAIN && do_poll) {
2159 struct pollfd pollfd;
2163 pollfd.events = POLLIN;
2165 if (poll(&pollfd, 1, -1) < 0) {
2169 return n > 0 ? n : -errno;
2172 if (pollfd.revents != POLLIN)
2173 return n > 0 ? n : -EIO;
2178 return n > 0 ? n : (k < 0 ? -errno : 0);
2189 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2198 while (nbytes > 0) {
2201 k = write(fd, p, nbytes);
2204 if (k < 0 && errno == EINTR)
2207 if (k < 0 && errno == EAGAIN && do_poll) {
2208 struct pollfd pollfd;
2212 pollfd.events = POLLOUT;
2214 if (poll(&pollfd, 1, -1) < 0) {
2218 return n > 0 ? n : -errno;
2221 if (pollfd.revents != POLLOUT)
2222 return n > 0 ? n : -EIO;
2227 return n > 0 ? n : (k < 0 ? -errno : 0);
2238 int parse_bytes(const char *t, off_t *bytes) {
2239 static const struct {
2245 { "M", 1024ULL*1024ULL },
2246 { "G", 1024ULL*1024ULL*1024ULL },
2247 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2248 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2249 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2266 l = strtoll(p, &e, 10);
2277 e += strspn(e, WHITESPACE);
2279 for (i = 0; i < ELEMENTSOF(table); i++)
2280 if (startswith(e, table[i].suffix)) {
2281 r += (off_t) l * table[i].factor;
2282 p = e + strlen(table[i].suffix);
2286 if (i >= ELEMENTSOF(table))
2296 int make_stdio(int fd) {
2301 r = dup3(fd, STDIN_FILENO, 0);
2302 s = dup3(fd, STDOUT_FILENO, 0);
2303 t = dup3(fd, STDERR_FILENO, 0);
2306 close_nointr_nofail(fd);
2308 if (r < 0 || s < 0 || t < 0)
2311 /* We rely here that the new fd has O_CLOEXEC not set */
2316 int make_null_stdio(void) {
2319 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2323 return make_stdio(null_fd);
2326 bool is_device_path(const char *path) {
2328 /* Returns true on paths that refer to a device, either in
2329 * sysfs or in /dev */
2332 path_startswith(path, "/dev/") ||
2333 path_startswith(path, "/sys/");
2336 int dir_is_empty(const char *path) {
2337 _cleanup_closedir_ DIR *d;
2346 union dirent_storage buf;
2348 r = readdir_r(d, &buf.de, &de);
2355 if (!ignore_file(de->d_name))
2360 char* dirname_malloc(const char *path) {
2361 char *d, *dir, *dir2;
2378 unsigned long long random_ull(void) {
2379 _cleanup_close_ int fd;
2383 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2387 r = loop_read(fd, &ull, sizeof(ull), true);
2388 if (r != sizeof(ull))
2394 return random() * RAND_MAX + random();
2397 void rename_process(const char name[8]) {
2400 /* This is a like a poor man's setproctitle(). It changes the
2401 * comm field, argv[0], and also the glibc's internally used
2402 * name of the process. For the first one a limit of 16 chars
2403 * applies, to the second one usually one of 10 (i.e. length
2404 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2405 * "systemd"). If you pass a longer string it will be
2408 prctl(PR_SET_NAME, name);
2410 if (program_invocation_name)
2411 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2413 if (saved_argc > 0) {
2417 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2419 for (i = 1; i < saved_argc; i++) {
2423 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2428 void sigset_add_many(sigset_t *ss, ...) {
2435 while ((sig = va_arg(ap, int)) > 0)
2436 assert_se(sigaddset(ss, sig) == 0);
2440 char* gethostname_malloc(void) {
2443 assert_se(uname(&u) >= 0);
2445 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2446 return strdup(u.nodename);
2448 return strdup(u.sysname);
2451 bool hostname_is_set(void) {
2454 assert_se(uname(&u) >= 0);
2456 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2459 static char *lookup_uid(uid_t uid) {
2462 _cleanup_free_ char *buf = NULL;
2463 struct passwd pwbuf, *pw = NULL;
2465 /* Shortcut things to avoid NSS lookups */
2467 return strdup("root");
2469 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2473 buf = malloc(bufsize);
2477 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2478 return strdup(pw->pw_name);
2480 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2486 char* getlogname_malloc(void) {
2490 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2495 return lookup_uid(uid);
2498 char *getusername_malloc(void) {
2505 return lookup_uid(getuid());
2508 int getttyname_malloc(int fd, char **r) {
2509 char path[PATH_MAX], *c;
2514 k = ttyname_r(fd, path, sizeof(path));
2520 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2528 int getttyname_harder(int fd, char **r) {
2532 k = getttyname_malloc(fd, &s);
2536 if (streq(s, "tty")) {
2538 return get_ctty(0, NULL, r);
2545 int get_ctty_devnr(pid_t pid, dev_t *d) {
2547 char line[LINE_MAX], *p, *fn;
2548 unsigned long ttynr;
2551 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2554 f = fopen(fn, "re");
2559 if (!fgets(line, sizeof(line), f)) {
2560 k = feof(f) ? -EIO : -errno;
2567 p = strrchr(line, ')');
2577 "%*d " /* session */
2582 if (major(ttynr) == 0 && minor(ttynr) == 0)
2589 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2591 char fn[PATH_MAX], *s, *b, *p;
2596 k = get_ctty_devnr(pid, &devnr);
2600 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2603 k = readlink_malloc(fn, &s);
2609 /* This is an ugly hack */
2610 if (major(devnr) == 136) {
2611 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2621 /* Probably something like the ptys which have no
2622 * symlink in /dev/char. Let's return something
2623 * vaguely useful. */
2636 if (startswith(s, "/dev/"))
2638 else if (startswith(s, "../"))
2656 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2662 /* This returns the first error we run into, but nevertheless
2663 * tries to go on. This closes the passed fd. */
2667 close_nointr_nofail(fd);
2669 return errno == ENOENT ? 0 : -errno;
2674 union dirent_storage buf;
2675 bool is_dir, keep_around;
2679 r = readdir_r(d, &buf.de, &de);
2680 if (r != 0 && ret == 0) {
2688 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2691 if (de->d_type == DT_UNKNOWN ||
2693 (de->d_type == DT_DIR && root_dev)) {
2694 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2695 if (ret == 0 && errno != ENOENT)
2700 is_dir = S_ISDIR(st.st_mode);
2703 (st.st_uid == 0 || st.st_uid == getuid()) &&
2704 (st.st_mode & S_ISVTX);
2706 is_dir = de->d_type == DT_DIR;
2707 keep_around = false;
2713 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2714 if (root_dev && st.st_dev != root_dev->st_dev)
2717 subdir_fd = openat(fd, de->d_name,
2718 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2719 if (subdir_fd < 0) {
2720 if (ret == 0 && errno != ENOENT)
2725 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2726 if (r < 0 && ret == 0)
2730 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2731 if (ret == 0 && errno != ENOENT)
2735 } else if (!only_dirs && !keep_around) {
2737 if (unlinkat(fd, de->d_name, 0) < 0) {
2738 if (ret == 0 && errno != ENOENT)
2749 static int is_temporary_fs(struct statfs *s) {
2751 return s->f_type == TMPFS_MAGIC ||
2752 (long)s->f_type == (long)RAMFS_MAGIC;
2755 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2760 if (fstatfs(fd, &s) < 0) {
2761 close_nointr_nofail(fd);
2765 /* We refuse to clean disk file systems with this call. This
2766 * is extra paranoia just to be sure we never ever remove
2768 if (!is_temporary_fs(&s)) {
2769 log_error("Attempted to remove disk file system, and we can't allow that.");
2770 close_nointr_nofail(fd);
2774 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2777 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2783 /* We refuse to clean the root file system with this
2784 * call. This is extra paranoia to never cause a really
2785 * seriously broken system. */
2786 if (path_equal(path, "/")) {
2787 log_error("Attempted to remove entire root file system, and we can't allow that.");
2791 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2794 if (errno != ENOTDIR)
2798 if (statfs(path, &s) < 0)
2801 if (!is_temporary_fs(&s)) {
2802 log_error("Attempted to remove disk file system, and we can't allow that.");
2807 if (delete_root && !only_dirs)
2808 if (unlink(path) < 0 && errno != ENOENT)
2815 if (fstatfs(fd, &s) < 0) {
2816 close_nointr_nofail(fd);
2820 if (!is_temporary_fs(&s)) {
2821 log_error("Attempted to remove disk file system, and we can't allow that.");
2822 close_nointr_nofail(fd);
2827 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2830 if (honour_sticky && file_is_priv_sticky(path) > 0)
2833 if (rmdir(path) < 0 && errno != ENOENT) {
2842 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2843 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2846 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2847 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2850 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2853 /* Under the assumption that we are running privileged we
2854 * first change the access mode and only then hand out
2855 * ownership to avoid a window where access is too open. */
2857 if (mode != (mode_t) -1)
2858 if (chmod(path, mode) < 0)
2861 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2862 if (chown(path, uid, gid) < 0)
2868 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2871 /* Under the assumption that we are running privileged we
2872 * first change the access mode and only then hand out
2873 * ownership to avoid a window where access is too open. */
2875 if (fchmod(fd, mode) < 0)
2878 if (fchown(fd, uid, gid) < 0)
2884 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2888 /* Allocates the cpuset in the right size */
2891 if (!(r = CPU_ALLOC(n)))
2894 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2895 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2905 if (errno != EINVAL)
2912 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2913 static const char status_indent[] = " "; /* "[" STATUS "] " */
2914 _cleanup_free_ char *s = NULL;
2915 _cleanup_close_ int fd = -1;
2916 struct iovec iovec[6];
2918 static bool prev_ephemeral;
2922 /* This is independent of logging, as status messages are
2923 * optional and go exclusively to the console. */
2925 if (vasprintf(&s, format, ap) < 0)
2928 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2941 sl = status ? sizeof(status_indent)-1 : 0;
2947 e = ellipsize(s, emax, 75);
2957 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2958 prev_ephemeral = ephemeral;
2961 if (!isempty(status)) {
2962 IOVEC_SET_STRING(iovec[n++], "[");
2963 IOVEC_SET_STRING(iovec[n++], status);
2964 IOVEC_SET_STRING(iovec[n++], "] ");
2966 IOVEC_SET_STRING(iovec[n++], status_indent);
2969 IOVEC_SET_STRING(iovec[n++], s);
2971 IOVEC_SET_STRING(iovec[n++], "\n");
2973 if (writev(fd, iovec, n) < 0)
2979 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2985 va_start(ap, format);
2986 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2992 int status_welcome(void) {
2994 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2996 r = parse_env_file("/etc/os-release", NEWLINE,
2997 "PRETTY_NAME", &pretty_name,
2998 "ANSI_COLOR", &ansi_color,
3000 if (r < 0 && r != -ENOENT)
3001 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3003 return status_printf(NULL, false, false,
3004 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3005 isempty(ansi_color) ? "1" : ansi_color,
3006 isempty(pretty_name) ? "Linux" : pretty_name);
3009 char *replace_env(const char *format, char **env) {
3016 const char *e, *word = format;
3021 for (e = format; *e; e ++) {
3032 if (!(k = strnappend(r, word, e-word-1)))
3041 } else if (*e == '$') {
3042 if (!(k = strnappend(r, word, e-word)))
3058 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3060 k = strappend(r, t);
3074 if (!(k = strnappend(r, word, e-word)))
3085 char **replace_env_argv(char **argv, char **env) {
3087 unsigned k = 0, l = 0;
3089 l = strv_length(argv);
3091 if (!(r = new(char*, l+1)))
3094 STRV_FOREACH(i, argv) {
3096 /* If $FOO appears as single word, replace it by the split up variable */
3097 if ((*i)[0] == '$' && (*i)[1] != '{') {
3102 e = strv_env_get(env, *i+1);
3105 if (!(m = strv_split_quoted(e))) {
3116 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3125 memcpy(r + k, m, q * sizeof(char*));
3133 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3134 if (!(r[k++] = replace_env(*i, env))) {
3144 int fd_columns(int fd) {
3148 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3157 unsigned columns(void) {
3161 if (_likely_(cached_columns > 0))
3162 return cached_columns;
3165 e = getenv("COLUMNS");
3170 c = fd_columns(STDOUT_FILENO);
3179 int fd_lines(int fd) {
3183 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3192 unsigned lines(void) {
3196 if (_likely_(cached_lines > 0))
3197 return cached_lines;
3200 e = getenv("LINES");
3205 l = fd_lines(STDOUT_FILENO);
3211 return cached_lines;
3214 /* intended to be used as a SIGWINCH sighandler */
3215 void columns_lines_cache_reset(int signum) {
3221 static int cached_on_tty = -1;
3223 if (_unlikely_(cached_on_tty < 0))
3224 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3226 return cached_on_tty;
3229 int running_in_chroot(void) {
3235 /* Only works as root */
3237 if (stat("/proc/1/root", &a) < 0)
3240 if (stat("/", &b) < 0)
3244 a.st_dev != b.st_dev ||
3245 a.st_ino != b.st_ino;
3248 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3253 assert(percent <= 100);
3254 assert(new_length >= 3);
3256 if (old_length <= 3 || old_length <= new_length)
3257 return strndup(s, old_length);
3259 r = new0(char, new_length+1);
3263 x = (new_length * percent) / 100;
3265 if (x > new_length - 3)
3273 s + old_length - (new_length - x - 3),
3274 new_length - x - 3);
3279 char *ellipsize(const char *s, size_t length, unsigned percent) {
3280 return ellipsize_mem(s, strlen(s), length, percent);
3283 int touch(const char *path) {
3288 /* This just opens the file for writing, ensuring it
3289 * exists. It doesn't call utimensat() the way /usr/bin/touch
3292 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3296 close_nointr_nofail(fd);
3300 char *unquote(const char *s, const char* quotes) {
3304 /* This is rather stupid, simply removes the heading and
3305 * trailing quotes if there is one. Doesn't care about
3306 * escaping or anything. We should make this smarter one
3313 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3314 return strndup(s+1, l-2);
3319 char *normalize_env_assignment(const char *s) {
3320 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3323 eq = strchr(s, '=');
3335 memmove(r, t, strlen(t) + 1);
3339 name = strndup(s, eq - s);
3347 value = unquote(strstrip(p), QUOTES);
3351 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3357 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3368 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3380 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3387 r = wait_for_terminate(pid, &status);
3389 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3393 if (status.si_code == CLD_EXITED) {
3394 if (status.si_status != 0) {
3395 log_warning("%s failed with error code %i.", name, status.si_status);
3396 return status.si_status;
3399 log_debug("%s succeeded.", name);
3402 } else if (status.si_code == CLD_KILLED ||
3403 status.si_code == CLD_DUMPED) {
3405 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3409 log_warning("%s failed due to unknown reason.", name);
3413 _noreturn_ void freeze(void) {
3415 /* Make sure nobody waits for us on a socket anymore */
3416 close_all_fds(NULL, 0);
3424 bool null_or_empty(struct stat *st) {
3427 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3430 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3436 int null_or_empty_path(const char *fn) {
3441 if (stat(fn, &st) < 0)
3444 return null_or_empty(&st);
3447 DIR *xopendirat(int fd, const char *name, int flags) {
3451 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3457 close_nointr_nofail(nfd);
3464 int signal_from_string_try_harder(const char *s) {
3468 signo = signal_from_string(s);
3470 if (startswith(s, "SIG"))
3471 return signal_from_string(s+3);
3476 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3480 /* FIXME: to follow udev's logic 100% we need to leave valid
3481 * UTF8 chars unescaped */
3483 u = unquote(tagvalue, "\"\'");
3487 t = xescape(u, "/ ");
3493 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3502 char *fstab_node_to_udev_node(const char *p) {
3505 if (startswith(p, "LABEL="))
3506 return tag_to_udev_node(p+6, "label");
3508 if (startswith(p, "UUID="))
3509 return tag_to_udev_node(p+5, "uuid");
3511 if (startswith(p, "PARTUUID="))
3512 return tag_to_udev_node(p+9, "partuuid");
3514 if (startswith(p, "PARTLABEL="))
3515 return tag_to_udev_node(p+10, "partlabel");
3520 bool tty_is_vc(const char *tty) {
3523 if (startswith(tty, "/dev/"))
3526 return vtnr_from_tty(tty) >= 0;
3529 bool tty_is_console(const char *tty) {
3532 if (startswith(tty, "/dev/"))
3535 return streq(tty, "console");
3538 int vtnr_from_tty(const char *tty) {
3543 if (startswith(tty, "/dev/"))
3546 if (!startswith(tty, "tty") )
3549 if (tty[3] < '0' || tty[3] > '9')
3552 r = safe_atoi(tty+3, &i);
3556 if (i < 0 || i > 63)
3562 char *resolve_dev_console(char **active) {
3565 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3566 * (i.e. not read-only-mounted which is a sign for container setups) */
3568 if (path_is_read_only_fs("/sys") > 0)
3571 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3574 /* If multiple log outputs are configured the last one is what
3575 * /dev/console points to */
3576 tty = strrchr(*active, ' ');
3585 bool tty_is_vc_resolve(const char *tty) {
3586 char *active = NULL;
3591 if (startswith(tty, "/dev/"))
3594 if (streq(tty, "console")) {
3595 tty = resolve_dev_console(&active);
3606 const char *default_term_for_tty(const char *tty) {
3609 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3612 bool dirent_is_file(const struct dirent *de) {
3615 if (ignore_file(de->d_name))
3618 if (de->d_type != DT_REG &&
3619 de->d_type != DT_LNK &&
3620 de->d_type != DT_UNKNOWN)
3626 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3629 if (de->d_type != DT_REG &&
3630 de->d_type != DT_LNK &&
3631 de->d_type != DT_UNKNOWN)
3634 if (ignore_file_allow_backup(de->d_name))
3637 return endswith(de->d_name, suffix);
3640 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3643 Hashmap *pids = NULL;
3647 /* Executes all binaries in a directory in parallel and
3648 * waits for them to finish. */
3651 if (!(_d = opendir(directory))) {
3653 if (errno == ENOENT)
3656 log_error("Failed to enumerate directory %s: %m", directory);
3663 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3664 log_error("Failed to allocate set.");
3668 while ((de = readdir(d))) {
3673 if (!dirent_is_file(de))
3676 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3681 if ((pid = fork()) < 0) {
3682 log_error("Failed to fork: %m");
3700 log_error("Failed to execute %s: %m", path);
3701 _exit(EXIT_FAILURE);
3704 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3706 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3707 log_error("Failed to add PID to set: %s", strerror(-k));
3712 while (!hashmap_isempty(pids)) {
3713 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3718 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3723 log_error("waitid() failed: %m");
3727 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3728 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3729 if (si.si_code == CLD_EXITED)
3730 log_error("%s exited with exit status %i.", path, si.si_status);
3732 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3734 log_debug("%s exited successfully.", path);
3745 hashmap_free_free(pids);
3748 int kill_and_sigcont(pid_t pid, int sig) {
3751 r = kill(pid, sig) < 0 ? -errno : 0;
3759 bool nulstr_contains(const char*nulstr, const char *needle) {
3765 NULSTR_FOREACH(i, nulstr)
3766 if (streq(i, needle))
3772 bool plymouth_running(void) {
3773 return access("/run/plymouth/pid", F_OK) >= 0;
3776 char* strshorten(char *s, size_t l) {
3785 static bool hostname_valid_char(char c) {
3787 (c >= 'a' && c <= 'z') ||
3788 (c >= 'A' && c <= 'Z') ||
3789 (c >= '0' && c <= '9') ||
3795 bool hostname_is_valid(const char *s) {
3802 for (p = s, dot = true; *p; p++) {
3809 if (!hostname_valid_char(*p))
3819 if (p-s > HOST_NAME_MAX)
3825 char* hostname_cleanup(char *s) {
3828 for (p = s, d = s; *p; p++)
3829 if ((*p >= 'a' && *p <= 'z') ||
3830 (*p >= 'A' && *p <= 'Z') ||
3831 (*p >= '0' && *p <= '9') ||
3839 strshorten(s, HOST_NAME_MAX);
3843 int pipe_eof(int fd) {
3844 struct pollfd pollfd;
3849 pollfd.events = POLLIN|POLLHUP;
3851 r = poll(&pollfd, 1, 0);
3858 return pollfd.revents & POLLHUP;
3861 int fd_wait_for_event(int fd, int event, usec_t t) {
3862 struct pollfd pollfd;
3867 pollfd.events = event;
3869 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3876 return pollfd.revents;
3879 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3890 t = new(char, strlen(path) + 1 + 6 + 1);
3894 fn = path_get_file_name(path);
3898 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3900 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3906 f = fdopen(fd, "we");
3919 int terminal_vhangup_fd(int fd) {
3922 if (ioctl(fd, TIOCVHANGUP) < 0)
3928 int terminal_vhangup(const char *name) {
3931 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3935 r = terminal_vhangup_fd(fd);
3936 close_nointr_nofail(fd);
3941 int vt_disallocate(const char *name) {
3945 /* Deallocate the VT if possible. If not possible
3946 * (i.e. because it is the active one), at least clear it
3947 * entirely (including the scrollback buffer) */
3949 if (!startswith(name, "/dev/"))
3952 if (!tty_is_vc(name)) {
3953 /* So this is not a VT. I guess we cannot deallocate
3954 * it then. But let's at least clear the screen */
3956 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3961 "\033[r" /* clear scrolling region */
3962 "\033[H" /* move home */
3963 "\033[2J", /* clear screen */
3965 close_nointr_nofail(fd);
3970 if (!startswith(name, "/dev/tty"))
3973 r = safe_atou(name+8, &u);
3980 /* Try to deallocate */
3981 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3985 r = ioctl(fd, VT_DISALLOCATE, u);
3986 close_nointr_nofail(fd);
3994 /* Couldn't deallocate, so let's clear it fully with
3996 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4001 "\033[r" /* clear scrolling region */
4002 "\033[H" /* move home */
4003 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4005 close_nointr_nofail(fd);
4010 int copy_file(const char *from, const char *to) {
4016 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4020 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4022 close_nointr_nofail(fdf);
4030 n = read(fdf, buf, sizeof(buf));
4034 close_nointr_nofail(fdf);
4045 k = loop_write(fdt, buf, n, false);
4047 r = k < 0 ? k : (errno ? -errno : -EIO);
4049 close_nointr_nofail(fdf);
4057 close_nointr_nofail(fdf);
4058 r = close_nointr(fdt);
4068 int symlink_atomic(const char *from, const char *to) {
4070 _cleanup_free_ char *t;
4073 unsigned long long ull;
4080 t = new(char, strlen(to) + 1 + 16 + 1);
4084 fn = path_get_file_name(to);
4088 x = stpcpy(t+k+1, fn);
4091 for (i = 0; i < 16; i++) {
4092 *(x++) = hexchar(ull & 0xF);
4098 if (symlink(from, t) < 0)
4101 if (rename(t, to) < 0) {
4110 bool display_is_local(const char *display) {
4114 display[0] == ':' &&
4115 display[1] >= '0' &&
4119 int socket_from_display(const char *display, char **path) {
4126 if (!display_is_local(display))
4129 k = strspn(display+1, "0123456789");
4131 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4135 c = stpcpy(f, "/tmp/.X11-unix/X");
4136 memcpy(c, display+1, k);
4145 const char **username,
4146 uid_t *uid, gid_t *gid,
4148 const char **shell) {
4156 /* We enforce some special rules for uid=0: in order to avoid
4157 * NSS lookups for root we hardcode its data. */
4159 if (streq(*username, "root") || streq(*username, "0")) {
4177 if (parse_uid(*username, &u) >= 0) {
4181 /* If there are multiple users with the same id, make
4182 * sure to leave $USER to the configured value instead
4183 * of the first occurrence in the database. However if
4184 * the uid was configured by a numeric uid, then let's
4185 * pick the real username from /etc/passwd. */
4187 *username = p->pw_name;
4190 p = getpwnam(*username);
4194 return errno > 0 ? -errno : -ESRCH;
4206 *shell = p->pw_shell;
4211 char* uid_to_name(uid_t uid) {
4216 return strdup("root");
4220 return strdup(p->pw_name);
4222 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4228 char* gid_to_name(gid_t gid) {
4233 return strdup("root");
4237 return strdup(p->gr_name);
4239 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4245 int get_group_creds(const char **groupname, gid_t *gid) {
4251 /* We enforce some special rules for gid=0: in order to avoid
4252 * NSS lookups for root we hardcode its data. */
4254 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4255 *groupname = "root";
4263 if (parse_gid(*groupname, &id) >= 0) {
4268 *groupname = g->gr_name;
4271 g = getgrnam(*groupname);
4275 return errno > 0 ? -errno : -ESRCH;
4283 int in_gid(gid_t gid) {
4285 int ngroups_max, r, i;
4287 if (getgid() == gid)
4290 if (getegid() == gid)
4293 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4294 assert(ngroups_max > 0);
4296 gids = alloca(sizeof(gid_t) * ngroups_max);
4298 r = getgroups(ngroups_max, gids);
4302 for (i = 0; i < r; i++)
4309 int in_group(const char *name) {
4313 r = get_group_creds(&name, &gid);
4320 int glob_exists(const char *path) {
4328 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4330 if (k == GLOB_NOMATCH)
4332 else if (k == GLOB_NOSPACE)
4335 r = !strv_isempty(g.gl_pathv);
4337 r = errno ? -errno : -EIO;
4344 int dirent_ensure_type(DIR *d, struct dirent *de) {
4350 if (de->d_type != DT_UNKNOWN)
4353 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4357 S_ISREG(st.st_mode) ? DT_REG :
4358 S_ISDIR(st.st_mode) ? DT_DIR :
4359 S_ISLNK(st.st_mode) ? DT_LNK :
4360 S_ISFIFO(st.st_mode) ? DT_FIFO :
4361 S_ISSOCK(st.st_mode) ? DT_SOCK :
4362 S_ISCHR(st.st_mode) ? DT_CHR :
4363 S_ISBLK(st.st_mode) ? DT_BLK :
4369 int in_search_path(const char *path, char **search) {
4373 r = path_get_parent(path, &parent);
4379 STRV_FOREACH(i, search) {
4380 if (path_equal(parent, *i)) {
4391 int get_files_in_directory(const char *path, char ***list) {
4399 /* Returns all files in a directory in *list, and the number
4400 * of files as return value. If list is NULL returns only the
4409 union dirent_storage buf;
4412 k = readdir_r(d, &buf.de, &de);
4421 dirent_ensure_type(d, de);
4423 if (!dirent_is_file(de))
4427 if ((unsigned) r >= n) {
4431 t = realloc(l, sizeof(char*) * n);
4440 assert((unsigned) r < n);
4442 l[r] = strdup(de->d_name);
4466 char *strjoin(const char *x, ...) {
4480 t = va_arg(ap, const char *);
4485 if (n > ((size_t) -1) - l) {
4509 t = va_arg(ap, const char *);
4523 bool is_main_thread(void) {
4524 static __thread int cached = 0;
4526 if (_unlikely_(cached == 0))
4527 cached = getpid() == gettid() ? 1 : -1;
4532 int block_get_whole_disk(dev_t d, dev_t *ret) {
4539 /* If it has a queue this is good enough for us */
4540 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4543 r = access(p, F_OK);
4551 /* If it is a partition find the originating device */
4552 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4555 r = access(p, F_OK);
4561 /* Get parent dev_t */
4562 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4565 r = read_one_line_file(p, &s);
4571 r = sscanf(s, "%u:%u", &m, &n);
4577 /* Only return this if it is really good enough for us. */
4578 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4581 r = access(p, F_OK);
4585 *ret = makedev(m, n);
4592 int file_is_priv_sticky(const char *p) {
4597 if (lstat(p, &st) < 0)
4601 (st.st_uid == 0 || st.st_uid == getuid()) &&
4602 (st.st_mode & S_ISVTX);
4605 static const char *const ioprio_class_table[] = {
4606 [IOPRIO_CLASS_NONE] = "none",
4607 [IOPRIO_CLASS_RT] = "realtime",
4608 [IOPRIO_CLASS_BE] = "best-effort",
4609 [IOPRIO_CLASS_IDLE] = "idle"
4612 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4614 static const char *const sigchld_code_table[] = {
4615 [CLD_EXITED] = "exited",
4616 [CLD_KILLED] = "killed",
4617 [CLD_DUMPED] = "dumped",
4618 [CLD_TRAPPED] = "trapped",
4619 [CLD_STOPPED] = "stopped",
4620 [CLD_CONTINUED] = "continued",
4623 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4625 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4626 [LOG_FAC(LOG_KERN)] = "kern",
4627 [LOG_FAC(LOG_USER)] = "user",
4628 [LOG_FAC(LOG_MAIL)] = "mail",
4629 [LOG_FAC(LOG_DAEMON)] = "daemon",
4630 [LOG_FAC(LOG_AUTH)] = "auth",
4631 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4632 [LOG_FAC(LOG_LPR)] = "lpr",
4633 [LOG_FAC(LOG_NEWS)] = "news",
4634 [LOG_FAC(LOG_UUCP)] = "uucp",
4635 [LOG_FAC(LOG_CRON)] = "cron",
4636 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4637 [LOG_FAC(LOG_FTP)] = "ftp",
4638 [LOG_FAC(LOG_LOCAL0)] = "local0",
4639 [LOG_FAC(LOG_LOCAL1)] = "local1",
4640 [LOG_FAC(LOG_LOCAL2)] = "local2",
4641 [LOG_FAC(LOG_LOCAL3)] = "local3",
4642 [LOG_FAC(LOG_LOCAL4)] = "local4",
4643 [LOG_FAC(LOG_LOCAL5)] = "local5",
4644 [LOG_FAC(LOG_LOCAL6)] = "local6",
4645 [LOG_FAC(LOG_LOCAL7)] = "local7"
4648 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4650 static const char *const log_level_table[] = {
4651 [LOG_EMERG] = "emerg",
4652 [LOG_ALERT] = "alert",
4653 [LOG_CRIT] = "crit",
4655 [LOG_WARNING] = "warning",
4656 [LOG_NOTICE] = "notice",
4657 [LOG_INFO] = "info",
4658 [LOG_DEBUG] = "debug"
4661 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4663 static const char* const sched_policy_table[] = {
4664 [SCHED_OTHER] = "other",
4665 [SCHED_BATCH] = "batch",
4666 [SCHED_IDLE] = "idle",
4667 [SCHED_FIFO] = "fifo",
4671 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4673 static const char* const rlimit_table[] = {
4674 [RLIMIT_CPU] = "LimitCPU",
4675 [RLIMIT_FSIZE] = "LimitFSIZE",
4676 [RLIMIT_DATA] = "LimitDATA",
4677 [RLIMIT_STACK] = "LimitSTACK",
4678 [RLIMIT_CORE] = "LimitCORE",
4679 [RLIMIT_RSS] = "LimitRSS",
4680 [RLIMIT_NOFILE] = "LimitNOFILE",
4681 [RLIMIT_AS] = "LimitAS",
4682 [RLIMIT_NPROC] = "LimitNPROC",
4683 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4684 [RLIMIT_LOCKS] = "LimitLOCKS",
4685 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4686 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4687 [RLIMIT_NICE] = "LimitNICE",
4688 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4689 [RLIMIT_RTTIME] = "LimitRTTIME"
4692 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4694 static const char* const ip_tos_table[] = {
4695 [IPTOS_LOWDELAY] = "low-delay",
4696 [IPTOS_THROUGHPUT] = "throughput",
4697 [IPTOS_RELIABILITY] = "reliability",
4698 [IPTOS_LOWCOST] = "low-cost",
4701 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4703 static const char *const __signal_table[] = {
4720 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4731 [SIGVTALRM] = "VTALRM",
4733 [SIGWINCH] = "WINCH",
4739 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4741 const char *signal_to_string(int signo) {
4742 static __thread char buf[12];
4745 name = __signal_to_string(signo);
4749 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4750 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4752 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4757 int signal_from_string(const char *s) {
4762 signo = __signal_from_string(s);
4766 if (startswith(s, "RTMIN+")) {
4770 if (safe_atou(s, &u) >= 0) {
4771 signo = (int) u + offset;
4772 if (signo > 0 && signo < _NSIG)
4778 bool kexec_loaded(void) {
4779 bool loaded = false;
4782 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4790 int strdup_or_null(const char *a, char **b) {
4808 int prot_from_flags(int flags) {
4810 switch (flags & O_ACCMODE) {
4819 return PROT_READ|PROT_WRITE;
4826 char *format_bytes(char *buf, size_t l, off_t t) {
4829 static const struct {
4833 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4834 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4835 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4836 { "G", 1024ULL*1024ULL*1024ULL },
4837 { "M", 1024ULL*1024ULL },
4841 for (i = 0; i < ELEMENTSOF(table); i++) {
4843 if (t >= table[i].factor) {
4846 (unsigned long long) (t / table[i].factor),
4847 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4854 snprintf(buf, l, "%lluB", (unsigned long long) t);
4862 void* memdup(const void *p, size_t l) {
4875 int fd_inc_sndbuf(int fd, size_t n) {
4877 socklen_t l = sizeof(value);
4879 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4881 l == sizeof(value) &&
4882 (size_t) value >= n*2)
4886 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4893 int fd_inc_rcvbuf(int fd, size_t n) {
4895 socklen_t l = sizeof(value);
4897 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4899 l == sizeof(value) &&
4900 (size_t) value >= n*2)
4904 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4911 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4912 pid_t parent_pid, agent_pid;
4914 bool stdout_is_tty, stderr_is_tty;
4922 parent_pid = getpid();
4924 /* Spawns a temporary TTY agent, making sure it goes away when
4931 if (agent_pid != 0) {
4938 * Make sure the agent goes away when the parent dies */
4939 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4940 _exit(EXIT_FAILURE);
4942 /* Check whether our parent died before we were able
4943 * to set the death signal */
4944 if (getppid() != parent_pid)
4945 _exit(EXIT_SUCCESS);
4947 /* Don't leak fds to the agent */
4948 close_all_fds(except, n_except);
4950 stdout_is_tty = isatty(STDOUT_FILENO);
4951 stderr_is_tty = isatty(STDERR_FILENO);
4953 if (!stdout_is_tty || !stderr_is_tty) {
4954 /* Detach from stdout/stderr. and reopen
4955 * /dev/tty for them. This is important to
4956 * ensure that when systemctl is started via
4957 * popen() or a similar call that expects to
4958 * read EOF we actually do generate EOF and
4959 * not delay this indefinitely by because we
4960 * keep an unused copy of stdin around. */
4961 fd = open("/dev/tty", O_WRONLY);
4963 log_error("Failed to open /dev/tty: %m");
4964 _exit(EXIT_FAILURE);
4968 dup2(fd, STDOUT_FILENO);
4971 dup2(fd, STDERR_FILENO);
4977 /* Count arguments */
4979 for (n = 0; va_arg(ap, char*); n++)
4984 l = alloca(sizeof(char *) * (n + 1));
4986 /* Fill in arguments */
4988 for (i = 0; i <= n; i++)
4989 l[i] = va_arg(ap, char*);
4993 _exit(EXIT_FAILURE);
4996 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4997 struct rlimit highest, fixed;
5001 if (setrlimit(resource, rlim) >= 0)
5007 /* So we failed to set the desired setrlimit, then let's try
5008 * to get as close as we can */
5009 assert_se(getrlimit(resource, &highest) == 0);
5011 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5012 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5014 if (setrlimit(resource, &fixed) < 0)
5020 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5021 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5033 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5036 f = fopen(path, "re");
5044 char line[LINE_MAX];
5047 for (i = 0; i < sizeof(line)-1; i++) {
5051 if (_unlikely_(c == EOF)) {
5061 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5062 value = strdup(line + l + 1);
5082 int can_sleep(const char *type) {
5086 _cleanup_free_ char *p = NULL;
5090 /* If /sys is read-only we cannot sleep */
5091 if (access("/sys/power/state", W_OK) < 0)
5094 r = read_one_line_file("/sys/power/state", &p);
5099 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5100 if (l == k && memcmp(w, type, l) == 0)
5106 int can_sleep_disk(const char *type) {
5110 _cleanup_free_ char *p = NULL;
5114 /* If /sys is read-only we cannot sleep */
5115 if (access("/sys/power/state", W_OK) < 0 ||
5116 access("/sys/power/disk", W_OK) < 0)
5119 r = read_one_line_file("/sys/power/disk", &p);
5124 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5125 if (l == k && memcmp(w, type, l) == 0)
5128 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[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 ? -errno : -ESRCH;
5257 if (!path_is_absolute(p->pw_dir))
5260 h = strdup(p->pw_dir);
5268 void fclosep(FILE **f) {
5273 void pclosep(FILE **f) {
5278 void closep(int *fd) {
5280 close_nointr_nofail(*fd);
5283 void closedirp(DIR **d) {
5288 bool filename_is_safe(const char *p) {
5302 if (strlen(p) > FILENAME_MAX)
5308 bool string_is_safe(const char *p) {
5313 for (t = p; *t; t++) {
5314 if (*t > 0 && *t < ' ')
5317 if (strchr("\\\"\'", *t))
5324 bool string_has_cc(const char *p) {
5329 for (t = p; *t; t++)
5330 if (*t > 0 && *t < ' ')
5336 bool path_is_safe(const char *p) {
5341 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5344 if (strlen(p) > PATH_MAX)
5347 /* The following two checks are not really dangerous, but hey, they still are confusing */
5348 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5351 if (strstr(p, "//"))
5357 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5358 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5359 int (*compar) (const void *, const void *, void *), void *arg) {
5368 p = (void *)(((const char *) base) + (idx * size));
5369 comparison = compar(key, p, arg);
5372 else if (comparison > 0)
5380 bool is_locale_utf8(void) {
5382 static int cached_answer = -1;
5384 if (cached_answer >= 0)
5387 if (!setlocale(LC_ALL, "")) {
5388 cached_answer = true;
5392 set = nl_langinfo(CODESET);
5394 cached_answer = true;
5398 cached_answer = streq(set, "UTF-8");
5400 return (bool)cached_answer;
5403 const char *draw_special_char(DrawSpecialChar ch) {
5404 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5406 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5407 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5408 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5409 [DRAW_TREE_SPACE] = " ", /* */
5410 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5412 /* ASCII fallback */ {
5413 [DRAW_TREE_VERT] = "| ",
5414 [DRAW_TREE_BRANCH] = "|-",
5415 [DRAW_TREE_RIGHT] = "`-",
5416 [DRAW_TREE_SPACE] = " ",
5417 [DRAW_TRIANGULAR_BULLET] = "> ",
5421 return draw_table[!is_locale_utf8()][ch];
5424 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5427 size_t l, old_len, new_len;
5433 old_len = strlen(old_string);
5434 new_len = strlen(new_string);
5447 if (!startswith(f, old_string)) {
5453 nl = l - old_len + new_len;
5454 a = realloc(r, nl + 1);
5462 t = stpcpy(t, new_string);
5474 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5475 const char *i, *begin = NULL;
5480 } state = STATE_OTHER;
5482 size_t osz = 0, isz;
5488 /* Strips ANSI color and replaces TABs by 8 spaces */
5490 isz = _isz ? *_isz : strlen(*ibuf);
5492 f = open_memstream(&obuf, &osz);
5496 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5501 if (i >= *ibuf + isz) /* EOT */
5503 else if (*i == '\x1B')
5504 state = STATE_ESCAPE;
5505 else if (*i == '\t')
5512 if (i >= *ibuf + isz) { /* EOT */
5515 } else if (*i == '[') {
5516 state = STATE_BRACKET;
5521 state = STATE_OTHER;
5528 if (i >= *ibuf + isz || /* EOT */
5529 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5532 state = STATE_OTHER;
5534 } else if (*i == 'm')
5535 state = STATE_OTHER;
5557 int on_ac_power(void) {
5558 bool found_offline = false, found_online = false;
5559 _cleanup_closedir_ DIR *d = NULL;
5561 d = opendir("/sys/class/power_supply");
5567 union dirent_storage buf;
5568 _cleanup_close_ int fd = -1, device = -1;
5573 k = readdir_r(d, &buf.de, &de);
5580 if (ignore_file(de->d_name))
5583 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5585 if (errno == ENOENT || errno == ENOTDIR)
5591 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5593 if (errno == ENOENT)
5599 n = read(fd, contents, sizeof(contents));
5603 if (n != 6 || memcmp(contents, "Mains\n", 6))
5606 close_nointr_nofail(fd);
5607 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5609 if (errno == ENOENT)
5615 n = read(fd, contents, sizeof(contents));
5619 if (n != 2 || contents[1] != '\n')
5622 if (contents[0] == '1') {
5623 found_online = true;
5625 } else if (contents[0] == '0')
5626 found_offline = true;
5631 return found_online || !found_offline;
5634 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5641 if (!path_strv_canonicalize_uniq(search))
5644 STRV_FOREACH(i, search) {
5645 _cleanup_free_ char *p = NULL;
5648 p = strjoin(*i, "/", path, NULL);
5658 if (errno != ENOENT)
5665 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5666 _cleanup_strv_free_ char **copy = NULL;
5672 if (path_is_absolute(path)) {
5675 f = fopen(path, mode);
5684 copy = strv_copy((char**) search);
5688 return search_and_fopen_internal(path, mode, copy, _f);
5691 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5692 _cleanup_strv_free_ char **s = NULL;
5694 if (path_is_absolute(path)) {
5697 f = fopen(path, mode);
5706 s = strv_split_nulstr(search);
5710 return search_and_fopen_internal(path, mode, s, _f);
5713 int create_tmp_dir(char template[], char** dir_name) {
5716 mode_t _cleanup_umask_ u;
5721 d = mkdtemp(template);
5723 log_error("Can't create directory %s: %m", template);
5727 dt = strjoin(d, "/tmp", NULL);
5734 r = mkdir(dt, 0777);
5736 log_error("Can't create directory %s: %m", dt);
5740 log_debug("Created temporary directory %s", dt);
5742 r = chmod(dt, 0777 | S_ISVTX);
5744 log_error("Failed to chmod %s: %m", dt);
5748 log_debug("Set sticky bit on %s", dt);
5762 char *strextend(char **x, ...) {
5769 l = f = *x ? strlen(*x) : 0;
5776 t = va_arg(ap, const char *);
5781 if (n > ((size_t) -1) - l) {
5790 r = realloc(*x, l+1);
5800 t = va_arg(ap, const char *);
5814 char *strrep(const char *s, unsigned n) {
5822 p = r = malloc(l * n + 1);
5826 for (i = 0; i < n; i++)