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 > 0 ? -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 > 0 ? -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)
1032 char hexchar(int x) {
1033 static const char table[16] = "0123456789abcdef";
1035 return table[x & 15];
1038 int unhexchar(char c) {
1040 if (c >= '0' && c <= '9')
1043 if (c >= 'a' && c <= 'f')
1044 return c - 'a' + 10;
1046 if (c >= 'A' && c <= 'F')
1047 return c - 'A' + 10;
1052 char *hexmem(const void *p, size_t l) {
1056 z = r = malloc(l * 2 + 1);
1060 for (x = p; x < (const uint8_t*) p + l; x++) {
1061 *(z++) = hexchar(*x >> 4);
1062 *(z++) = hexchar(*x & 15);
1069 char octchar(int x) {
1070 return '0' + (x & 7);
1073 int unoctchar(char c) {
1075 if (c >= '0' && c <= '7')
1081 char decchar(int x) {
1082 return '0' + (x % 10);
1085 int undecchar(char c) {
1087 if (c >= '0' && c <= '9')
1093 char *cescape(const char *s) {
1099 /* Does C style string escaping. */
1101 r = new(char, strlen(s)*4 + 1);
1105 for (f = s, t = r; *f; f++)
1151 /* For special chars we prefer octal over
1152 * hexadecimal encoding, simply because glib's
1153 * g_strescape() does the same */
1154 if ((*f < ' ') || (*f >= 127)) {
1156 *(t++) = octchar((unsigned char) *f >> 6);
1157 *(t++) = octchar((unsigned char) *f >> 3);
1158 *(t++) = octchar((unsigned char) *f);
1169 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1176 /* Undoes C style string escaping, and optionally prefixes it. */
1178 pl = prefix ? strlen(prefix) : 0;
1180 r = new(char, pl+length+1);
1185 memcpy(r, prefix, pl);
1187 for (f = s, t = r + pl; f < s + length; f++) {
1230 /* This is an extension of the XDG syntax files */
1235 /* hexadecimal encoding */
1238 a = unhexchar(f[1]);
1239 b = unhexchar(f[2]);
1241 if (a < 0 || b < 0) {
1242 /* Invalid escape code, let's take it literal then */
1246 *(t++) = (char) ((a << 4) | b);
1261 /* octal encoding */
1264 a = unoctchar(f[0]);
1265 b = unoctchar(f[1]);
1266 c = unoctchar(f[2]);
1268 if (a < 0 || b < 0 || c < 0) {
1269 /* Invalid escape code, let's take it literal then */
1273 *(t++) = (char) ((a << 6) | (b << 3) | c);
1281 /* premature end of string.*/
1286 /* Invalid escape code, let's take it literal then */
1298 char *cunescape_length(const char *s, size_t length) {
1299 return cunescape_length_with_prefix(s, length, NULL);
1302 char *cunescape(const char *s) {
1305 return cunescape_length(s, strlen(s));
1308 char *xescape(const char *s, const char *bad) {
1312 /* Escapes all chars in bad, in addition to \ and all special
1313 * chars, in \xFF style escaping. May be reversed with
1316 r = new(char, strlen(s) * 4 + 1);
1320 for (f = s, t = r; *f; f++) {
1322 if ((*f < ' ') || (*f >= 127) ||
1323 (*f == '\\') || strchr(bad, *f)) {
1326 *(t++) = hexchar(*f >> 4);
1327 *(t++) = hexchar(*f);
1337 char *bus_path_escape(const char *s) {
1343 /* Escapes all chars that D-Bus' object path cannot deal
1344 * with. Can be reverse with bus_path_unescape(). We special
1345 * case the empty string. */
1350 r = new(char, strlen(s)*3 + 1);
1354 for (f = s, t = r; *f; f++) {
1356 /* Escape everything that is not a-zA-Z0-9. We also
1357 * escape 0-9 if it's the first character */
1359 if (!(*f >= 'A' && *f <= 'Z') &&
1360 !(*f >= 'a' && *f <= 'z') &&
1361 !(f > s && *f >= '0' && *f <= '9')) {
1363 *(t++) = hexchar(*f >> 4);
1364 *(t++) = hexchar(*f);
1374 char *bus_path_unescape(const char *f) {
1379 /* Special case for the empty string */
1383 r = new(char, strlen(f) + 1);
1387 for (t = r; *f; f++) {
1392 if ((a = unhexchar(f[1])) < 0 ||
1393 (b = unhexchar(f[2])) < 0) {
1394 /* Invalid escape code, let's take it literal then */
1397 *(t++) = (char) ((a << 4) | b);
1409 char *ascii_strlower(char *t) {
1414 for (p = t; *p; p++)
1415 if (*p >= 'A' && *p <= 'Z')
1416 *p = *p - 'A' + 'a';
1421 static bool ignore_file_allow_backup(const char *filename) {
1425 filename[0] == '.' ||
1426 streq(filename, "lost+found") ||
1427 streq(filename, "aquota.user") ||
1428 streq(filename, "aquota.group") ||
1429 endswith(filename, ".rpmnew") ||
1430 endswith(filename, ".rpmsave") ||
1431 endswith(filename, ".rpmorig") ||
1432 endswith(filename, ".dpkg-old") ||
1433 endswith(filename, ".dpkg-new") ||
1434 endswith(filename, ".swp");
1437 bool ignore_file(const char *filename) {
1440 if (endswith(filename, "~"))
1443 return ignore_file_allow_backup(filename);
1446 int fd_nonblock(int fd, bool nonblock) {
1451 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1455 flags |= O_NONBLOCK;
1457 flags &= ~O_NONBLOCK;
1459 if (fcntl(fd, F_SETFL, flags) < 0)
1465 int fd_cloexec(int fd, bool cloexec) {
1470 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1474 flags |= FD_CLOEXEC;
1476 flags &= ~FD_CLOEXEC;
1478 if (fcntl(fd, F_SETFD, flags) < 0)
1484 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1487 assert(n_fdset == 0 || fdset);
1489 for (i = 0; i < n_fdset; i++)
1496 int close_all_fds(const int except[], unsigned n_except) {
1501 assert(n_except == 0 || except);
1503 d = opendir("/proc/self/fd");
1508 /* When /proc isn't available (for example in chroots)
1509 * the fallback is brute forcing through the fd
1512 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1513 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1515 if (fd_in_set(fd, except, n_except))
1518 if (close_nointr(fd) < 0)
1519 if (errno != EBADF && r == 0)
1526 while ((de = readdir(d))) {
1529 if (ignore_file(de->d_name))
1532 if (safe_atoi(de->d_name, &fd) < 0)
1533 /* Let's better ignore this, just in case */
1542 if (fd_in_set(fd, except, n_except))
1545 if (close_nointr(fd) < 0) {
1546 /* Valgrind has its own FD and doesn't want to have it closed */
1547 if (errno != EBADF && r == 0)
1556 bool chars_intersect(const char *a, const char *b) {
1559 /* Returns true if any of the chars in a are in b. */
1560 for (p = a; *p; p++)
1567 bool fstype_is_network(const char *fstype) {
1568 static const char table[] =
1577 return nulstr_contains(table, fstype);
1581 _cleanup_close_ int fd;
1583 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1589 TIOCL_GETKMSGREDIRECT,
1593 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1596 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1599 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1605 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1606 struct termios old_termios, new_termios;
1608 char line[LINE_MAX];
1613 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1614 new_termios = old_termios;
1616 new_termios.c_lflag &= ~ICANON;
1617 new_termios.c_cc[VMIN] = 1;
1618 new_termios.c_cc[VTIME] = 0;
1620 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1623 if (t != (usec_t) -1) {
1624 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1625 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1630 k = fread(&c, 1, 1, f);
1632 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1638 *need_nl = c != '\n';
1645 if (t != (usec_t) -1)
1646 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1649 if (!fgets(line, sizeof(line), f))
1654 if (strlen(line) != 1)
1664 int ask(char *ret, const char *replies, const char *text, ...) {
1674 bool need_nl = true;
1677 fputs(ANSI_HIGHLIGHT_ON, stdout);
1684 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1688 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1691 if (r == -EBADMSG) {
1692 puts("Bad input, please try again.");
1703 if (strchr(replies, c)) {
1708 puts("Read unexpected character, please try again.");
1712 int reset_terminal_fd(int fd, bool switch_to_text) {
1713 struct termios termios;
1716 /* Set terminal to some sane defaults */
1720 /* We leave locked terminal attributes untouched, so that
1721 * Plymouth may set whatever it wants to set, and we don't
1722 * interfere with that. */
1724 /* Disable exclusive mode, just in case */
1725 ioctl(fd, TIOCNXCL);
1727 /* Switch to text mode */
1729 ioctl(fd, KDSETMODE, KD_TEXT);
1731 /* Enable console unicode mode */
1732 ioctl(fd, KDSKBMODE, K_UNICODE);
1734 if (tcgetattr(fd, &termios) < 0) {
1739 /* We only reset the stuff that matters to the software. How
1740 * hardware is set up we don't touch assuming that somebody
1741 * else will do that for us */
1743 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1744 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1745 termios.c_oflag |= ONLCR;
1746 termios.c_cflag |= CREAD;
1747 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1749 termios.c_cc[VINTR] = 03; /* ^C */
1750 termios.c_cc[VQUIT] = 034; /* ^\ */
1751 termios.c_cc[VERASE] = 0177;
1752 termios.c_cc[VKILL] = 025; /* ^X */
1753 termios.c_cc[VEOF] = 04; /* ^D */
1754 termios.c_cc[VSTART] = 021; /* ^Q */
1755 termios.c_cc[VSTOP] = 023; /* ^S */
1756 termios.c_cc[VSUSP] = 032; /* ^Z */
1757 termios.c_cc[VLNEXT] = 026; /* ^V */
1758 termios.c_cc[VWERASE] = 027; /* ^W */
1759 termios.c_cc[VREPRINT] = 022; /* ^R */
1760 termios.c_cc[VEOL] = 0;
1761 termios.c_cc[VEOL2] = 0;
1763 termios.c_cc[VTIME] = 0;
1764 termios.c_cc[VMIN] = 1;
1766 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1770 /* Just in case, flush all crap out */
1771 tcflush(fd, TCIOFLUSH);
1776 int reset_terminal(const char *name) {
1779 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1783 r = reset_terminal_fd(fd, true);
1784 close_nointr_nofail(fd);
1789 int open_terminal(const char *name, int mode) {
1794 * If a TTY is in the process of being closed opening it might
1795 * cause EIO. This is horribly awful, but unlikely to be
1796 * changed in the kernel. Hence we work around this problem by
1797 * retrying a couple of times.
1799 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1803 fd = open(name, mode);
1810 /* Max 1s in total */
1814 usleep(50 * USEC_PER_MSEC);
1823 close_nointr_nofail(fd);
1828 close_nointr_nofail(fd);
1835 int flush_fd(int fd) {
1836 struct pollfd pollfd;
1840 pollfd.events = POLLIN;
1847 if ((r = poll(&pollfd, 1, 0)) < 0) {
1858 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1863 if (errno == EAGAIN)
1874 int acquire_terminal(
1878 bool ignore_tiocstty_eperm,
1881 int fd = -1, notify = -1, r = 0, wd = -1;
1883 struct sigaction sa_old, sa_new;
1887 /* We use inotify to be notified when the tty is closed. We
1888 * create the watch before checking if we can actually acquire
1889 * it, so that we don't lose any event.
1891 * Note: strictly speaking this actually watches for the
1892 * device being closed, it does *not* really watch whether a
1893 * tty loses its controlling process. However, unless some
1894 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1895 * its tty otherwise this will not become a problem. As long
1896 * as the administrator makes sure not configure any service
1897 * on the same tty as an untrusted user this should not be a
1898 * problem. (Which he probably should not do anyway.) */
1900 if (timeout != (usec_t) -1)
1901 ts = now(CLOCK_MONOTONIC);
1903 if (!fail && !force) {
1904 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1910 wd = inotify_add_watch(notify, name, IN_CLOSE);
1919 r = flush_fd(notify);
1924 /* We pass here O_NOCTTY only so that we can check the return
1925 * value TIOCSCTTY and have a reliable way to figure out if we
1926 * successfully became the controlling process of the tty */
1927 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1931 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1932 * if we already own the tty. */
1934 sa_new.sa_handler = SIG_IGN;
1935 sa_new.sa_flags = SA_RESTART;
1936 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1938 /* First, try to get the tty */
1939 if (ioctl(fd, TIOCSCTTY, force) < 0)
1942 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1944 /* Sometimes it makes sense to ignore TIOCSCTTY
1945 * returning EPERM, i.e. when very likely we already
1946 * are have this controlling terminal. */
1947 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1950 if (r < 0 && (force || fail || r != -EPERM)) {
1959 assert(notify >= 0);
1962 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1964 struct inotify_event *e;
1966 if (timeout != (usec_t) -1) {
1969 n = now(CLOCK_MONOTONIC);
1970 if (ts + timeout < n) {
1975 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1985 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1988 if (errno == EINTR || errno == EAGAIN)
1995 e = (struct inotify_event*) inotify_buffer;
2000 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2005 step = sizeof(struct inotify_event) + e->len;
2006 assert(step <= (size_t) l);
2008 e = (struct inotify_event*) ((uint8_t*) e + step);
2015 /* We close the tty fd here since if the old session
2016 * ended our handle will be dead. It's important that
2017 * we do this after sleeping, so that we don't enter
2018 * an endless loop. */
2019 close_nointr_nofail(fd);
2023 close_nointr_nofail(notify);
2025 r = reset_terminal_fd(fd, true);
2027 log_warning("Failed to reset terminal: %s", strerror(-r));
2033 close_nointr_nofail(fd);
2036 close_nointr_nofail(notify);
2041 int release_terminal(void) {
2043 struct sigaction sa_old, sa_new;
2045 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2048 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2049 * by our own TIOCNOTTY */
2052 sa_new.sa_handler = SIG_IGN;
2053 sa_new.sa_flags = SA_RESTART;
2054 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2056 if (ioctl(fd, TIOCNOTTY) < 0)
2059 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2061 close_nointr_nofail(fd);
2065 int sigaction_many(const struct sigaction *sa, ...) {
2070 while ((sig = va_arg(ap, int)) > 0)
2071 if (sigaction(sig, sa, NULL) < 0)
2078 int ignore_signals(int sig, ...) {
2079 struct sigaction sa;
2084 sa.sa_handler = SIG_IGN;
2085 sa.sa_flags = SA_RESTART;
2087 if (sigaction(sig, &sa, NULL) < 0)
2091 while ((sig = va_arg(ap, int)) > 0)
2092 if (sigaction(sig, &sa, NULL) < 0)
2099 int default_signals(int sig, ...) {
2100 struct sigaction sa;
2105 sa.sa_handler = SIG_DFL;
2106 sa.sa_flags = SA_RESTART;
2108 if (sigaction(sig, &sa, NULL) < 0)
2112 while ((sig = va_arg(ap, int)) > 0)
2113 if (sigaction(sig, &sa, NULL) < 0)
2120 int close_pipe(int p[]) {
2126 a = close_nointr(p[0]);
2131 b = close_nointr(p[1]);
2135 return a < 0 ? a : b;
2138 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2147 while (nbytes > 0) {
2150 if ((k = read(fd, p, nbytes)) <= 0) {
2152 if (k < 0 && errno == EINTR)
2155 if (k < 0 && errno == EAGAIN && do_poll) {
2156 struct pollfd pollfd;
2160 pollfd.events = POLLIN;
2162 if (poll(&pollfd, 1, -1) < 0) {
2166 return n > 0 ? n : -errno;
2169 if (pollfd.revents != POLLIN)
2170 return n > 0 ? n : -EIO;
2175 return n > 0 ? n : (k < 0 ? -errno : 0);
2186 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2195 while (nbytes > 0) {
2198 k = write(fd, p, nbytes);
2201 if (k < 0 && errno == EINTR)
2204 if (k < 0 && errno == EAGAIN && do_poll) {
2205 struct pollfd pollfd;
2209 pollfd.events = POLLOUT;
2211 if (poll(&pollfd, 1, -1) < 0) {
2215 return n > 0 ? n : -errno;
2218 if (pollfd.revents != POLLOUT)
2219 return n > 0 ? n : -EIO;
2224 return n > 0 ? n : (k < 0 ? -errno : 0);
2235 int parse_bytes(const char *t, off_t *bytes) {
2236 static const struct {
2242 { "M", 1024ULL*1024ULL },
2243 { "G", 1024ULL*1024ULL*1024ULL },
2244 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2245 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2246 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2263 l = strtoll(p, &e, 10);
2274 e += strspn(e, WHITESPACE);
2276 for (i = 0; i < ELEMENTSOF(table); i++)
2277 if (startswith(e, table[i].suffix)) {
2278 r += (off_t) l * table[i].factor;
2279 p = e + strlen(table[i].suffix);
2283 if (i >= ELEMENTSOF(table))
2293 int make_stdio(int fd) {
2298 r = dup3(fd, STDIN_FILENO, 0);
2299 s = dup3(fd, STDOUT_FILENO, 0);
2300 t = dup3(fd, STDERR_FILENO, 0);
2303 close_nointr_nofail(fd);
2305 if (r < 0 || s < 0 || t < 0)
2308 /* We rely here that the new fd has O_CLOEXEC not set */
2313 int make_null_stdio(void) {
2316 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2320 return make_stdio(null_fd);
2323 bool is_device_path(const char *path) {
2325 /* Returns true on paths that refer to a device, either in
2326 * sysfs or in /dev */
2329 path_startswith(path, "/dev/") ||
2330 path_startswith(path, "/sys/");
2333 int dir_is_empty(const char *path) {
2334 _cleanup_closedir_ DIR *d;
2343 union dirent_storage buf;
2345 r = readdir_r(d, &buf.de, &de);
2352 if (!ignore_file(de->d_name))
2357 unsigned long long random_ull(void) {
2358 _cleanup_close_ int fd;
2362 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2366 r = loop_read(fd, &ull, sizeof(ull), true);
2367 if (r != sizeof(ull))
2373 return random() * RAND_MAX + random();
2376 void rename_process(const char name[8]) {
2379 /* This is a like a poor man's setproctitle(). It changes the
2380 * comm field, argv[0], and also the glibc's internally used
2381 * name of the process. For the first one a limit of 16 chars
2382 * applies, to the second one usually one of 10 (i.e. length
2383 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2384 * "systemd"). If you pass a longer string it will be
2387 prctl(PR_SET_NAME, name);
2389 if (program_invocation_name)
2390 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2392 if (saved_argc > 0) {
2396 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2398 for (i = 1; i < saved_argc; i++) {
2402 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2407 void sigset_add_many(sigset_t *ss, ...) {
2414 while ((sig = va_arg(ap, int)) > 0)
2415 assert_se(sigaddset(ss, sig) == 0);
2419 char* gethostname_malloc(void) {
2422 assert_se(uname(&u) >= 0);
2424 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2425 return strdup(u.nodename);
2427 return strdup(u.sysname);
2430 bool hostname_is_set(void) {
2433 assert_se(uname(&u) >= 0);
2435 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2438 static char *lookup_uid(uid_t uid) {
2441 _cleanup_free_ char *buf = NULL;
2442 struct passwd pwbuf, *pw = NULL;
2444 /* Shortcut things to avoid NSS lookups */
2446 return strdup("root");
2448 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2452 buf = malloc(bufsize);
2456 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2457 return strdup(pw->pw_name);
2459 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2465 char* getlogname_malloc(void) {
2469 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2474 return lookup_uid(uid);
2477 char *getusername_malloc(void) {
2484 return lookup_uid(getuid());
2487 int getttyname_malloc(int fd, char **r) {
2488 char path[PATH_MAX], *c;
2493 k = ttyname_r(fd, path, sizeof(path));
2499 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2507 int getttyname_harder(int fd, char **r) {
2511 k = getttyname_malloc(fd, &s);
2515 if (streq(s, "tty")) {
2517 return get_ctty(0, NULL, r);
2524 int get_ctty_devnr(pid_t pid, dev_t *d) {
2526 char line[LINE_MAX], *p, *fn;
2527 unsigned long ttynr;
2530 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2533 f = fopen(fn, "re");
2538 if (!fgets(line, sizeof(line), f)) {
2539 k = feof(f) ? -EIO : -errno;
2546 p = strrchr(line, ')');
2556 "%*d " /* session */
2561 if (major(ttynr) == 0 && minor(ttynr) == 0)
2568 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2570 char fn[PATH_MAX], *s, *b, *p;
2575 k = get_ctty_devnr(pid, &devnr);
2579 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2582 k = readlink_malloc(fn, &s);
2588 /* This is an ugly hack */
2589 if (major(devnr) == 136) {
2590 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2600 /* Probably something like the ptys which have no
2601 * symlink in /dev/char. Let's return something
2602 * vaguely useful. */
2615 if (startswith(s, "/dev/"))
2617 else if (startswith(s, "../"))
2635 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2641 /* This returns the first error we run into, but nevertheless
2642 * tries to go on. This closes the passed fd. */
2646 close_nointr_nofail(fd);
2648 return errno == ENOENT ? 0 : -errno;
2653 union dirent_storage buf;
2654 bool is_dir, keep_around;
2658 r = readdir_r(d, &buf.de, &de);
2659 if (r != 0 && ret == 0) {
2667 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2670 if (de->d_type == DT_UNKNOWN ||
2672 (de->d_type == DT_DIR && root_dev)) {
2673 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2674 if (ret == 0 && errno != ENOENT)
2679 is_dir = S_ISDIR(st.st_mode);
2682 (st.st_uid == 0 || st.st_uid == getuid()) &&
2683 (st.st_mode & S_ISVTX);
2685 is_dir = de->d_type == DT_DIR;
2686 keep_around = false;
2692 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2693 if (root_dev && st.st_dev != root_dev->st_dev)
2696 subdir_fd = openat(fd, de->d_name,
2697 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2698 if (subdir_fd < 0) {
2699 if (ret == 0 && errno != ENOENT)
2704 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2705 if (r < 0 && ret == 0)
2709 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2710 if (ret == 0 && errno != ENOENT)
2714 } else if (!only_dirs && !keep_around) {
2716 if (unlinkat(fd, de->d_name, 0) < 0) {
2717 if (ret == 0 && errno != ENOENT)
2728 static int is_temporary_fs(struct statfs *s) {
2730 return s->f_type == TMPFS_MAGIC ||
2731 (long)s->f_type == (long)RAMFS_MAGIC;
2734 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2739 if (fstatfs(fd, &s) < 0) {
2740 close_nointr_nofail(fd);
2744 /* We refuse to clean disk file systems with this call. This
2745 * is extra paranoia just to be sure we never ever remove
2747 if (!is_temporary_fs(&s)) {
2748 log_error("Attempted to remove disk file system, and we can't allow that.");
2749 close_nointr_nofail(fd);
2753 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2756 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2762 /* We refuse to clean the root file system with this
2763 * call. This is extra paranoia to never cause a really
2764 * seriously broken system. */
2765 if (path_equal(path, "/")) {
2766 log_error("Attempted to remove entire root file system, and we can't allow that.");
2770 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2773 if (errno != ENOTDIR)
2777 if (statfs(path, &s) < 0)
2780 if (!is_temporary_fs(&s)) {
2781 log_error("Attempted to remove disk file system, and we can't allow that.");
2786 if (delete_root && !only_dirs)
2787 if (unlink(path) < 0 && errno != ENOENT)
2794 if (fstatfs(fd, &s) < 0) {
2795 close_nointr_nofail(fd);
2799 if (!is_temporary_fs(&s)) {
2800 log_error("Attempted to remove disk file system, and we can't allow that.");
2801 close_nointr_nofail(fd);
2806 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2809 if (honour_sticky && file_is_priv_sticky(path) > 0)
2812 if (rmdir(path) < 0 && errno != ENOENT) {
2821 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2822 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2825 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2826 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2829 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2832 /* Under the assumption that we are running privileged we
2833 * first change the access mode and only then hand out
2834 * ownership to avoid a window where access is too open. */
2836 if (mode != (mode_t) -1)
2837 if (chmod(path, mode) < 0)
2840 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2841 if (chown(path, uid, gid) < 0)
2847 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2850 /* Under the assumption that we are running privileged we
2851 * first change the access mode and only then hand out
2852 * ownership to avoid a window where access is too open. */
2854 if (fchmod(fd, mode) < 0)
2857 if (fchown(fd, uid, gid) < 0)
2863 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2867 /* Allocates the cpuset in the right size */
2870 if (!(r = CPU_ALLOC(n)))
2873 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2874 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2884 if (errno != EINVAL)
2891 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2892 static const char status_indent[] = " "; /* "[" STATUS "] " */
2893 _cleanup_free_ char *s = NULL;
2894 _cleanup_close_ int fd = -1;
2895 struct iovec iovec[6];
2897 static bool prev_ephemeral;
2901 /* This is independent of logging, as status messages are
2902 * optional and go exclusively to the console. */
2904 if (vasprintf(&s, format, ap) < 0)
2907 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2920 sl = status ? sizeof(status_indent)-1 : 0;
2926 e = ellipsize(s, emax, 75);
2936 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2937 prev_ephemeral = ephemeral;
2940 if (!isempty(status)) {
2941 IOVEC_SET_STRING(iovec[n++], "[");
2942 IOVEC_SET_STRING(iovec[n++], status);
2943 IOVEC_SET_STRING(iovec[n++], "] ");
2945 IOVEC_SET_STRING(iovec[n++], status_indent);
2948 IOVEC_SET_STRING(iovec[n++], s);
2950 IOVEC_SET_STRING(iovec[n++], "\n");
2952 if (writev(fd, iovec, n) < 0)
2958 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2964 va_start(ap, format);
2965 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2971 int status_welcome(void) {
2973 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2975 r = parse_env_file("/etc/os-release", NEWLINE,
2976 "PRETTY_NAME", &pretty_name,
2977 "ANSI_COLOR", &ansi_color,
2979 if (r < 0 && r != -ENOENT)
2980 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2982 return status_printf(NULL, false, false,
2983 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2984 isempty(ansi_color) ? "1" : ansi_color,
2985 isempty(pretty_name) ? "Linux" : pretty_name);
2988 char *replace_env(const char *format, char **env) {
2995 const char *e, *word = format;
3000 for (e = format; *e; e ++) {
3011 if (!(k = strnappend(r, word, e-word-1)))
3020 } else if (*e == '$') {
3021 if (!(k = strnappend(r, word, e-word)))
3037 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3039 k = strappend(r, t);
3053 if (!(k = strnappend(r, word, e-word)))
3064 char **replace_env_argv(char **argv, char **env) {
3066 unsigned k = 0, l = 0;
3068 l = strv_length(argv);
3070 if (!(r = new(char*, l+1)))
3073 STRV_FOREACH(i, argv) {
3075 /* If $FOO appears as single word, replace it by the split up variable */
3076 if ((*i)[0] == '$' && (*i)[1] != '{') {
3081 e = strv_env_get(env, *i+1);
3084 if (!(m = strv_split_quoted(e))) {
3095 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3104 memcpy(r + k, m, q * sizeof(char*));
3112 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3113 if (!(r[k++] = replace_env(*i, env))) {
3123 int fd_columns(int fd) {
3127 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3136 unsigned columns(void) {
3140 if (_likely_(cached_columns > 0))
3141 return cached_columns;
3144 e = getenv("COLUMNS");
3149 c = fd_columns(STDOUT_FILENO);
3158 int fd_lines(int fd) {
3162 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3171 unsigned lines(void) {
3175 if (_likely_(cached_lines > 0))
3176 return cached_lines;
3179 e = getenv("LINES");
3184 l = fd_lines(STDOUT_FILENO);
3190 return cached_lines;
3193 /* intended to be used as a SIGWINCH sighandler */
3194 void columns_lines_cache_reset(int signum) {
3200 static int cached_on_tty = -1;
3202 if (_unlikely_(cached_on_tty < 0))
3203 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3205 return cached_on_tty;
3208 int running_in_chroot(void) {
3214 /* Only works as root */
3216 if (stat("/proc/1/root", &a) < 0)
3219 if (stat("/", &b) < 0)
3223 a.st_dev != b.st_dev ||
3224 a.st_ino != b.st_ino;
3227 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3232 assert(percent <= 100);
3233 assert(new_length >= 3);
3235 if (old_length <= 3 || old_length <= new_length)
3236 return strndup(s, old_length);
3238 r = new0(char, new_length+1);
3242 x = (new_length * percent) / 100;
3244 if (x > new_length - 3)
3252 s + old_length - (new_length - x - 3),
3253 new_length - x - 3);
3258 char *ellipsize(const char *s, size_t length, unsigned percent) {
3259 return ellipsize_mem(s, strlen(s), length, percent);
3262 int touch(const char *path) {
3267 /* This just opens the file for writing, ensuring it
3268 * exists. It doesn't call utimensat() the way /usr/bin/touch
3271 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3275 close_nointr_nofail(fd);
3279 char *unquote(const char *s, const char* quotes) {
3283 /* This is rather stupid, simply removes the heading and
3284 * trailing quotes if there is one. Doesn't care about
3285 * escaping or anything. We should make this smarter one
3292 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3293 return strndup(s+1, l-2);
3298 char *normalize_env_assignment(const char *s) {
3299 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3302 eq = strchr(s, '=');
3314 memmove(r, t, strlen(t) + 1);
3318 name = strndup(s, eq - s);
3326 value = unquote(strstrip(p), QUOTES);
3330 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3336 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3347 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3359 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3366 r = wait_for_terminate(pid, &status);
3368 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3372 if (status.si_code == CLD_EXITED) {
3373 if (status.si_status != 0) {
3374 log_warning("%s failed with error code %i.", name, status.si_status);
3375 return status.si_status;
3378 log_debug("%s succeeded.", name);
3381 } else if (status.si_code == CLD_KILLED ||
3382 status.si_code == CLD_DUMPED) {
3384 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3388 log_warning("%s failed due to unknown reason.", name);
3392 _noreturn_ void freeze(void) {
3394 /* Make sure nobody waits for us on a socket anymore */
3395 close_all_fds(NULL, 0);
3403 bool null_or_empty(struct stat *st) {
3406 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3409 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3415 int null_or_empty_path(const char *fn) {
3420 if (stat(fn, &st) < 0)
3423 return null_or_empty(&st);
3426 DIR *xopendirat(int fd, const char *name, int flags) {
3430 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3436 close_nointr_nofail(nfd);
3443 int signal_from_string_try_harder(const char *s) {
3447 signo = signal_from_string(s);
3449 if (startswith(s, "SIG"))
3450 return signal_from_string(s+3);
3455 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3459 /* FIXME: to follow udev's logic 100% we need to leave valid
3460 * UTF8 chars unescaped */
3462 u = unquote(tagvalue, "\"\'");
3466 t = xescape(u, "/ ");
3472 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3481 char *fstab_node_to_udev_node(const char *p) {
3484 if (startswith(p, "LABEL="))
3485 return tag_to_udev_node(p+6, "label");
3487 if (startswith(p, "UUID="))
3488 return tag_to_udev_node(p+5, "uuid");
3490 if (startswith(p, "PARTUUID="))
3491 return tag_to_udev_node(p+9, "partuuid");
3493 if (startswith(p, "PARTLABEL="))
3494 return tag_to_udev_node(p+10, "partlabel");
3499 bool tty_is_vc(const char *tty) {
3502 if (startswith(tty, "/dev/"))
3505 return vtnr_from_tty(tty) >= 0;
3508 bool tty_is_console(const char *tty) {
3511 if (startswith(tty, "/dev/"))
3514 return streq(tty, "console");
3517 int vtnr_from_tty(const char *tty) {
3522 if (startswith(tty, "/dev/"))
3525 if (!startswith(tty, "tty") )
3528 if (tty[3] < '0' || tty[3] > '9')
3531 r = safe_atoi(tty+3, &i);
3535 if (i < 0 || i > 63)
3541 char *resolve_dev_console(char **active) {
3544 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3545 * (i.e. not read-only-mounted which is a sign for container setups) */
3547 if (path_is_read_only_fs("/sys") > 0)
3550 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3553 /* If multiple log outputs are configured the last one is what
3554 * /dev/console points to */
3555 tty = strrchr(*active, ' ');
3564 bool tty_is_vc_resolve(const char *tty) {
3565 char *active = NULL;
3570 if (startswith(tty, "/dev/"))
3573 if (streq(tty, "console")) {
3574 tty = resolve_dev_console(&active);
3585 const char *default_term_for_tty(const char *tty) {
3588 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3591 bool dirent_is_file(const struct dirent *de) {
3594 if (ignore_file(de->d_name))
3597 if (de->d_type != DT_REG &&
3598 de->d_type != DT_LNK &&
3599 de->d_type != DT_UNKNOWN)
3605 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3608 if (de->d_type != DT_REG &&
3609 de->d_type != DT_LNK &&
3610 de->d_type != DT_UNKNOWN)
3613 if (ignore_file_allow_backup(de->d_name))
3616 return endswith(de->d_name, suffix);
3619 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3622 Hashmap *pids = NULL;
3626 /* Executes all binaries in a directory in parallel and
3627 * waits for them to finish. */
3630 if (!(_d = opendir(directory))) {
3632 if (errno == ENOENT)
3635 log_error("Failed to enumerate directory %s: %m", directory);
3642 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3643 log_error("Failed to allocate set.");
3647 while ((de = readdir(d))) {
3652 if (!dirent_is_file(de))
3655 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3660 if ((pid = fork()) < 0) {
3661 log_error("Failed to fork: %m");
3679 log_error("Failed to execute %s: %m", path);
3680 _exit(EXIT_FAILURE);
3683 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3685 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3686 log_error("Failed to add PID to set: %s", strerror(-k));
3691 while (!hashmap_isempty(pids)) {
3692 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3697 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3702 log_error("waitid() failed: %m");
3706 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3707 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3708 if (si.si_code == CLD_EXITED)
3709 log_error("%s exited with exit status %i.", path, si.si_status);
3711 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3713 log_debug("%s exited successfully.", path);
3724 hashmap_free_free(pids);
3727 int kill_and_sigcont(pid_t pid, int sig) {
3730 r = kill(pid, sig) < 0 ? -errno : 0;
3738 bool nulstr_contains(const char*nulstr, const char *needle) {
3744 NULSTR_FOREACH(i, nulstr)
3745 if (streq(i, needle))
3751 bool plymouth_running(void) {
3752 return access("/run/plymouth/pid", F_OK) >= 0;
3755 char* strshorten(char *s, size_t l) {
3764 static bool hostname_valid_char(char c) {
3766 (c >= 'a' && c <= 'z') ||
3767 (c >= 'A' && c <= 'Z') ||
3768 (c >= '0' && c <= '9') ||
3774 bool hostname_is_valid(const char *s) {
3781 for (p = s, dot = true; *p; p++) {
3788 if (!hostname_valid_char(*p))
3798 if (p-s > HOST_NAME_MAX)
3804 char* hostname_cleanup(char *s) {
3807 for (p = s, d = s; *p; p++)
3808 if ((*p >= 'a' && *p <= 'z') ||
3809 (*p >= 'A' && *p <= 'Z') ||
3810 (*p >= '0' && *p <= '9') ||
3818 strshorten(s, HOST_NAME_MAX);
3822 int pipe_eof(int fd) {
3823 struct pollfd pollfd;
3828 pollfd.events = POLLIN|POLLHUP;
3830 r = poll(&pollfd, 1, 0);
3837 return pollfd.revents & POLLHUP;
3840 int fd_wait_for_event(int fd, int event, usec_t t) {
3841 struct pollfd pollfd;
3846 pollfd.events = event;
3848 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3855 return pollfd.revents;
3858 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3869 t = new(char, strlen(path) + 1 + 6 + 1);
3873 fn = path_get_file_name(path);
3877 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3879 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3885 f = fdopen(fd, "we");
3898 int terminal_vhangup_fd(int fd) {
3901 if (ioctl(fd, TIOCVHANGUP) < 0)
3907 int terminal_vhangup(const char *name) {
3910 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3914 r = terminal_vhangup_fd(fd);
3915 close_nointr_nofail(fd);
3920 int vt_disallocate(const char *name) {
3924 /* Deallocate the VT if possible. If not possible
3925 * (i.e. because it is the active one), at least clear it
3926 * entirely (including the scrollback buffer) */
3928 if (!startswith(name, "/dev/"))
3931 if (!tty_is_vc(name)) {
3932 /* So this is not a VT. I guess we cannot deallocate
3933 * it then. But let's at least clear the screen */
3935 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3940 "\033[r" /* clear scrolling region */
3941 "\033[H" /* move home */
3942 "\033[2J", /* clear screen */
3944 close_nointr_nofail(fd);
3949 if (!startswith(name, "/dev/tty"))
3952 r = safe_atou(name+8, &u);
3959 /* Try to deallocate */
3960 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3964 r = ioctl(fd, VT_DISALLOCATE, u);
3965 close_nointr_nofail(fd);
3973 /* Couldn't deallocate, so let's clear it fully with
3975 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3980 "\033[r" /* clear scrolling region */
3981 "\033[H" /* move home */
3982 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3984 close_nointr_nofail(fd);
3989 int copy_file(const char *from, const char *to) {
3995 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
3999 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4001 close_nointr_nofail(fdf);
4009 n = read(fdf, buf, sizeof(buf));
4013 close_nointr_nofail(fdf);
4024 k = loop_write(fdt, buf, n, false);
4026 r = k < 0 ? k : (errno ? -errno : -EIO);
4028 close_nointr_nofail(fdf);
4036 close_nointr_nofail(fdf);
4037 r = close_nointr(fdt);
4047 int symlink_atomic(const char *from, const char *to) {
4049 _cleanup_free_ char *t;
4052 unsigned long long ull;
4059 t = new(char, strlen(to) + 1 + 16 + 1);
4063 fn = path_get_file_name(to);
4067 x = stpcpy(t+k+1, fn);
4070 for (i = 0; i < 16; i++) {
4071 *(x++) = hexchar(ull & 0xF);
4077 if (symlink(from, t) < 0)
4080 if (rename(t, to) < 0) {
4089 bool display_is_local(const char *display) {
4093 display[0] == ':' &&
4094 display[1] >= '0' &&
4098 int socket_from_display(const char *display, char **path) {
4105 if (!display_is_local(display))
4108 k = strspn(display+1, "0123456789");
4110 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4114 c = stpcpy(f, "/tmp/.X11-unix/X");
4115 memcpy(c, display+1, k);
4124 const char **username,
4125 uid_t *uid, gid_t *gid,
4127 const char **shell) {
4135 /* We enforce some special rules for uid=0: in order to avoid
4136 * NSS lookups for root we hardcode its data. */
4138 if (streq(*username, "root") || streq(*username, "0")) {
4156 if (parse_uid(*username, &u) >= 0) {
4160 /* If there are multiple users with the same id, make
4161 * sure to leave $USER to the configured value instead
4162 * of the first occurrence in the database. However if
4163 * the uid was configured by a numeric uid, then let's
4164 * pick the real username from /etc/passwd. */
4166 *username = p->pw_name;
4169 p = getpwnam(*username);
4173 return errno != 0 ? -errno : -ESRCH;
4185 *shell = p->pw_shell;
4190 char* uid_to_name(uid_t uid) {
4195 return strdup("root");
4199 return strdup(p->pw_name);
4201 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4207 char* gid_to_name(gid_t gid) {
4212 return strdup("root");
4216 return strdup(p->gr_name);
4218 if (asprintf(&r, "%lu", (unsigned long) gid) < 0)
4224 int get_group_creds(const char **groupname, gid_t *gid) {
4230 /* We enforce some special rules for gid=0: in order to avoid
4231 * NSS lookups for root we hardcode its data. */
4233 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4234 *groupname = "root";
4242 if (parse_gid(*groupname, &id) >= 0) {
4247 *groupname = g->gr_name;
4250 g = getgrnam(*groupname);
4254 return errno != 0 ? -errno : -ESRCH;
4262 int in_gid(gid_t gid) {
4264 int ngroups_max, r, i;
4266 if (getgid() == gid)
4269 if (getegid() == gid)
4272 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4273 assert(ngroups_max > 0);
4275 gids = alloca(sizeof(gid_t) * ngroups_max);
4277 r = getgroups(ngroups_max, gids);
4281 for (i = 0; i < r; i++)
4288 int in_group(const char *name) {
4292 r = get_group_creds(&name, &gid);
4299 int glob_exists(const char *path) {
4307 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4309 if (k == GLOB_NOMATCH)
4311 else if (k == GLOB_NOSPACE)
4314 r = !strv_isempty(g.gl_pathv);
4316 r = errno ? -errno : -EIO;
4323 int dirent_ensure_type(DIR *d, struct dirent *de) {
4329 if (de->d_type != DT_UNKNOWN)
4332 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4336 S_ISREG(st.st_mode) ? DT_REG :
4337 S_ISDIR(st.st_mode) ? DT_DIR :
4338 S_ISLNK(st.st_mode) ? DT_LNK :
4339 S_ISFIFO(st.st_mode) ? DT_FIFO :
4340 S_ISSOCK(st.st_mode) ? DT_SOCK :
4341 S_ISCHR(st.st_mode) ? DT_CHR :
4342 S_ISBLK(st.st_mode) ? DT_BLK :
4348 int in_search_path(const char *path, char **search) {
4352 r = path_get_parent(path, &parent);
4358 STRV_FOREACH(i, search) {
4359 if (path_equal(parent, *i)) {
4370 int get_files_in_directory(const char *path, char ***list) {
4378 /* Returns all files in a directory in *list, and the number
4379 * of files as return value. If list is NULL returns only the
4388 union dirent_storage buf;
4391 k = readdir_r(d, &buf.de, &de);
4400 dirent_ensure_type(d, de);
4402 if (!dirent_is_file(de))
4406 if ((unsigned) r >= n) {
4410 t = realloc(l, sizeof(char*) * n);
4419 assert((unsigned) r < n);
4421 l[r] = strdup(de->d_name);
4445 char *strjoin(const char *x, ...) {
4459 t = va_arg(ap, const char *);
4464 if (n > ((size_t) -1) - l) {
4488 t = va_arg(ap, const char *);
4502 bool is_main_thread(void) {
4503 static __thread int cached = 0;
4505 if (_unlikely_(cached == 0))
4506 cached = getpid() == gettid() ? 1 : -1;
4511 int block_get_whole_disk(dev_t d, dev_t *ret) {
4518 /* If it has a queue this is good enough for us */
4519 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4522 r = access(p, F_OK);
4530 /* If it is a partition find the originating device */
4531 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4534 r = access(p, F_OK);
4540 /* Get parent dev_t */
4541 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4544 r = read_one_line_file(p, &s);
4550 r = sscanf(s, "%u:%u", &m, &n);
4556 /* Only return this if it is really good enough for us. */
4557 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4560 r = access(p, F_OK);
4564 *ret = makedev(m, n);
4571 int file_is_priv_sticky(const char *p) {
4576 if (lstat(p, &st) < 0)
4580 (st.st_uid == 0 || st.st_uid == getuid()) &&
4581 (st.st_mode & S_ISVTX);
4584 static const char *const ioprio_class_table[] = {
4585 [IOPRIO_CLASS_NONE] = "none",
4586 [IOPRIO_CLASS_RT] = "realtime",
4587 [IOPRIO_CLASS_BE] = "best-effort",
4588 [IOPRIO_CLASS_IDLE] = "idle"
4591 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4593 static const char *const sigchld_code_table[] = {
4594 [CLD_EXITED] = "exited",
4595 [CLD_KILLED] = "killed",
4596 [CLD_DUMPED] = "dumped",
4597 [CLD_TRAPPED] = "trapped",
4598 [CLD_STOPPED] = "stopped",
4599 [CLD_CONTINUED] = "continued",
4602 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4604 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4605 [LOG_FAC(LOG_KERN)] = "kern",
4606 [LOG_FAC(LOG_USER)] = "user",
4607 [LOG_FAC(LOG_MAIL)] = "mail",
4608 [LOG_FAC(LOG_DAEMON)] = "daemon",
4609 [LOG_FAC(LOG_AUTH)] = "auth",
4610 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4611 [LOG_FAC(LOG_LPR)] = "lpr",
4612 [LOG_FAC(LOG_NEWS)] = "news",
4613 [LOG_FAC(LOG_UUCP)] = "uucp",
4614 [LOG_FAC(LOG_CRON)] = "cron",
4615 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4616 [LOG_FAC(LOG_FTP)] = "ftp",
4617 [LOG_FAC(LOG_LOCAL0)] = "local0",
4618 [LOG_FAC(LOG_LOCAL1)] = "local1",
4619 [LOG_FAC(LOG_LOCAL2)] = "local2",
4620 [LOG_FAC(LOG_LOCAL3)] = "local3",
4621 [LOG_FAC(LOG_LOCAL4)] = "local4",
4622 [LOG_FAC(LOG_LOCAL5)] = "local5",
4623 [LOG_FAC(LOG_LOCAL6)] = "local6",
4624 [LOG_FAC(LOG_LOCAL7)] = "local7"
4627 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4629 static const char *const log_level_table[] = {
4630 [LOG_EMERG] = "emerg",
4631 [LOG_ALERT] = "alert",
4632 [LOG_CRIT] = "crit",
4634 [LOG_WARNING] = "warning",
4635 [LOG_NOTICE] = "notice",
4636 [LOG_INFO] = "info",
4637 [LOG_DEBUG] = "debug"
4640 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4642 static const char* const sched_policy_table[] = {
4643 [SCHED_OTHER] = "other",
4644 [SCHED_BATCH] = "batch",
4645 [SCHED_IDLE] = "idle",
4646 [SCHED_FIFO] = "fifo",
4650 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4652 static const char* const rlimit_table[] = {
4653 [RLIMIT_CPU] = "LimitCPU",
4654 [RLIMIT_FSIZE] = "LimitFSIZE",
4655 [RLIMIT_DATA] = "LimitDATA",
4656 [RLIMIT_STACK] = "LimitSTACK",
4657 [RLIMIT_CORE] = "LimitCORE",
4658 [RLIMIT_RSS] = "LimitRSS",
4659 [RLIMIT_NOFILE] = "LimitNOFILE",
4660 [RLIMIT_AS] = "LimitAS",
4661 [RLIMIT_NPROC] = "LimitNPROC",
4662 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4663 [RLIMIT_LOCKS] = "LimitLOCKS",
4664 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4665 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4666 [RLIMIT_NICE] = "LimitNICE",
4667 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4668 [RLIMIT_RTTIME] = "LimitRTTIME"
4671 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4673 static const char* const ip_tos_table[] = {
4674 [IPTOS_LOWDELAY] = "low-delay",
4675 [IPTOS_THROUGHPUT] = "throughput",
4676 [IPTOS_RELIABILITY] = "reliability",
4677 [IPTOS_LOWCOST] = "low-cost",
4680 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4682 static const char *const __signal_table[] = {
4699 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4710 [SIGVTALRM] = "VTALRM",
4712 [SIGWINCH] = "WINCH",
4718 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4720 const char *signal_to_string(int signo) {
4721 static __thread char buf[12];
4724 name = __signal_to_string(signo);
4728 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4729 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4731 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4736 int signal_from_string(const char *s) {
4741 signo = __signal_from_string(s);
4745 if (startswith(s, "RTMIN+")) {
4749 if (safe_atou(s, &u) >= 0) {
4750 signo = (int) u + offset;
4751 if (signo > 0 && signo < _NSIG)
4757 bool kexec_loaded(void) {
4758 bool loaded = false;
4761 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4769 int strdup_or_null(const char *a, char **b) {
4787 int prot_from_flags(int flags) {
4789 switch (flags & O_ACCMODE) {
4798 return PROT_READ|PROT_WRITE;
4805 char *format_bytes(char *buf, size_t l, off_t t) {
4808 static const struct {
4812 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4813 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4814 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4815 { "G", 1024ULL*1024ULL*1024ULL },
4816 { "M", 1024ULL*1024ULL },
4820 for (i = 0; i < ELEMENTSOF(table); i++) {
4822 if (t >= table[i].factor) {
4825 (unsigned long long) (t / table[i].factor),
4826 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4833 snprintf(buf, l, "%lluB", (unsigned long long) t);
4841 void* memdup(const void *p, size_t l) {
4854 int fd_inc_sndbuf(int fd, size_t n) {
4856 socklen_t l = sizeof(value);
4858 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4860 l == sizeof(value) &&
4861 (size_t) value >= n*2)
4865 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4872 int fd_inc_rcvbuf(int fd, size_t n) {
4874 socklen_t l = sizeof(value);
4876 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4878 l == sizeof(value) &&
4879 (size_t) value >= n*2)
4883 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4890 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4891 pid_t parent_pid, agent_pid;
4893 bool stdout_is_tty, stderr_is_tty;
4901 parent_pid = getpid();
4903 /* Spawns a temporary TTY agent, making sure it goes away when
4910 if (agent_pid != 0) {
4917 * Make sure the agent goes away when the parent dies */
4918 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4919 _exit(EXIT_FAILURE);
4921 /* Check whether our parent died before we were able
4922 * to set the death signal */
4923 if (getppid() != parent_pid)
4924 _exit(EXIT_SUCCESS);
4926 /* Don't leak fds to the agent */
4927 close_all_fds(except, n_except);
4929 stdout_is_tty = isatty(STDOUT_FILENO);
4930 stderr_is_tty = isatty(STDERR_FILENO);
4932 if (!stdout_is_tty || !stderr_is_tty) {
4933 /* Detach from stdout/stderr. and reopen
4934 * /dev/tty for them. This is important to
4935 * ensure that when systemctl is started via
4936 * popen() or a similar call that expects to
4937 * read EOF we actually do generate EOF and
4938 * not delay this indefinitely by because we
4939 * keep an unused copy of stdin around. */
4940 fd = open("/dev/tty", O_WRONLY);
4942 log_error("Failed to open /dev/tty: %m");
4943 _exit(EXIT_FAILURE);
4947 dup2(fd, STDOUT_FILENO);
4950 dup2(fd, STDERR_FILENO);
4956 /* Count arguments */
4958 for (n = 0; va_arg(ap, char*); n++)
4963 l = alloca(sizeof(char *) * (n + 1));
4965 /* Fill in arguments */
4967 for (i = 0; i <= n; i++)
4968 l[i] = va_arg(ap, char*);
4972 _exit(EXIT_FAILURE);
4975 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4976 struct rlimit highest, fixed;
4980 if (setrlimit(resource, rlim) >= 0)
4986 /* So we failed to set the desired setrlimit, then let's try
4987 * to get as close as we can */
4988 assert_se(getrlimit(resource, &highest) == 0);
4990 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4991 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4993 if (setrlimit(resource, &fixed) < 0)
4999 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5000 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5012 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5015 f = fopen(path, "re");
5023 char line[LINE_MAX];
5026 for (i = 0; i < sizeof(line)-1; i++) {
5030 if (_unlikely_(c == EOF)) {
5040 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5041 value = strdup(line + l + 1);
5061 int can_sleep(const char *type) {
5065 _cleanup_free_ char *p = NULL;
5069 /* If /sys is read-only we cannot sleep */
5070 if (access("/sys/power/state", W_OK) < 0)
5073 r = read_one_line_file("/sys/power/state", &p);
5078 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5079 if (l == k && memcmp(w, type, l) == 0)
5085 int can_sleep_disk(const char *type) {
5089 _cleanup_free_ char *p = NULL;
5093 /* If /sys is read-only we cannot sleep */
5094 if (access("/sys/power/state", W_OK) < 0 ||
5095 access("/sys/power/disk", W_OK) < 0)
5098 r = read_one_line_file("/sys/power/disk", &p);
5103 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5104 if (l == k && memcmp(w, type, l) == 0)
5107 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5114 bool is_valid_documentation_url(const char *url) {
5117 if (startswith(url, "http://") && url[7])
5120 if (startswith(url, "https://") && url[8])
5123 if (startswith(url, "file:") && url[5])
5126 if (startswith(url, "info:") && url[5])
5129 if (startswith(url, "man:") && url[4])
5135 bool in_initrd(void) {
5136 static __thread int saved = -1;
5142 /* We make two checks here:
5144 * 1. the flag file /etc/initrd-release must exist
5145 * 2. the root file system must be a memory file system
5147 * The second check is extra paranoia, since misdetecting an
5148 * initrd can have bad bad consequences due the initrd
5149 * emptying when transititioning to the main systemd.
5152 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5153 statfs("/", &s) >= 0 &&
5154 is_temporary_fs(&s);
5159 void warn_melody(void) {
5160 _cleanup_close_ int fd = -1;
5162 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5166 /* Yeah, this is synchronous. Kinda sucks. But well... */
5168 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5169 usleep(125*USEC_PER_MSEC);
5171 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5172 usleep(125*USEC_PER_MSEC);
5174 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5175 usleep(125*USEC_PER_MSEC);
5177 ioctl(fd, KIOCSOUND, 0);
5180 int make_console_stdio(void) {
5183 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5185 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5187 log_error("Failed to acquire terminal: %s", strerror(-fd));
5193 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5200 int get_home_dir(char **_h) {
5208 /* Take the user specified one */
5219 /* Hardcode home directory for root to avoid NSS */
5222 h = strdup("/root");
5230 /* Check the database... */
5234 return errno ? -errno : -ESRCH;
5236 if (!path_is_absolute(p->pw_dir))
5239 h = strdup(p->pw_dir);
5247 int get_shell(char **_sh) {
5255 /* Take the user specified one */
5256 e = getenv("SHELL");
5266 /* Hardcode home directory for root to avoid NSS */
5269 sh = strdup("/bin/sh");
5277 /* Check the database... */
5281 return errno ? -errno : -ESRCH;
5283 if (!path_is_absolute(p->pw_shell))
5286 sh = strdup(p->pw_shell);
5294 void fclosep(FILE **f) {
5299 void pclosep(FILE **f) {
5304 void closep(int *fd) {
5306 close_nointr_nofail(*fd);
5309 void closedirp(DIR **d) {
5314 bool filename_is_safe(const char *p) {
5328 if (strlen(p) > FILENAME_MAX)
5334 bool string_is_safe(const char *p) {
5339 for (t = p; *t; t++) {
5340 if (*t > 0 && *t < ' ')
5343 if (strchr("\\\"\'", *t))
5350 bool string_has_cc(const char *p) {
5355 for (t = p; *t; t++)
5356 if (*t > 0 && *t < ' ')
5362 bool path_is_safe(const char *p) {
5367 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5370 if (strlen(p) > PATH_MAX)
5373 /* The following two checks are not really dangerous, but hey, they still are confusing */
5374 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5377 if (strstr(p, "//"))
5383 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5384 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5385 int (*compar) (const void *, const void *, void *), void *arg) {
5394 p = (void *)(((const char *) base) + (idx * size));
5395 comparison = compar(key, p, arg);
5398 else if (comparison > 0)
5406 bool is_locale_utf8(void) {
5408 static int cached_answer = -1;
5410 if (cached_answer >= 0)
5413 if (!setlocale(LC_ALL, "")) {
5414 cached_answer = true;
5418 set = nl_langinfo(CODESET);
5420 cached_answer = true;
5424 cached_answer = streq(set, "UTF-8");
5426 return (bool)cached_answer;
5429 const char *draw_special_char(DrawSpecialChar ch) {
5430 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5432 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5433 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5434 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5435 [DRAW_TREE_SPACE] = " ", /* */
5436 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5438 /* ASCII fallback */ {
5439 [DRAW_TREE_VERT] = "| ",
5440 [DRAW_TREE_BRANCH] = "|-",
5441 [DRAW_TREE_RIGHT] = "`-",
5442 [DRAW_TREE_SPACE] = " ",
5443 [DRAW_TRIANGULAR_BULLET] = "> ",
5447 return draw_table[!is_locale_utf8()][ch];
5450 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5453 size_t l, old_len, new_len;
5459 old_len = strlen(old_string);
5460 new_len = strlen(new_string);
5473 if (!startswith(f, old_string)) {
5479 nl = l - old_len + new_len;
5480 a = realloc(r, nl + 1);
5488 t = stpcpy(t, new_string);
5500 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5501 const char *i, *begin = NULL;
5506 } state = STATE_OTHER;
5508 size_t osz = 0, isz;
5514 /* Strips ANSI color and replaces TABs by 8 spaces */
5516 isz = _isz ? *_isz : strlen(*ibuf);
5518 f = open_memstream(&obuf, &osz);
5522 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5527 if (i >= *ibuf + isz) /* EOT */
5529 else if (*i == '\x1B')
5530 state = STATE_ESCAPE;
5531 else if (*i == '\t')
5538 if (i >= *ibuf + isz) { /* EOT */
5541 } else if (*i == '[') {
5542 state = STATE_BRACKET;
5547 state = STATE_OTHER;
5554 if (i >= *ibuf + isz || /* EOT */
5555 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5558 state = STATE_OTHER;
5560 } else if (*i == 'm')
5561 state = STATE_OTHER;
5583 int on_ac_power(void) {
5584 bool found_offline = false, found_online = false;
5585 _cleanup_closedir_ DIR *d = NULL;
5587 d = opendir("/sys/class/power_supply");
5593 union dirent_storage buf;
5594 _cleanup_close_ int fd = -1, device = -1;
5599 k = readdir_r(d, &buf.de, &de);
5606 if (ignore_file(de->d_name))
5609 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5611 if (errno == ENOENT || errno == ENOTDIR)
5617 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5619 if (errno == ENOENT)
5625 n = read(fd, contents, sizeof(contents));
5629 if (n != 6 || memcmp(contents, "Mains\n", 6))
5632 close_nointr_nofail(fd);
5633 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5635 if (errno == ENOENT)
5641 n = read(fd, contents, sizeof(contents));
5645 if (n != 2 || contents[1] != '\n')
5648 if (contents[0] == '1') {
5649 found_online = true;
5651 } else if (contents[0] == '0')
5652 found_offline = true;
5657 return found_online || !found_offline;
5660 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5667 if (!path_strv_canonicalize_uniq(search))
5670 STRV_FOREACH(i, search) {
5671 _cleanup_free_ char *p = NULL;
5674 p = strjoin(*i, "/", path, NULL);
5684 if (errno != ENOENT)
5691 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5692 _cleanup_strv_free_ char **copy = NULL;
5698 if (path_is_absolute(path)) {
5701 f = fopen(path, mode);
5710 copy = strv_copy((char**) search);
5714 return search_and_fopen_internal(path, mode, copy, _f);
5717 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5718 _cleanup_strv_free_ char **s = NULL;
5720 if (path_is_absolute(path)) {
5723 f = fopen(path, mode);
5732 s = strv_split_nulstr(search);
5736 return search_and_fopen_internal(path, mode, s, _f);
5739 int create_tmp_dir(char template[], char** dir_name) {
5742 mode_t _cleanup_umask_ u;
5747 d = mkdtemp(template);
5749 log_error("Can't create directory %s: %m", template);
5753 dt = strjoin(d, "/tmp", NULL);
5760 r = mkdir(dt, 0777);
5762 log_error("Can't create directory %s: %m", dt);
5766 log_debug("Created temporary directory %s", dt);
5768 r = chmod(dt, 0777 | S_ISVTX);
5770 log_error("Failed to chmod %s: %m", dt);
5774 log_debug("Set sticky bit on %s", dt);
5786 char *strextend(char **x, ...) {
5793 l = f = *x ? strlen(*x) : 0;
5800 t = va_arg(ap, const char *);
5805 if (n > ((size_t) -1) - l) {
5814 r = realloc(*x, l+1);
5824 t = va_arg(ap, const char *);
5838 char *strrep(const char *s, unsigned n) {
5846 p = r = malloc(l * n + 1);
5850 for (i = 0; i < n; i++)