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 bool tty_is_vc_resolve(const char *tty) {
3513 char *active = NULL;
3518 if (startswith(tty, "/dev/"))
3521 /* Resolve where /dev/console is pointing to, if /sys is
3522 * actually ours (i.e. not read-only-mounted which is a sign
3523 * for container setups) */
3524 if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
3525 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
3526 /* If multiple log outputs are configured the
3527 * last one is what /dev/console points to */
3528 tty = strrchr(active, ' ');
3541 const char *default_term_for_tty(const char *tty) {
3544 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
3547 bool dirent_is_file(const struct dirent *de) {
3550 if (ignore_file(de->d_name))
3553 if (de->d_type != DT_REG &&
3554 de->d_type != DT_LNK &&
3555 de->d_type != DT_UNKNOWN)
3561 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3564 if (de->d_type != DT_REG &&
3565 de->d_type != DT_LNK &&
3566 de->d_type != DT_UNKNOWN)
3569 if (ignore_file_allow_backup(de->d_name))
3572 return endswith(de->d_name, suffix);
3575 void execute_directory(const char *directory, DIR *d, char *argv[]) {
3578 Hashmap *pids = NULL;
3582 /* Executes all binaries in a directory in parallel and waits
3583 * until all they all finished. */
3586 if (!(_d = opendir(directory))) {
3588 if (errno == ENOENT)
3591 log_error("Failed to enumerate directory %s: %m", directory);
3598 if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
3599 log_error("Failed to allocate set.");
3603 while ((de = readdir(d))) {
3608 if (!dirent_is_file(de))
3611 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
3616 if ((pid = fork()) < 0) {
3617 log_error("Failed to fork: %m");
3635 log_error("Failed to execute %s: %m", path);
3636 _exit(EXIT_FAILURE);
3639 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
3641 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
3642 log_error("Failed to add PID to set: %s", strerror(-k));
3647 while (!hashmap_isempty(pids)) {
3648 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
3653 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
3658 log_error("waitid() failed: %m");
3662 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
3663 if (!is_clean_exit(si.si_code, si.si_status, NULL)) {
3664 if (si.si_code == CLD_EXITED)
3665 log_error("%s exited with exit status %i.", path, si.si_status);
3667 log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
3669 log_debug("%s exited successfully.", path);
3680 hashmap_free_free(pids);
3683 int kill_and_sigcont(pid_t pid, int sig) {
3686 r = kill(pid, sig) < 0 ? -errno : 0;
3694 bool nulstr_contains(const char*nulstr, const char *needle) {
3700 NULSTR_FOREACH(i, nulstr)
3701 if (streq(i, needle))
3707 bool plymouth_running(void) {
3708 return access("/run/plymouth/pid", F_OK) >= 0;
3711 char* strshorten(char *s, size_t l) {
3720 static bool hostname_valid_char(char c) {
3722 (c >= 'a' && c <= 'z') ||
3723 (c >= 'A' && c <= 'Z') ||
3724 (c >= '0' && c <= '9') ||
3730 bool hostname_is_valid(const char *s) {
3736 for (p = s; *p; p++)
3737 if (!hostname_valid_char(*p))
3740 if (p-s > HOST_NAME_MAX)
3746 char* hostname_cleanup(char *s) {
3749 for (p = s, d = s; *p; p++)
3750 if ((*p >= 'a' && *p <= 'z') ||
3751 (*p >= 'A' && *p <= 'Z') ||
3752 (*p >= '0' && *p <= '9') ||
3760 strshorten(s, HOST_NAME_MAX);
3764 int pipe_eof(int fd) {
3765 struct pollfd pollfd;
3770 pollfd.events = POLLIN|POLLHUP;
3772 r = poll(&pollfd, 1, 0);
3779 return pollfd.revents & POLLHUP;
3782 int fd_wait_for_event(int fd, int event, usec_t t) {
3783 struct pollfd pollfd;
3788 pollfd.events = event;
3790 r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
3797 return pollfd.revents;
3800 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3811 t = new(char, strlen(path) + 1 + 6 + 1);
3815 fn = path_get_file_name(path);
3819 stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
3821 fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
3827 f = fdopen(fd, "we");
3840 int terminal_vhangup_fd(int fd) {
3843 if (ioctl(fd, TIOCVHANGUP) < 0)
3849 int terminal_vhangup(const char *name) {
3852 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3856 r = terminal_vhangup_fd(fd);
3857 close_nointr_nofail(fd);
3862 int vt_disallocate(const char *name) {
3866 /* Deallocate the VT if possible. If not possible
3867 * (i.e. because it is the active one), at least clear it
3868 * entirely (including the scrollback buffer) */
3870 if (!startswith(name, "/dev/"))
3873 if (!tty_is_vc(name)) {
3874 /* So this is not a VT. I guess we cannot deallocate
3875 * it then. But let's at least clear the screen */
3877 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3882 "\033[r" /* clear scrolling region */
3883 "\033[H" /* move home */
3884 "\033[2J", /* clear screen */
3886 close_nointr_nofail(fd);
3891 if (!startswith(name, "/dev/tty"))
3894 r = safe_atou(name+8, &u);
3901 /* Try to deallocate */
3902 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3906 r = ioctl(fd, VT_DISALLOCATE, u);
3907 close_nointr_nofail(fd);
3915 /* Couldn't deallocate, so let's clear it fully with
3917 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3922 "\033[r" /* clear scrolling region */
3923 "\033[H" /* move home */
3924 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3926 close_nointr_nofail(fd);
3931 int copy_file(const char *from, const char *to) {
3937 fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
3941 fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
3943 close_nointr_nofail(fdf);
3951 n = read(fdf, buf, sizeof(buf));
3955 close_nointr_nofail(fdf);
3966 k = loop_write(fdt, buf, n, false);
3968 r = k < 0 ? k : (errno ? -errno : -EIO);
3970 close_nointr_nofail(fdf);
3978 close_nointr_nofail(fdf);
3979 r = close_nointr(fdt);
3989 int symlink_atomic(const char *from, const char *to) {
3991 _cleanup_free_ char *t;
3994 unsigned long long ull;
4001 t = new(char, strlen(to) + 1 + 16 + 1);
4005 fn = path_get_file_name(to);
4009 x = stpcpy(t+k+1, fn);
4012 for (i = 0; i < 16; i++) {
4013 *(x++) = hexchar(ull & 0xF);
4019 if (symlink(from, t) < 0)
4022 if (rename(t, to) < 0) {
4031 bool display_is_local(const char *display) {
4035 display[0] == ':' &&
4036 display[1] >= '0' &&
4040 int socket_from_display(const char *display, char **path) {
4047 if (!display_is_local(display))
4050 k = strspn(display+1, "0123456789");
4052 f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4056 c = stpcpy(f, "/tmp/.X11-unix/X");
4057 memcpy(c, display+1, k);
4066 const char **username,
4067 uid_t *uid, gid_t *gid,
4069 const char **shell) {
4077 /* We enforce some special rules for uid=0: in order to avoid
4078 * NSS lookups for root we hardcode its data. */
4080 if (streq(*username, "root") || streq(*username, "0")) {
4098 if (parse_uid(*username, &u) >= 0) {
4102 /* If there are multiple users with the same id, make
4103 * sure to leave $USER to the configured value instead
4104 * of the first occurrence in the database. However if
4105 * the uid was configured by a numeric uid, then let's
4106 * pick the real username from /etc/passwd. */
4108 *username = p->pw_name;
4111 p = getpwnam(*username);
4115 return errno != 0 ? -errno : -ESRCH;
4127 *shell = p->pw_shell;
4132 char* uid_to_name(uid_t uid) {
4137 return strdup("root");
4141 return strdup(p->pw_name);
4143 if (asprintf(&r, "%lu", (unsigned long) uid) < 0)
4149 int get_group_creds(const char **groupname, gid_t *gid) {
4155 /* We enforce some special rules for gid=0: in order to avoid
4156 * NSS lookups for root we hardcode its data. */
4158 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4159 *groupname = "root";
4167 if (parse_gid(*groupname, &id) >= 0) {
4172 *groupname = g->gr_name;
4175 g = getgrnam(*groupname);
4179 return errno != 0 ? -errno : -ESRCH;
4187 int in_group(const char *name) {
4189 int ngroups_max, r, i;
4191 r = get_group_creds(&name, &gid);
4195 if (getgid() == gid)
4198 if (getegid() == gid)
4201 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4202 assert(ngroups_max > 0);
4204 gids = alloca(sizeof(gid_t) * ngroups_max);
4206 r = getgroups(ngroups_max, gids);
4210 for (i = 0; i < r; i++)
4217 int glob_exists(const char *path) {
4225 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4227 if (k == GLOB_NOMATCH)
4229 else if (k == GLOB_NOSPACE)
4232 r = !strv_isempty(g.gl_pathv);
4234 r = errno ? -errno : -EIO;
4241 int dirent_ensure_type(DIR *d, struct dirent *de) {
4247 if (de->d_type != DT_UNKNOWN)
4250 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4254 S_ISREG(st.st_mode) ? DT_REG :
4255 S_ISDIR(st.st_mode) ? DT_DIR :
4256 S_ISLNK(st.st_mode) ? DT_LNK :
4257 S_ISFIFO(st.st_mode) ? DT_FIFO :
4258 S_ISSOCK(st.st_mode) ? DT_SOCK :
4259 S_ISCHR(st.st_mode) ? DT_CHR :
4260 S_ISBLK(st.st_mode) ? DT_BLK :
4266 int in_search_path(const char *path, char **search) {
4270 r = path_get_parent(path, &parent);
4276 STRV_FOREACH(i, search) {
4277 if (path_equal(parent, *i)) {
4288 int get_files_in_directory(const char *path, char ***list) {
4296 /* Returns all files in a directory in *list, and the number
4297 * of files as return value. If list is NULL returns only the
4306 union dirent_storage buf;
4309 k = readdir_r(d, &buf.de, &de);
4318 dirent_ensure_type(d, de);
4320 if (!dirent_is_file(de))
4324 if ((unsigned) r >= n) {
4328 t = realloc(l, sizeof(char*) * n);
4337 assert((unsigned) r < n);
4339 l[r] = strdup(de->d_name);
4363 char *strjoin(const char *x, ...) {
4377 t = va_arg(ap, const char *);
4382 if (n > ((size_t) -1) - l) {
4406 t = va_arg(ap, const char *);
4420 bool is_main_thread(void) {
4421 static __thread int cached = 0;
4423 if (_unlikely_(cached == 0))
4424 cached = getpid() == gettid() ? 1 : -1;
4429 int block_get_whole_disk(dev_t d, dev_t *ret) {
4436 /* If it has a queue this is good enough for us */
4437 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4440 r = access(p, F_OK);
4448 /* If it is a partition find the originating device */
4449 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4452 r = access(p, F_OK);
4458 /* Get parent dev_t */
4459 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4462 r = read_one_line_file(p, &s);
4468 r = sscanf(s, "%u:%u", &m, &n);
4474 /* Only return this if it is really good enough for us. */
4475 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4478 r = access(p, F_OK);
4482 *ret = makedev(m, n);
4489 int file_is_priv_sticky(const char *p) {
4494 if (lstat(p, &st) < 0)
4498 (st.st_uid == 0 || st.st_uid == getuid()) &&
4499 (st.st_mode & S_ISVTX);
4502 static const char *const ioprio_class_table[] = {
4503 [IOPRIO_CLASS_NONE] = "none",
4504 [IOPRIO_CLASS_RT] = "realtime",
4505 [IOPRIO_CLASS_BE] = "best-effort",
4506 [IOPRIO_CLASS_IDLE] = "idle"
4509 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4511 static const char *const sigchld_code_table[] = {
4512 [CLD_EXITED] = "exited",
4513 [CLD_KILLED] = "killed",
4514 [CLD_DUMPED] = "dumped",
4515 [CLD_TRAPPED] = "trapped",
4516 [CLD_STOPPED] = "stopped",
4517 [CLD_CONTINUED] = "continued",
4520 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4522 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4523 [LOG_FAC(LOG_KERN)] = "kern",
4524 [LOG_FAC(LOG_USER)] = "user",
4525 [LOG_FAC(LOG_MAIL)] = "mail",
4526 [LOG_FAC(LOG_DAEMON)] = "daemon",
4527 [LOG_FAC(LOG_AUTH)] = "auth",
4528 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4529 [LOG_FAC(LOG_LPR)] = "lpr",
4530 [LOG_FAC(LOG_NEWS)] = "news",
4531 [LOG_FAC(LOG_UUCP)] = "uucp",
4532 [LOG_FAC(LOG_CRON)] = "cron",
4533 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4534 [LOG_FAC(LOG_FTP)] = "ftp",
4535 [LOG_FAC(LOG_LOCAL0)] = "local0",
4536 [LOG_FAC(LOG_LOCAL1)] = "local1",
4537 [LOG_FAC(LOG_LOCAL2)] = "local2",
4538 [LOG_FAC(LOG_LOCAL3)] = "local3",
4539 [LOG_FAC(LOG_LOCAL4)] = "local4",
4540 [LOG_FAC(LOG_LOCAL5)] = "local5",
4541 [LOG_FAC(LOG_LOCAL6)] = "local6",
4542 [LOG_FAC(LOG_LOCAL7)] = "local7"
4545 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4547 static const char *const log_level_table[] = {
4548 [LOG_EMERG] = "emerg",
4549 [LOG_ALERT] = "alert",
4550 [LOG_CRIT] = "crit",
4552 [LOG_WARNING] = "warning",
4553 [LOG_NOTICE] = "notice",
4554 [LOG_INFO] = "info",
4555 [LOG_DEBUG] = "debug"
4558 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4560 static const char* const sched_policy_table[] = {
4561 [SCHED_OTHER] = "other",
4562 [SCHED_BATCH] = "batch",
4563 [SCHED_IDLE] = "idle",
4564 [SCHED_FIFO] = "fifo",
4568 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4570 static const char* const rlimit_table[] = {
4571 [RLIMIT_CPU] = "LimitCPU",
4572 [RLIMIT_FSIZE] = "LimitFSIZE",
4573 [RLIMIT_DATA] = "LimitDATA",
4574 [RLIMIT_STACK] = "LimitSTACK",
4575 [RLIMIT_CORE] = "LimitCORE",
4576 [RLIMIT_RSS] = "LimitRSS",
4577 [RLIMIT_NOFILE] = "LimitNOFILE",
4578 [RLIMIT_AS] = "LimitAS",
4579 [RLIMIT_NPROC] = "LimitNPROC",
4580 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4581 [RLIMIT_LOCKS] = "LimitLOCKS",
4582 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4583 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4584 [RLIMIT_NICE] = "LimitNICE",
4585 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4586 [RLIMIT_RTTIME] = "LimitRTTIME"
4589 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4591 static const char* const ip_tos_table[] = {
4592 [IPTOS_LOWDELAY] = "low-delay",
4593 [IPTOS_THROUGHPUT] = "throughput",
4594 [IPTOS_RELIABILITY] = "reliability",
4595 [IPTOS_LOWCOST] = "low-cost",
4598 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4600 static const char *const __signal_table[] = {
4617 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4628 [SIGVTALRM] = "VTALRM",
4630 [SIGWINCH] = "WINCH",
4636 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4638 const char *signal_to_string(int signo) {
4639 static __thread char buf[12];
4642 name = __signal_to_string(signo);
4646 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4647 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
4649 snprintf(buf, sizeof(buf) - 1, "%d", signo);
4654 int signal_from_string(const char *s) {
4659 signo = __signal_from_string(s);
4663 if (startswith(s, "RTMIN+")) {
4667 if (safe_atou(s, &u) >= 0) {
4668 signo = (int) u + offset;
4669 if (signo > 0 && signo < _NSIG)
4675 bool kexec_loaded(void) {
4676 bool loaded = false;
4679 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4687 int strdup_or_null(const char *a, char **b) {
4705 int prot_from_flags(int flags) {
4707 switch (flags & O_ACCMODE) {
4716 return PROT_READ|PROT_WRITE;
4723 char *format_bytes(char *buf, size_t l, off_t t) {
4726 static const struct {
4730 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4731 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4732 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4733 { "G", 1024ULL*1024ULL*1024ULL },
4734 { "M", 1024ULL*1024ULL },
4738 for (i = 0; i < ELEMENTSOF(table); i++) {
4740 if (t >= table[i].factor) {
4743 (unsigned long long) (t / table[i].factor),
4744 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4751 snprintf(buf, l, "%lluB", (unsigned long long) t);
4759 void* memdup(const void *p, size_t l) {
4772 int fd_inc_sndbuf(int fd, size_t n) {
4774 socklen_t l = sizeof(value);
4776 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4778 l == sizeof(value) &&
4779 (size_t) value >= n*2)
4783 r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
4790 int fd_inc_rcvbuf(int fd, size_t n) {
4792 socklen_t l = sizeof(value);
4794 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4796 l == sizeof(value) &&
4797 (size_t) value >= n*2)
4801 r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
4808 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4809 pid_t parent_pid, agent_pid;
4811 bool stdout_is_tty, stderr_is_tty;
4819 parent_pid = getpid();
4821 /* Spawns a temporary TTY agent, making sure it goes away when
4828 if (agent_pid != 0) {
4835 * Make sure the agent goes away when the parent dies */
4836 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4837 _exit(EXIT_FAILURE);
4839 /* Check whether our parent died before we were able
4840 * to set the death signal */
4841 if (getppid() != parent_pid)
4842 _exit(EXIT_SUCCESS);
4844 /* Don't leak fds to the agent */
4845 close_all_fds(except, n_except);
4847 stdout_is_tty = isatty(STDOUT_FILENO);
4848 stderr_is_tty = isatty(STDERR_FILENO);
4850 if (!stdout_is_tty || !stderr_is_tty) {
4851 /* Detach from stdout/stderr. and reopen
4852 * /dev/tty for them. This is important to
4853 * ensure that when systemctl is started via
4854 * popen() or a similar call that expects to
4855 * read EOF we actually do generate EOF and
4856 * not delay this indefinitely by because we
4857 * keep an unused copy of stdin around. */
4858 fd = open("/dev/tty", O_WRONLY);
4860 log_error("Failed to open /dev/tty: %m");
4861 _exit(EXIT_FAILURE);
4865 dup2(fd, STDOUT_FILENO);
4868 dup2(fd, STDERR_FILENO);
4874 /* Count arguments */
4876 for (n = 0; va_arg(ap, char*); n++)
4881 l = alloca(sizeof(char *) * (n + 1));
4883 /* Fill in arguments */
4885 for (i = 0; i <= n; i++)
4886 l[i] = va_arg(ap, char*);
4890 _exit(EXIT_FAILURE);
4893 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4894 struct rlimit highest, fixed;
4898 if (setrlimit(resource, rlim) >= 0)
4904 /* So we failed to set the desired setrlimit, then let's try
4905 * to get as close as we can */
4906 assert_se(getrlimit(resource, &highest) == 0);
4908 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4909 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4911 if (setrlimit(resource, &fixed) < 0)
4917 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
4918 char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
4930 snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
4933 f = fopen(path, "re");
4941 char line[LINE_MAX];
4944 for (i = 0; i < sizeof(line)-1; i++) {
4948 if (_unlikely_(c == EOF)) {
4958 if (memcmp(line, field, l) == 0 && line[l] == '=') {
4959 value = strdup(line + l + 1);
4979 int can_sleep(const char *type) {
4983 _cleanup_free_ char *p = NULL;
4987 /* If /sys is read-only we cannot sleep */
4988 if (access("/sys/power/state", W_OK) < 0)
4991 r = read_one_line_file("/sys/power/state", &p);
4996 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state)
4997 if (l == k && memcmp(w, type, l) == 0)
5003 int can_sleep_disk(const char *type) {
5007 _cleanup_free_ char *p = NULL;
5011 /* If /sys is read-only we cannot sleep */
5012 if (access("/sys/power/state", W_OK) < 0 ||
5013 access("/sys/power/disk", W_OK) < 0)
5016 r = read_one_line_file("/sys/power/disk", &p);
5021 FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5022 if (l == k && memcmp(w, type, l) == 0)
5025 if (l == k + 2 && w[0] == '[' && memcmp(w + 1, type, l - 2) == 0 && w[l-1] == ']')
5032 bool is_valid_documentation_url(const char *url) {
5035 if (startswith(url, "http://") && url[7])
5038 if (startswith(url, "https://") && url[8])
5041 if (startswith(url, "file:") && url[5])
5044 if (startswith(url, "info:") && url[5])
5047 if (startswith(url, "man:") && url[4])
5053 bool in_initrd(void) {
5054 static __thread int saved = -1;
5060 /* We make two checks here:
5062 * 1. the flag file /etc/initrd-release must exist
5063 * 2. the root file system must be a memory file system
5065 * The second check is extra paranoia, since misdetecting an
5066 * initrd can have bad bad consequences due the initrd
5067 * emptying when transititioning to the main systemd.
5070 saved = access("/etc/initrd-release", F_OK) >= 0 &&
5071 statfs("/", &s) >= 0 &&
5072 is_temporary_fs(&s);
5077 void warn_melody(void) {
5078 _cleanup_close_ int fd = -1;
5080 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5084 /* Yeah, this is synchronous. Kinda sucks. But well... */
5086 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5087 usleep(125*USEC_PER_MSEC);
5089 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5090 usleep(125*USEC_PER_MSEC);
5092 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5093 usleep(125*USEC_PER_MSEC);
5095 ioctl(fd, KIOCSOUND, 0);
5098 int make_console_stdio(void) {
5101 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5103 fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5105 log_error("Failed to acquire terminal: %s", strerror(-fd));
5111 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5118 int get_home_dir(char **_h) {
5126 /* Take the user specified one */
5137 /* Hardcode home directory for root to avoid NSS */
5140 h = strdup("/root");
5148 /* Check the database... */
5152 return errno ? -errno : -ESRCH;
5154 if (!path_is_absolute(p->pw_dir))
5157 h = strdup(p->pw_dir);
5165 int get_shell(char **_sh) {
5173 /* Take the user specified one */
5174 e = getenv("SHELL");
5184 /* Hardcode home directory for root to avoid NSS */
5187 sh = strdup("/bin/sh");
5195 /* Check the database... */
5199 return errno ? -errno : -ESRCH;
5201 if (!path_is_absolute(p->pw_shell))
5204 sh = strdup(p->pw_shell);
5212 void freep(void *p) {
5216 void fclosep(FILE **f) {
5221 void pclosep(FILE **f) {
5226 void closep(int *fd) {
5228 close_nointr_nofail(*fd);
5231 void closedirp(DIR **d) {
5236 void umaskp(mode_t *u) {
5240 bool filename_is_safe(const char *p) {
5254 if (strlen(p) > FILENAME_MAX)
5260 bool string_is_safe(const char *p) {
5265 for (t = p; *t; t++) {
5266 if (*t > 0 && *t < ' ')
5269 if (strchr("\\\"\'", *t))
5276 bool string_has_cc(const char *p) {
5281 for (t = p; *t; t++)
5282 if (*t > 0 && *t < ' ')
5288 bool path_is_safe(const char *p) {
5293 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5296 if (strlen(p) > PATH_MAX)
5299 /* The following two checks are not really dangerous, but hey, they still are confusing */
5300 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5303 if (strstr(p, "//"))
5309 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5310 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5311 int (*compar) (const void *, const void *, void *), void *arg) {
5320 p = (void *)(((const char *) base) + (idx * size));
5321 comparison = compar(key, p, arg);
5324 else if (comparison > 0)
5332 bool is_locale_utf8(void) {
5334 static int cached_answer = -1;
5336 if (cached_answer >= 0)
5339 if (!setlocale(LC_ALL, "")) {
5340 cached_answer = true;
5344 set = nl_langinfo(CODESET);
5346 cached_answer = true;
5350 cached_answer = streq(set, "UTF-8");
5352 return (bool)cached_answer;
5355 const char *draw_special_char(DrawSpecialChar ch) {
5356 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5358 [DRAW_TREE_VERT] = "\342\224\202 ", /* │ */
5359 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5360 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5361 [DRAW_TREE_SPACE] = " ", /* */
5362 [DRAW_TRIANGULAR_BULLET] = "\342\200\243 ", /* ‣ */
5364 /* ASCII fallback */ {
5365 [DRAW_TREE_VERT] = "| ",
5366 [DRAW_TREE_BRANCH] = "|-",
5367 [DRAW_TREE_RIGHT] = "`-",
5368 [DRAW_TREE_SPACE] = " ",
5369 [DRAW_TRIANGULAR_BULLET] = "> ",
5373 return draw_table[!is_locale_utf8()][ch];
5376 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5379 size_t l, old_len, new_len;
5385 old_len = strlen(old_string);
5386 new_len = strlen(new_string);
5399 if (!startswith(f, old_string)) {
5405 nl = l - old_len + new_len;
5406 a = realloc(r, nl + 1);
5414 t = stpcpy(t, new_string);
5426 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5427 const char *i, *begin = NULL;
5432 } state = STATE_OTHER;
5434 size_t osz = 0, isz;
5440 /* Strips ANSI color and replaces TABs by 8 spaces */
5442 isz = _isz ? *_isz : strlen(*ibuf);
5444 f = open_memstream(&obuf, &osz);
5448 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5453 if (i >= *ibuf + isz) /* EOT */
5455 else if (*i == '\x1B')
5456 state = STATE_ESCAPE;
5457 else if (*i == '\t')
5464 if (i >= *ibuf + isz) { /* EOT */
5467 } else if (*i == '[') {
5468 state = STATE_BRACKET;
5473 state = STATE_OTHER;
5480 if (i >= *ibuf + isz || /* EOT */
5481 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5484 state = STATE_OTHER;
5486 } else if (*i == 'm')
5487 state = STATE_OTHER;
5509 int on_ac_power(void) {
5510 bool found_offline = false, found_online = false;
5511 _cleanup_closedir_ DIR *d = NULL;
5513 d = opendir("/sys/class/power_supply");
5519 union dirent_storage buf;
5520 _cleanup_free_ char *p = NULL;
5521 _cleanup_close_ int fd = -1, device = -1;
5526 k = readdir_r(d, &buf.de, &de);
5533 if (ignore_file(de->d_name))
5536 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5538 if (errno == ENOENT || errno == ENOTDIR)
5544 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5546 if (errno == ENOENT)
5552 n = read(fd, contents, sizeof(contents));
5556 if (n != 6 || memcmp(contents, "Mains\n", 6))
5559 close_nointr_nofail(fd);
5560 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5562 if (errno == ENOENT)
5568 n = read(fd, contents, sizeof(contents));
5572 if (n != 2 || contents[1] != '\n')
5575 if (contents[0] == '1') {
5576 found_online = true;
5578 } else if (contents[0] == '0')
5579 found_offline = true;
5584 return found_online || !found_offline;
5587 static int search_and_fopen_internal(const char *path, const char *mode, char **search, FILE **_f) {
5594 if (!path_strv_canonicalize_uniq(search))
5597 STRV_FOREACH(i, search) {
5598 _cleanup_free_ char *p = NULL;
5601 p = strjoin(*i, "/", path, NULL);
5611 if (errno != ENOENT)
5618 int search_and_fopen(const char *path, const char *mode, const char **search, FILE **_f) {
5619 _cleanup_strv_free_ char **copy = NULL;
5625 if (path_is_absolute(path)) {
5628 f = fopen(path, mode);
5637 copy = strv_copy((char**) search);
5641 return search_and_fopen_internal(path, mode, copy, _f);
5644 int search_and_fopen_nulstr(const char *path, const char *mode, const char *search, FILE **_f) {
5645 _cleanup_strv_free_ char **s = NULL;
5647 if (path_is_absolute(path)) {
5650 f = fopen(path, mode);
5659 s = strv_split_nulstr(search);
5663 return search_and_fopen_internal(path, mode, s, _f);