1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
49 #include <netinet/ip.h>
58 #include <linux/magic.h>
70 #include "path-util.h"
71 #include "exit-status.h"
77 char **saved_argv = NULL;
79 static volatile unsigned cached_columns = 0;
80 static volatile unsigned cached_lines = 0;
82 size_t page_size(void) {
83 static __thread size_t pgsz = 0;
86 if (_likely_(pgsz > 0))
89 r = sysconf(_SC_PAGESIZE);
96 bool streq_ptr(const char *a, const char *b) {
98 /* Like streq(), but tries to make sense of NULL pointers */
109 char* endswith(const char *s, const char *postfix) {
116 pl = strlen(postfix);
119 return (char*) s + sl;
124 if (memcmp(s + sl - pl, postfix, pl) != 0)
127 return (char*) s + sl - pl;
130 char* startswith(const char *s, const char *prefix) {
147 char* startswith_no_case(const char *s, const char *prefix) {
157 if (tolower(*a) != tolower(*b))
164 bool first_word(const char *s, const char *word) {
179 if (memcmp(s, word, wl) != 0)
183 strchr(WHITESPACE, s[wl]);
186 int close_nointr(int fd) {
192 /* Just ignore EINTR; a retry loop is the wrong
193 * thing to do on Linux.
195 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
196 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
197 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
198 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
200 if (_unlikely_(r < 0 && errno == EINTR))
208 void close_nointr_nofail(int fd) {
209 int saved_errno = errno;
211 /* like close_nointr() but cannot fail, and guarantees errno
214 assert_se(close_nointr(fd) == 0);
219 void close_many(const int fds[], unsigned n_fd) {
222 for (i = 0; i < n_fd; i++)
223 close_nointr_nofail(fds[i]);
226 int parse_boolean(const char *v) {
229 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
231 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
237 int parse_pid(const char *s, pid_t* ret_pid) {
238 unsigned long ul = 0;
245 r = safe_atolu(s, &ul);
251 if ((unsigned long) pid != ul)
261 int parse_uid(const char *s, uid_t* ret_uid) {
262 unsigned long ul = 0;
269 r = safe_atolu(s, &ul);
275 if ((unsigned long) uid != ul)
282 int safe_atou(const char *s, unsigned *ret_u) {
290 l = strtoul(s, &x, 0);
292 if (!x || x == s || *x || errno)
293 return errno ? -errno : -EINVAL;
295 if ((unsigned long) (unsigned) l != l)
298 *ret_u = (unsigned) l;
302 int safe_atoi(const char *s, int *ret_i) {
310 l = strtol(s, &x, 0);
312 if (!x || x == s || *x || errno)
313 return errno ? -errno : -EINVAL;
315 if ((long) (int) l != l)
322 int safe_atollu(const char *s, long long unsigned *ret_llu) {
324 unsigned long long l;
330 l = strtoull(s, &x, 0);
332 if (!x || x == s || *x || errno)
333 return errno ? -errno : -EINVAL;
339 int safe_atolli(const char *s, long long int *ret_lli) {
347 l = strtoll(s, &x, 0);
349 if (!x || x == s || *x || errno)
350 return errno ? -errno : -EINVAL;
356 int safe_atod(const char *s, double *ret_d) {
366 if (!x || x == s || *x || errno)
367 return errno ? -errno : -EINVAL;
373 /* Split a string into words. */
374 char *split(const char *c, size_t *l, const char *separator, char **state) {
377 current = *state ? *state : (char*) c;
379 if (!*current || *c == 0)
382 current += strspn(current, separator);
383 *l = strcspn(current, separator);
386 return (char*) current;
389 /* Split a string into words, but consider strings enclosed in '' and
390 * "" as words even if they include spaces. */
391 char *split_quoted(const char *c, size_t *l, char **state) {
393 bool escaped = false;
395 current = *state ? *state : (char*) c;
397 if (!*current || *c == 0)
400 current += strspn(current, WHITESPACE);
402 if (*current == '\'') {
405 for (e = current; *e; e++) {
415 *state = *e == 0 ? e : e+1;
416 } else if (*current == '\"') {
419 for (e = current; *e; e++) {
429 *state = *e == 0 ? e : e+1;
431 for (e = current; *e; e++) {
436 else if (strchr(WHITESPACE, *e))
443 return (char*) current;
446 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
448 _cleanup_fclose_ FILE *f = NULL;
449 char fn[PATH_MAX], line[LINE_MAX], *p;
455 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
462 if (!fgets(line, sizeof(line), f)) {
463 r = feof(f) ? -EIO : -errno;
467 /* Let's skip the pid and comm fields. The latter is enclosed
468 * in () but does not escape any () in its value, so let's
469 * skip over it manually */
471 p = strrchr(line, ')');
483 if ((long unsigned) (pid_t) ppid != ppid)
486 *_ppid = (pid_t) ppid;
491 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
492 _cleanup_fclose_ FILE *f = NULL;
493 char fn[PATH_MAX], line[LINE_MAX], *p;
498 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
505 if (!fgets(line, sizeof(line), f)) {
512 /* Let's skip the pid and comm fields. The latter is enclosed
513 * in () but does not escape any () in its value, so let's
514 * skip over it manually */
516 p = strrchr(line, ')');
538 "%*d " /* priority */
540 "%*d " /* num_threads */
541 "%*d " /* itrealvalue */
542 "%llu " /* starttime */,
549 int fchmod_umask(int fd, mode_t m) {
554 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
560 char *truncate_nl(char *s) {
563 s[strcspn(s, NEWLINE)] = 0;
567 int get_process_comm(pid_t pid, char **name) {
573 r = read_one_line_file("/proc/self/comm", name);
576 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
579 r = read_one_line_file(p, name);
586 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
594 f = fopen("/proc/self/cmdline", "re");
597 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
606 if (max_length == 0) {
608 while ((c = getc(f)) != EOF) {
609 k = realloc(r, len+1);
616 r[len-1] = isprint(c) ? c : ' ';
623 r = new(char, max_length);
631 while ((c = getc(f)) != EOF) {
653 size_t n = MIN(left-1, 3U);
662 /* Kernel threads have no argv[] */
663 if (r == NULL || r[0] == 0) {
672 h = get_process_comm(pid, &t);
676 r = strjoin("[", t, "]", NULL);
687 int is_kernel_thread(pid_t pid) {
697 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
706 count = fread(&c, 1, 1, f);
710 /* Kernel threads have an empty cmdline */
713 return eof ? 1 : -errno;
718 int get_process_exe(pid_t pid, char **name) {
724 r = readlink_malloc("/proc/self/exe", name);
727 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
730 r = readlink_malloc(p, name);
737 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
738 _cleanup_fclose_ FILE *f = NULL;
739 _cleanup_free_ char *p = NULL;
748 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
755 FOREACH_LINE(line, f, return -errno) {
760 if (startswith(l, field)) {
762 l += strspn(l, WHITESPACE);
764 l[strcspn(l, WHITESPACE)] = 0;
766 return parse_uid(l, uid);
773 int get_process_uid(pid_t pid, uid_t *uid) {
774 return get_process_id(pid, "Uid:", uid);
777 int get_process_gid(pid_t pid, gid_t *gid) {
778 return get_process_id(pid, "Gid:", gid);
781 char *strnappend(const char *s, const char *suffix, size_t b) {
789 return strndup(suffix, b);
798 if (b > ((size_t) -1) - a)
801 r = new(char, a+b+1);
806 memcpy(r+a, suffix, b);
812 char *strappend(const char *s, const char *suffix) {
813 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
816 int readlink_malloc(const char *p, char **r) {
826 if (!(c = new(char, l)))
829 if ((n = readlink(p, c, l-1)) < 0) {
835 if ((size_t) n < l-1) {
846 int readlink_and_make_absolute(const char *p, char **r) {
853 if ((j = readlink_malloc(p, &target)) < 0)
856 k = file_in_same_dir(p, target);
866 int readlink_and_canonicalize(const char *p, char **r) {
873 j = readlink_and_make_absolute(p, &t);
877 s = canonicalize_file_name(t);
884 path_kill_slashes(*r);
889 int reset_all_signal_handlers(void) {
892 for (sig = 1; sig < _NSIG; sig++) {
895 if (sig == SIGKILL || sig == SIGSTOP)
899 sa.sa_handler = SIG_DFL;
900 sa.sa_flags = SA_RESTART;
902 /* On Linux the first two RT signals are reserved by
903 * glibc, and sigaction() will return EINVAL for them. */
904 if ((sigaction(sig, &sa, NULL) < 0))
912 char *strstrip(char *s) {
915 /* Drops trailing whitespace. Modifies the string in
916 * place. Returns pointer to first non-space character */
918 s += strspn(s, WHITESPACE);
920 for (e = strchr(s, 0); e > s; e --)
921 if (!strchr(WHITESPACE, e[-1]))
929 char *delete_chars(char *s, const char *bad) {
932 /* Drops all whitespace, regardless where in the string */
934 for (f = s, t = s; *f; f++) {
946 bool in_charset(const char *s, const char* charset) {
953 if (!strchr(charset, *i))
959 char *file_in_same_dir(const char *path, const char *filename) {
966 /* This removes the last component of path and appends
967 * filename, unless the latter is absolute anyway or the
970 if (path_is_absolute(filename))
971 return strdup(filename);
973 if (!(e = strrchr(path, '/')))
974 return strdup(filename);
976 k = strlen(filename);
977 if (!(r = new(char, e-path+1+k+1)))
980 memcpy(r, path, e-path+1);
981 memcpy(r+(e-path)+1, filename, k+1);
986 int rmdir_parents(const char *path, const char *stop) {
995 /* Skip trailing slashes */
996 while (l > 0 && path[l-1] == '/')
1002 /* Skip last component */
1003 while (l > 0 && path[l-1] != '/')
1006 /* Skip trailing slashes */
1007 while (l > 0 && path[l-1] == '/')
1013 if (!(t = strndup(path, l)))
1016 if (path_startswith(stop, t)) {
1025 if (errno != ENOENT)
1033 char hexchar(int x) {
1034 static const char table[16] = "0123456789abcdef";
1036 return table[x & 15];
1039 int unhexchar(char c) {
1041 if (c >= '0' && c <= '9')
1044 if (c >= 'a' && c <= 'f')
1045 return c - 'a' + 10;
1047 if (c >= 'A' && c <= 'F')
1048 return c - 'A' + 10;
1053 char octchar(int x) {
1054 return '0' + (x & 7);
1057 int unoctchar(char c) {
1059 if (c >= '0' && c <= '7')
1065 char decchar(int x) {
1066 return '0' + (x % 10);
1069 int undecchar(char c) {
1071 if (c >= '0' && c <= '9')
1077 char *cescape(const char *s) {
1083 /* Does C style string escaping. */
1085 r = new(char, strlen(s)*4 + 1);
1089 for (f = s, t = r; *f; f++)
1135 /* For special chars we prefer octal over
1136 * hexadecimal encoding, simply because glib's
1137 * g_strescape() does the same */
1138 if ((*f < ' ') || (*f >= 127)) {
1140 *(t++) = octchar((unsigned char) *f >> 6);
1141 *(t++) = octchar((unsigned char) *f >> 3);
1142 *(t++) = octchar((unsigned char) *f);
1153 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1160 /* Undoes C style string escaping, and optionally prefixes it. */
1162 pl = prefix ? strlen(prefix) : 0;
1164 r = new(char, pl+length+1);
1169 memcpy(r, prefix, pl);
1171 for (f = s, t = r + pl; f < s + length; f++) {
1214 /* This is an extension of the XDG syntax files */
1219 /* hexadecimal encoding */
1222 a = unhexchar(f[1]);
1223 b = unhexchar(f[2]);
1225 if (a < 0 || b < 0) {
1226 /* Invalid escape code, let's take it literal then */
1230 *(t++) = (char) ((a << 4) | b);
1245 /* octal encoding */
1248 a = unoctchar(f[0]);
1249 b = unoctchar(f[1]);
1250 c = unoctchar(f[2]);
1252 if (a < 0 || b < 0 || c < 0) {
1253 /* Invalid escape code, let's take it literal then */
1257 *(t++) = (char) ((a << 6) | (b << 3) | c);
1265 /* premature end of string.*/
1270 /* Invalid escape code, let's take it literal then */
1282 char *cunescape_length(const char *s, size_t length) {
1283 return cunescape_length_with_prefix(s, length, NULL);
1286 char *cunescape(const char *s) {
1289 return cunescape_length(s, strlen(s));
1292 char *xescape(const char *s, const char *bad) {
1296 /* Escapes all chars in bad, in addition to \ and all special
1297 * chars, in \xFF style escaping. May be reversed with
1300 r = new(char, strlen(s) * 4 + 1);
1304 for (f = s, t = r; *f; f++) {
1306 if ((*f < ' ') || (*f >= 127) ||
1307 (*f == '\\') || strchr(bad, *f)) {
1310 *(t++) = hexchar(*f >> 4);
1311 *(t++) = hexchar(*f);
1321 char *bus_path_escape(const char *s) {
1327 /* Escapes all chars that D-Bus' object path cannot deal
1328 * with. Can be reverse with bus_path_unescape(). We special
1329 * case the empty string. */
1334 r = new(char, strlen(s)*3 + 1);
1338 for (f = s, t = r; *f; f++) {
1340 /* Escape everything that is not a-zA-Z0-9. We also
1341 * escape 0-9 if it's the first character */
1343 if (!(*f >= 'A' && *f <= 'Z') &&
1344 !(*f >= 'a' && *f <= 'z') &&
1345 !(f > s && *f >= '0' && *f <= '9')) {
1347 *(t++) = hexchar(*f >> 4);
1348 *(t++) = hexchar(*f);
1358 char *bus_path_unescape(const char *f) {
1363 /* Special case for the empty string */
1367 r = new(char, strlen(f) + 1);
1371 for (t = r; *f; f++) {
1376 if ((a = unhexchar(f[1])) < 0 ||
1377 (b = unhexchar(f[2])) < 0) {
1378 /* Invalid escape code, let's take it literal then */
1381 *(t++) = (char) ((a << 4) | b);
1393 char *ascii_strlower(char *t) {
1398 for (p = t; *p; p++)
1399 if (*p >= 'A' && *p <= 'Z')
1400 *p = *p - 'A' + 'a';
1405 static bool ignore_file_allow_backup(const char *filename) {
1409 filename[0] == '.' ||
1410 streq(filename, "lost+found") ||
1411 streq(filename, "aquota.user") ||
1412 streq(filename, "aquota.group") ||
1413 endswith(filename, ".rpmnew") ||
1414 endswith(filename, ".rpmsave") ||
1415 endswith(filename, ".rpmorig") ||
1416 endswith(filename, ".dpkg-old") ||
1417 endswith(filename, ".dpkg-new") ||
1418 endswith(filename, ".swp");
1421 bool ignore_file(const char *filename) {
1424 if (endswith(filename, "~"))
1427 return ignore_file_allow_backup(filename);
1430 int fd_nonblock(int fd, bool nonblock) {
1435 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1439 flags |= O_NONBLOCK;
1441 flags &= ~O_NONBLOCK;
1443 if (fcntl(fd, F_SETFL, flags) < 0)
1449 int fd_cloexec(int fd, bool cloexec) {
1454 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1458 flags |= FD_CLOEXEC;
1460 flags &= ~FD_CLOEXEC;
1462 if (fcntl(fd, F_SETFD, flags) < 0)
1468 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1471 assert(n_fdset == 0 || fdset);
1473 for (i = 0; i < n_fdset; i++)
1480 int close_all_fds(const int except[], unsigned n_except) {
1485 assert(n_except == 0 || except);
1487 d = opendir("/proc/self/fd");
1492 /* When /proc isn't available (for example in chroots)
1493 * the fallback is brute forcing through the fd
1496 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1497 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1499 if (fd_in_set(fd, except, n_except))
1502 if (close_nointr(fd) < 0)
1503 if (errno != EBADF && r == 0)
1510 while ((de = readdir(d))) {
1513 if (ignore_file(de->d_name))
1516 if (safe_atoi(de->d_name, &fd) < 0)
1517 /* Let's better ignore this, just in case */
1526 if (fd_in_set(fd, except, n_except))
1529 if (close_nointr(fd) < 0) {
1530 /* Valgrind has its own FD and doesn't want to have it closed */
1531 if (errno != EBADF && r == 0)
1540 bool chars_intersect(const char *a, const char *b) {
1543 /* Returns true if any of the chars in a are in b. */
1544 for (p = a; *p; p++)
1551 bool fstype_is_network(const char *fstype) {
1552 static const char table[] =
1561 return nulstr_contains(table, fstype);
1565 _cleanup_close_ int fd;
1567 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1573 TIOCL_GETKMSGREDIRECT,
1577 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1580 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1583 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1589 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1590 struct termios old_termios, new_termios;
1592 char line[LINE_MAX];
1597 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1598 new_termios = old_termios;
1600 new_termios.c_lflag &= ~ICANON;
1601 new_termios.c_cc[VMIN] = 1;
1602 new_termios.c_cc[VTIME] = 0;
1604 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1607 if (t != (usec_t) -1) {
1608 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1609 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1614 k = fread(&c, 1, 1, f);
1616 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1622 *need_nl = c != '\n';
1629 if (t != (usec_t) -1)
1630 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1633 if (!fgets(line, sizeof(line), f))
1638 if (strlen(line) != 1)
1648 int ask(char *ret, const char *replies, const char *text, ...) {
1658 bool need_nl = true;
1661 fputs(ANSI_HIGHLIGHT_ON, stdout);
1668 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1672 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1675 if (r == -EBADMSG) {
1676 puts("Bad input, please try again.");
1687 if (strchr(replies, c)) {
1692 puts("Read unexpected character, please try again.");
1696 int reset_terminal_fd(int fd, bool switch_to_text) {
1697 struct termios termios;
1700 /* Set terminal to some sane defaults */
1704 /* We leave locked terminal attributes untouched, so that
1705 * Plymouth may set whatever it wants to set, and we don't
1706 * interfere with that. */
1708 /* Disable exclusive mode, just in case */
1709 ioctl(fd, TIOCNXCL);
1711 /* Switch to text mode */
1713 ioctl(fd, KDSETMODE, KD_TEXT);
1715 /* Enable console unicode mode */
1716 ioctl(fd, KDSKBMODE, K_UNICODE);
1718 if (tcgetattr(fd, &termios) < 0) {
1723 /* We only reset the stuff that matters to the software. How
1724 * hardware is set up we don't touch assuming that somebody
1725 * else will do that for us */
1727 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1728 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1729 termios.c_oflag |= ONLCR;
1730 termios.c_cflag |= CREAD;
1731 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1733 termios.c_cc[VINTR] = 03; /* ^C */
1734 termios.c_cc[VQUIT] = 034; /* ^\ */
1735 termios.c_cc[VERASE] = 0177;
1736 termios.c_cc[VKILL] = 025; /* ^X */
1737 termios.c_cc[VEOF] = 04; /* ^D */
1738 termios.c_cc[VSTART] = 021; /* ^Q */
1739 termios.c_cc[VSTOP] = 023; /* ^S */
1740 termios.c_cc[VSUSP] = 032; /* ^Z */
1741 termios.c_cc[VLNEXT] = 026; /* ^V */
1742 termios.c_cc[VWERASE] = 027; /* ^W */
1743 termios.c_cc[VREPRINT] = 022; /* ^R */
1744 termios.c_cc[VEOL] = 0;
1745 termios.c_cc[VEOL2] = 0;
1747 termios.c_cc[VTIME] = 0;
1748 termios.c_cc[VMIN] = 1;
1750 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1754 /* Just in case, flush all crap out */
1755 tcflush(fd, TCIOFLUSH);
1760 int reset_terminal(const char *name) {
1763 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1767 r = reset_terminal_fd(fd, true);
1768 close_nointr_nofail(fd);
1773 int open_terminal(const char *name, int mode) {
1778 * If a TTY is in the process of being closed opening it might
1779 * cause EIO. This is horribly awful, but unlikely to be
1780 * changed in the kernel. Hence we work around this problem by
1781 * retrying a couple of times.
1783 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1787 fd = open(name, mode);
1794 /* Max 1s in total */
1798 usleep(50 * USEC_PER_MSEC);
1807 close_nointr_nofail(fd);
1812 close_nointr_nofail(fd);
1819 int flush_fd(int fd) {
1820 struct pollfd pollfd;
1824 pollfd.events = POLLIN;
1831 if ((r = poll(&pollfd, 1, 0)) < 0) {
1842 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1847 if (errno == EAGAIN)
1858 int acquire_terminal(
1862 bool ignore_tiocstty_eperm,
1865 int fd = -1, notify = -1, r = 0, wd = -1;
1867 struct sigaction sa_old, sa_new;
1871 /* We use inotify to be notified when the tty is closed. We
1872 * create the watch before checking if we can actually acquire
1873 * it, so that we don't lose any event.
1875 * Note: strictly speaking this actually watches for the
1876 * device being closed, it does *not* really watch whether a
1877 * tty loses its controlling process. However, unless some
1878 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1879 * its tty otherwise this will not become a problem. As long
1880 * as the administrator makes sure not configure any service
1881 * on the same tty as an untrusted user this should not be a
1882 * problem. (Which he probably should not do anyway.) */
1884 if (timeout != (usec_t) -1)
1885 ts = now(CLOCK_MONOTONIC);
1887 if (!fail && !force) {
1888 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1894 wd = inotify_add_watch(notify, name, IN_CLOSE);
1903 r = flush_fd(notify);
1908 /* We pass here O_NOCTTY only so that we can check the return
1909 * value TIOCSCTTY and have a reliable way to figure out if we
1910 * successfully became the controlling process of the tty */
1911 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1915 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1916 * if we already own the tty. */
1918 sa_new.sa_handler = SIG_IGN;
1919 sa_new.sa_flags = SA_RESTART;
1920 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1922 /* First, try to get the tty */
1923 if (ioctl(fd, TIOCSCTTY, force) < 0)
1926 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1928 /* Sometimes it makes sense to ignore TIOCSCTTY
1929 * returning EPERM, i.e. when very likely we already
1930 * are have this controlling terminal. */
1931 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1934 if (r < 0 && (force || fail || r != -EPERM)) {
1943 assert(notify >= 0);
1946 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1948 struct inotify_event *e;
1950 if (timeout != (usec_t) -1) {
1953 n = now(CLOCK_MONOTONIC);
1954 if (ts + timeout < n) {
1959 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1969 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1972 if (errno == EINTR || errno == EAGAIN)
1979 e = (struct inotify_event*) inotify_buffer;
1984 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1989 step = sizeof(struct inotify_event) + e->len;
1990 assert(step <= (size_t) l);
1992 e = (struct inotify_event*) ((uint8_t*) e + step);
1999 /* We close the tty fd here since if the old session
2000 * ended our handle will be dead. It's important that
2001 * we do this after sleeping, so that we don't enter
2002 * an endless loop. */
2003 close_nointr_nofail(fd);
2007 close_nointr_nofail(notify);
2009 r = reset_terminal_fd(fd, true);
2011 log_warning("Failed to reset terminal: %s", strerror(-r));
2017 close_nointr_nofail(fd);
2020 close_nointr_nofail(notify);
2025 int release_terminal(void) {
2027 struct sigaction sa_old, sa_new;
2029 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2032 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2033 * by our own TIOCNOTTY */
2036 sa_new.sa_handler = SIG_IGN;
2037 sa_new.sa_flags = SA_RESTART;
2038 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2040 if (ioctl(fd, TIOCNOTTY) < 0)
2043 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2045 close_nointr_nofail(fd);
2049 int sigaction_many(const struct sigaction *sa, ...) {
2054 while ((sig = va_arg(ap, int)) > 0)
2055 if (sigaction(sig, sa, NULL) < 0)
2062 int ignore_signals(int sig, ...) {
2063 struct sigaction sa;
2068 sa.sa_handler = SIG_IGN;
2069 sa.sa_flags = SA_RESTART;
2071 if (sigaction(sig, &sa, NULL) < 0)
2075 while ((sig = va_arg(ap, int)) > 0)
2076 if (sigaction(sig, &sa, NULL) < 0)
2083 int default_signals(int sig, ...) {
2084 struct sigaction sa;
2089 sa.sa_handler = SIG_DFL;
2090 sa.sa_flags = SA_RESTART;
2092 if (sigaction(sig, &sa, NULL) < 0)
2096 while ((sig = va_arg(ap, int)) > 0)
2097 if (sigaction(sig, &sa, NULL) < 0)
2104 int close_pipe(int p[]) {
2110 a = close_nointr(p[0]);
2115 b = close_nointr(p[1]);
2119 return a < 0 ? a : b;
2122 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2131 while (nbytes > 0) {
2134 if ((k = read(fd, p, nbytes)) <= 0) {
2136 if (k < 0 && errno == EINTR)
2139 if (k < 0 && errno == EAGAIN && do_poll) {
2140 struct pollfd pollfd;
2144 pollfd.events = POLLIN;
2146 if (poll(&pollfd, 1, -1) < 0) {
2150 return n > 0 ? n : -errno;
2153 if (pollfd.revents != POLLIN)
2154 return n > 0 ? n : -EIO;
2159 return n > 0 ? n : (k < 0 ? -errno : 0);
2170 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2179 while (nbytes > 0) {
2182 k = write(fd, p, nbytes);
2185 if (k < 0 && errno == EINTR)
2188 if (k < 0 && errno == EAGAIN && do_poll) {
2189 struct pollfd pollfd;
2193 pollfd.events = POLLOUT;
2195 if (poll(&pollfd, 1, -1) < 0) {
2199 return n > 0 ? n : -errno;
2202 if (pollfd.revents != POLLOUT)
2203 return n > 0 ? n : -EIO;
2208 return n > 0 ? n : (k < 0 ? -errno : 0);
2219 int parse_bytes(const char *t, off_t *bytes) {
2220 static const struct {
2226 { "M", 1024ULL*1024ULL },
2227 { "G", 1024ULL*1024ULL*1024ULL },
2228 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2229 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2230 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2247 l = strtoll(p, &e, 10);
2258 e += strspn(e, WHITESPACE);
2260 for (i = 0; i < ELEMENTSOF(table); i++)
2261 if (startswith(e, table[i].suffix)) {
2262 r += (off_t) l * table[i].factor;
2263 p = e + strlen(table[i].suffix);
2267 if (i >= ELEMENTSOF(table))
2277 int make_stdio(int fd) {
2282 r = dup3(fd, STDIN_FILENO, 0);
2283 s = dup3(fd, STDOUT_FILENO, 0);
2284 t = dup3(fd, STDERR_FILENO, 0);
2287 close_nointr_nofail(fd);
2289 if (r < 0 || s < 0 || t < 0)
2292 /* We rely here that the new fd has O_CLOEXEC not set */
2297 int make_null_stdio(void) {
2300 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2304 return make_stdio(null_fd);
2307 bool is_device_path(const char *path) {
2309 /* Returns true on paths that refer to a device, either in
2310 * sysfs or in /dev */
2313 path_startswith(path, "/dev/") ||
2314 path_startswith(path, "/sys/");
2317 int dir_is_empty(const char *path) {
2318 _cleanup_closedir_ DIR *d;
2327 union dirent_storage buf;
2329 r = readdir_r(d, &buf.de, &de);
2336 if (!ignore_file(de->d_name))
2341 unsigned long long random_ull(void) {
2342 _cleanup_close_ int fd;
2346 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2350 r = loop_read(fd, &ull, sizeof(ull), true);
2351 if (r != sizeof(ull))
2357 return random() * RAND_MAX + random();
2360 void rename_process(const char name[8]) {
2363 /* This is a like a poor man's setproctitle(). It changes the
2364 * comm field, argv[0], and also the glibc's internally used
2365 * name of the process. For the first one a limit of 16 chars
2366 * applies, to the second one usually one of 10 (i.e. length
2367 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2368 * "systemd"). If you pass a longer string it will be
2371 prctl(PR_SET_NAME, name);
2373 if (program_invocation_name)
2374 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2376 if (saved_argc > 0) {
2380 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2382 for (i = 1; i < saved_argc; i++) {
2386 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2391 void sigset_add_many(sigset_t *ss, ...) {
2398 while ((sig = va_arg(ap, int)) > 0)
2399 assert_se(sigaddset(ss, sig) == 0);
2403 char* gethostname_malloc(void) {
2406 assert_se(uname(&u) >= 0);
2408 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2409 return strdup(u.nodename);
2411 return strdup(u.sysname);
2414 bool hostname_is_set(void) {
2417 assert_se(uname(&u) >= 0);
2419 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2422 static char *lookup_uid(uid_t uid) {
2425 _cleanup_free_ char *buf = NULL;
2426 struct passwd pwbuf, *pw = NULL;
2428 /* Shortcut things to avoid NSS lookups */
2430 return strdup("root");
2432 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2436 buf = malloc(bufsize);
2440 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2441 return strdup(pw->pw_name);
2443 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2449 char* getlogname_malloc(void) {
2453 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2458 return lookup_uid(uid);
2461 char *getusername_malloc(void) {
2468 return lookup_uid(getuid());
2471 int getttyname_malloc(int fd, char **r) {
2472 char path[PATH_MAX], *c;
2477 k = ttyname_r(fd, path, sizeof(path));
2483 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2491 int getttyname_harder(int fd, char **r) {
2495 k = getttyname_malloc(fd, &s);
2499 if (streq(s, "tty")) {
2501 return get_ctty(0, NULL, r);
2508 int get_ctty_devnr(pid_t pid, dev_t *d) {
2510 char line[LINE_MAX], *p, *fn;
2511 unsigned long ttynr;
2514 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2517 f = fopen(fn, "re");
2522 if (!fgets(line, sizeof(line), f)) {
2523 k = feof(f) ? -EIO : -errno;
2530 p = strrchr(line, ')');
2540 "%*d " /* session */
2545 if (major(ttynr) == 0 && minor(ttynr) == 0)
2552 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2554 char fn[PATH_MAX], *s, *b, *p;
2559 k = get_ctty_devnr(pid, &devnr);
2563 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2566 k = readlink_malloc(fn, &s);
2572 /* This is an ugly hack */
2573 if (major(devnr) == 136) {
2574 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2584 /* Probably something like the ptys which have no
2585 * symlink in /dev/char. Let's return something
2586 * vaguely useful. */
2599 if (startswith(s, "/dev/"))
2601 else if (startswith(s, "../"))
2619 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2625 /* This returns the first error we run into, but nevertheless
2626 * tries to go on. This closes the passed fd. */
2630 close_nointr_nofail(fd);
2632 return errno == ENOENT ? 0 : -errno;
2637 union dirent_storage buf;
2638 bool is_dir, keep_around;
2642 r = readdir_r(d, &buf.de, &de);
2643 if (r != 0 && ret == 0) {
2651 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2654 if (de->d_type == DT_UNKNOWN ||
2656 (de->d_type == DT_DIR && root_dev)) {
2657 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2658 if (ret == 0 && errno != ENOENT)
2663 is_dir = S_ISDIR(st.st_mode);
2666 (st.st_uid == 0 || st.st_uid == getuid()) &&
2667 (st.st_mode & S_ISVTX);
2669 is_dir = de->d_type == DT_DIR;
2670 keep_around = false;
2676 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2677 if (root_dev && st.st_dev != root_dev->st_dev)
2680 subdir_fd = openat(fd, de->d_name,
2681 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2682 if (subdir_fd < 0) {
2683 if (ret == 0 && errno != ENOENT)
2688 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2689 if (r < 0 && ret == 0)
2693 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2694 if (ret == 0 && errno != ENOENT)
2698 } else if (!only_dirs && !keep_around) {
2700 if (unlinkat(fd, de->d_name, 0) < 0) {
2701 if (ret == 0 && errno != ENOENT)
2712 static int is_temporary_fs(struct statfs *s) {
2714 return s->f_type == TMPFS_MAGIC ||
2715 (long)s->f_type == (long)RAMFS_MAGIC;
2718 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2723 if (fstatfs(fd, &s) < 0) {
2724 close_nointr_nofail(fd);
2728 /* We refuse to clean disk file systems with this call. This
2729 * is extra paranoia just to be sure we never ever remove
2731 if (!is_temporary_fs(&s)) {
2732 log_error("Attempted to remove disk file system, and we can't allow that.");
2733 close_nointr_nofail(fd);
2737 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2740 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2746 /* We refuse to clean the root file system with this
2747 * call. This is extra paranoia to never cause a really
2748 * seriously broken system. */
2749 if (path_equal(path, "/")) {
2750 log_error("Attempted to remove entire root file system, and we can't allow that.");
2754 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2757 if (errno != ENOTDIR)
2761 if (statfs(path, &s) < 0)
2764 if (!is_temporary_fs(&s)) {
2765 log_error("Attempted to remove disk file system, and we can't allow that.");
2770 if (delete_root && !only_dirs)
2771 if (unlink(path) < 0 && errno != ENOENT)
2778 if (fstatfs(fd, &s) < 0) {
2779 close_nointr_nofail(fd);
2783 if (!is_temporary_fs(&s)) {
2784 log_error("Attempted to remove disk file system, and we can't allow that.");
2785 close_nointr_nofail(fd);
2790 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2793 if (honour_sticky && file_is_priv_sticky(path) > 0)
2796 if (rmdir(path) < 0 && errno != ENOENT) {
2805 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2806 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2809 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2810 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2813 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2816 /* Under the assumption that we are running privileged we
2817 * first change the access mode and only then hand out
2818 * ownership to avoid a window where access is too open. */
2820 if (mode != (mode_t) -1)
2821 if (chmod(path, mode) < 0)
2824 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2825 if (chown(path, uid, gid) < 0)
2831 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2834 /* Under the assumption that we are running privileged we
2835 * first change the access mode and only then hand out
2836 * ownership to avoid a window where access is too open. */
2838 if (fchmod(fd, mode) < 0)
2841 if (fchown(fd, uid, gid) < 0)
2847 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2851 /* Allocates the cpuset in the right size */
2854 if (!(r = CPU_ALLOC(n)))
2857 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2858 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2868 if (errno != EINVAL)
2875 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2876 static const char status_indent[] = " "; /* "[" STATUS "] " */
2877 _cleanup_free_ char *s = NULL;
2878 _cleanup_close_ int fd = -1;
2879 struct iovec iovec[6];
2881 static bool prev_ephemeral;
2885 /* This is independent of logging, as status messages are
2886 * optional and go exclusively to the console. */
2888 if (vasprintf(&s, format, ap) < 0)
2891 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2904 sl = status ? sizeof(status_indent)-1 : 0;
2910 e = ellipsize(s, emax, 75);
2920 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2921 prev_ephemeral = ephemeral;
2924 if (!isempty(status)) {
2925 IOVEC_SET_STRING(iovec[n++], "[");
2926 IOVEC_SET_STRING(iovec[n++], status);
2927 IOVEC_SET_STRING(iovec[n++], "] ");
2929 IOVEC_SET_STRING(iovec[n++], status_indent);
2932 IOVEC_SET_STRING(iovec[n++], s);
2934 IOVEC_SET_STRING(iovec[n++], "\n");
2936 if (writev(fd, iovec, n) < 0)
2942 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2948 va_start(ap, format);
2949 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2955 int status_welcome(void) {
2957 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2959 r = parse_env_file("/etc/os-release", NEWLINE,
2960 "PRETTY_NAME", &pretty_name,
2961 "ANSI_COLOR", &ansi_color,
2963 if (r < 0 && r != -ENOENT)
2964 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2966 return status_printf(NULL, false,
2967 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2968 isempty(ansi_color) ? "1" : ansi_color,
2969 isempty(pretty_name) ? "Linux" : pretty_name);
2972 char *replace_env(const char *format, char **env) {
2979 const char *e, *word = format;
2984 for (e = format; *e; e ++) {
2995 if (!(k = strnappend(r, word, e-word-1)))
3004 } else if (*e == '$') {
3005 if (!(k = strnappend(r, word, e-word)))
3021 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3023 k = strappend(r, t);
3037 if (!(k = strnappend(r, word, e-word)))
3048 char **replace_env_argv(char **argv, char **env) {
3050 unsigned k = 0, l = 0;
3052 l = strv_length(argv);
3054 if (!(r = new(char*, l+1)))
3057 STRV_FOREACH(i, argv) {
3059 /* If $FOO appears as single word, replace it by the split up variable */
3060 if ((*i)[0] == '$' && (*i)[1] != '{') {
3065 e = strv_env_get(env, *i+1);
3068 if (!(m = strv_split_quoted(e))) {
3079 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3088 memcpy(r + k, m, q * sizeof(char*));
3096 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3097 if (!(r[k++] = replace_env(*i, env))) {
3107 int fd_columns(int fd) {
3111 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3120 unsigned columns(void) {
3124 if (_likely_(cached_columns > 0))
3125 return cached_columns;
3128 e = getenv("COLUMNS");
3133 c = fd_columns(STDOUT_FILENO);
3142 int fd_lines(int fd) {
3146 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3155 unsigned lines(void) {
3159 if (_likely_(cached_lines > 0))
3160 return cached_lines;
3163 e = getenv("LINES");
3168 l = fd_lines(STDOUT_FILENO);
3174 return cached_lines;
3177 /* intended to be used as a SIGWINCH sighandler */
3178 void columns_lines_cache_reset(int signum) {
3184 static int cached_on_tty = -1;
3186 if (_unlikely_(cached_on_tty < 0))
3187 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3189 return cached_on_tty;
3192 int running_in_chroot(void) {
3198 /* Only works as root */
3200 if (stat("/proc/1/root", &a) < 0)
3203 if (stat("/", &b) < 0)
3207 a.st_dev != b.st_dev ||
3208 a.st_ino != b.st_ino;
3211 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3216 assert(percent <= 100);
3217 assert(new_length >= 3);
3219 if (old_length <= 3 || old_length <= new_length)
3220 return strndup(s, old_length);
3222 r = new0(char, new_length+1);
3226 x = (new_length * percent) / 100;
3228 if (x > new_length - 3)
3236 s + old_length - (new_length - x - 3),
3237 new_length - x - 3);
3242 char *ellipsize(const char *s, size_t length, unsigned percent) {
3243 return ellipsize_mem(s, strlen(s), length, percent);
3246 int touch(const char *path) {
3251 /* This just opens the file for writing, ensuring it
3252 * exists. It doesn't call utimensat() the way /usr/bin/touch
3255 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3259 close_nointr_nofail(fd);
3263 char *unquote(const char *s, const char* quotes) {
3267 /* This is rather stupid, simply removes the heading and
3268 * trailing quotes if there is one. Doesn't care about
3269 * escaping or anything. We should make this smarter one
3276 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3277 return strndup(s+1, l-2);
3282 char *normalize_env_assignment(const char *s) {
3283 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3286 eq = strchr(s, '=');
3298 memmove(r, t, strlen(t) + 1);
3302 name = strndup(s, eq - s);
3310 value = unquote(strstrip(p), QUOTES);
3314 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3320 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3331 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3343 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3350 r = wait_for_terminate(pid, &status);
3352 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3356 if (status.si_code == CLD_EXITED) {
3357 if (status.si_status != 0) {
3358 log_warning("%s failed with error code %i.", name, status.si_status);
3359 return status.si_status;
3362 log_debug("%s succeeded.", name);
3365 } else if (status.si_code == CLD_KILLED ||
3366 status.si_code == CLD_DUMPED) {
3368 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3372 log_warning("%s failed due to unknown reason.", name);
3376 _noreturn_ void freeze(void) {
3378 /* Make sure nobody waits for us on a socket anymore */
3379 close_all_fds(NULL, 0);
3387 bool null_or_empty(struct stat *st) {
3390 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3393 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3399 int null_or_empty_path(const char *fn) {
3404 if (stat(fn, &st) < 0)
3407 return null_or_empty(&st);
3410 DIR *xopendirat(int fd, const char *name, int flags) {
3414 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3420 close_nointr_nofail(nfd);
3427 int signal_from_string_try_harder(const char *s) {
3431 signo = signal_from_string(s);
3433 if (startswith(s, "SIG"))
3434 return signal_from_string(s+3);
3439 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3443 /* FIXME: to follow udev's logic 100% we need to leave valid
3444 * UTF8 chars unescaped */
3446 u = unquote(tagvalue, "\"\'");
3450 t = xescape(u, "/ ");
3456 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3465 char *fstab_node_to_udev_node(const char *p) {
3468 if (startswith(p, "LABEL="))
3469 return tag_to_udev_node(p+6, "label");
3471 if (startswith(p, "UUID="))
3472 return tag_to_udev_node(p+5, "uuid");
3474 if (startswith(p, "PARTUUID="))
3475 return tag_to_udev_node(p+9, "partuuid");
3477 if (startswith(p, "PARTLABEL="))
3478 return tag_to_udev_node(p+10, "partlabel");
3483 bool tty_is_vc(const char *tty) {
3486 if (startswith(tty, "/dev/"))
3489 return vtnr_from_tty(tty) >= 0;
3492 bool tty_is_console(const char *tty) {
3495 if (startswith(tty, "/dev/"))
3498 return streq(tty, "console");
3501 int vtnr_from_tty(const char *tty) {
3506 if (startswith(tty, "/dev/"))
3509 if (!startswith(tty, "tty") )
3512 if (tty[3] < '0' || tty[3] > '9')
3515 r = safe_atoi(tty+3, &i);
3519 if (i < 0 || i > 63)
3525 char *resolve_dev_console(char **active) {
3528 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3529 * (i.e. not read-only-mounted which is a sign for container setups) */
3531 if (path_is_read_only_fs("/sys") > 0)
3534 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3537 /* If multiple log outputs are configured the last one is what
3538 * /dev/console points to */
3539 tty = strrchr(*active, ' ');
3548 bool tty_is_vc_resolve(const char *tty) {
3549 char *active = NULL;
3554 if (startswith(tty, "/dev/"))
3557 if (streq(tty, "console")) {
3558 tty = resolve_dev_console(&active);
3569 const char *default_term_for_tty(const char *tty) {
3572 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3575 bool dirent_is_file(const struct dirent *de) {
3578 if (ignore_file(de->d_name))
3581 if (de->d_type != DT_REG &&
3582 de->d_type != DT_LNK &&
3583 de->d_type != DT_UNKNOWN)
3589 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3592 if (de->d_type != DT_REG &&
3593 de->d_type != DT_LNK &&
3594 de->d_type != DT_UNKNOWN)
3597 if (ignore_file_allow_backup(de->d_name))
3600 return endswith(de->d_name, suffix);
3603 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3606 Hashmap *pids = NULL;
3610 /* Executes all binaries in a directory in parallel and waits
3611 * until all they all finished. */
3614 if (!(_d = opendir(directory))) {
3616 if (errno == ENOENT)
3619 log_error("Failed to enumerate directory %s: %m", directory);
3626 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3627 log_error("Failed to allocate set.");
3631 while ((de = readdir(d))) {
3636 if (!dirent_is_file(de))
3639 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3644 if ((pid = fork()) < 0) {
3645 log_error("Failed to fork: %m");
3663 log_error("Failed to execute %s: %m", path);
3664 _exit(EXIT_FAILURE);
3667 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3669 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3670 log_error("Failed to add PID to set: %s", strerror(-k));
3675 while (!hashmap_isempty(pids)) {
3676 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3681 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3686 log_error("waitid() failed: %m");
3690 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3691 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3692 if (si.si_code == CLD_EXITED)
3693 log_error("%s exited with exit status %i.", path, si.si_status);
3695 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3697 log_debug("%s exited successfully.", path);
3708 hashmap_free_free(pids);
3711 int kill_and_sigcont(pid_t pid, int sig) {
3714 r = kill(pid, sig) < 0 ? -errno : 0;
3722 bool nulstr_contains(const char*nulstr, const char *needle) {
3728 NULSTR_FOREACH(i, nulstr)
3729 if (streq(i, needle))
3735 bool plymouth_running(void) {
3736 return access("/run/plymouth/pid", F_OK) >= 0;
3739 char* strshorten(char *s, size_t l) {
3748 static bool hostname_valid_char(char c) {
3750 (c >= 'a' && c <= 'z') ||
3751 (c >= 'A' && c <= 'Z') ||
3752 (c >= '0' && c <= '9') ||
3758 bool hostname_is_valid(const char *s) {
3764 for (p = s; *p; p++)
3765 if (!hostname_valid_char(*p))
3768 if (p-s > HOST_NAME_MAX)
3774 char* hostname_cleanup(char *s) {
3777 for (p = s, d = s; *p; p++)
3778 if ((*p >= 'a' && *p <= 'z') ||
3779 (*p >= 'A' && *p <= 'Z') ||
3780 (*p >= '0' && *p <= '9') ||
3788 strshorten(s, HOST_NAME_MAX);
3792 int pipe_eof(int fd) {
3793 struct pollfd pollfd;
3798 pollfd.events = POLLIN|POLLHUP;
3800 r = poll(&pollfd, 1, 0);
3807 return pollfd.revents & POLLHUP;
3810 int fd_wait_for_event(int fd, int event, usec_t t) {
3811 struct pollfd pollfd;
3816 pollfd.events = event;
3818 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3825 return pollfd.revents;
3828 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3839 t = new(char, strlen(path) + 1 + 6 + 1);
3843 fn = path_get_file_name(path);
3847 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3849 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3855 f = fdopen(fd, "we");
3868 int terminal_vhangup_fd(int fd) {
3871 if (ioctl(fd, TIOCVHANGUP) < 0)
3877 int terminal_vhangup(const char *name) {
3880 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3884 r = terminal_vhangup_fd(fd);
3885 close_nointr_nofail(fd);
3890 int vt_disallocate(const char *name) {
3894 /* Deallocate the VT if possible. If not possible
3895 * (i.e. because it is the active one), at least clear it
3896 * entirely (including the scrollback buffer) */
3898 if (!startswith(name, "/dev/"))
3901 if (!tty_is_vc(name)) {
3902 /* So this is not a VT. I guess we cannot deallocate
3903 * it then. But let's at least clear the screen */
3905 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3910 "\033[r" /* clear scrolling region */
3911 "\033[H" /* move home */
3912 "\033[2J", /* clear screen */
3914 close_nointr_nofail(fd);
3919 if (!startswith(name, "/dev/tty"))
3922 r = safe_atou(name+8, &u);
3929 /* Try to deallocate */
3930 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3934 r = ioctl(fd, VT_DISALLOCATE, u);
3935 close_nointr_nofail(fd);
3943 /* Couldn't deallocate, so let's clear it fully with
3945 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3950 "\033[r" /* clear scrolling region */
3951 "\033[H" /* move home */
3952 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3954 close_nointr_nofail(fd);
3959 int copy_file(const char *from, const char *to) {
3965 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
3969 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
3971 close_nointr_nofail(fdf);
3979 n = read(fdf, buf, sizeof(buf));
3983 close_nointr_nofail(fdf);
3994 k = loop_write(fdt, buf, n, false);
3996 r = k < 0 ? k : (errno ? -errno : -EIO);
3998 close_nointr_nofail(fdf);
4006 close_nointr_nofail(fdf);
4007 r = close_nointr(fdt);
4017 int symlink_atomic(const char *from, const char *to) {
4019 _cleanup_free_ char *t;
4022 unsigned long long ull;
4029 t = new(char, strlen(to) + 1 + 16 + 1);
4033 fn = path_get_file_name(to);
4037 x = stpcpy(t+k+1, fn);
4040 for (i = 0; i < 16; i++) {
4041 *(x++) = hexchar(ull & 0xF);
4047 if (symlink(from, t) < 0)
4050 if (rename(t, to) < 0) {
4059 bool display_is_local(const char *display) {
4063 display[0] == ':' &&
4064 display[1] >= '0' &&
4068 int socket_from_display(const char *display, char **path) {
4075 if (!display_is_local(display))
4078 k = strspn(display+1, "0123456789");
4080 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4084 c = stpcpy(f, "/tmp/.X11-unix/X");
4085 memcpy(c, display+1, k);
4094 const char **username,
4095 uid_t *uid, gid_t *gid,
4097 const char **shell) {
4105 /* We enforce some special rules for uid=0: in order to avoid
4106 * NSS lookups for root we hardcode its data. */
4108 if (streq(*username, "root") || streq(*username, "0")) {
4126 if (parse_uid(*username, &u) >= 0) {
4130 /* If there are multiple users with the same id, make
4131 * sure to leave $USER to the configured value instead
4132 * of the first occurrence in the database. However if
4133 * the uid was configured by a numeric uid, then let's
4134 * pick the real username from /etc/passwd. */
4136 *username = p->pw_name;
4139 p = getpwnam(*username);
4143 return errno != 0 ? -errno : -ESRCH;
4155 *shell = p->pw_shell;
4160 char* uid_to_name(uid_t uid) {
4165 return strdup("root");
4169 return strdup(p->pw_name);
4171 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4177 int get_group_creds(const char **groupname, gid_t *gid) {
4183 /* We enforce some special rules for gid=0: in order to avoid
4184 * NSS lookups for root we hardcode its data. */
4186 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4187 *groupname = "root";
4195 if (parse_gid(*groupname, &id) >= 0) {
4200 *groupname = g->gr_name;
4203 g = getgrnam(*groupname);
4207 return errno != 0 ? -errno : -ESRCH;
4215 int in_group(const char *name) {
4217 int ngroups_max, r, i;
4219 r = get_group_creds(&name, &gid);
4223 if (getgid() == gid)
4226 if (getegid() == gid)
4229 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4230 assert(ngroups_max > 0);
4232 gids = alloca(sizeof(gid_t) * ngroups_max);
4234 r = getgroups(ngroups_max, gids);
4238 for (i = 0; i < r; i++)
4245 int glob_exists(const char *path) {
4253 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4255 if (k == GLOB_NOMATCH)
4257 else if (k == GLOB_NOSPACE)
4260 r = !strv_isempty(g.gl_pathv);
4262 r = errno ? -errno : -EIO;
4269 int dirent_ensure_type(DIR *d, struct dirent *de) {
4275 if (de->d_type != DT_UNKNOWN)
4278 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4282 S_ISREG(st.st_mode) ? DT_REG :
4283 S_ISDIR(st.st_mode) ? DT_DIR :
4284 S_ISLNK(st.st_mode) ? DT_LNK :
4285 S_ISFIFO(st.st_mode) ? DT_FIFO :
4286 S_ISSOCK(st.st_mode) ? DT_SOCK :
4287 S_ISCHR(st.st_mode) ? DT_CHR :
4288 S_ISBLK(st.st_mode) ? DT_BLK :
4294 int in_search_path(const char *path, char **search) {
4298 r = path_get_parent(path, &parent);
4304 STRV_FOREACH(i, search) {
4305 if (path_equal(parent, *i)) {
4316 int get_files_in_directory(const char *path, char ***list) {
4324 /* Returns all files in a directory in *list, and the number
4325 * of files as return value. If list is NULL returns only the
4334 union dirent_storage buf;
4337 k = readdir_r(d, &buf.de, &de);
4346 dirent_ensure_type(d, de);
4348 if (!dirent_is_file(de))
4352 if ((unsigned) r >= n) {
4356 t = realloc(l, sizeof(char*) * n);
4365 assert((unsigned) r < n);
4367 l[r] = strdup(de->d_name);
4391 char *strjoin(const char *x, ...) {
4405 t = va_arg(ap, const char *);
4410 if (n > ((size_t) -1) - l) {
4434 t = va_arg(ap, const char *);
4448 bool is_main_thread(void) {
4449 static __thread int cached = 0;
4451 if (_unlikely_(cached == 0))
4452 cached = getpid() == gettid() ? 1 : -1;
4457 int block_get_whole_disk(dev_t d, dev_t *ret) {
4464 /* If it has a queue this is good enough for us */
4465 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4468 r = access(p, F_OK);
4476 /* If it is a partition find the originating device */
4477 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4480 r = access(p, F_OK);
4486 /* Get parent dev_t */
4487 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4490 r = read_one_line_file(p, &s);
4496 r = sscanf(s, "%u:%u", &m, &n);
4502 /* Only return this if it is really good enough for us. */
4503 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4506 r = access(p, F_OK);
4510 *ret = makedev(m, n);
4517 int file_is_priv_sticky(const char *p) {
4522 if (lstat(p, &st) < 0)
4526 (st.st_uid == 0 || st.st_uid == getuid()) &&
4527 (st.st_mode & S_ISVTX);
4530 static const char *const ioprio_class_table[] = {
4531 [IOPRIO_CLASS_NONE] = "none",
4532 [IOPRIO_CLASS_RT] = "realtime",
4533 [IOPRIO_CLASS_BE] = "best-effort",
4534 [IOPRIO_CLASS_IDLE] = "idle"
4537 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4539 static const char *const sigchld_code_table[] = {
4540 [CLD_EXITED] = "exited",
4541 [CLD_KILLED] = "killed",
4542 [CLD_DUMPED] = "dumped",
4543 [CLD_TRAPPED] = "trapped",
4544 [CLD_STOPPED] = "stopped",
4545 [CLD_CONTINUED] = "continued",
4548 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4550 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4551 [LOG_FAC(LOG_KERN)] = "kern",
4552 [LOG_FAC(LOG_USER)] = "user",
4553 [LOG_FAC(LOG_MAIL)] = "mail",
4554 [LOG_FAC(LOG_DAEMON)] = "daemon",
4555 [LOG_FAC(LOG_AUTH)] = "auth",
4556 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4557 [LOG_FAC(LOG_LPR)] = "lpr",
4558 [LOG_FAC(LOG_NEWS)] = "news",
4559 [LOG_FAC(LOG_UUCP)] = "uucp",
4560 [LOG_FAC(LOG_CRON)] = "cron",
4561 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4562 [LOG_FAC(LOG_FTP)] = "ftp",
4563 [LOG_FAC(LOG_LOCAL0)] = "local0",
4564 [LOG_FAC(LOG_LOCAL1)] = "local1",
4565 [LOG_FAC(LOG_LOCAL2)] = "local2",
4566 [LOG_FAC(LOG_LOCAL3)] = "local3",
4567 [LOG_FAC(LOG_LOCAL4)] = "local4",
4568 [LOG_FAC(LOG_LOCAL5)] = "local5",
4569 [LOG_FAC(LOG_LOCAL6)] = "local6",
4570 [LOG_FAC(LOG_LOCAL7)] = "local7"
4573 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4575 static const char *const log_level_table[] = {
4576 [LOG_EMERG] = "emerg",
4577 [LOG_ALERT] = "alert",
4578 [LOG_CRIT] = "crit",
4580 [LOG_WARNING] = "warning",
4581 [LOG_NOTICE] = "notice",
4582 [LOG_INFO] = "info",
4583 [LOG_DEBUG] = "debug"
4586 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4588 static const char* const sched_policy_table[] = {
4589 [SCHED_OTHER] = "other",
4590 [SCHED_BATCH] = "batch",
4591 [SCHED_IDLE] = "idle",
4592 [SCHED_FIFO] = "fifo",
4596 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4598 static const char* const rlimit_table[] = {
4599 [RLIMIT_CPU] = "LimitCPU",
4600 [RLIMIT_FSIZE] = "LimitFSIZE",
4601 [RLIMIT_DATA] = "LimitDATA",
4602 [RLIMIT_STACK] = "LimitSTACK",
4603 [RLIMIT_CORE] = "LimitCORE",
4604 [RLIMIT_RSS] = "LimitRSS",
4605 [RLIMIT_NOFILE] = "LimitNOFILE",
4606 [RLIMIT_AS] = "LimitAS",
4607 [RLIMIT_NPROC] = "LimitNPROC",
4608 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4609 [RLIMIT_LOCKS] = "LimitLOCKS",
4610 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4611 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4612 [RLIMIT_NICE] = "LimitNICE",
4613 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4614 [RLIMIT_RTTIME] = "LimitRTTIME"
4617 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4619 static const char* const ip_tos_table[] = {
4620 [IPTOS_LOWDELAY] = "low-delay",
4621 [IPTOS_THROUGHPUT] = "throughput",
4622 [IPTOS_RELIABILITY] = "reliability",
4623 [IPTOS_LOWCOST] = "low-cost",
4626 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4628 static const char *const __signal_table[] = {
4645 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4656 [SIGVTALRM] = "VTALRM",
4658 [SIGWINCH] = "WINCH",
4664 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4666 const char *signal_to_string(int signo) {
4667 static __thread char buf[12];
4670 name = __signal_to_string(signo);
4674 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4675 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4677 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4682 int signal_from_string(const char *s) {
4687 signo = __signal_from_string(s);
4691 if (startswith(s, "RTMIN+")) {
4695 if (safe_atou(s, &u) >= 0) {
4696 signo = (int) u + offset;
4697 if (signo > 0 && signo < _NSIG)
4703 bool kexec_loaded(void) {
4704 bool loaded = false;
4707 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4715 int strdup_or_null(const char *a, char **b) {
4733 int prot_from_flags(int flags) {
4735 switch (flags & O_ACCMODE) {
4744 return PROT_READ|PROT_WRITE;
4751 char *format_bytes(char *buf, size_t l, off_t t) {
4754 static const struct {
4758 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4759 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4760 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4761 { "G", 1024ULL*1024ULL*1024ULL },
4762 { "M", 1024ULL*1024ULL },
4766 for (i = 0; i < ELEMENTSOF(table); i++) {
4768 if (t >= table[i].factor) {
4771 (unsigned long long) (t / table[i].factor),
4772 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4779 snprintf(buf, l, "%lluB", (unsigned long long) t);
4787 void* memdup(const void *p, size_t l) {
4800 int fd_inc_sndbuf(int fd, size_t n) {
4802 socklen_t l = sizeof(value);
4804 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4806 l == sizeof(value) &&
4807 (size_t) value >= n*2)
4811 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4818 int fd_inc_rcvbuf(int fd, size_t n) {
4820 socklen_t l = sizeof(value);
4822 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4824 l == sizeof(value) &&
4825 (size_t) value >= n*2)
4829 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4836 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4837 pid_t parent_pid, agent_pid;
4839 bool stdout_is_tty, stderr_is_tty;
4847 parent_pid = getpid();
4849 /* Spawns a temporary TTY agent, making sure it goes away when
4856 if (agent_pid != 0) {
4863 * Make sure the agent goes away when the parent dies */
4864 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4865 _exit(EXIT_FAILURE);
4867 /* Check whether our parent died before we were able
4868 * to set the death signal */
4869 if (getppid() != parent_pid)
4870 _exit(EXIT_SUCCESS);
4872 /* Don't leak fds to the agent */
4873 close_all_fds(except, n_except);
4875 stdout_is_tty = isatty(STDOUT_FILENO);
4876 stderr_is_tty = isatty(STDERR_FILENO);
4878 if (!stdout_is_tty || !stderr_is_tty) {
4879 /* Detach from stdout/stderr. and reopen
4880 * /dev/tty for them. This is important to
4881 * ensure that when systemctl is started via
4882 * popen() or a similar call that expects to
4883 * read EOF we actually do generate EOF and
4884 * not delay this indefinitely by because we
4885 * keep an unused copy of stdin around. */
4886 fd = open("/dev/tty", O_WRONLY);
4888 log_error("Failed to open /dev/tty: %m");
4889 _exit(EXIT_FAILURE);
4893 dup2(fd, STDOUT_FILENO);
4896 dup2(fd, STDERR_FILENO);
4902 /* Count arguments */
4904 for (n = 0; va_arg(ap, char*); n++)
4909 l = alloca(sizeof(char *) * (n + 1));
4911 /* Fill in arguments */
4913 for (i = 0; i <= n; i++)
4914 l[i] = va_arg(ap, char*);
4918 _exit(EXIT_FAILURE);
4921 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4922 struct rlimit highest, fixed;
4926 if (setrlimit(resource, rlim) >= 0)
4932 /* So we failed to set the desired setrlimit, then let's try
4933 * to get as close as we can */
4934 assert_se(getrlimit(resource, &highest) == 0);
4936 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4937 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4939 if (setrlimit(resource, &fixed) < 0)
4945 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
4946 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
4958 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
4961 f = fopen(path, "re");
4969 char line[LINE_MAX];
4972 for (i = 0; i < sizeof(line)-1; i++) {
4976 if (_unlikely_(c == EOF)) {
4986 if (memcmp(line, field, l) == 0 && line[l] == '=') {
4987 value = strdup(line + l + 1);
5007 int can_sleep(const char *type) {
5011 _cleanup_free_ char *p = NULL;
5015 /* If /sys is read-only we cannot sleep */
5016 if (access("/sys/power/state", W_OK) < 0)
5019 r = read_one_line_file("/sys/power/state", &p);
5024 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5025 if (l == k && memcmp(w, type, l) == 0)
5031 int can_sleep_disk(const char *type) {
5035 _cleanup_free_ char *p = NULL;
5039 /* If /sys is read-only we cannot sleep */
5040 if (access("/sys/power/state", W_OK) < 0 ||
5041 access("/sys/power/disk", W_OK) < 0)
5044 r = read_one_line_file("/sys/power/disk", &p);
5049 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5050 if (l == k && memcmp(w, type, l) == 0)
5053 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5060 bool is_valid_documentation_url(const char *url) {
5063 if (startswith(url, "http://") && url[7])
5066 if (startswith(url, "https://") && url[8])
5069 if (startswith(url, "file:") && url[5])
5072 if (startswith(url, "info:") && url[5])
5075 if (startswith(url, "man:") && url[4])
5081 bool in_initrd(void) {
5082 static __thread int saved = -1;
5088 /* We make two checks here:
5090 * 1. the flag file /etc/initrd-release must exist
5091 * 2. the root file system must be a memory file system
5093 * The second check is extra paranoia, since misdetecting an
5094 * initrd can have bad bad consequences due the initrd
5095 * emptying when transititioning to the main systemd.
5098 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5099 statfs("/", &s) >= 0 &&
5100 is_temporary_fs(&s);
5105 void warn_melody(void) {
5106 _cleanup_close_ int fd = -1;
5108 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5112 /* Yeah, this is synchronous. Kinda sucks. But well... */
5114 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5115 usleep(125*USEC_PER_MSEC);
5117 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5118 usleep(125*USEC_PER_MSEC);
5120 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5121 usleep(125*USEC_PER_MSEC);
5123 ioctl(fd, KIOCSOUND, 0);
5126 int make_console_stdio(void) {
5129 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5131 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5133 log_error("Failed to acquire terminal: %s", strerror(-fd));
5139 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5146 int get_home_dir(char **_h) {
5154 /* Take the user specified one */
5165 /* Hardcode home directory for root to avoid NSS */
5168 h = strdup("/root");
5176 /* Check the database... */
5180 return errno ? -errno : -ESRCH;
5182 if (!path_is_absolute(p->pw_dir))
5185 h = strdup(p->pw_dir);
5193 int get_shell(char **_sh) {
5201 /* Take the user specified one */
5202 e = getenv("SHELL");
5212 /* Hardcode home directory for root to avoid NSS */
5215 sh = strdup("/bin/sh");
5223 /* Check the database... */
5227 return errno ? -errno : -ESRCH;
5229 if (!path_is_absolute(p->pw_shell))
5232 sh = strdup(p->pw_shell);
5240 void freep(void *p) {
5244 void fclosep(FILE **f) {
5249 void pclosep(FILE **f) {
5254 void closep(int *fd) {
5256 close_nointr_nofail(*fd);
5259 void closedirp(DIR **d) {
5264 void umaskp(mode_t *u) {
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))
5304 bool string_has_cc(const char *p) {
5309 for (t = p; *t; t++)
5310 if (*t > 0 && *t < ' ')
5316 bool path_is_safe(const char *p) {
5321 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5324 if (strlen(p) > PATH_MAX)
5327 /* The following two checks are not really dangerous, but hey, they still are confusing */
5328 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5331 if (strstr(p, "//"))
5337 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5338 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5339 int (*compar) (const void *, const void *, void *), void *arg) {
5348 p = (void *)(((const char *) base) + (idx * size));
5349 comparison = compar(key, p, arg);
5352 else if (comparison > 0)
5360 bool is_locale_utf8(void) {
5362 static int cached_answer = -1;
5364 if (cached_answer >= 0)
5367 if (!setlocale(LC_ALL, "")) {
5368 cached_answer = true;
5372 set = nl_langinfo(CODESET);
5374 cached_answer = true;
5378 cached_answer = streq(set, "UTF-8");
5380 return (bool)cached_answer;
5383 const char *draw_special_char(DrawSpecialChar ch) {
5384 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5386 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5387 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5388 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5389 [DRAW_TREE_SPACE] = " ", /* */
5390 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5392 /* ASCII fallback */ {
5393 [DRAW_TREE_VERT] = "| ",
5394 [DRAW_TREE_BRANCH] = "|-",
5395 [DRAW_TREE_RIGHT] = "`-",
5396 [DRAW_TREE_SPACE] = " ",
5397 [DRAW_TRIANGULAR_BULLET] = "> ",
5401 return draw_table[!is_locale_utf8()][ch];
5404 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5407 size_t l, old_len, new_len;
5413 old_len = strlen(old_string);
5414 new_len = strlen(new_string);
5427 if (!startswith(f, old_string)) {
5433 nl = l - old_len + new_len;
5434 a = realloc(r, nl + 1);
5442 t = stpcpy(t, new_string);
5454 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5455 const char *i, *begin = NULL;
5460 } state = STATE_OTHER;
5462 size_t osz = 0, isz;
5468 /* Strips ANSI color and replaces TABs by 8 spaces */
5470 isz = _isz ? *_isz : strlen(*ibuf);
5472 f = open_memstream(&obuf, &osz);
5476 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5481 if (i >= *ibuf + isz) /* EOT */
5483 else if (*i == '\x1B')
5484 state = STATE_ESCAPE;
5485 else if (*i == '\t')
5492 if (i >= *ibuf + isz) { /* EOT */
5495 } else if (*i == '[') {
5496 state = STATE_BRACKET;
5501 state = STATE_OTHER;
5508 if (i >= *ibuf + isz || /* EOT */
5509 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5512 state = STATE_OTHER;
5514 } else if (*i == 'm')
5515 state = STATE_OTHER;
5537 int on_ac_power(void) {
5538 bool found_offline = false, found_online = false;
5539 _cleanup_closedir_ DIR *d = NULL;
5541 d = opendir("/sys/class/power_supply");
5547 union dirent_storage buf;
5548 _cleanup_free_ char *p = NULL;
5549 _cleanup_close_ int fd = -1, device = -1;
5554 k = readdir_r(d, &buf.de, &de);
5561 if (ignore_file(de->d_name))
5564 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5566 if (errno == ENOENT || errno == ENOTDIR)
5572 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5574 if (errno == ENOENT)
5580 n = read(fd, contents, sizeof(contents));
5584 if (n != 6 || memcmp(contents, "Mains\n", 6))
5587 close_nointr_nofail(fd);
5588 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5590 if (errno == ENOENT)
5596 n = read(fd, contents, sizeof(contents));
5600 if (n != 2 || contents[1] != '\n')
5603 if (contents[0] == '1') {
5604 found_online = true;
5606 } else if (contents[0] == '0')
5607 found_offline = true;
5612 return found_online || !found_offline;
5615 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5622 if (!path_strv_canonicalize_uniq(search))
5625 STRV_FOREACH(i, search) {
5626 _cleanup_free_ char *p = NULL;
5629 p = strjoin(*i, "/", path, NULL);
5639 if (errno != ENOENT)
5646 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5647 _cleanup_strv_free_ char **copy = NULL;
5653 if (path_is_absolute(path)) {
5656 f = fopen(path, mode);
5665 copy = strv_copy((char**) search);
5669 return search_and_fopen_internal(path, mode, copy, _f);
5672 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5673 _cleanup_strv_free_ char **s = NULL;
5675 if (path_is_absolute(path)) {
5678 f = fopen(path, mode);
5687 s = strv_split_nulstr(search);
5691 return search_and_fopen_internal(path, mode, s, _f);