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() */
1330 if (!(r = new(char, strlen(s)*3+1)))
1333 for (f = s, t = r; *f; f++) {
1335 if (!(*f >= 'A' && *f <= 'Z') &&
1336 !(*f >= 'a' && *f <= 'z') &&
1337 !(*f >= '0' && *f <= '9')) {
1339 *(t++) = hexchar(*f >> 4);
1340 *(t++) = hexchar(*f);
1350 char *bus_path_unescape(const char *f) {
1355 if (!(r = strdup(f)))
1358 for (t = r; *f; f++) {
1363 if ((a = unhexchar(f[1])) < 0 ||
1364 (b = unhexchar(f[2])) < 0) {
1365 /* Invalid escape code, let's take it literal then */
1368 *(t++) = (char) ((a << 4) | b);
1380 char *ascii_strlower(char *t) {
1385 for (p = t; *p; p++)
1386 if (*p >= 'A' && *p <= 'Z')
1387 *p = *p - 'A' + 'a';
1392 static bool ignore_file_allow_backup(const char *filename) {
1396 filename[0] == '.' ||
1397 streq(filename, "lost+found") ||
1398 streq(filename, "aquota.user") ||
1399 streq(filename, "aquota.group") ||
1400 endswith(filename, ".rpmnew") ||
1401 endswith(filename, ".rpmsave") ||
1402 endswith(filename, ".rpmorig") ||
1403 endswith(filename, ".dpkg-old") ||
1404 endswith(filename, ".dpkg-new") ||
1405 endswith(filename, ".swp");
1408 bool ignore_file(const char *filename) {
1411 if (endswith(filename, "~"))
1414 return ignore_file_allow_backup(filename);
1417 int fd_nonblock(int fd, bool nonblock) {
1422 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1426 flags |= O_NONBLOCK;
1428 flags &= ~O_NONBLOCK;
1430 if (fcntl(fd, F_SETFL, flags) < 0)
1436 int fd_cloexec(int fd, bool cloexec) {
1441 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1445 flags |= FD_CLOEXEC;
1447 flags &= ~FD_CLOEXEC;
1449 if (fcntl(fd, F_SETFD, flags) < 0)
1455 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1458 assert(n_fdset == 0 || fdset);
1460 for (i = 0; i < n_fdset; i++)
1467 int close_all_fds(const int except[], unsigned n_except) {
1472 assert(n_except == 0 || except);
1474 d = opendir("/proc/self/fd");
1479 /* When /proc isn't available (for example in chroots)
1480 * the fallback is brute forcing through the fd
1483 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1484 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1486 if (fd_in_set(fd, except, n_except))
1489 if (close_nointr(fd) < 0)
1490 if (errno != EBADF && r == 0)
1497 while ((de = readdir(d))) {
1500 if (ignore_file(de->d_name))
1503 if (safe_atoi(de->d_name, &fd) < 0)
1504 /* Let's better ignore this, just in case */
1513 if (fd_in_set(fd, except, n_except))
1516 if (close_nointr(fd) < 0) {
1517 /* Valgrind has its own FD and doesn't want to have it closed */
1518 if (errno != EBADF && r == 0)
1527 bool chars_intersect(const char *a, const char *b) {
1530 /* Returns true if any of the chars in a are in b. */
1531 for (p = a; *p; p++)
1538 bool fstype_is_network(const char *fstype) {
1539 static const char table[] =
1548 return nulstr_contains(table, fstype);
1552 _cleanup_close_ int fd;
1554 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1560 TIOCL_GETKMSGREDIRECT,
1564 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1567 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1570 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1576 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1577 struct termios old_termios, new_termios;
1579 char line[LINE_MAX];
1584 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1585 new_termios = old_termios;
1587 new_termios.c_lflag &= ~ICANON;
1588 new_termios.c_cc[VMIN] = 1;
1589 new_termios.c_cc[VTIME] = 0;
1591 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1594 if (t != (usec_t) -1) {
1595 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1596 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1601 k = fread(&c, 1, 1, f);
1603 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1609 *need_nl = c != '\n';
1616 if (t != (usec_t) -1)
1617 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1620 if (!fgets(line, sizeof(line), f))
1625 if (strlen(line) != 1)
1635 int ask(char *ret, const char *replies, const char *text, ...) {
1645 bool need_nl = true;
1648 fputs(ANSI_HIGHLIGHT_ON, stdout);
1655 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1659 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1662 if (r == -EBADMSG) {
1663 puts("Bad input, please try again.");
1674 if (strchr(replies, c)) {
1679 puts("Read unexpected character, please try again.");
1683 int reset_terminal_fd(int fd, bool switch_to_text) {
1684 struct termios termios;
1687 /* Set terminal to some sane defaults */
1691 /* We leave locked terminal attributes untouched, so that
1692 * Plymouth may set whatever it wants to set, and we don't
1693 * interfere with that. */
1695 /* Disable exclusive mode, just in case */
1696 ioctl(fd, TIOCNXCL);
1698 /* Switch to text mode */
1700 ioctl(fd, KDSETMODE, KD_TEXT);
1702 /* Enable console unicode mode */
1703 ioctl(fd, KDSKBMODE, K_UNICODE);
1705 if (tcgetattr(fd, &termios) < 0) {
1710 /* We only reset the stuff that matters to the software. How
1711 * hardware is set up we don't touch assuming that somebody
1712 * else will do that for us */
1714 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1715 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1716 termios.c_oflag |= ONLCR;
1717 termios.c_cflag |= CREAD;
1718 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1720 termios.c_cc[VINTR] = 03; /* ^C */
1721 termios.c_cc[VQUIT] = 034; /* ^\ */
1722 termios.c_cc[VERASE] = 0177;
1723 termios.c_cc[VKILL] = 025; /* ^X */
1724 termios.c_cc[VEOF] = 04; /* ^D */
1725 termios.c_cc[VSTART] = 021; /* ^Q */
1726 termios.c_cc[VSTOP] = 023; /* ^S */
1727 termios.c_cc[VSUSP] = 032; /* ^Z */
1728 termios.c_cc[VLNEXT] = 026; /* ^V */
1729 termios.c_cc[VWERASE] = 027; /* ^W */
1730 termios.c_cc[VREPRINT] = 022; /* ^R */
1731 termios.c_cc[VEOL] = 0;
1732 termios.c_cc[VEOL2] = 0;
1734 termios.c_cc[VTIME] = 0;
1735 termios.c_cc[VMIN] = 1;
1737 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1741 /* Just in case, flush all crap out */
1742 tcflush(fd, TCIOFLUSH);
1747 int reset_terminal(const char *name) {
1750 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1754 r = reset_terminal_fd(fd, true);
1755 close_nointr_nofail(fd);
1760 int open_terminal(const char *name, int mode) {
1765 * If a TTY is in the process of being closed opening it might
1766 * cause EIO. This is horribly awful, but unlikely to be
1767 * changed in the kernel. Hence we work around this problem by
1768 * retrying a couple of times.
1770 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1774 fd = open(name, mode);
1781 /* Max 1s in total */
1785 usleep(50 * USEC_PER_MSEC);
1794 close_nointr_nofail(fd);
1799 close_nointr_nofail(fd);
1806 int flush_fd(int fd) {
1807 struct pollfd pollfd;
1811 pollfd.events = POLLIN;
1818 if ((r = poll(&pollfd, 1, 0)) < 0) {
1829 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1834 if (errno == EAGAIN)
1845 int acquire_terminal(
1849 bool ignore_tiocstty_eperm,
1852 int fd = -1, notify = -1, r = 0, wd = -1;
1854 struct sigaction sa_old, sa_new;
1858 /* We use inotify to be notified when the tty is closed. We
1859 * create the watch before checking if we can actually acquire
1860 * it, so that we don't lose any event.
1862 * Note: strictly speaking this actually watches for the
1863 * device being closed, it does *not* really watch whether a
1864 * tty loses its controlling process. However, unless some
1865 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1866 * its tty otherwise this will not become a problem. As long
1867 * as the administrator makes sure not configure any service
1868 * on the same tty as an untrusted user this should not be a
1869 * problem. (Which he probably should not do anyway.) */
1871 if (timeout != (usec_t) -1)
1872 ts = now(CLOCK_MONOTONIC);
1874 if (!fail && !force) {
1875 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1881 wd = inotify_add_watch(notify, name, IN_CLOSE);
1890 r = flush_fd(notify);
1895 /* We pass here O_NOCTTY only so that we can check the return
1896 * value TIOCSCTTY and have a reliable way to figure out if we
1897 * successfully became the controlling process of the tty */
1898 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1902 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1903 * if we already own the tty. */
1905 sa_new.sa_handler = SIG_IGN;
1906 sa_new.sa_flags = SA_RESTART;
1907 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1909 /* First, try to get the tty */
1910 if (ioctl(fd, TIOCSCTTY, force) < 0)
1913 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1915 /* Sometimes it makes sense to ignore TIOCSCTTY
1916 * returning EPERM, i.e. when very likely we already
1917 * are have this controlling terminal. */
1918 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1921 if (r < 0 && (force || fail || r != -EPERM)) {
1930 assert(notify >= 0);
1933 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1935 struct inotify_event *e;
1937 if (timeout != (usec_t) -1) {
1940 n = now(CLOCK_MONOTONIC);
1941 if (ts + timeout < n) {
1946 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1956 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1959 if (errno == EINTR || errno == EAGAIN)
1966 e = (struct inotify_event*) inotify_buffer;
1971 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1976 step = sizeof(struct inotify_event) + e->len;
1977 assert(step <= (size_t) l);
1979 e = (struct inotify_event*) ((uint8_t*) e + step);
1986 /* We close the tty fd here since if the old session
1987 * ended our handle will be dead. It's important that
1988 * we do this after sleeping, so that we don't enter
1989 * an endless loop. */
1990 close_nointr_nofail(fd);
1994 close_nointr_nofail(notify);
1996 r = reset_terminal_fd(fd, true);
1998 log_warning("Failed to reset terminal: %s", strerror(-r));
2004 close_nointr_nofail(fd);
2007 close_nointr_nofail(notify);
2012 int release_terminal(void) {
2014 struct sigaction sa_old, sa_new;
2016 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2019 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2020 * by our own TIOCNOTTY */
2023 sa_new.sa_handler = SIG_IGN;
2024 sa_new.sa_flags = SA_RESTART;
2025 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2027 if (ioctl(fd, TIOCNOTTY) < 0)
2030 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2032 close_nointr_nofail(fd);
2036 int sigaction_many(const struct sigaction *sa, ...) {
2041 while ((sig = va_arg(ap, int)) > 0)
2042 if (sigaction(sig, sa, NULL) < 0)
2049 int ignore_signals(int sig, ...) {
2050 struct sigaction sa;
2055 sa.sa_handler = SIG_IGN;
2056 sa.sa_flags = SA_RESTART;
2058 if (sigaction(sig, &sa, NULL) < 0)
2062 while ((sig = va_arg(ap, int)) > 0)
2063 if (sigaction(sig, &sa, NULL) < 0)
2070 int default_signals(int sig, ...) {
2071 struct sigaction sa;
2076 sa.sa_handler = SIG_DFL;
2077 sa.sa_flags = SA_RESTART;
2079 if (sigaction(sig, &sa, NULL) < 0)
2083 while ((sig = va_arg(ap, int)) > 0)
2084 if (sigaction(sig, &sa, NULL) < 0)
2091 int close_pipe(int p[]) {
2097 a = close_nointr(p[0]);
2102 b = close_nointr(p[1]);
2106 return a < 0 ? a : b;
2109 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2118 while (nbytes > 0) {
2121 if ((k = read(fd, p, nbytes)) <= 0) {
2123 if (k < 0 && errno == EINTR)
2126 if (k < 0 && errno == EAGAIN && do_poll) {
2127 struct pollfd pollfd;
2131 pollfd.events = POLLIN;
2133 if (poll(&pollfd, 1, -1) < 0) {
2137 return n > 0 ? n : -errno;
2140 if (pollfd.revents != POLLIN)
2141 return n > 0 ? n : -EIO;
2146 return n > 0 ? n : (k < 0 ? -errno : 0);
2157 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2166 while (nbytes > 0) {
2169 k = write(fd, p, nbytes);
2172 if (k < 0 && errno == EINTR)
2175 if (k < 0 && errno == EAGAIN && do_poll) {
2176 struct pollfd pollfd;
2180 pollfd.events = POLLOUT;
2182 if (poll(&pollfd, 1, -1) < 0) {
2186 return n > 0 ? n : -errno;
2189 if (pollfd.revents != POLLOUT)
2190 return n > 0 ? n : -EIO;
2195 return n > 0 ? n : (k < 0 ? -errno : 0);
2206 int parse_bytes(const char *t, off_t *bytes) {
2207 static const struct {
2213 { "M", 1024ULL*1024ULL },
2214 { "G", 1024ULL*1024ULL*1024ULL },
2215 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2216 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2217 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2234 l = strtoll(p, &e, 10);
2245 e += strspn(e, WHITESPACE);
2247 for (i = 0; i < ELEMENTSOF(table); i++)
2248 if (startswith(e, table[i].suffix)) {
2249 r += (off_t) l * table[i].factor;
2250 p = e + strlen(table[i].suffix);
2254 if (i >= ELEMENTSOF(table))
2264 int make_stdio(int fd) {
2269 r = dup3(fd, STDIN_FILENO, 0);
2270 s = dup3(fd, STDOUT_FILENO, 0);
2271 t = dup3(fd, STDERR_FILENO, 0);
2274 close_nointr_nofail(fd);
2276 if (r < 0 || s < 0 || t < 0)
2279 /* We rely here that the new fd has O_CLOEXEC not set */
2284 int make_null_stdio(void) {
2287 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2291 return make_stdio(null_fd);
2294 bool is_device_path(const char *path) {
2296 /* Returns true on paths that refer to a device, either in
2297 * sysfs or in /dev */
2300 path_startswith(path, "/dev/") ||
2301 path_startswith(path, "/sys/");
2304 int dir_is_empty(const char *path) {
2305 _cleanup_closedir_ DIR *d;
2314 union dirent_storage buf;
2316 r = readdir_r(d, &buf.de, &de);
2323 if (!ignore_file(de->d_name))
2328 unsigned long long random_ull(void) {
2329 _cleanup_close_ int fd;
2333 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2337 r = loop_read(fd, &ull, sizeof(ull), true);
2338 if (r != sizeof(ull))
2344 return random() * RAND_MAX + random();
2347 void rename_process(const char name[8]) {
2350 /* This is a like a poor man's setproctitle(). It changes the
2351 * comm field, argv[0], and also the glibc's internally used
2352 * name of the process. For the first one a limit of 16 chars
2353 * applies, to the second one usually one of 10 (i.e. length
2354 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2355 * "systemd"). If you pass a longer string it will be
2358 prctl(PR_SET_NAME, name);
2360 if (program_invocation_name)
2361 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2363 if (saved_argc > 0) {
2367 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2369 for (i = 1; i < saved_argc; i++) {
2373 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2378 void sigset_add_many(sigset_t *ss, ...) {
2385 while ((sig = va_arg(ap, int)) > 0)
2386 assert_se(sigaddset(ss, sig) == 0);
2390 char* gethostname_malloc(void) {
2393 assert_se(uname(&u) >= 0);
2395 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2396 return strdup(u.nodename);
2398 return strdup(u.sysname);
2401 bool hostname_is_set(void) {
2404 assert_se(uname(&u) >= 0);
2406 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2409 static char *lookup_uid(uid_t uid) {
2412 _cleanup_free_ char *buf = NULL;
2413 struct passwd pwbuf, *pw = NULL;
2415 /* Shortcut things to avoid NSS lookups */
2417 return strdup("root");
2419 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2423 buf = malloc(bufsize);
2427 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2428 return strdup(pw->pw_name);
2430 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2436 char* getlogname_malloc(void) {
2440 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2445 return lookup_uid(uid);
2448 char *getusername_malloc(void) {
2455 return lookup_uid(getuid());
2458 int getttyname_malloc(int fd, char **r) {
2459 char path[PATH_MAX], *c;
2464 k = ttyname_r(fd, path, sizeof(path));
2470 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2478 int getttyname_harder(int fd, char **r) {
2482 k = getttyname_malloc(fd, &s);
2486 if (streq(s, "tty")) {
2488 return get_ctty(0, NULL, r);
2495 int get_ctty_devnr(pid_t pid, dev_t *d) {
2497 char line[LINE_MAX], *p, *fn;
2498 unsigned long ttynr;
2501 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2504 f = fopen(fn, "re");
2509 if (!fgets(line, sizeof(line), f)) {
2510 k = feof(f) ? -EIO : -errno;
2517 p = strrchr(line, ')');
2527 "%*d " /* session */
2532 if (major(ttynr) == 0 && minor(ttynr) == 0)
2539 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2541 char fn[PATH_MAX], *s, *b, *p;
2546 k = get_ctty_devnr(pid, &devnr);
2550 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2553 k = readlink_malloc(fn, &s);
2559 /* This is an ugly hack */
2560 if (major(devnr) == 136) {
2561 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2571 /* Probably something like the ptys which have no
2572 * symlink in /dev/char. Let's return something
2573 * vaguely useful. */
2586 if (startswith(s, "/dev/"))
2588 else if (startswith(s, "../"))
2606 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2612 /* This returns the first error we run into, but nevertheless
2613 * tries to go on. This closes the passed fd. */
2617 close_nointr_nofail(fd);
2619 return errno == ENOENT ? 0 : -errno;
2624 union dirent_storage buf;
2625 bool is_dir, keep_around;
2629 r = readdir_r(d, &buf.de, &de);
2630 if (r != 0 && ret == 0) {
2638 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2641 if (de->d_type == DT_UNKNOWN ||
2643 (de->d_type == DT_DIR && root_dev)) {
2644 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2645 if (ret == 0 && errno != ENOENT)
2650 is_dir = S_ISDIR(st.st_mode);
2653 (st.st_uid == 0 || st.st_uid == getuid()) &&
2654 (st.st_mode & S_ISVTX);
2656 is_dir = de->d_type == DT_DIR;
2657 keep_around = false;
2663 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2664 if (root_dev && st.st_dev != root_dev->st_dev)
2667 subdir_fd = openat(fd, de->d_name,
2668 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2669 if (subdir_fd < 0) {
2670 if (ret == 0 && errno != ENOENT)
2675 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2676 if (r < 0 && ret == 0)
2680 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2681 if (ret == 0 && errno != ENOENT)
2685 } else if (!only_dirs && !keep_around) {
2687 if (unlinkat(fd, de->d_name, 0) < 0) {
2688 if (ret == 0 && errno != ENOENT)
2699 static int is_temporary_fs(struct statfs *s) {
2701 return s->f_type == TMPFS_MAGIC ||
2702 (long)s->f_type == (long)RAMFS_MAGIC;
2705 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2710 if (fstatfs(fd, &s) < 0) {
2711 close_nointr_nofail(fd);
2715 /* We refuse to clean disk file systems with this call. This
2716 * is extra paranoia just to be sure we never ever remove
2718 if (!is_temporary_fs(&s)) {
2719 log_error("Attempted to remove disk file system, and we can't allow that.");
2720 close_nointr_nofail(fd);
2724 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2727 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2733 /* We refuse to clean the root file system with this
2734 * call. This is extra paranoia to never cause a really
2735 * seriously broken system. */
2736 if (path_equal(path, "/")) {
2737 log_error("Attempted to remove entire root file system, and we can't allow that.");
2741 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2744 if (errno != ENOTDIR)
2748 if (statfs(path, &s) < 0)
2751 if (!is_temporary_fs(&s)) {
2752 log_error("Attempted to remove disk file system, and we can't allow that.");
2757 if (delete_root && !only_dirs)
2758 if (unlink(path) < 0 && errno != ENOENT)
2765 if (fstatfs(fd, &s) < 0) {
2766 close_nointr_nofail(fd);
2770 if (!is_temporary_fs(&s)) {
2771 log_error("Attempted to remove disk file system, and we can't allow that.");
2772 close_nointr_nofail(fd);
2777 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2780 if (honour_sticky && file_is_priv_sticky(path) > 0)
2783 if (rmdir(path) < 0 && errno != ENOENT) {
2792 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2793 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2796 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2797 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2800 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2803 /* Under the assumption that we are running privileged we
2804 * first change the access mode and only then hand out
2805 * ownership to avoid a window where access is too open. */
2807 if (mode != (mode_t) -1)
2808 if (chmod(path, mode) < 0)
2811 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2812 if (chown(path, uid, gid) < 0)
2818 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2821 /* Under the assumption that we are running privileged we
2822 * first change the access mode and only then hand out
2823 * ownership to avoid a window where access is too open. */
2825 if (fchmod(fd, mode) < 0)
2828 if (fchown(fd, uid, gid) < 0)
2834 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2838 /* Allocates the cpuset in the right size */
2841 if (!(r = CPU_ALLOC(n)))
2844 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2845 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2855 if (errno != EINVAL)
2862 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2863 static const char status_indent[] = " "; /* "[" STATUS "] " */
2864 _cleanup_free_ char *s = NULL;
2865 _cleanup_close_ int fd = -1;
2866 struct iovec iovec[6];
2868 static bool prev_ephemeral;
2872 /* This is independent of logging, as status messages are
2873 * optional and go exclusively to the console. */
2875 if (vasprintf(&s, format, ap) < 0)
2878 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2891 sl = status ? sizeof(status_indent)-1 : 0;
2897 e = ellipsize(s, emax, 75);
2907 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2908 prev_ephemeral = ephemeral;
2911 if (!isempty(status)) {
2912 IOVEC_SET_STRING(iovec[n++], "[");
2913 IOVEC_SET_STRING(iovec[n++], status);
2914 IOVEC_SET_STRING(iovec[n++], "] ");
2916 IOVEC_SET_STRING(iovec[n++], status_indent);
2919 IOVEC_SET_STRING(iovec[n++], s);
2921 IOVEC_SET_STRING(iovec[n++], "\n");
2923 if (writev(fd, iovec, n) < 0)
2929 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2935 va_start(ap, format);
2936 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2942 int status_welcome(void) {
2944 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2946 r = parse_env_file("/etc/os-release", NEWLINE,
2947 "PRETTY_NAME", &pretty_name,
2948 "ANSI_COLOR", &ansi_color,
2950 if (r < 0 && r != -ENOENT)
2951 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2953 return status_printf(NULL, false,
2954 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2955 isempty(ansi_color) ? "1" : ansi_color,
2956 isempty(pretty_name) ? "Linux" : pretty_name);
2959 char *replace_env(const char *format, char **env) {
2966 const char *e, *word = format;
2971 for (e = format; *e; e ++) {
2982 if (!(k = strnappend(r, word, e-word-1)))
2991 } else if (*e == '$') {
2992 if (!(k = strnappend(r, word, e-word)))
3008 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3010 k = strappend(r, t);
3024 if (!(k = strnappend(r, word, e-word)))
3035 char **replace_env_argv(char **argv, char **env) {
3037 unsigned k = 0, l = 0;
3039 l = strv_length(argv);
3041 if (!(r = new(char*, l+1)))
3044 STRV_FOREACH(i, argv) {
3046 /* If $FOO appears as single word, replace it by the split up variable */
3047 if ((*i)[0] == '$' && (*i)[1] != '{') {
3052 e = strv_env_get(env, *i+1);
3055 if (!(m = strv_split_quoted(e))) {
3066 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3075 memcpy(r + k, m, q * sizeof(char*));
3083 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3084 if (!(r[k++] = replace_env(*i, env))) {
3094 int fd_columns(int fd) {
3098 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3107 unsigned columns(void) {
3111 if (_likely_(cached_columns > 0))
3112 return cached_columns;
3115 e = getenv("COLUMNS");
3120 c = fd_columns(STDOUT_FILENO);
3129 int fd_lines(int fd) {
3133 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3142 unsigned lines(void) {
3146 if (_likely_(cached_lines > 0))
3147 return cached_lines;
3150 e = getenv("LINES");
3155 l = fd_lines(STDOUT_FILENO);
3161 return cached_lines;
3164 /* intended to be used as a SIGWINCH sighandler */
3165 void columns_lines_cache_reset(int signum) {
3171 static int cached_on_tty = -1;
3173 if (_unlikely_(cached_on_tty < 0))
3174 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3176 return cached_on_tty;
3179 int running_in_chroot(void) {
3185 /* Only works as root */
3187 if (stat("/proc/1/root", &a) < 0)
3190 if (stat("/", &b) < 0)
3194 a.st_dev != b.st_dev ||
3195 a.st_ino != b.st_ino;
3198 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3203 assert(percent <= 100);
3204 assert(new_length >= 3);
3206 if (old_length <= 3 || old_length <= new_length)
3207 return strndup(s, old_length);
3209 r = new0(char, new_length+1);
3213 x = (new_length * percent) / 100;
3215 if (x > new_length - 3)
3223 s + old_length - (new_length - x - 3),
3224 new_length - x - 3);
3229 char *ellipsize(const char *s, size_t length, unsigned percent) {
3230 return ellipsize_mem(s, strlen(s), length, percent);
3233 int touch(const char *path) {
3238 /* This just opens the file for writing, ensuring it
3239 * exists. It doesn't call utimensat() the way /usr/bin/touch
3242 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3246 close_nointr_nofail(fd);
3250 char *unquote(const char *s, const char* quotes) {
3254 /* This is rather stupid, simply removes the heading and
3255 * trailing quotes if there is one. Doesn't care about
3256 * escaping or anything. We should make this smarter one
3263 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3264 return strndup(s+1, l-2);
3269 char *normalize_env_assignment(const char *s) {
3270 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3273 eq = strchr(s, '=');
3285 memmove(r, t, strlen(t) + 1);
3289 name = strndup(s, eq - s);
3297 value = unquote(strstrip(p), QUOTES);
3301 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3307 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3318 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3330 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3337 r = wait_for_terminate(pid, &status);
3339 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3343 if (status.si_code == CLD_EXITED) {
3344 if (status.si_status != 0) {
3345 log_warning("%s failed with error code %i.", name, status.si_status);
3346 return status.si_status;
3349 log_debug("%s succeeded.", name);
3352 } else if (status.si_code == CLD_KILLED ||
3353 status.si_code == CLD_DUMPED) {
3355 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3359 log_warning("%s failed due to unknown reason.", name);
3363 _noreturn_ void freeze(void) {
3365 /* Make sure nobody waits for us on a socket anymore */
3366 close_all_fds(NULL, 0);
3374 bool null_or_empty(struct stat *st) {
3377 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3380 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3386 int null_or_empty_path(const char *fn) {
3391 if (stat(fn, &st) < 0)
3394 return null_or_empty(&st);
3397 DIR *xopendirat(int fd, const char *name, int flags) {
3401 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3407 close_nointr_nofail(nfd);
3414 int signal_from_string_try_harder(const char *s) {
3418 signo = signal_from_string(s);
3420 if (startswith(s, "SIG"))
3421 return signal_from_string(s+3);
3426 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3430 /* FIXME: to follow udev's logic 100% we need to leave valid
3431 * UTF8 chars unescaped */
3433 u = unquote(tagvalue, "\"\'");
3437 t = xescape(u, "/ ");
3443 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3452 char *fstab_node_to_udev_node(const char *p) {
3455 if (startswith(p, "LABEL="))
3456 return tag_to_udev_node(p+6, "label");
3458 if (startswith(p, "UUID="))
3459 return tag_to_udev_node(p+5, "uuid");
3461 if (startswith(p, "PARTUUID="))
3462 return tag_to_udev_node(p+9, "partuuid");
3464 if (startswith(p, "PARTLABEL="))
3465 return tag_to_udev_node(p+10, "partlabel");
3470 bool tty_is_vc(const char *tty) {
3473 if (startswith(tty, "/dev/"))
3476 return vtnr_from_tty(tty) >= 0;
3479 bool tty_is_console(const char *tty) {
3482 if (startswith(tty, "/dev/"))
3485 return streq(tty, "console");
3488 int vtnr_from_tty(const char *tty) {
3493 if (startswith(tty, "/dev/"))
3496 if (!startswith(tty, "tty") )
3499 if (tty[3] < '0' || tty[3] > '9')
3502 r = safe_atoi(tty+3, &i);
3506 if (i < 0 || i > 63)
3512 char *resolve_dev_console(char **active) {
3515 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3516 * (i.e. not read-only-mounted which is a sign for container setups) */
3518 if (path_is_read_only_fs("/sys") > 0)
3521 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3524 /* If multiple log outputs are configured the last one is what
3525 * /dev/console points to */
3526 tty = strrchr(*active, ' ');
3535 bool tty_is_vc_resolve(const char *tty) {
3536 char *active = NULL;
3541 if (startswith(tty, "/dev/"))
3544 if (streq(tty, "console")) {
3545 tty = resolve_dev_console(&active);
3556 const char *default_term_for_tty(const char *tty) {
3559 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3562 bool dirent_is_file(const struct dirent *de) {
3565 if (ignore_file(de->d_name))
3568 if (de->d_type != DT_REG &&
3569 de->d_type != DT_LNK &&
3570 de->d_type != DT_UNKNOWN)
3576 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3579 if (de->d_type != DT_REG &&
3580 de->d_type != DT_LNK &&
3581 de->d_type != DT_UNKNOWN)
3584 if (ignore_file_allow_backup(de->d_name))
3587 return endswith(de->d_name, suffix);
3590 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3593 Hashmap *pids = NULL;
3597 /* Executes all binaries in a directory in parallel and waits
3598 * until all they all finished. */
3601 if (!(_d = opendir(directory))) {
3603 if (errno == ENOENT)
3606 log_error("Failed to enumerate directory %s: %m", directory);
3613 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3614 log_error("Failed to allocate set.");
3618 while ((de = readdir(d))) {
3623 if (!dirent_is_file(de))
3626 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3631 if ((pid = fork()) < 0) {
3632 log_error("Failed to fork: %m");
3650 log_error("Failed to execute %s: %m", path);
3651 _exit(EXIT_FAILURE);
3654 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3656 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3657 log_error("Failed to add PID to set: %s", strerror(-k));
3662 while (!hashmap_isempty(pids)) {
3663 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3668 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3673 log_error("waitid() failed: %m");
3677 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3678 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3679 if (si.si_code == CLD_EXITED)
3680 log_error("%s exited with exit status %i.", path, si.si_status);
3682 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3684 log_debug("%s exited successfully.", path);
3695 hashmap_free_free(pids);
3698 int kill_and_sigcont(pid_t pid, int sig) {
3701 r = kill(pid, sig) < 0 ? -errno : 0;
3709 bool nulstr_contains(const char*nulstr, const char *needle) {
3715 NULSTR_FOREACH(i, nulstr)
3716 if (streq(i, needle))
3722 bool plymouth_running(void) {
3723 return access("/run/plymouth/pid", F_OK) >= 0;
3726 char* strshorten(char *s, size_t l) {
3735 static bool hostname_valid_char(char c) {
3737 (c >= 'a' && c <= 'z') ||
3738 (c >= 'A' && c <= 'Z') ||
3739 (c >= '0' && c <= '9') ||
3745 bool hostname_is_valid(const char *s) {
3751 for (p = s; *p; p++)
3752 if (!hostname_valid_char(*p))
3755 if (p-s > HOST_NAME_MAX)
3761 char* hostname_cleanup(char *s) {
3764 for (p = s, d = s; *p; p++)
3765 if ((*p >= 'a' && *p <= 'z') ||
3766 (*p >= 'A' && *p <= 'Z') ||
3767 (*p >= '0' && *p <= '9') ||
3775 strshorten(s, HOST_NAME_MAX);
3779 int pipe_eof(int fd) {
3780 struct pollfd pollfd;
3785 pollfd.events = POLLIN|POLLHUP;
3787 r = poll(&pollfd, 1, 0);
3794 return pollfd.revents & POLLHUP;
3797 int fd_wait_for_event(int fd, int event, usec_t t) {
3798 struct pollfd pollfd;
3803 pollfd.events = event;
3805 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3812 return pollfd.revents;
3815 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3826 t = new(char, strlen(path) + 1 + 6 + 1);
3830 fn = path_get_file_name(path);
3834 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3836 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3842 f = fdopen(fd, "we");
3855 int terminal_vhangup_fd(int fd) {
3858 if (ioctl(fd, TIOCVHANGUP) < 0)
3864 int terminal_vhangup(const char *name) {
3867 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3871 r = terminal_vhangup_fd(fd);
3872 close_nointr_nofail(fd);
3877 int vt_disallocate(const char *name) {
3881 /* Deallocate the VT if possible. If not possible
3882 * (i.e. because it is the active one), at least clear it
3883 * entirely (including the scrollback buffer) */
3885 if (!startswith(name, "/dev/"))
3888 if (!tty_is_vc(name)) {
3889 /* So this is not a VT. I guess we cannot deallocate
3890 * it then. But let's at least clear the screen */
3892 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3897 "\033[r" /* clear scrolling region */
3898 "\033[H" /* move home */
3899 "\033[2J", /* clear screen */
3901 close_nointr_nofail(fd);
3906 if (!startswith(name, "/dev/tty"))
3909 r = safe_atou(name+8, &u);
3916 /* Try to deallocate */
3917 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3921 r = ioctl(fd, VT_DISALLOCATE, u);
3922 close_nointr_nofail(fd);
3930 /* Couldn't deallocate, so let's clear it fully with
3932 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3937 "\033[r" /* clear scrolling region */
3938 "\033[H" /* move home */
3939 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3941 close_nointr_nofail(fd);
3946 int copy_file(const char *from, const char *to) {
3952 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
3956 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
3958 close_nointr_nofail(fdf);
3966 n = read(fdf, buf, sizeof(buf));
3970 close_nointr_nofail(fdf);
3981 k = loop_write(fdt, buf, n, false);
3983 r = k < 0 ? k : (errno ? -errno : -EIO);
3985 close_nointr_nofail(fdf);
3993 close_nointr_nofail(fdf);
3994 r = close_nointr(fdt);
4004 int symlink_atomic(const char *from, const char *to) {
4006 _cleanup_free_ char *t;
4009 unsigned long long ull;
4016 t = new(char, strlen(to) + 1 + 16 + 1);
4020 fn = path_get_file_name(to);
4024 x = stpcpy(t+k+1, fn);
4027 for (i = 0; i < 16; i++) {
4028 *(x++) = hexchar(ull & 0xF);
4034 if (symlink(from, t) < 0)
4037 if (rename(t, to) < 0) {
4046 bool display_is_local(const char *display) {
4050 display[0] == ':' &&
4051 display[1] >= '0' &&
4055 int socket_from_display(const char *display, char **path) {
4062 if (!display_is_local(display))
4065 k = strspn(display+1, "0123456789");
4067 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4071 c = stpcpy(f, "/tmp/.X11-unix/X");
4072 memcpy(c, display+1, k);
4081 const char **username,
4082 uid_t *uid, gid_t *gid,
4084 const char **shell) {
4092 /* We enforce some special rules for uid=0: in order to avoid
4093 * NSS lookups for root we hardcode its data. */
4095 if (streq(*username, "root") || streq(*username, "0")) {
4113 if (parse_uid(*username, &u) >= 0) {
4117 /* If there are multiple users with the same id, make
4118 * sure to leave $USER to the configured value instead
4119 * of the first occurrence in the database. However if
4120 * the uid was configured by a numeric uid, then let's
4121 * pick the real username from /etc/passwd. */
4123 *username = p->pw_name;
4126 p = getpwnam(*username);
4130 return errno != 0 ? -errno : -ESRCH;
4142 *shell = p->pw_shell;
4147 char* uid_to_name(uid_t uid) {
4152 return strdup("root");
4156 return strdup(p->pw_name);
4158 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4164 int get_group_creds(const char **groupname, gid_t *gid) {
4170 /* We enforce some special rules for gid=0: in order to avoid
4171 * NSS lookups for root we hardcode its data. */
4173 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4174 *groupname = "root";
4182 if (parse_gid(*groupname, &id) >= 0) {
4187 *groupname = g->gr_name;
4190 g = getgrnam(*groupname);
4194 return errno != 0 ? -errno : -ESRCH;
4202 int in_group(const char *name) {
4204 int ngroups_max, r, i;
4206 r = get_group_creds(&name, &gid);
4210 if (getgid() == gid)
4213 if (getegid() == gid)
4216 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4217 assert(ngroups_max > 0);
4219 gids = alloca(sizeof(gid_t) * ngroups_max);
4221 r = getgroups(ngroups_max, gids);
4225 for (i = 0; i < r; i++)
4232 int glob_exists(const char *path) {
4240 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4242 if (k == GLOB_NOMATCH)
4244 else if (k == GLOB_NOSPACE)
4247 r = !strv_isempty(g.gl_pathv);
4249 r = errno ? -errno : -EIO;
4256 int dirent_ensure_type(DIR *d, struct dirent *de) {
4262 if (de->d_type != DT_UNKNOWN)
4265 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4269 S_ISREG(st.st_mode) ? DT_REG :
4270 S_ISDIR(st.st_mode) ? DT_DIR :
4271 S_ISLNK(st.st_mode) ? DT_LNK :
4272 S_ISFIFO(st.st_mode) ? DT_FIFO :
4273 S_ISSOCK(st.st_mode) ? DT_SOCK :
4274 S_ISCHR(st.st_mode) ? DT_CHR :
4275 S_ISBLK(st.st_mode) ? DT_BLK :
4281 int in_search_path(const char *path, char **search) {
4285 r = path_get_parent(path, &parent);
4291 STRV_FOREACH(i, search) {
4292 if (path_equal(parent, *i)) {
4303 int get_files_in_directory(const char *path, char ***list) {
4311 /* Returns all files in a directory in *list, and the number
4312 * of files as return value. If list is NULL returns only the
4321 union dirent_storage buf;
4324 k = readdir_r(d, &buf.de, &de);
4333 dirent_ensure_type(d, de);
4335 if (!dirent_is_file(de))
4339 if ((unsigned) r >= n) {
4343 t = realloc(l, sizeof(char*) * n);
4352 assert((unsigned) r < n);
4354 l[r] = strdup(de->d_name);
4378 char *strjoin(const char *x, ...) {
4392 t = va_arg(ap, const char *);
4397 if (n > ((size_t) -1) - l) {
4421 t = va_arg(ap, const char *);
4435 bool is_main_thread(void) {
4436 static __thread int cached = 0;
4438 if (_unlikely_(cached == 0))
4439 cached = getpid() == gettid() ? 1 : -1;
4444 int block_get_whole_disk(dev_t d, dev_t *ret) {
4451 /* If it has a queue this is good enough for us */
4452 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4455 r = access(p, F_OK);
4463 /* If it is a partition find the originating device */
4464 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4467 r = access(p, F_OK);
4473 /* Get parent dev_t */
4474 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4477 r = read_one_line_file(p, &s);
4483 r = sscanf(s, "%u:%u", &m, &n);
4489 /* Only return this if it is really good enough for us. */
4490 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4493 r = access(p, F_OK);
4497 *ret = makedev(m, n);
4504 int file_is_priv_sticky(const char *p) {
4509 if (lstat(p, &st) < 0)
4513 (st.st_uid == 0 || st.st_uid == getuid()) &&
4514 (st.st_mode & S_ISVTX);
4517 static const char *const ioprio_class_table[] = {
4518 [IOPRIO_CLASS_NONE] = "none",
4519 [IOPRIO_CLASS_RT] = "realtime",
4520 [IOPRIO_CLASS_BE] = "best-effort",
4521 [IOPRIO_CLASS_IDLE] = "idle"
4524 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4526 static const char *const sigchld_code_table[] = {
4527 [CLD_EXITED] = "exited",
4528 [CLD_KILLED] = "killed",
4529 [CLD_DUMPED] = "dumped",
4530 [CLD_TRAPPED] = "trapped",
4531 [CLD_STOPPED] = "stopped",
4532 [CLD_CONTINUED] = "continued",
4535 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4537 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4538 [LOG_FAC(LOG_KERN)] = "kern",
4539 [LOG_FAC(LOG_USER)] = "user",
4540 [LOG_FAC(LOG_MAIL)] = "mail",
4541 [LOG_FAC(LOG_DAEMON)] = "daemon",
4542 [LOG_FAC(LOG_AUTH)] = "auth",
4543 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4544 [LOG_FAC(LOG_LPR)] = "lpr",
4545 [LOG_FAC(LOG_NEWS)] = "news",
4546 [LOG_FAC(LOG_UUCP)] = "uucp",
4547 [LOG_FAC(LOG_CRON)] = "cron",
4548 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4549 [LOG_FAC(LOG_FTP)] = "ftp",
4550 [LOG_FAC(LOG_LOCAL0)] = "local0",
4551 [LOG_FAC(LOG_LOCAL1)] = "local1",
4552 [LOG_FAC(LOG_LOCAL2)] = "local2",
4553 [LOG_FAC(LOG_LOCAL3)] = "local3",
4554 [LOG_FAC(LOG_LOCAL4)] = "local4",
4555 [LOG_FAC(LOG_LOCAL5)] = "local5",
4556 [LOG_FAC(LOG_LOCAL6)] = "local6",
4557 [LOG_FAC(LOG_LOCAL7)] = "local7"
4560 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4562 static const char *const log_level_table[] = {
4563 [LOG_EMERG] = "emerg",
4564 [LOG_ALERT] = "alert",
4565 [LOG_CRIT] = "crit",
4567 [LOG_WARNING] = "warning",
4568 [LOG_NOTICE] = "notice",
4569 [LOG_INFO] = "info",
4570 [LOG_DEBUG] = "debug"
4573 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4575 static const char* const sched_policy_table[] = {
4576 [SCHED_OTHER] = "other",
4577 [SCHED_BATCH] = "batch",
4578 [SCHED_IDLE] = "idle",
4579 [SCHED_FIFO] = "fifo",
4583 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4585 static const char* const rlimit_table[] = {
4586 [RLIMIT_CPU] = "LimitCPU",
4587 [RLIMIT_FSIZE] = "LimitFSIZE",
4588 [RLIMIT_DATA] = "LimitDATA",
4589 [RLIMIT_STACK] = "LimitSTACK",
4590 [RLIMIT_CORE] = "LimitCORE",
4591 [RLIMIT_RSS] = "LimitRSS",
4592 [RLIMIT_NOFILE] = "LimitNOFILE",
4593 [RLIMIT_AS] = "LimitAS",
4594 [RLIMIT_NPROC] = "LimitNPROC",
4595 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4596 [RLIMIT_LOCKS] = "LimitLOCKS",
4597 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4598 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4599 [RLIMIT_NICE] = "LimitNICE",
4600 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4601 [RLIMIT_RTTIME] = "LimitRTTIME"
4604 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4606 static const char* const ip_tos_table[] = {
4607 [IPTOS_LOWDELAY] = "low-delay",
4608 [IPTOS_THROUGHPUT] = "throughput",
4609 [IPTOS_RELIABILITY] = "reliability",
4610 [IPTOS_LOWCOST] = "low-cost",
4613 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4615 static const char *const __signal_table[] = {
4632 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4643 [SIGVTALRM] = "VTALRM",
4645 [SIGWINCH] = "WINCH",
4651 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4653 const char *signal_to_string(int signo) {
4654 static __thread char buf[12];
4657 name = __signal_to_string(signo);
4661 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4662 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4664 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4669 int signal_from_string(const char *s) {
4674 signo = __signal_from_string(s);
4678 if (startswith(s, "RTMIN+")) {
4682 if (safe_atou(s, &u) >= 0) {
4683 signo = (int) u + offset;
4684 if (signo > 0 && signo < _NSIG)
4690 bool kexec_loaded(void) {
4691 bool loaded = false;
4694 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4702 int strdup_or_null(const char *a, char **b) {
4720 int prot_from_flags(int flags) {
4722 switch (flags & O_ACCMODE) {
4731 return PROT_READ|PROT_WRITE;
4738 char *format_bytes(char *buf, size_t l, off_t t) {
4741 static const struct {
4745 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4746 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4747 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4748 { "G", 1024ULL*1024ULL*1024ULL },
4749 { "M", 1024ULL*1024ULL },
4753 for (i = 0; i < ELEMENTSOF(table); i++) {
4755 if (t >= table[i].factor) {
4758 (unsigned long long) (t / table[i].factor),
4759 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4766 snprintf(buf, l, "%lluB", (unsigned long long) t);
4774 void* memdup(const void *p, size_t l) {
4787 int fd_inc_sndbuf(int fd, size_t n) {
4789 socklen_t l = sizeof(value);
4791 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4793 l == sizeof(value) &&
4794 (size_t) value >= n*2)
4798 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4805 int fd_inc_rcvbuf(int fd, size_t n) {
4807 socklen_t l = sizeof(value);
4809 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4811 l == sizeof(value) &&
4812 (size_t) value >= n*2)
4816 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4823 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4824 pid_t parent_pid, agent_pid;
4826 bool stdout_is_tty, stderr_is_tty;
4834 parent_pid = getpid();
4836 /* Spawns a temporary TTY agent, making sure it goes away when
4843 if (agent_pid != 0) {
4850 * Make sure the agent goes away when the parent dies */
4851 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4852 _exit(EXIT_FAILURE);
4854 /* Check whether our parent died before we were able
4855 * to set the death signal */
4856 if (getppid() != parent_pid)
4857 _exit(EXIT_SUCCESS);
4859 /* Don't leak fds to the agent */
4860 close_all_fds(except, n_except);
4862 stdout_is_tty = isatty(STDOUT_FILENO);
4863 stderr_is_tty = isatty(STDERR_FILENO);
4865 if (!stdout_is_tty || !stderr_is_tty) {
4866 /* Detach from stdout/stderr. and reopen
4867 * /dev/tty for them. This is important to
4868 * ensure that when systemctl is started via
4869 * popen() or a similar call that expects to
4870 * read EOF we actually do generate EOF and
4871 * not delay this indefinitely by because we
4872 * keep an unused copy of stdin around. */
4873 fd = open("/dev/tty", O_WRONLY);
4875 log_error("Failed to open /dev/tty: %m");
4876 _exit(EXIT_FAILURE);
4880 dup2(fd, STDOUT_FILENO);
4883 dup2(fd, STDERR_FILENO);
4889 /* Count arguments */
4891 for (n = 0; va_arg(ap, char*); n++)
4896 l = alloca(sizeof(char *) * (n + 1));
4898 /* Fill in arguments */
4900 for (i = 0; i <= n; i++)
4901 l[i] = va_arg(ap, char*);
4905 _exit(EXIT_FAILURE);
4908 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4909 struct rlimit highest, fixed;
4913 if (setrlimit(resource, rlim) >= 0)
4919 /* So we failed to set the desired setrlimit, then let's try
4920 * to get as close as we can */
4921 assert_se(getrlimit(resource, &highest) == 0);
4923 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4924 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4926 if (setrlimit(resource, &fixed) < 0)
4932 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
4933 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
4945 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
4948 f = fopen(path, "re");
4956 char line[LINE_MAX];
4959 for (i = 0; i < sizeof(line)-1; i++) {
4963 if (_unlikely_(c == EOF)) {
4973 if (memcmp(line, field, l) == 0 && line[l] == '=') {
4974 value = strdup(line + l + 1);
4994 int can_sleep(const char *type) {
4998 _cleanup_free_ char *p = NULL;
5002 /* If /sys is read-only we cannot sleep */
5003 if (access("/sys/power/state", W_OK) < 0)
5006 r = read_one_line_file("/sys/power/state", &p);
5011 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
5012 if (l == k && memcmp(w, type, l) == 0)
5018 int can_sleep_disk(const char *type) {
5022 _cleanup_free_ char *p = NULL;
5026 /* If /sys is read-only we cannot sleep */
5027 if (access("/sys/power/state", W_OK) < 0 ||
5028 access("/sys/power/disk", W_OK) < 0)
5031 r = read_one_line_file("/sys/power/disk", &p);
5036 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5037 if (l == k && memcmp(w, type, l) == 0)
5040 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5047 bool is_valid_documentation_url(const char *url) {
5050 if (startswith(url, "http://") && url[7])
5053 if (startswith(url, "https://") && url[8])
5056 if (startswith(url, "file:") && url[5])
5059 if (startswith(url, "info:") && url[5])
5062 if (startswith(url, "man:") && url[4])
5068 bool in_initrd(void) {
5069 static __thread int saved = -1;
5075 /* We make two checks here:
5077 * 1. the flag file /etc/initrd-release must exist
5078 * 2. the root file system must be a memory file system
5080 * The second check is extra paranoia, since misdetecting an
5081 * initrd can have bad bad consequences due the initrd
5082 * emptying when transititioning to the main systemd.
5085 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5086 statfs("/", &s) >= 0 &&
5087 is_temporary_fs(&s);
5092 void warn_melody(void) {
5093 _cleanup_close_ int fd = -1;
5095 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5099 /* Yeah, this is synchronous. Kinda sucks. But well... */
5101 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5102 usleep(125*USEC_PER_MSEC);
5104 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5105 usleep(125*USEC_PER_MSEC);
5107 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5108 usleep(125*USEC_PER_MSEC);
5110 ioctl(fd, KIOCSOUND, 0);
5113 int make_console_stdio(void) {
5116 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5118 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5120 log_error("Failed to acquire terminal: %s", strerror(-fd));
5126 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5133 int get_home_dir(char **_h) {
5141 /* Take the user specified one */
5152 /* Hardcode home directory for root to avoid NSS */
5155 h = strdup("/root");
5163 /* Check the database... */
5167 return errno ? -errno : -ESRCH;
5169 if (!path_is_absolute(p->pw_dir))
5172 h = strdup(p->pw_dir);
5180 int get_shell(char **_sh) {
5188 /* Take the user specified one */
5189 e = getenv("SHELL");
5199 /* Hardcode home directory for root to avoid NSS */
5202 sh = strdup("/bin/sh");
5210 /* Check the database... */
5214 return errno ? -errno : -ESRCH;
5216 if (!path_is_absolute(p->pw_shell))
5219 sh = strdup(p->pw_shell);
5227 void freep(void *p) {
5231 void fclosep(FILE **f) {
5236 void pclosep(FILE **f) {
5241 void closep(int *fd) {
5243 close_nointr_nofail(*fd);
5246 void closedirp(DIR **d) {
5251 void umaskp(mode_t *u) {
5255 bool filename_is_safe(const char *p) {
5269 if (strlen(p) > FILENAME_MAX)
5275 bool string_is_safe(const char *p) {
5280 for (t = p; *t; t++) {
5281 if (*t > 0 && *t < ' ')
5284 if (strchr("\\\"\'", *t))
5291 bool string_has_cc(const char *p) {
5296 for (t = p; *t; t++)
5297 if (*t > 0 && *t < ' ')
5303 bool path_is_safe(const char *p) {
5308 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5311 if (strlen(p) > PATH_MAX)
5314 /* The following two checks are not really dangerous, but hey, they still are confusing */
5315 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5318 if (strstr(p, "//"))
5324 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5325 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5326 int (*compar) (const void *, const void *, void *), void *arg) {
5335 p = (void *)(((const char *) base) + (idx * size));
5336 comparison = compar(key, p, arg);
5339 else if (comparison > 0)
5347 bool is_locale_utf8(void) {
5349 static int cached_answer = -1;
5351 if (cached_answer >= 0)
5354 if (!setlocale(LC_ALL, "")) {
5355 cached_answer = true;
5359 set = nl_langinfo(CODESET);
5361 cached_answer = true;
5365 cached_answer = streq(set, "UTF-8");
5367 return (bool)cached_answer;
5370 const char *draw_special_char(DrawSpecialChar ch) {
5371 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5373 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5374 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5375 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5376 [DRAW_TREE_SPACE] = " ", /* */
5377 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5379 /* ASCII fallback */ {
5380 [DRAW_TREE_VERT] = "| ",
5381 [DRAW_TREE_BRANCH] = "|-",
5382 [DRAW_TREE_RIGHT] = "`-",
5383 [DRAW_TREE_SPACE] = " ",
5384 [DRAW_TRIANGULAR_BULLET] = "> ",
5388 return draw_table[!is_locale_utf8()][ch];
5391 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5394 size_t l, old_len, new_len;
5400 old_len = strlen(old_string);
5401 new_len = strlen(new_string);
5414 if (!startswith(f, old_string)) {
5420 nl = l - old_len + new_len;
5421 a = realloc(r, nl + 1);
5429 t = stpcpy(t, new_string);
5441 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5442 const char *i, *begin = NULL;
5447 } state = STATE_OTHER;
5449 size_t osz = 0, isz;
5455 /* Strips ANSI color and replaces TABs by 8 spaces */
5457 isz = _isz ? *_isz : strlen(*ibuf);
5459 f = open_memstream(&obuf, &osz);
5463 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5468 if (i >= *ibuf + isz) /* EOT */
5470 else if (*i == '\x1B')
5471 state = STATE_ESCAPE;
5472 else if (*i == '\t')
5479 if (i >= *ibuf + isz) { /* EOT */
5482 } else if (*i == '[') {
5483 state = STATE_BRACKET;
5488 state = STATE_OTHER;
5495 if (i >= *ibuf + isz || /* EOT */
5496 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5499 state = STATE_OTHER;
5501 } else if (*i == 'm')
5502 state = STATE_OTHER;
5524 int on_ac_power(void) {
5525 bool found_offline = false, found_online = false;
5526 _cleanup_closedir_ DIR *d = NULL;
5528 d = opendir("/sys/class/power_supply");
5534 union dirent_storage buf;
5535 _cleanup_free_ char *p = NULL;
5536 _cleanup_close_ int fd = -1, device = -1;
5541 k = readdir_r(d, &buf.de, &de);
5548 if (ignore_file(de->d_name))
5551 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5553 if (errno == ENOENT || errno == ENOTDIR)
5559 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5561 if (errno == ENOENT)
5567 n = read(fd, contents, sizeof(contents));
5571 if (n != 6 || memcmp(contents, "Mains\n", 6))
5574 close_nointr_nofail(fd);
5575 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5577 if (errno == ENOENT)
5583 n = read(fd, contents, sizeof(contents));
5587 if (n != 2 || contents[1] != '\n')
5590 if (contents[0] == '1') {
5591 found_online = true;
5593 } else if (contents[0] == '0')
5594 found_offline = true;
5599 return found_online || !found_offline;
5602 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5609 if (!path_strv_canonicalize_uniq(search))
5612 STRV_FOREACH(i, search) {
5613 _cleanup_free_ char *p = NULL;
5616 p = strjoin(*i, "/", path, NULL);
5626 if (errno != ENOENT)
5633 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5634 _cleanup_strv_free_ char **copy = NULL;
5640 if (path_is_absolute(path)) {
5643 f = fopen(path, mode);
5652 copy = strv_copy((char**) search);
5656 return search_and_fopen_internal(path, mode, copy, _f);
5659 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5660 _cleanup_strv_free_ char **s = NULL;
5662 if (path_is_absolute(path)) {
5665 f = fopen(path, mode);
5674 s = strv_split_nulstr(search);
5678 return search_and_fopen_internal(path, mode, s, _f);