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 assert(fds || n_fd <= 0);
224 for (i = 0; i < n_fd; i++)
225 close_nointr_nofail(fds[i]);
228 int parse_boolean(const char *v) {
231 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
233 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
239 int parse_pid(const char *s, pid_t* ret_pid) {
240 unsigned long ul = 0;
247 r = safe_atolu(s, &ul);
253 if ((unsigned long) pid != ul)
263 int parse_uid(const char *s, uid_t* ret_uid) {
264 unsigned long ul = 0;
271 r = safe_atolu(s, &ul);
277 if ((unsigned long) uid != ul)
284 int safe_atou(const char *s, unsigned *ret_u) {
292 l = strtoul(s, &x, 0);
294 if (!x || x == s || *x || errno)
295 return errno > 0 ? -errno : -EINVAL;
297 if ((unsigned long) (unsigned) l != l)
300 *ret_u = (unsigned) l;
304 int safe_atoi(const char *s, int *ret_i) {
312 l = strtol(s, &x, 0);
314 if (!x || x == s || *x || errno)
315 return errno > 0 ? -errno : -EINVAL;
317 if ((long) (int) l != l)
324 int safe_atollu(const char *s, long long unsigned *ret_llu) {
326 unsigned long long l;
332 l = strtoull(s, &x, 0);
334 if (!x || x == s || *x || errno)
335 return errno ? -errno : -EINVAL;
341 int safe_atolli(const char *s, long long int *ret_lli) {
349 l = strtoll(s, &x, 0);
351 if (!x || x == s || *x || errno)
352 return errno ? -errno : -EINVAL;
358 int safe_atod(const char *s, double *ret_d) {
368 if (!x || x == s || *x || errno)
369 return errno ? -errno : -EINVAL;
375 /* Split a string into words. */
376 char *split(const char *c, size_t *l, const char *separator, char **state) {
379 current = *state ? *state : (char*) c;
381 if (!*current || *c == 0)
384 current += strspn(current, separator);
385 *l = strcspn(current, separator);
388 return (char*) current;
391 /* Split a string into words, but consider strings enclosed in '' and
392 * "" as words even if they include spaces. */
393 char *split_quoted(const char *c, size_t *l, char **state) {
395 bool escaped = false;
397 current = *state ? *state : (char*) c;
399 if (!*current || *c == 0)
402 current += strspn(current, WHITESPACE);
404 if (*current == '\'') {
407 for (e = current; *e; e++) {
417 *state = *e == 0 ? e : e+1;
418 } else if (*current == '\"') {
421 for (e = current; *e; e++) {
431 *state = *e == 0 ? e : e+1;
433 for (e = current; *e; e++) {
438 else if (strchr(WHITESPACE, *e))
445 return (char*) current;
448 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
450 _cleanup_fclose_ FILE *f = NULL;
451 char fn[PATH_MAX], line[LINE_MAX], *p;
457 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
464 if (!fgets(line, sizeof(line), f)) {
465 r = feof(f) ? -EIO : -errno;
469 /* Let's skip the pid and comm fields. The latter is enclosed
470 * in () but does not escape any () in its value, so let's
471 * skip over it manually */
473 p = strrchr(line, ')');
485 if ((long unsigned) (pid_t) ppid != ppid)
488 *_ppid = (pid_t) ppid;
493 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
494 _cleanup_fclose_ FILE *f = NULL;
495 char fn[PATH_MAX], line[LINE_MAX], *p;
500 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
507 if (!fgets(line, sizeof(line), f)) {
514 /* Let's skip the pid and comm fields. The latter is enclosed
515 * in () but does not escape any () in its value, so let's
516 * skip over it manually */
518 p = strrchr(line, ')');
540 "%*d " /* priority */
542 "%*d " /* num_threads */
543 "%*d " /* itrealvalue */
544 "%llu " /* starttime */,
551 int fchmod_umask(int fd, mode_t m) {
556 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
562 char *truncate_nl(char *s) {
565 s[strcspn(s, NEWLINE)] = 0;
569 int get_process_comm(pid_t pid, char **name) {
575 r = read_one_line_file("/proc/self/comm", name);
578 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
581 r = read_one_line_file(p, name);
588 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
596 f = fopen("/proc/self/cmdline", "re");
599 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
608 if (max_length == 0) {
610 while ((c = getc(f)) != EOF) {
611 k = realloc(r, len+1);
618 r[len-1] = isprint(c) ? c : ' ';
625 r = new(char, max_length);
633 while ((c = getc(f)) != EOF) {
655 size_t n = MIN(left-1, 3U);
664 /* Kernel threads have no argv[] */
665 if (r == NULL || r[0] == 0) {
674 h = get_process_comm(pid, &t);
678 r = strjoin("[", t, "]", NULL);
689 int is_kernel_thread(pid_t pid) {
699 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
708 count = fread(&c, 1, 1, f);
712 /* Kernel threads have an empty cmdline */
715 return eof ? 1 : -errno;
720 int get_process_exe(pid_t pid, char **name) {
726 r = readlink_malloc("/proc/self/exe", name);
729 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
732 r = readlink_malloc(p, name);
739 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
740 _cleanup_fclose_ FILE *f = NULL;
741 _cleanup_free_ char *p = NULL;
750 if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
757 FOREACH_LINE(line, f, return -errno) {
762 if (startswith(l, field)) {
764 l += strspn(l, WHITESPACE);
766 l[strcspn(l, WHITESPACE)] = 0;
768 return parse_uid(l, uid);
775 int get_process_uid(pid_t pid, uid_t *uid) {
776 return get_process_id(pid, "Uid:", uid);
779 int get_process_gid(pid_t pid, gid_t *gid) {
780 return get_process_id(pid, "Gid:", gid);
783 char *strnappend(const char *s, const char *suffix, size_t b) {
791 return strndup(suffix, b);
800 if (b > ((size_t) -1) - a)
803 r = new(char, a+b+1);
808 memcpy(r+a, suffix, b);
814 char *strappend(const char *s, const char *suffix) {
815 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
818 int readlink_malloc(const char *p, char **r) {
828 if (!(c = new(char, l)))
831 if ((n = readlink(p, c, l-1)) < 0) {
837 if ((size_t) n < l-1) {
848 int readlink_and_make_absolute(const char *p, char **r) {
855 if ((j = readlink_malloc(p, &target)) < 0)
858 k = file_in_same_dir(p, target);
868 int readlink_and_canonicalize(const char *p, char **r) {
875 j = readlink_and_make_absolute(p, &t);
879 s = canonicalize_file_name(t);
886 path_kill_slashes(*r);
891 int reset_all_signal_handlers(void) {
894 for (sig = 1; sig < _NSIG; sig++) {
897 if (sig == SIGKILL || sig == SIGSTOP)
901 sa.sa_handler = SIG_DFL;
902 sa.sa_flags = SA_RESTART;
904 /* On Linux the first two RT signals are reserved by
905 * glibc, and sigaction() will return EINVAL for them. */
906 if ((sigaction(sig, &sa, NULL) < 0))
914 char *strstrip(char *s) {
917 /* Drops trailing whitespace. Modifies the string in
918 * place. Returns pointer to first non-space character */
920 s += strspn(s, WHITESPACE);
922 for (e = strchr(s, 0); e > s; e --)
923 if (!strchr(WHITESPACE, e[-1]))
931 char *delete_chars(char *s, const char *bad) {
934 /* Drops all whitespace, regardless where in the string */
936 for (f = s, t = s; *f; f++) {
948 bool in_charset(const char *s, const char* charset) {
955 if (!strchr(charset, *i))
961 char *file_in_same_dir(const char *path, const char *filename) {
968 /* This removes the last component of path and appends
969 * filename, unless the latter is absolute anyway or the
972 if (path_is_absolute(filename))
973 return strdup(filename);
975 if (!(e = strrchr(path, '/')))
976 return strdup(filename);
978 k = strlen(filename);
979 if (!(r = new(char, e-path+1+k+1)))
982 memcpy(r, path, e-path+1);
983 memcpy(r+(e-path)+1, filename, k+1);
988 int rmdir_parents(const char *path, const char *stop) {
997 /* Skip trailing slashes */
998 while (l > 0 && path[l-1] == '/')
1004 /* Skip last component */
1005 while (l > 0 && path[l-1] != '/')
1008 /* Skip trailing slashes */
1009 while (l > 0 && path[l-1] == '/')
1015 if (!(t = strndup(path, l)))
1018 if (path_startswith(stop, t)) {
1027 if (errno != ENOENT)
1034 char hexchar(int x) {
1035 static const char table[16] = "0123456789abcdef";
1037 return table[x & 15];
1040 int unhexchar(char c) {
1042 if (c >= '0' && c <= '9')
1045 if (c >= 'a' && c <= 'f')
1046 return c - 'a' + 10;
1048 if (c >= 'A' && c <= 'F')
1049 return c - 'A' + 10;
1054 char *hexmem(const void *p, size_t l) {
1058 z = r = malloc(l * 2 + 1);
1062 for (x = p; x < (const uint8_t*) p + l; x++) {
1063 *(z++) = hexchar(*x >> 4);
1064 *(z++) = hexchar(*x & 15);
1071 char octchar(int x) {
1072 return '0' + (x & 7);
1075 int unoctchar(char c) {
1077 if (c >= '0' && c <= '7')
1083 char decchar(int x) {
1084 return '0' + (x % 10);
1087 int undecchar(char c) {
1089 if (c >= '0' && c <= '9')
1095 char *cescape(const char *s) {
1101 /* Does C style string escaping. */
1103 r = new(char, strlen(s)*4 + 1);
1107 for (f = s, t = r; *f; f++)
1153 /* For special chars we prefer octal over
1154 * hexadecimal encoding, simply because glib's
1155 * g_strescape() does the same */
1156 if ((*f < ' ') || (*f >= 127)) {
1158 *(t++) = octchar((unsigned char) *f >> 6);
1159 *(t++) = octchar((unsigned char) *f >> 3);
1160 *(t++) = octchar((unsigned char) *f);
1171 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1178 /* Undoes C style string escaping, and optionally prefixes it. */
1180 pl = prefix ? strlen(prefix) : 0;
1182 r = new(char, pl+length+1);
1187 memcpy(r, prefix, pl);
1189 for (f = s, t = r + pl; f < s + length; f++) {
1232 /* This is an extension of the XDG syntax files */
1237 /* hexadecimal encoding */
1240 a = unhexchar(f[1]);
1241 b = unhexchar(f[2]);
1243 if (a < 0 || b < 0) {
1244 /* Invalid escape code, let's take it literal then */
1248 *(t++) = (char) ((a << 4) | b);
1263 /* octal encoding */
1266 a = unoctchar(f[0]);
1267 b = unoctchar(f[1]);
1268 c = unoctchar(f[2]);
1270 if (a < 0 || b < 0 || c < 0) {
1271 /* Invalid escape code, let's take it literal then */
1275 *(t++) = (char) ((a << 6) | (b << 3) | c);
1283 /* premature end of string.*/
1288 /* Invalid escape code, let's take it literal then */
1300 char *cunescape_length(const char *s, size_t length) {
1301 return cunescape_length_with_prefix(s, length, NULL);
1304 char *cunescape(const char *s) {
1307 return cunescape_length(s, strlen(s));
1310 char *xescape(const char *s, const char *bad) {
1314 /* Escapes all chars in bad, in addition to \ and all special
1315 * chars, in \xFF style escaping. May be reversed with
1318 r = new(char, strlen(s) * 4 + 1);
1322 for (f = s, t = r; *f; f++) {
1324 if ((*f < ' ') || (*f >= 127) ||
1325 (*f == '\\') || strchr(bad, *f)) {
1328 *(t++) = hexchar(*f >> 4);
1329 *(t++) = hexchar(*f);
1339 char *bus_path_escape(const char *s) {
1345 /* Escapes all chars that D-Bus' object path cannot deal
1346 * with. Can be reverse with bus_path_unescape(). We special
1347 * case the empty string. */
1352 r = new(char, strlen(s)*3 + 1);
1356 for (f = s, t = r; *f; f++) {
1358 /* Escape everything that is not a-zA-Z0-9. We also
1359 * escape 0-9 if it's the first character */
1361 if (!(*f >= 'A' && *f <= 'Z') &&
1362 !(*f >= 'a' && *f <= 'z') &&
1363 !(f > s && *f >= '0' && *f <= '9')) {
1365 *(t++) = hexchar(*f >> 4);
1366 *(t++) = hexchar(*f);
1376 char *bus_path_unescape(const char *f) {
1381 /* Special case for the empty string */
1385 r = new(char, strlen(f) + 1);
1389 for (t = r; *f; f++) {
1394 if ((a = unhexchar(f[1])) < 0 ||
1395 (b = unhexchar(f[2])) < 0) {
1396 /* Invalid escape code, let's take it literal then */
1399 *(t++) = (char) ((a << 4) | b);
1411 char *ascii_strlower(char *t) {
1416 for (p = t; *p; p++)
1417 if (*p >= 'A' && *p <= 'Z')
1418 *p = *p - 'A' + 'a';
1423 static bool ignore_file_allow_backup(const char *filename) {
1427 filename[0] == '.' ||
1428 streq(filename, "lost+found") ||
1429 streq(filename, "aquota.user") ||
1430 streq(filename, "aquota.group") ||
1431 endswith(filename, ".rpmnew") ||
1432 endswith(filename, ".rpmsave") ||
1433 endswith(filename, ".rpmorig") ||
1434 endswith(filename, ".dpkg-old") ||
1435 endswith(filename, ".dpkg-new") ||
1436 endswith(filename, ".swp");
1439 bool ignore_file(const char *filename) {
1442 if (endswith(filename, "~"))
1445 return ignore_file_allow_backup(filename);
1448 int fd_nonblock(int fd, bool nonblock) {
1453 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1457 flags |= O_NONBLOCK;
1459 flags &= ~O_NONBLOCK;
1461 if (fcntl(fd, F_SETFL, flags) < 0)
1467 int fd_cloexec(int fd, bool cloexec) {
1472 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1476 flags |= FD_CLOEXEC;
1478 flags &= ~FD_CLOEXEC;
1480 if (fcntl(fd, F_SETFD, flags) < 0)
1486 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1489 assert(n_fdset == 0 || fdset);
1491 for (i = 0; i < n_fdset; i++)
1498 int close_all_fds(const int except[], unsigned n_except) {
1503 assert(n_except == 0 || except);
1505 d = opendir("/proc/self/fd");
1510 /* When /proc isn't available (for example in chroots)
1511 * the fallback is brute forcing through the fd
1514 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1515 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1517 if (fd_in_set(fd, except, n_except))
1520 if (close_nointr(fd) < 0)
1521 if (errno != EBADF && r == 0)
1528 while ((de = readdir(d))) {
1531 if (ignore_file(de->d_name))
1534 if (safe_atoi(de->d_name, &fd) < 0)
1535 /* Let's better ignore this, just in case */
1544 if (fd_in_set(fd, except, n_except))
1547 if (close_nointr(fd) < 0) {
1548 /* Valgrind has its own FD and doesn't want to have it closed */
1549 if (errno != EBADF && r == 0)
1558 bool chars_intersect(const char *a, const char *b) {
1561 /* Returns true if any of the chars in a are in b. */
1562 for (p = a; *p; p++)
1569 bool fstype_is_network(const char *fstype) {
1570 static const char table[] =
1579 return nulstr_contains(table, fstype);
1583 _cleanup_close_ int fd;
1585 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1591 TIOCL_GETKMSGREDIRECT,
1595 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1598 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1601 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1607 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1608 struct termios old_termios, new_termios;
1610 char line[LINE_MAX];
1615 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1616 new_termios = old_termios;
1618 new_termios.c_lflag &= ~ICANON;
1619 new_termios.c_cc[VMIN] = 1;
1620 new_termios.c_cc[VTIME] = 0;
1622 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1625 if (t != (usec_t) -1) {
1626 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1627 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1632 k = fread(&c, 1, 1, f);
1634 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1640 *need_nl = c != '\n';
1647 if (t != (usec_t) -1)
1648 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1651 if (!fgets(line, sizeof(line), f))
1656 if (strlen(line) != 1)
1666 int ask(char *ret, const char *replies, const char *text, ...) {
1676 bool need_nl = true;
1679 fputs(ANSI_HIGHLIGHT_ON, stdout);
1686 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1690 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1693 if (r == -EBADMSG) {
1694 puts("Bad input, please try again.");
1705 if (strchr(replies, c)) {
1710 puts("Read unexpected character, please try again.");
1714 int reset_terminal_fd(int fd, bool switch_to_text) {
1715 struct termios termios;
1718 /* Set terminal to some sane defaults */
1722 /* We leave locked terminal attributes untouched, so that
1723 * Plymouth may set whatever it wants to set, and we don't
1724 * interfere with that. */
1726 /* Disable exclusive mode, just in case */
1727 ioctl(fd, TIOCNXCL);
1729 /* Switch to text mode */
1731 ioctl(fd, KDSETMODE, KD_TEXT);
1733 /* Enable console unicode mode */
1734 ioctl(fd, KDSKBMODE, K_UNICODE);
1736 if (tcgetattr(fd, &termios) < 0) {
1741 /* We only reset the stuff that matters to the software. How
1742 * hardware is set up we don't touch assuming that somebody
1743 * else will do that for us */
1745 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1746 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1747 termios.c_oflag |= ONLCR;
1748 termios.c_cflag |= CREAD;
1749 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1751 termios.c_cc[VINTR] = 03; /* ^C */
1752 termios.c_cc[VQUIT] = 034; /* ^\ */
1753 termios.c_cc[VERASE] = 0177;
1754 termios.c_cc[VKILL] = 025; /* ^X */
1755 termios.c_cc[VEOF] = 04; /* ^D */
1756 termios.c_cc[VSTART] = 021; /* ^Q */
1757 termios.c_cc[VSTOP] = 023; /* ^S */
1758 termios.c_cc[VSUSP] = 032; /* ^Z */
1759 termios.c_cc[VLNEXT] = 026; /* ^V */
1760 termios.c_cc[VWERASE] = 027; /* ^W */
1761 termios.c_cc[VREPRINT] = 022; /* ^R */
1762 termios.c_cc[VEOL] = 0;
1763 termios.c_cc[VEOL2] = 0;
1765 termios.c_cc[VTIME] = 0;
1766 termios.c_cc[VMIN] = 1;
1768 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1772 /* Just in case, flush all crap out */
1773 tcflush(fd, TCIOFLUSH);
1778 int reset_terminal(const char *name) {
1781 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1785 r = reset_terminal_fd(fd, true);
1786 close_nointr_nofail(fd);
1791 int open_terminal(const char *name, int mode) {
1796 * If a TTY is in the process of being closed opening it might
1797 * cause EIO. This is horribly awful, but unlikely to be
1798 * changed in the kernel. Hence we work around this problem by
1799 * retrying a couple of times.
1801 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1805 fd = open(name, mode);
1812 /* Max 1s in total */
1816 usleep(50 * USEC_PER_MSEC);
1825 close_nointr_nofail(fd);
1830 close_nointr_nofail(fd);
1837 int flush_fd(int fd) {
1838 struct pollfd pollfd;
1842 pollfd.events = POLLIN;
1849 if ((r = poll(&pollfd, 1, 0)) < 0) {
1860 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1865 if (errno == EAGAIN)
1876 int acquire_terminal(
1880 bool ignore_tiocstty_eperm,
1883 int fd = -1, notify = -1, r = 0, wd = -1;
1885 struct sigaction sa_old, sa_new;
1889 /* We use inotify to be notified when the tty is closed. We
1890 * create the watch before checking if we can actually acquire
1891 * it, so that we don't lose any event.
1893 * Note: strictly speaking this actually watches for the
1894 * device being closed, it does *not* really watch whether a
1895 * tty loses its controlling process. However, unless some
1896 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1897 * its tty otherwise this will not become a problem. As long
1898 * as the administrator makes sure not configure any service
1899 * on the same tty as an untrusted user this should not be a
1900 * problem. (Which he probably should not do anyway.) */
1902 if (timeout != (usec_t) -1)
1903 ts = now(CLOCK_MONOTONIC);
1905 if (!fail && !force) {
1906 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1912 wd = inotify_add_watch(notify, name, IN_CLOSE);
1921 r = flush_fd(notify);
1926 /* We pass here O_NOCTTY only so that we can check the return
1927 * value TIOCSCTTY and have a reliable way to figure out if we
1928 * successfully became the controlling process of the tty */
1929 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1933 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1934 * if we already own the tty. */
1936 sa_new.sa_handler = SIG_IGN;
1937 sa_new.sa_flags = SA_RESTART;
1938 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1940 /* First, try to get the tty */
1941 if (ioctl(fd, TIOCSCTTY, force) < 0)
1944 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1946 /* Sometimes it makes sense to ignore TIOCSCTTY
1947 * returning EPERM, i.e. when very likely we already
1948 * are have this controlling terminal. */
1949 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1952 if (r < 0 && (force || fail || r != -EPERM)) {
1961 assert(notify >= 0);
1964 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1966 struct inotify_event *e;
1968 if (timeout != (usec_t) -1) {
1971 n = now(CLOCK_MONOTONIC);
1972 if (ts + timeout < n) {
1977 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1987 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1990 if (errno == EINTR || errno == EAGAIN)
1997 e = (struct inotify_event*) inotify_buffer;
2002 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2007 step = sizeof(struct inotify_event) + e->len;
2008 assert(step <= (size_t) l);
2010 e = (struct inotify_event*) ((uint8_t*) e + step);
2017 /* We close the tty fd here since if the old session
2018 * ended our handle will be dead. It's important that
2019 * we do this after sleeping, so that we don't enter
2020 * an endless loop. */
2021 close_nointr_nofail(fd);
2025 close_nointr_nofail(notify);
2027 r = reset_terminal_fd(fd, true);
2029 log_warning("Failed to reset terminal: %s", strerror(-r));
2035 close_nointr_nofail(fd);
2038 close_nointr_nofail(notify);
2043 int release_terminal(void) {
2045 struct sigaction sa_old, sa_new;
2047 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2050 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2051 * by our own TIOCNOTTY */
2054 sa_new.sa_handler = SIG_IGN;
2055 sa_new.sa_flags = SA_RESTART;
2056 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2058 if (ioctl(fd, TIOCNOTTY) < 0)
2061 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2063 close_nointr_nofail(fd);
2067 int sigaction_many(const struct sigaction *sa, ...) {
2072 while ((sig = va_arg(ap, int)) > 0)
2073 if (sigaction(sig, sa, NULL) < 0)
2080 int ignore_signals(int sig, ...) {
2081 struct sigaction sa;
2086 sa.sa_handler = SIG_IGN;
2087 sa.sa_flags = SA_RESTART;
2089 if (sigaction(sig, &sa, NULL) < 0)
2093 while ((sig = va_arg(ap, int)) > 0)
2094 if (sigaction(sig, &sa, NULL) < 0)
2101 int default_signals(int sig, ...) {
2102 struct sigaction sa;
2107 sa.sa_handler = SIG_DFL;
2108 sa.sa_flags = SA_RESTART;
2110 if (sigaction(sig, &sa, NULL) < 0)
2114 while ((sig = va_arg(ap, int)) > 0)
2115 if (sigaction(sig, &sa, NULL) < 0)
2122 int close_pipe(int p[]) {
2128 a = close_nointr(p[0]);
2133 b = close_nointr(p[1]);
2137 return a < 0 ? a : b;
2140 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2149 while (nbytes > 0) {
2152 if ((k = read(fd, p, nbytes)) <= 0) {
2154 if (k < 0 && errno == EINTR)
2157 if (k < 0 && errno == EAGAIN && do_poll) {
2158 struct pollfd pollfd;
2162 pollfd.events = POLLIN;
2164 if (poll(&pollfd, 1, -1) < 0) {
2168 return n > 0 ? n : -errno;
2171 if (pollfd.revents != POLLIN)
2172 return n > 0 ? n : -EIO;
2177 return n > 0 ? n : (k < 0 ? -errno : 0);
2188 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2197 while (nbytes > 0) {
2200 k = write(fd, p, nbytes);
2203 if (k < 0 && errno == EINTR)
2206 if (k < 0 && errno == EAGAIN && do_poll) {
2207 struct pollfd pollfd;
2211 pollfd.events = POLLOUT;
2213 if (poll(&pollfd, 1, -1) < 0) {
2217 return n > 0 ? n : -errno;
2220 if (pollfd.revents != POLLOUT)
2221 return n > 0 ? n : -EIO;
2226 return n > 0 ? n : (k < 0 ? -errno : 0);
2237 int parse_bytes(const char *t, off_t *bytes) {
2238 static const struct {
2244 { "M", 1024ULL*1024ULL },
2245 { "G", 1024ULL*1024ULL*1024ULL },
2246 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2247 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2248 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2265 l = strtoll(p, &e, 10);
2276 e += strspn(e, WHITESPACE);
2278 for (i = 0; i < ELEMENTSOF(table); i++)
2279 if (startswith(e, table[i].suffix)) {
2280 r += (off_t) l * table[i].factor;
2281 p = e + strlen(table[i].suffix);
2285 if (i >= ELEMENTSOF(table))
2295 int make_stdio(int fd) {
2300 r = dup3(fd, STDIN_FILENO, 0);
2301 s = dup3(fd, STDOUT_FILENO, 0);
2302 t = dup3(fd, STDERR_FILENO, 0);
2305 close_nointr_nofail(fd);
2307 if (r < 0 || s < 0 || t < 0)
2310 /* We rely here that the new fd has O_CLOEXEC not set */
2315 int make_null_stdio(void) {
2318 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2322 return make_stdio(null_fd);
2325 bool is_device_path(const char *path) {
2327 /* Returns true on paths that refer to a device, either in
2328 * sysfs or in /dev */
2331 path_startswith(path, "/dev/") ||
2332 path_startswith(path, "/sys/");
2335 int dir_is_empty(const char *path) {
2336 _cleanup_closedir_ DIR *d;
2345 union dirent_storage buf;
2347 r = readdir_r(d, &buf.de, &de);
2354 if (!ignore_file(de->d_name))
2359 unsigned long long random_ull(void) {
2360 _cleanup_close_ int fd;
2364 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2368 r = loop_read(fd, &ull, sizeof(ull), true);
2369 if (r != sizeof(ull))
2375 return random() * RAND_MAX + random();
2378 void rename_process(const char name[8]) {
2381 /* This is a like a poor man's setproctitle(). It changes the
2382 * comm field, argv[0], and also the glibc's internally used
2383 * name of the process. For the first one a limit of 16 chars
2384 * applies, to the second one usually one of 10 (i.e. length
2385 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2386 * "systemd"). If you pass a longer string it will be
2389 prctl(PR_SET_NAME, name);
2391 if (program_invocation_name)
2392 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2394 if (saved_argc > 0) {
2398 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2400 for (i = 1; i < saved_argc; i++) {
2404 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2409 void sigset_add_many(sigset_t *ss, ...) {
2416 while ((sig = va_arg(ap, int)) > 0)
2417 assert_se(sigaddset(ss, sig) == 0);
2421 char* gethostname_malloc(void) {
2424 assert_se(uname(&u) >= 0);
2426 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2427 return strdup(u.nodename);
2429 return strdup(u.sysname);
2432 bool hostname_is_set(void) {
2435 assert_se(uname(&u) >= 0);
2437 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2440 static char *lookup_uid(uid_t uid) {
2443 _cleanup_free_ char *buf = NULL;
2444 struct passwd pwbuf, *pw = NULL;
2446 /* Shortcut things to avoid NSS lookups */
2448 return strdup("root");
2450 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2454 buf = malloc(bufsize);
2458 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2459 return strdup(pw->pw_name);
2461 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2467 char* getlogname_malloc(void) {
2471 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2476 return lookup_uid(uid);
2479 char *getusername_malloc(void) {
2486 return lookup_uid(getuid());
2489 int getttyname_malloc(int fd, char **r) {
2490 char path[PATH_MAX], *c;
2495 k = ttyname_r(fd, path, sizeof(path));
2501 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2509 int getttyname_harder(int fd, char **r) {
2513 k = getttyname_malloc(fd, &s);
2517 if (streq(s, "tty")) {
2519 return get_ctty(0, NULL, r);
2526 int get_ctty_devnr(pid_t pid, dev_t *d) {
2528 char line[LINE_MAX], *p, *fn;
2529 unsigned long ttynr;
2532 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2535 f = fopen(fn, "re");
2540 if (!fgets(line, sizeof(line), f)) {
2541 k = feof(f) ? -EIO : -errno;
2548 p = strrchr(line, ')');
2558 "%*d " /* session */
2563 if (major(ttynr) == 0 && minor(ttynr) == 0)
2570 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2572 char fn[PATH_MAX], *s, *b, *p;
2577 k = get_ctty_devnr(pid, &devnr);
2581 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2584 k = readlink_malloc(fn, &s);
2590 /* This is an ugly hack */
2591 if (major(devnr) == 136) {
2592 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2602 /* Probably something like the ptys which have no
2603 * symlink in /dev/char. Let's return something
2604 * vaguely useful. */
2617 if (startswith(s, "/dev/"))
2619 else if (startswith(s, "../"))
2637 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2643 /* This returns the first error we run into, but nevertheless
2644 * tries to go on. This closes the passed fd. */
2648 close_nointr_nofail(fd);
2650 return errno == ENOENT ? 0 : -errno;
2655 union dirent_storage buf;
2656 bool is_dir, keep_around;
2660 r = readdir_r(d, &buf.de, &de);
2661 if (r != 0 && ret == 0) {
2669 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2672 if (de->d_type == DT_UNKNOWN ||
2674 (de->d_type == DT_DIR && root_dev)) {
2675 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2676 if (ret == 0 && errno != ENOENT)
2681 is_dir = S_ISDIR(st.st_mode);
2684 (st.st_uid == 0 || st.st_uid == getuid()) &&
2685 (st.st_mode & S_ISVTX);
2687 is_dir = de->d_type == DT_DIR;
2688 keep_around = false;
2694 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2695 if (root_dev && st.st_dev != root_dev->st_dev)
2698 subdir_fd = openat(fd, de->d_name,
2699 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2700 if (subdir_fd < 0) {
2701 if (ret == 0 && errno != ENOENT)
2706 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2707 if (r < 0 && ret == 0)
2711 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2712 if (ret == 0 && errno != ENOENT)
2716 } else if (!only_dirs && !keep_around) {
2718 if (unlinkat(fd, de->d_name, 0) < 0) {
2719 if (ret == 0 && errno != ENOENT)
2730 static int is_temporary_fs(struct statfs *s) {
2732 return s->f_type == TMPFS_MAGIC ||
2733 (long)s->f_type == (long)RAMFS_MAGIC;
2736 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2741 if (fstatfs(fd, &s) < 0) {
2742 close_nointr_nofail(fd);
2746 /* We refuse to clean disk file systems with this call. This
2747 * is extra paranoia just to be sure we never ever remove
2749 if (!is_temporary_fs(&s)) {
2750 log_error("Attempted to remove disk file system, and we can't allow that.");
2751 close_nointr_nofail(fd);
2755 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2758 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2764 /* We refuse to clean the root file system with this
2765 * call. This is extra paranoia to never cause a really
2766 * seriously broken system. */
2767 if (path_equal(path, "/")) {
2768 log_error("Attempted to remove entire root file system, and we can't allow that.");
2772 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2775 if (errno != ENOTDIR)
2779 if (statfs(path, &s) < 0)
2782 if (!is_temporary_fs(&s)) {
2783 log_error("Attempted to remove disk file system, and we can't allow that.");
2788 if (delete_root && !only_dirs)
2789 if (unlink(path) < 0 && errno != ENOENT)
2796 if (fstatfs(fd, &s) < 0) {
2797 close_nointr_nofail(fd);
2801 if (!is_temporary_fs(&s)) {
2802 log_error("Attempted to remove disk file system, and we can't allow that.");
2803 close_nointr_nofail(fd);
2808 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2811 if (honour_sticky && file_is_priv_sticky(path) > 0)
2814 if (rmdir(path) < 0 && errno != ENOENT) {
2823 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2824 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2827 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2828 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2831 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2834 /* Under the assumption that we are running privileged we
2835 * first change the access mode and only then hand out
2836 * ownership to avoid a window where access is too open. */
2838 if (mode != (mode_t) -1)
2839 if (chmod(path, mode) < 0)
2842 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2843 if (chown(path, uid, gid) < 0)
2849 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2852 /* Under the assumption that we are running privileged we
2853 * first change the access mode and only then hand out
2854 * ownership to avoid a window where access is too open. */
2856 if (fchmod(fd, mode) < 0)
2859 if (fchown(fd, uid, gid) < 0)
2865 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2869 /* Allocates the cpuset in the right size */
2872 if (!(r = CPU_ALLOC(n)))
2875 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2876 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2886 if (errno != EINVAL)
2893 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2894 static const char status_indent[] = " "; /* "[" STATUS "] " */
2895 _cleanup_free_ char *s = NULL;
2896 _cleanup_close_ int fd = -1;
2897 struct iovec iovec[6];
2899 static bool prev_ephemeral;
2903 /* This is independent of logging, as status messages are
2904 * optional and go exclusively to the console. */
2906 if (vasprintf(&s, format, ap) < 0)
2909 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2922 sl = status ? sizeof(status_indent)-1 : 0;
2928 e = ellipsize(s, emax, 75);
2938 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2939 prev_ephemeral = ephemeral;
2942 if (!isempty(status)) {
2943 IOVEC_SET_STRING(iovec[n++], "[");
2944 IOVEC_SET_STRING(iovec[n++], status);
2945 IOVEC_SET_STRING(iovec[n++], "] ");
2947 IOVEC_SET_STRING(iovec[n++], status_indent);
2950 IOVEC_SET_STRING(iovec[n++], s);
2952 IOVEC_SET_STRING(iovec[n++], "\n");
2954 if (writev(fd, iovec, n) < 0)
2960 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2966 va_start(ap, format);
2967 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2973 int status_welcome(void) {
2975 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2977 r = parse_env_file("/etc/os-release", NEWLINE,
2978 "PRETTY_NAME", &pretty_name,
2979 "ANSI_COLOR", &ansi_color,
2981 if (r < 0 && r != -ENOENT)
2982 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2984 return status_printf(NULL, false, false,
2985 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2986 isempty(ansi_color) ? "1" : ansi_color,
2987 isempty(pretty_name) ? "Linux" : pretty_name);
2990 char *replace_env(const char *format, char **env) {
2997 const char *e, *word = format;
3002 for (e = format; *e; e ++) {
3013 if (!(k = strnappend(r, word, e-word-1)))
3022 } else if (*e == '$') {
3023 if (!(k = strnappend(r, word, e-word)))
3039 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3041 k = strappend(r, t);
3055 if (!(k = strnappend(r, word, e-word)))
3066 char **replace_env_argv(char **argv, char **env) {
3068 unsigned k = 0, l = 0;
3070 l = strv_length(argv);
3072 if (!(r = new(char*, l+1)))
3075 STRV_FOREACH(i, argv) {
3077 /* If $FOO appears as single word, replace it by the split up variable */
3078 if ((*i)[0] == '$' && (*i)[1] != '{') {
3083 e = strv_env_get(env, *i+1);
3086 if (!(m = strv_split_quoted(e))) {
3097 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3106 memcpy(r + k, m, q * sizeof(char*));
3114 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3115 if (!(r[k++] = replace_env(*i, env))) {
3125 int fd_columns(int fd) {
3129 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3138 unsigned columns(void) {
3142 if (_likely_(cached_columns > 0))
3143 return cached_columns;
3146 e = getenv("COLUMNS");
3151 c = fd_columns(STDOUT_FILENO);
3160 int fd_lines(int fd) {
3164 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3173 unsigned lines(void) {
3177 if (_likely_(cached_lines > 0))
3178 return cached_lines;
3181 e = getenv("LINES");
3186 l = fd_lines(STDOUT_FILENO);
3192 return cached_lines;
3195 /* intended to be used as a SIGWINCH sighandler */
3196 void columns_lines_cache_reset(int signum) {
3202 static int cached_on_tty = -1;
3204 if (_unlikely_(cached_on_tty < 0))
3205 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3207 return cached_on_tty;
3210 int running_in_chroot(void) {
3216 /* Only works as root */
3218 if (stat("/proc/1/root", &a) < 0)
3221 if (stat("/", &b) < 0)
3225 a.st_dev != b.st_dev ||
3226 a.st_ino != b.st_ino;
3229 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3234 assert(percent <= 100);
3235 assert(new_length >= 3);
3237 if (old_length <= 3 || old_length <= new_length)
3238 return strndup(s, old_length);
3240 r = new0(char, new_length+1);
3244 x = (new_length * percent) / 100;
3246 if (x > new_length - 3)
3254 s + old_length - (new_length - x - 3),
3255 new_length - x - 3);
3260 char *ellipsize(const char *s, size_t length, unsigned percent) {
3261 return ellipsize_mem(s, strlen(s), length, percent);
3264 int touch(const char *path) {
3269 /* This just opens the file for writing, ensuring it
3270 * exists. It doesn't call utimensat() the way /usr/bin/touch
3273 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3277 close_nointr_nofail(fd);
3281 char *unquote(const char *s, const char* quotes) {
3285 /* This is rather stupid, simply removes the heading and
3286 * trailing quotes if there is one. Doesn't care about
3287 * escaping or anything. We should make this smarter one
3294 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3295 return strndup(s+1, l-2);
3300 char *normalize_env_assignment(const char *s) {
3301 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3304 eq = strchr(s, '=');
3316 memmove(r, t, strlen(t) + 1);
3320 name = strndup(s, eq - s);
3328 value = unquote(strstrip(p), QUOTES);
3332 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3338 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3349 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3361 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3368 r = wait_for_terminate(pid, &status);
3370 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3374 if (status.si_code == CLD_EXITED) {
3375 if (status.si_status != 0) {
3376 log_warning("%s failed with error code %i.", name, status.si_status);
3377 return status.si_status;
3380 log_debug("%s succeeded.", name);
3383 } else if (status.si_code == CLD_KILLED ||
3384 status.si_code == CLD_DUMPED) {
3386 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3390 log_warning("%s failed due to unknown reason.", name);
3394 _noreturn_ void freeze(void) {
3396 /* Make sure nobody waits for us on a socket anymore */
3397 close_all_fds(NULL, 0);