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, 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[5];
2871 /* This is independent of logging, as status messages are
2872 * optional and go exclusively to the console. */
2874 if (vasprintf(&s, format, ap) < 0)
2877 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2890 sl = status ? sizeof(status_indent)-1 : 0;
2896 e = ellipsize(s, emax, 75);
2906 if (!isempty(status)) {
2907 IOVEC_SET_STRING(iovec[n++], "[");
2908 IOVEC_SET_STRING(iovec[n++], status);
2909 IOVEC_SET_STRING(iovec[n++], "] ");
2911 IOVEC_SET_STRING(iovec[n++], status_indent);
2914 IOVEC_SET_STRING(iovec[n++], s);
2915 IOVEC_SET_STRING(iovec[n++], "\n");
2917 if (writev(fd, iovec, n) < 0)
2923 int status_printf(const char *status, bool ellipse, const char *format, ...) {
2929 va_start(ap, format);
2930 r = status_vprintf(status, ellipse, format, ap);
2936 int status_welcome(void) {
2938 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2940 r = parse_env_file("/etc/os-release", NEWLINE,
2941 "PRETTY_NAME", &pretty_name,
2942 "ANSI_COLOR", &ansi_color,
2944 if (r < 0 && r != -ENOENT)
2945 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2947 return status_printf(NULL, false,
2948 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2949 isempty(ansi_color) ? "1" : ansi_color,
2950 isempty(pretty_name) ? "Linux" : pretty_name);
2953 char *replace_env(const char *format, char **env) {
2960 const char *e, *word = format;
2965 for (e = format; *e; e ++) {
2976 if (!(k = strnappend(r, word, e-word-1)))
2985 } else if (*e == '$') {
2986 if (!(k = strnappend(r, word, e-word)))
3002 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3004 k = strappend(r, t);
3018 if (!(k = strnappend(r, word, e-word)))
3029 char **replace_env_argv(char **argv, char **env) {
3031 unsigned k = 0, l = 0;
3033 l = strv_length(argv);
3035 if (!(r = new(char*, l+1)))
3038 STRV_FOREACH(i, argv) {
3040 /* If $FOO appears as single word, replace it by the split up variable */
3041 if ((*i)[0] == '$' && (*i)[1] != '{') {
3046 e = strv_env_get(env, *i+1);
3049 if (!(m = strv_split_quoted(e))) {
3060 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3069 memcpy(r + k, m, q * sizeof(char*));
3077 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3078 if (!(r[k++] = replace_env(*i, env))) {
3088 int fd_columns(int fd) {
3092 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3101 unsigned columns(void) {
3105 if (_likely_(cached_columns > 0))
3106 return cached_columns;
3109 e = getenv("COLUMNS");
3114 c = fd_columns(STDOUT_FILENO);
3123 int fd_lines(int fd) {
3127 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3136 unsigned lines(void) {
3140 if (_likely_(cached_lines > 0))
3141 return cached_lines;
3144 e = getenv("LINES");
3149 l = fd_lines(STDOUT_FILENO);
3155 return cached_lines;
3158 /* intended to be used as a SIGWINCH sighandler */
3159 void columns_lines_cache_reset(int signum) {
3165 static int cached_on_tty = -1;
3167 if (_unlikely_(cached_on_tty < 0))
3168 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3170 return cached_on_tty;
3173 int running_in_chroot(void) {
3179 /* Only works as root */
3181 if (stat("/proc/1/root", &a) < 0)
3184 if (stat("/", &b) < 0)
3188 a.st_dev != b.st_dev ||
3189 a.st_ino != b.st_ino;
3192 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3197 assert(percent <= 100);
3198 assert(new_length >= 3);
3200 if (old_length <= 3 || old_length <= new_length)
3201 return strndup(s, old_length);
3203 r = new0(char, new_length+1);
3207 x = (new_length * percent) / 100;
3209 if (x > new_length - 3)
3217 s + old_length - (new_length - x - 3),
3218 new_length - x - 3);
3223 char *ellipsize(const char *s, size_t length, unsigned percent) {
3224 return ellipsize_mem(s, strlen(s), length, percent);
3227 int touch(const char *path) {
3232 /* This just opens the file for writing, ensuring it
3233 * exists. It doesn't call utimensat() the way /usr/bin/touch
3236 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3240 close_nointr_nofail(fd);
3244 char *unquote(const char *s, const char* quotes) {
3248 /* This is rather stupid, simply removes the heading and
3249 * trailing quotes if there is one. Doesn't care about
3250 * escaping or anything. We should make this smarter one
3257 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3258 return strndup(s+1, l-2);
3263 char *normalize_env_assignment(const char *s) {
3264 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3267 eq = strchr(s, '=');
3279 memmove(r, t, strlen(t) + 1);
3283 name = strndup(s, eq - s);
3291 value = unquote(strstrip(p), QUOTES);
3295 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3301 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3312 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3324 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3331 r = wait_for_terminate(pid, &status);
3333 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3337 if (status.si_code == CLD_EXITED) {
3338 if (status.si_status != 0) {
3339 log_warning("%s failed with error code %i.", name, status.si_status);
3340 return status.si_status;
3343 log_debug("%s succeeded.", name);
3346 } else if (status.si_code == CLD_KILLED ||
3347 status.si_code == CLD_DUMPED) {
3349 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3353 log_warning("%s failed due to unknown reason.", name);
3357 _noreturn_ void freeze(void) {
3359 /* Make sure nobody waits for us on a socket anymore */
3360 close_all_fds(NULL, 0);
3368 bool null_or_empty(struct stat *st) {
3371 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3374 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3380 int null_or_empty_path(const char *fn) {
3385 if (stat(fn, &st) < 0)
3388 return null_or_empty(&st);
3391 DIR *xopendirat(int fd, const char *name, int flags) {
3395 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags);
3401 close_nointr_nofail(nfd);
3408 int signal_from_string_try_harder(const char *s) {
3412 signo = signal_from_string(s);
3414 if (startswith(s, "SIG"))
3415 return signal_from_string(s+3);
3420 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3424 /* FIXME: to follow udev's logic 100% we need to leave valid
3425 * UTF8 chars unescaped */
3427 u = unquote(tagvalue, "\"\'");
3431 t = xescape(u, "/ ");
3437 r = asprintf(&dn, "/dev/disk/by-%s/%s", by, t);
3446 char *fstab_node_to_udev_node(const char *p) {
3449 if (startswith(p, "LABEL="))
3450 return tag_to_udev_node(p+6, "label");
3452 if (startswith(p, "UUID="))
3453 return tag_to_udev_node(p+5, "uuid");
3455 if (startswith(p, "PARTUUID="))
3456 return tag_to_udev_node(p+9, "partuuid");
3458 if (startswith(p, "PARTLABEL="))
3459 return tag_to_udev_node(p+10, "partlabel");
3464 bool tty_is_vc(const char *tty) {
3467 if (startswith(tty, "/dev/"))
3470 return vtnr_from_tty(tty) >= 0;
3473 bool tty_is_console(const char *tty) {
3476 if (startswith(tty, "/dev/"))
3479 return streq(tty, "console");
3482 int vtnr_from_tty(const char *tty) {
3487 if (startswith(tty, "/dev/"))
3490 if (!startswith(tty, "tty") )
3493 if (tty[3] < '0' || tty[3] > '9')
3496 r = safe_atoi(tty+3, &i);
3500 if (i < 0 || i > 63)
3506 bool tty_is_vc_resolve(const char *tty) {
3507 char *active = NULL;
3512 if (startswith(tty, "/dev/"))
3515 /* Resolve where /dev/console is pointing to, if /sys is
3516 * actually ours (i.e. not read-only-mounted which is a sign
3517 * for container setups) */
3518 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3519 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3520 /* If multiple log outputs are configured the
3521 * last one is what /dev/console points to */
3522 tty = strrchr(active, ' ');
3535 const char *default_term_for_tty(const char *tty) {
3538 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3541 bool dirent_is_file(const struct dirent *de) {
3544 if (ignore_file(de->d_name))
3547 if (de->d_type != DT_REG &&
3548 de->d_type != DT_LNK &&
3549 de->d_type != DT_UNKNOWN)
3555 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3558 if (de->d_type != DT_REG &&
3559 de->d_type != DT_LNK &&
3560 de->d_type != DT_UNKNOWN)
3563 if (ignore_file_allow_backup(de->d_name))
3566 return endswith(de->d_name, suffix);
3569 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3572 Hashmap *pids = NULL;
3576 /* Executes all binaries in a directory in parallel and waits
3577 * until all they all finished. */
3580 if (!(_d = opendir(directory))) {
3582 if (errno == ENOENT)
3585 log_error("Failed to enumerate directory %s: %m", directory);
3592 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3593 log_error("Failed to allocate set.");
3597 while ((de = readdir(d))) {
3602 if (!dirent_is_file(de))
3605 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3610 if ((pid = fork()) < 0) {
3611 log_error("Failed to fork: %m");
3629 log_error("Failed to execute %s: %m", path);
3630 _exit(EXIT_FAILURE);
3633 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3635 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3636 log_error("Failed to add PID to set: %s", strerror(-k));
3641 while (!hashmap_isempty(pids)) {
3642 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3647 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3652 log_error("waitid() failed: %m");
3656 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3657 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3658 if (si.si_code == CLD_EXITED)
3659 log_error("%s exited with exit status %i.", path, si.si_status);
3661 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3663 log_debug("%s exited successfully.", path);
3674 hashmap_free_free(pids);
3677 int kill_and_sigcont(pid_t pid, int sig) {
3680 r = kill(pid, sig) < 0 ? -errno : 0;
3688 bool nulstr_contains(const char*nulstr, const char *needle) {
3694 NULSTR_FOREACH(i, nulstr)
3695 if (streq(i, needle))
3701 bool plymouth_running(void) {
3702 return access("/run/plymouth/pid", F_OK) >= 0;
3705 char* strshorten(char *s, size_t l) {
3714 static bool hostname_valid_char(char c) {
3716 (c >= 'a' && c <= 'z') ||
3717 (c >= 'A' && c <= 'Z') ||
3718 (c >= '0' && c <= '9') ||
3724 bool hostname_is_valid(const char *s) {
3730 for (p = s; *p; p++)
3731 if (!hostname_valid_char(*p))
3734 if (p-s > HOST_NAME_MAX)
3740 char* hostname_cleanup(char *s) {
3743 for (p = s, d = s; *p; p++)
3744 if ((*p >= 'a' && *p <= 'z') ||
3745 (*p >= 'A' && *p <= 'Z') ||
3746 (*p >= '0' && *p <= '9') ||
3754 strshorten(s, HOST_NAME_MAX);
3758 int pipe_eof(int fd) {
3759 struct pollfd pollfd;
3764 pollfd.events = POLLIN|POLLHUP;
3766 r = poll(&pollfd, 1, 0);
3773 return pollfd.revents & POLLHUP;
3776 int fd_wait_for_event(int fd, int event, usec_t t) {
3777 struct pollfd pollfd;
3782 pollfd.events = event;
3784 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3791 return pollfd.revents;
3794 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3805 t = new(char, strlen(path) + 1 + 6 + 1);
3809 fn = path_get_file_name(path);
3813 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3815 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3821 f = fdopen(fd, "we");
3834 int terminal_vhangup_fd(int fd) {
3837 if (ioctl(fd, TIOCVHANGUP) < 0)
3843 int terminal_vhangup(const char *name) {
3846 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3850 r = terminal_vhangup_fd(fd);
3851 close_nointr_nofail(fd);
3856 int vt_disallocate(const char *name) {
3860 /* Deallocate the VT if possible. If not possible
3861 * (i.e. because it is the active one), at least clear it
3862 * entirely (including the scrollback buffer) */
3864 if (!startswith(name, "/dev/"))
3867 if (!tty_is_vc(name)) {
3868 /* So this is not a VT. I guess we cannot deallocate
3869 * it then. But let's at least clear the screen */
3871 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3876 "\033[r" /* clear scrolling region */
3877 "\033[H" /* move home */
3878 "\033[2J", /* clear screen */
3880 close_nointr_nofail(fd);
3885 if (!startswith(name, "/dev/tty"))
3888 r = safe_atou(name+8, &u);
3895 /* Try to deallocate */
3896 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3900 r = ioctl(fd, VT_DISALLOCATE, u);
3901 close_nointr_nofail(fd);
3909 /* Couldn't deallocate, so let's clear it fully with
3911 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3916 "\033[r" /* clear scrolling region */
3917 "\033[H" /* move home */
3918 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3920 close_nointr_nofail(fd);
3925 int copy_file(const char *from, const char *to) {
3931 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
3935 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
3937 close_nointr_nofail(fdf);
3945 n = read(fdf, buf, sizeof(buf));
3949 close_nointr_nofail(fdf);
3960 k = loop_write(fdt, buf, n, false);
3962 r = k < 0 ? k : (errno ? -errno : -EIO);
3964 close_nointr_nofail(fdf);
3972 close_nointr_nofail(fdf);
3973 r = close_nointr(fdt);
3983 int symlink_atomic(const char *from, const char *to) {
3985 _cleanup_free_ char *t;
3988 unsigned long long ull;
3995 t = new(char, strlen(to) + 1 + 16 + 1);
3999 fn = path_get_file_name(to);
4003 x = stpcpy(t+k+1, fn);
4006 for (i = 0; i < 16; i++) {
4007 *(x++) = hexchar(ull & 0xF);
4013 if (symlink(from, t) < 0)
4016 if (rename(t, to) < 0) {
4025 bool display_is_local(const char *display) {
4029 display[0] == ':' &&
4030 display[1] >= '0' &&
4034 int socket_from_display(const char *display, char **path) {
4041 if (!display_is_local(display))
4044 k = strspn(display+1, "0123456789");
4046 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4050 c = stpcpy(f, "/tmp/.X11-unix/X");
4051 memcpy(c, display+1, k);
4060 const char **username,
4061 uid_t *uid, gid_t *gid,
4063 const char **shell) {
4071 /* We enforce some special rules for uid=0: in order to avoid
4072 * NSS lookups for root we hardcode its data. */
4074 if (streq(*username, "root") || streq(*username, "0")) {
4092 if (parse_uid(*username, &u) >= 0) {
4096 /* If there are multiple users with the same id, make
4097 * sure to leave $USER to the configured value instead
4098 * of the first occurrence in the database. However if
4099 * the uid was configured by a numeric uid, then let's
4100 * pick the real username from /etc/passwd. */
4102 *username = p->pw_name;
4105 p = getpwnam(*username);
4109 return errno != 0 ? -errno : -ESRCH;
4121 *shell = p->pw_shell;
4126 char* uid_to_name(uid_t uid) {
4131 return strdup("root");
4135 return strdup(p->pw_name);
4137 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4143 int get_group_creds(const char **groupname, gid_t *gid) {
4149 /* We enforce some special rules for gid=0: in order to avoid
4150 * NSS lookups for root we hardcode its data. */
4152 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4153 *groupname = "root";
4161 if (parse_gid(*groupname, &id) >= 0) {
4166 *groupname = g->gr_name;
4169 g = getgrnam(*groupname);
4173 return errno != 0 ? -errno : -ESRCH;
4181 int in_group(const char *name) {
4183 int ngroups_max, r, i;
4185 r = get_group_creds(&name, &gid);
4189 if (getgid() == gid)
4192 if (getegid() == gid)
4195 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4196 assert(ngroups_max > 0);
4198 gids = alloca(sizeof(gid_t) * ngroups_max);
4200 r = getgroups(ngroups_max, gids);
4204 for (i = 0; i < r; i++)
4211 int glob_exists(const char *path) {
4219 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4221 if (k == GLOB_NOMATCH)
4223 else if (k == GLOB_NOSPACE)
4226 r = !strv_isempty(g.gl_pathv);
4228 r = errno ? -errno : -EIO;
4235 int dirent_ensure_type(DIR *d, struct dirent *de) {
4241 if (de->d_type != DT_UNKNOWN)
4244 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4248 S_ISREG(st.st_mode) ? DT_REG :
4249 S_ISDIR(st.st_mode) ? DT_DIR :
4250 S_ISLNK(st.st_mode) ? DT_LNK :
4251 S_ISFIFO(st.st_mode) ? DT_FIFO :
4252 S_ISSOCK(st.st_mode) ? DT_SOCK :
4253 S_ISCHR(st.st_mode) ? DT_CHR :
4254 S_ISBLK(st.st_mode) ? DT_BLK :
4260 int in_search_path(const char *path, char **search) {
4264 r = path_get_parent(path, &parent);
4270 STRV_FOREACH(i, search) {
4271 if (path_equal(parent, *i)) {
4282 int get_files_in_directory(const char *path, char ***list) {
4290 /* Returns all files in a directory in *list, and the number
4291 * of files as return value. If list is NULL returns only the
4300 union dirent_storage buf;
4303 k = readdir_r(d, &buf.de, &de);
4312 dirent_ensure_type(d, de);
4314 if (!dirent_is_file(de))
4318 if ((unsigned) r >= n) {
4322 t = realloc(l, sizeof(char*) * n);
4331 assert((unsigned) r < n);
4333 l[r] = strdup(de->d_name);
4357 char *strjoin(const char *x, ...) {
4371 t = va_arg(ap, const char *);
4376 if (n > ((size_t) -1) - l) {
4400 t = va_arg(ap, const char *);
4414 bool is_main_thread(void) {
4415 static __thread int cached = 0;
4417 if (_unlikely_(cached == 0))
4418 cached = getpid() == gettid() ? 1 : -1;
4423 int block_get_whole_disk(dev_t d, dev_t *ret) {
4430 /* If it has a queue this is good enough for us */
4431 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4434 r = access(p, F_OK);
4442 /* If it is a partition find the originating device */
4443 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4446 r = access(p, F_OK);
4452 /* Get parent dev_t */
4453 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4456 r = read_one_line_file(p, &s);
4462 r = sscanf(s, "%u:%u", &m, &n);
4468 /* Only return this if it is really good enough for us. */
4469 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4472 r = access(p, F_OK);
4476 *ret = makedev(m, n);
4483 int file_is_priv_sticky(const char *p) {
4488 if (lstat(p, &st) < 0)
4492 (st.st_uid == 0 || st.st_uid == getuid()) &&
4493 (st.st_mode & S_ISVTX);
4496 static const char *const ioprio_class_table[] = {
4497 [IOPRIO_CLASS_NONE] = "none",
4498 [IOPRIO_CLASS_RT] = "realtime",
4499 [IOPRIO_CLASS_BE] = "best-effort",
4500 [IOPRIO_CLASS_IDLE] = "idle"
4503 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4505 static const char *const sigchld_code_table[] = {
4506 [CLD_EXITED] = "exited",
4507 [CLD_KILLED] = "killed",
4508 [CLD_DUMPED] = "dumped",
4509 [CLD_TRAPPED] = "trapped",
4510 [CLD_STOPPED] = "stopped",
4511 [CLD_CONTINUED] = "continued",
4514 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4516 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4517 [LOG_FAC(LOG_KERN)] = "kern",
4518 [LOG_FAC(LOG_USER)] = "user",
4519 [LOG_FAC(LOG_MAIL)] = "mail",
4520 [LOG_FAC(LOG_DAEMON)] = "daemon",
4521 [LOG_FAC(LOG_AUTH)] = "auth",
4522 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4523 [LOG_FAC(LOG_LPR)] = "lpr",
4524 [LOG_FAC(LOG_NEWS)] = "news",
4525 [LOG_FAC(LOG_UUCP)] = "uucp",
4526 [LOG_FAC(LOG_CRON)] = "cron",
4527 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4528 [LOG_FAC(LOG_FTP)] = "ftp",
4529 [LOG_FAC(LOG_LOCAL0)] = "local0",
4530 [LOG_FAC(LOG_LOCAL1)] = "local1",
4531 [LOG_FAC(LOG_LOCAL2)] = "local2",
4532 [LOG_FAC(LOG_LOCAL3)] = "local3",
4533 [LOG_FAC(LOG_LOCAL4)] = "local4",
4534 [LOG_FAC(LOG_LOCAL5)] = "local5",
4535 [LOG_FAC(LOG_LOCAL6)] = "local6",
4536 [LOG_FAC(LOG_LOCAL7)] = "local7"
4539 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4541 static const char *const log_level_table[] = {
4542 [LOG_EMERG] = "emerg",
4543 [LOG_ALERT] = "alert",
4544 [LOG_CRIT] = "crit",
4546 [LOG_WARNING] = "warning",
4547 [LOG_NOTICE] = "notice",
4548 [LOG_INFO] = "info",
4549 [LOG_DEBUG] = "debug"
4552 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4554 static const char* const sched_policy_table[] = {
4555 [SCHED_OTHER] = "other",
4556 [SCHED_BATCH] = "batch",
4557 [SCHED_IDLE] = "idle",
4558 [SCHED_FIFO] = "fifo",
4562 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4564 static const char* const rlimit_table[] = {
4565 [RLIMIT_CPU] = "LimitCPU",
4566 [RLIMIT_FSIZE] = "LimitFSIZE",
4567 [RLIMIT_DATA] = "LimitDATA",
4568 [RLIMIT_STACK] = "LimitSTACK",
4569 [RLIMIT_CORE] = "LimitCORE",
4570 [RLIMIT_RSS] = "LimitRSS",
4571 [RLIMIT_NOFILE] = "LimitNOFILE",
4572 [RLIMIT_AS] = "LimitAS",
4573 [RLIMIT_NPROC] = "LimitNPROC",
4574 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4575 [RLIMIT_LOCKS] = "LimitLOCKS",
4576 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4577 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4578 [RLIMIT_NICE] = "LimitNICE",
4579 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4580 [RLIMIT_RTTIME] = "LimitRTTIME"
4583 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4585 static const char* const ip_tos_table[] = {
4586 [IPTOS_LOWDELAY] = "low-delay",
4587 [IPTOS_THROUGHPUT] = "throughput",
4588 [IPTOS_RELIABILITY] = "reliability",
4589 [IPTOS_LOWCOST] = "low-cost",
4592 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4594 static const char *const __signal_table[] = {
4611 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4622 [SIGVTALRM] = "VTALRM",
4624 [SIGWINCH] = "WINCH",
4630 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4632 const char *signal_to_string(int signo) {
4633 static __thread char buf[12];
4636 name = __signal_to_string(signo);
4640 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4641 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4643 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4648 int signal_from_string(const char *s) {
4653 signo = __signal_from_string(s);
4657 if (startswith(s, "RTMIN+")) {
4661 if (safe_atou(s, &u) >= 0) {
4662 signo = (int) u + offset;
4663 if (signo > 0 && signo < _NSIG)
4669 bool kexec_loaded(void) {
4670 bool loaded = false;
4673 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4681 int strdup_or_null(const char *a, char **b) {
4699 int prot_from_flags(int flags) {
4701 switch (flags & O_ACCMODE) {
4710 return PROT_READ|PROT_WRITE;
4717 char *format_bytes(char *buf, size_t l, off_t t) {
4720 static const struct {
4724 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4725 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4726 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4727 { "G", 1024ULL*1024ULL*1024ULL },
4728 { "M", 1024ULL*1024ULL },
4732 for (i = 0; i < ELEMENTSOF(table); i++) {
4734 if (t >= table[i].factor) {
4737 (unsigned long long) (t / table[i].factor),
4738 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4745 snprintf(buf, l, "%lluB", (unsigned long long) t);
4753 void* memdup(const void *p, size_t l) {
4766 int fd_inc_sndbuf(int fd, size_t n) {
4768 socklen_t l = sizeof(value);
4770 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4772 l == sizeof(value) &&
4773 (size_t) value >= n*2)
4777 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4784 int fd_inc_rcvbuf(int fd, size_t n) {
4786 socklen_t l = sizeof(value);
4788 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4790 l == sizeof(value) &&
4791 (size_t) value >= n*2)
4795 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4802 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4803 pid_t parent_pid, agent_pid;
4805 bool stdout_is_tty, stderr_is_tty;
4813 parent_pid = getpid();
4815 /* Spawns a temporary TTY agent, making sure it goes away when
4822 if (agent_pid != 0) {
4829 * Make sure the agent goes away when the parent dies */
4830 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4831 _exit(EXIT_FAILURE);
4833 /* Check whether our parent died before we were able
4834 * to set the death signal */
4835 if (getppid() != parent_pid)
4836 _exit(EXIT_SUCCESS);
4838 /* Don't leak fds to the agent */
4839 close_all_fds(except, n_except);
4841 stdout_is_tty = isatty(STDOUT_FILENO);
4842 stderr_is_tty = isatty(STDERR_FILENO);
4844 if (!stdout_is_tty || !stderr_is_tty) {
4845 /* Detach from stdout/stderr. and reopen
4846 * /dev/tty for them. This is important to
4847 * ensure that when systemctl is started via
4848 * popen() or a similar call that expects to
4849 * read EOF we actually do generate EOF and
4850 * not delay this indefinitely by because we
4851 * keep an unused copy of stdin around. */
4852 fd = open("/dev/tty", O_WRONLY);
4854 log_error("Failed to open /dev/tty: %m");
4855 _exit(EXIT_FAILURE);
4859 dup2(fd, STDOUT_FILENO);
4862 dup2(fd, STDERR_FILENO);
4868 /* Count arguments */
4870 for (n = 0; va_arg(ap, char*); n++)
4875 l = alloca(sizeof(char *) * (n + 1));
4877 /* Fill in arguments */
4879 for (i = 0; i <= n; i++)
4880 l[i] = va_arg(ap, char*);
4884 _exit(EXIT_FAILURE);
4887 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4888 struct rlimit highest, fixed;
4892 if (setrlimit(resource, rlim) >= 0)
4898 /* So we failed to set the desired setrlimit, then let's try
4899 * to get as close as we can */
4900 assert_se(getrlimit(resource, &highest) == 0);
4902 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4903 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4905 if (setrlimit(resource, &fixed) < 0)
4911 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
4912 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
4924 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
4927 f = fopen(path, "re");
4935 char line[LINE_MAX];
4938 for (i = 0; i < sizeof(line)-1; i++) {
4942 if (_unlikely_(c == EOF)) {
4952 if (memcmp(line, field, l) == 0 && line[l] == '=') {
4953 value = strdup(line + l + 1);
4973 int can_sleep(const char *type) {
4977 _cleanup_free_ char *p = NULL;
4981 /* If /sys is read-only we cannot sleep */
4982 if (access("/sys/power/state", W_OK) < 0)
4985 r = read_one_line_file("/sys/power/state", &p);
4990 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
4991 if (l == k && memcmp(w, type, l) == 0)
4997 int can_sleep_disk(const char *type) {
5001 _cleanup_free_ char *p = NULL;
5005 /* If /sys is read-only we cannot sleep */
5006 if (access("/sys/power/state", W_OK) < 0 ||
5007 access("/sys/power/disk", W_OK) < 0)
5010 r = read_one_line_file("/sys/power/disk", &p);
5015 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5016 if (l == k && memcmp(w, type, l) == 0)
5019 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5026 bool is_valid_documentation_url(const char *url) {
5029 if (startswith(url, "http://") && url[7])
5032 if (startswith(url, "https://") && url[8])
5035 if (startswith(url, "file:") && url[5])
5038 if (startswith(url, "info:") && url[5])
5041 if (startswith(url, "man:") && url[4])
5047 bool in_initrd(void) {
5048 static __thread int saved = -1;
5054 /* We make two checks here:
5056 * 1. the flag file /etc/initrd-release must exist
5057 * 2. the root file system must be a memory file system
5059 * The second check is extra paranoia, since misdetecting an
5060 * initrd can have bad bad consequences due the initrd
5061 * emptying when transititioning to the main systemd.
5064 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5065 statfs("/", &s) >= 0 &&
5066 is_temporary_fs(&s);
5071 void warn_melody(void) {
5072 _cleanup_close_ int fd = -1;
5074 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5078 /* Yeah, this is synchronous. Kinda sucks. But well... */
5080 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5081 usleep(125*USEC_PER_MSEC);
5083 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5084 usleep(125*USEC_PER_MSEC);
5086 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5087 usleep(125*USEC_PER_MSEC);
5089 ioctl(fd, KIOCSOUND, 0);
5092 int make_console_stdio(void) {
5095 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5097 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5099 log_error("Failed to acquire terminal: %s", strerror(-fd));
5105 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5112 int get_home_dir(char **_h) {
5120 /* Take the user specified one */
5131 /* Hardcode home directory for root to avoid NSS */
5134 h = strdup("/root");
5142 /* Check the database... */
5146 return errno ? -errno : -ESRCH;
5148 if (!path_is_absolute(p->pw_dir))
5151 h = strdup(p->pw_dir);
5159 int get_shell(char **_sh) {
5167 /* Take the user specified one */
5168 e = getenv("SHELL");
5178 /* Hardcode home directory for root to avoid NSS */
5181 sh = strdup("/bin/sh");
5189 /* Check the database... */
5193 return errno ? -errno : -ESRCH;
5195 if (!path_is_absolute(p->pw_shell))
5198 sh = strdup(p->pw_shell);
5206 void freep(void *p) {
5210 void fclosep(FILE **f) {
5215 void pclosep(FILE **f) {
5220 void closep(int *fd) {
5222 close_nointr_nofail(*fd);
5225 void closedirp(DIR **d) {
5230 void umaskp(mode_t *u) {
5234 bool filename_is_safe(const char *p) {
5248 if (strlen(p) > FILENAME_MAX)
5254 bool string_is_safe(const char *p) {
5259 for (t = p; *t; t++) {
5260 if (*t > 0 && *t < ' ')
5263 if (strchr("\\\"\'", *t))
5270 bool string_has_cc(const char *p) {
5275 for (t = p; *t; t++)
5276 if (*t > 0 && *t < ' ')
5282 bool path_is_safe(const char *p) {
5287 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5290 if (strlen(p) > PATH_MAX)
5293 /* The following two checks are not really dangerous, but hey, they still are confusing */
5294 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5297 if (strstr(p, "//"))
5303 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5304 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5305 int (*compar) (const void *, const void *, void *), void *arg) {
5314 p = (void *)(((const char *) base) + (idx * size));
5315 comparison = compar(key, p, arg);
5318 else if (comparison > 0)
5326 bool is_locale_utf8(void) {
5328 static int cached_answer = -1;
5330 if (cached_answer >= 0)
5333 if (!setlocale(LC_ALL, "")) {
5334 cached_answer = true;
5338 set = nl_langinfo(CODESET);
5340 cached_answer = true;
5344 cached_answer = streq(set, "UTF-8");
5346 return (bool)cached_answer;
5349 const char *draw_special_char(DrawSpecialChar ch) {
5350 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5352 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5353 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5354 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5355 [DRAW_TREE_SPACE] = " ", /* */
5356 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5358 /* ASCII fallback */ {
5359 [DRAW_TREE_VERT] = "| ",
5360 [DRAW_TREE_BRANCH] = "|-",
5361 [DRAW_TREE_RIGHT] = "`-",
5362 [DRAW_TREE_SPACE] = " ",
5363 [DRAW_TRIANGULAR_BULLET] = "> ",
5367 return draw_table[!is_locale_utf8()][ch];
5370 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5373 size_t l, old_len, new_len;
5379 old_len = strlen(old_string);
5380 new_len = strlen(new_string);
5393 if (!startswith(f, old_string)) {
5399 nl = l - old_len + new_len;
5400 a = realloc(r, nl + 1);
5408 t = stpcpy(t, new_string);
5420 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5421 const char *i, *begin = NULL;
5426 } state = STATE_OTHER;
5428 size_t osz = 0, isz;
5434 /* Strips ANSI color and replaces TABs by 8 spaces */
5436 isz = _isz ? *_isz : strlen(*ibuf);
5438 f = open_memstream(&obuf, &osz);
5442 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5447 if (i >= *ibuf + isz) /* EOT */
5449 else if (*i == '\x1B')
5450 state = STATE_ESCAPE;
5451 else if (*i == '\t')
5458 if (i >= *ibuf + isz) { /* EOT */
5461 } else if (*i == '[') {
5462 state = STATE_BRACKET;
5467 state = STATE_OTHER;
5474 if (i >= *ibuf + isz || /* EOT */
5475 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5478 state = STATE_OTHER;
5480 } else if (*i == 'm')
5481 state = STATE_OTHER;
5503 int on_ac_power(void) {
5504 bool found_offline = false, found_online = false;
5505 _cleanup_closedir_ DIR *d = NULL;
5507 d = opendir("/sys/class/power_supply");
5513 union dirent_storage buf;
5514 _cleanup_free_ char *p = NULL;
5515 _cleanup_close_ int fd = -1, device = -1;
5520 k = readdir_r(d, &buf.de, &de);
5527 if (ignore_file(de->d_name))
5530 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5532 if (errno == ENOENT || errno == ENOTDIR)
5538 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5540 if (errno == ENOENT)
5546 n = read(fd, contents, sizeof(contents));
5550 if (n != 6 || memcmp(contents, "Mains\n", 6))
5553 close_nointr_nofail(fd);
5554 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5556 if (errno == ENOENT)
5562 n = read(fd, contents, sizeof(contents));
5566 if (n != 2 || contents[1] != '\n')
5569 if (contents[0] == '1') {
5570 found_online = true;
5572 } else if (contents[0] == '0')
5573 found_offline = true;
5578 return found_online || !found_offline;
5581 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5588 if (!path_strv_canonicalize_uniq(search))
5591 STRV_FOREACH(i, search) {
5592 _cleanup_free_ char *p = NULL;
5595 p = strjoin(*i, "/", path, NULL);
5605 if (errno != ENOENT)
5612 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5613 _cleanup_strv_free_ char **copy = NULL;
5619 if (path_is_absolute(path)) {
5622 f = fopen(path, mode);
5631 copy = strv_copy((char**) search);
5635 return search_and_fopen_internal(path, mode, copy, _f);
5638 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5639 _cleanup_strv_free_ char **s = NULL;
5641 if (path_is_absolute(path)) {
5644 f = fopen(path, mode);
5653 s = strv_split_nulstr(search);
5657 return search_and_fopen_internal(path, mode, s, _f);