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>
71 #include "path-util.h"
72 #include "exit-status.h"
78 char **saved_argv = NULL;
80 static volatile unsigned cached_columns = 0;
81 static volatile unsigned cached_lines = 0;
83 size_t page_size(void) {
84 static __thread size_t pgsz = 0;
87 if (_likely_(pgsz > 0))
90 r = sysconf(_SC_PAGESIZE);
97 bool streq_ptr(const char *a, const char *b) {
99 /* Like streq(), but tries to make sense of NULL pointers */
110 char* endswith(const char *s, const char *postfix) {
117 pl = strlen(postfix);
120 return (char*) s + sl;
125 if (memcmp(s + sl - pl, postfix, pl) != 0)
128 return (char*) s + sl - pl;
131 char* startswith(const char *s, const char *prefix) {
148 char* startswith_no_case(const char *s, const char *prefix) {
158 if (tolower(*a) != tolower(*b))
165 bool first_word(const char *s, const char *word) {
180 if (memcmp(s, word, wl) != 0)
184 strchr(WHITESPACE, s[wl]);
187 int close_nointr(int fd) {
193 /* Just ignore EINTR; a retry loop is the wrong
194 * thing to do on Linux.
196 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
197 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
198 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
199 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
201 if (_unlikely_(r < 0 && errno == EINTR))
209 void close_nointr_nofail(int fd) {
212 /* like close_nointr() but cannot fail, and guarantees errno
215 assert_se(close_nointr(fd) == 0);
218 void close_many(const int fds[], unsigned n_fd) {
221 assert(fds || n_fd <= 0);
223 for (i = 0; i < n_fd; i++)
224 close_nointr_nofail(fds[i]);
227 int unlink_noerrno(const char *path) {
238 int parse_boolean(const char *v) {
241 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
243 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
249 int parse_pid(const char *s, pid_t* ret_pid) {
250 unsigned long ul = 0;
257 r = safe_atolu(s, &ul);
263 if ((unsigned long) pid != ul)
273 int parse_uid(const char *s, uid_t* ret_uid) {
274 unsigned long ul = 0;
281 r = safe_atolu(s, &ul);
287 if ((unsigned long) uid != ul)
294 int safe_atou(const char *s, unsigned *ret_u) {
302 l = strtoul(s, &x, 0);
304 if (!x || x == s || *x || errno)
305 return errno > 0 ? -errno : -EINVAL;
307 if ((unsigned long) (unsigned) l != l)
310 *ret_u = (unsigned) l;
314 int safe_atoi(const char *s, int *ret_i) {
322 l = strtol(s, &x, 0);
324 if (!x || x == s || *x || errno)
325 return errno > 0 ? -errno : -EINVAL;
327 if ((long) (int) l != l)
334 int safe_atollu(const char *s, long long unsigned *ret_llu) {
336 unsigned long long l;
342 l = strtoull(s, &x, 0);
344 if (!x || x == s || *x || errno)
345 return errno ? -errno : -EINVAL;
351 int safe_atolli(const char *s, long long int *ret_lli) {
359 l = strtoll(s, &x, 0);
361 if (!x || x == s || *x || errno)
362 return errno ? -errno : -EINVAL;
368 int safe_atod(const char *s, double *ret_d) {
375 RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
380 if (!x || x == s || *x || errno)
381 return errno ? -errno : -EINVAL;
387 /* Split a string into words. */
388 char *split(const char *c, size_t *l, const char *separator, char **state) {
391 current = *state ? *state : (char*) c;
393 if (!*current || *c == 0)
396 current += strspn(current, separator);
397 *l = strcspn(current, separator);
400 return (char*) current;
403 /* Split a string into words, but consider strings enclosed in '' and
404 * "" as words even if they include spaces. */
405 char *split_quoted(const char *c, size_t *l, char **state) {
407 bool escaped = false;
409 current = *state ? *state : (char*) c;
411 if (!*current || *c == 0)
414 current += strspn(current, WHITESPACE);
416 if (*current == '\'') {
419 for (e = current; *e; e++) {
429 *state = *e == 0 ? e : e+1;
430 } else if (*current == '\"') {
433 for (e = current; *e; e++) {
443 *state = *e == 0 ? e : e+1;
445 for (e = current; *e; e++) {
450 else if (strchr(WHITESPACE, *e))
457 return (char*) current;
460 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
462 _cleanup_fclose_ FILE *f = NULL;
475 p = procfs_file_alloca(pid, "stat");
480 if (!fgets(line, sizeof(line), f)) {
481 r = feof(f) ? -EIO : -errno;
485 /* Let's skip the pid and comm fields. The latter is enclosed
486 * in () but does not escape any () in its value, so let's
487 * skip over it manually */
489 p = strrchr(line, ')');
501 if ((long unsigned) (pid_t) ppid != ppid)
504 *_ppid = (pid_t) ppid;
509 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
510 _cleanup_fclose_ FILE *f = NULL;
518 p = "/proc/self/stat";
520 p = procfs_file_alloca(pid, "stat");
526 if (!fgets(line, sizeof(line), f)) {
533 /* Let's skip the pid and comm fields. The latter is enclosed
534 * in () but does not escape any () in its value, so let's
535 * skip over it manually */
537 p = strrchr(line, ')');
559 "%*d " /* priority */
561 "%*d " /* num_threads */
562 "%*d " /* itrealvalue */
563 "%llu " /* starttime */,
570 int fchmod_umask(int fd, mode_t m) {
575 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
581 char *truncate_nl(char *s) {
584 s[strcspn(s, NEWLINE)] = 0;
588 int get_process_comm(pid_t pid, char **name) {
595 p = "/proc/self/comm";
597 p = procfs_file_alloca(pid, "comm");
599 return read_one_line_file(p, name);
602 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
603 _cleanup_fclose_ FILE *f = NULL;
612 p = "/proc/self/cmdline";
614 p = procfs_file_alloca(pid, "cmdline");
620 if (max_length == 0) {
621 size_t len = 0, allocated = 0;
623 while ((c = getc(f)) != EOF) {
625 if (!GREEDY_REALLOC(r, allocated, len+2)) {
630 r[len++] = isprint(c) ? c : ' ';
640 r = new(char, max_length);
646 while ((c = getc(f)) != EOF) {
668 size_t n = MIN(left-1, 3U);
675 /* Kernel threads have no argv[] */
676 if (r == NULL || r[0] == 0) {
685 h = get_process_comm(pid, &t);
689 r = strjoin("[", t, "]", NULL);
700 int is_kernel_thread(pid_t pid) {
712 p = procfs_file_alloca(pid, "cmdline");
717 count = fread(&c, 1, 1, f);
721 /* Kernel threads have an empty cmdline */
724 return eof ? 1 : -errno;
730 int get_process_exe(pid_t pid, char **name) {
737 p = "/proc/self/exe";
739 p = procfs_file_alloca(pid, "exe");
741 return readlink_malloc(p, name);
744 static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
745 _cleanup_fclose_ FILE *f = NULL;
755 p = procfs_file_alloca(pid, "status");
760 FOREACH_LINE(line, f, return -errno) {
765 if (startswith(l, field)) {
767 l += strspn(l, WHITESPACE);
769 l[strcspn(l, WHITESPACE)] = 0;
771 return parse_uid(l, uid);
778 int get_process_uid(pid_t pid, uid_t *uid) {
779 return get_process_id(pid, "Uid:", uid);
782 int get_process_gid(pid_t pid, gid_t *gid) {
783 assert_cc(sizeof(uid_t) == sizeof(gid_t));
784 return get_process_id(pid, "Gid:", gid);
787 char *strnappend(const char *s, const char *suffix, size_t b) {
795 return strndup(suffix, b);
804 if (b > ((size_t) -1) - a)
807 r = new(char, a+b+1);
812 memcpy(r+a, suffix, b);
818 char *strappend(const char *s, const char *suffix) {
819 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
822 int readlink_malloc(const char *p, char **r) {
832 if (!(c = new(char, l)))
835 if ((n = readlink(p, c, l-1)) < 0) {
841 if ((size_t) n < l-1) {
852 int readlink_and_make_absolute(const char *p, char **r) {
853 _cleanup_free_ char *target = NULL;
860 j = readlink_malloc(p, &target);
864 k = file_in_same_dir(p, target);
872 int readlink_and_canonicalize(const char *p, char **r) {
879 j = readlink_and_make_absolute(p, &t);
883 s = canonicalize_file_name(t);
890 path_kill_slashes(*r);
895 int reset_all_signal_handlers(void) {
898 for (sig = 1; sig < _NSIG; sig++) {
899 struct sigaction sa = {
900 .sa_handler = SIG_DFL,
901 .sa_flags = SA_RESTART,
904 if (sig == SIGKILL || sig == SIGSTOP)
907 /* On Linux the first two RT signals are reserved by
908 * glibc, and sigaction() will return EINVAL for them. */
909 if ((sigaction(sig, &sa, NULL) < 0))
917 char *strstrip(char *s) {
920 /* Drops trailing whitespace. Modifies the string in
921 * place. Returns pointer to first non-space character */
923 s += strspn(s, WHITESPACE);
925 for (e = strchr(s, 0); e > s; e --)
926 if (!strchr(WHITESPACE, e[-1]))
934 char *delete_chars(char *s, const char *bad) {
937 /* Drops all whitespace, regardless where in the string */
939 for (f = s, t = s; *f; f++) {
951 bool in_charset(const char *s, const char* charset) {
958 if (!strchr(charset, *i))
964 char *file_in_same_dir(const char *path, const char *filename) {
971 /* This removes the last component of path and appends
972 * filename, unless the latter is absolute anyway or the
975 if (path_is_absolute(filename))
976 return strdup(filename);
978 if (!(e = strrchr(path, '/')))
979 return strdup(filename);
981 k = strlen(filename);
982 if (!(r = new(char, e-path+1+k+1)))
985 memcpy(r, path, e-path+1);
986 memcpy(r+(e-path)+1, filename, k+1);
991 int rmdir_parents(const char *path, const char *stop) {
1000 /* Skip trailing slashes */
1001 while (l > 0 && path[l-1] == '/')
1007 /* Skip last component */
1008 while (l > 0 && path[l-1] != '/')
1011 /* Skip trailing slashes */
1012 while (l > 0 && path[l-1] == '/')
1018 if (!(t = strndup(path, l)))
1021 if (path_startswith(stop, t)) {
1030 if (errno != ENOENT)
1037 char hexchar(int x) {
1038 static const char table[16] = "0123456789abcdef";
1040 return table[x & 15];
1043 int unhexchar(char c) {
1045 if (c >= '0' && c <= '9')
1048 if (c >= 'a' && c <= 'f')
1049 return c - 'a' + 10;
1051 if (c >= 'A' && c <= 'F')
1052 return c - 'A' + 10;
1057 char *hexmem(const void *p, size_t l) {
1061 z = r = malloc(l * 2 + 1);
1065 for (x = p; x < (const uint8_t*) p + l; x++) {
1066 *(z++) = hexchar(*x >> 4);
1067 *(z++) = hexchar(*x & 15);
1074 void *unhexmem(const char *p, size_t l) {
1080 z = r = malloc((l + 1) / 2 + 1);
1084 for (x = p; x < p + l; x += 2) {
1087 a = unhexchar(x[0]);
1089 b = unhexchar(x[1]);
1093 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
1100 char octchar(int x) {
1101 return '0' + (x & 7);
1104 int unoctchar(char c) {
1106 if (c >= '0' && c <= '7')
1112 char decchar(int x) {
1113 return '0' + (x % 10);
1116 int undecchar(char c) {
1118 if (c >= '0' && c <= '9')
1124 char *cescape(const char *s) {
1130 /* Does C style string escaping. */
1132 r = new(char, strlen(s)*4 + 1);
1136 for (f = s, t = r; *f; f++)
1182 /* For special chars we prefer octal over
1183 * hexadecimal encoding, simply because glib's
1184 * g_strescape() does the same */
1185 if ((*f < ' ') || (*f >= 127)) {
1187 *(t++) = octchar((unsigned char) *f >> 6);
1188 *(t++) = octchar((unsigned char) *f >> 3);
1189 *(t++) = octchar((unsigned char) *f);
1200 char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1207 /* Undoes C style string escaping, and optionally prefixes it. */
1209 pl = prefix ? strlen(prefix) : 0;
1211 r = new(char, pl+length+1);
1216 memcpy(r, prefix, pl);
1218 for (f = s, t = r + pl; f < s + length; f++) {
1261 /* This is an extension of the XDG syntax files */
1266 /* hexadecimal encoding */
1269 a = unhexchar(f[1]);
1270 b = unhexchar(f[2]);
1272 if (a < 0 || b < 0) {
1273 /* Invalid escape code, let's take it literal then */
1277 *(t++) = (char) ((a << 4) | b);
1292 /* octal encoding */
1295 a = unoctchar(f[0]);
1296 b = unoctchar(f[1]);
1297 c = unoctchar(f[2]);
1299 if (a < 0 || b < 0 || c < 0) {
1300 /* Invalid escape code, let's take it literal then */
1304 *(t++) = (char) ((a << 6) | (b << 3) | c);
1312 /* premature end of string.*/
1317 /* Invalid escape code, let's take it literal then */
1329 char *cunescape_length(const char *s, size_t length) {
1330 return cunescape_length_with_prefix(s, length, NULL);
1333 char *cunescape(const char *s) {
1336 return cunescape_length(s, strlen(s));
1339 char *xescape(const char *s, const char *bad) {
1343 /* Escapes all chars in bad, in addition to \ and all special
1344 * chars, in \xFF style escaping. May be reversed with
1347 r = new(char, strlen(s) * 4 + 1);
1351 for (f = s, t = r; *f; f++) {
1353 if ((*f < ' ') || (*f >= 127) ||
1354 (*f == '\\') || strchr(bad, *f)) {
1357 *(t++) = hexchar(*f >> 4);
1358 *(t++) = hexchar(*f);
1368 char *bus_path_escape(const char *s) {
1374 /* Escapes all chars that D-Bus' object path cannot deal
1375 * with. Can be reverse with bus_path_unescape(). We special
1376 * case the empty string. */
1381 r = new(char, strlen(s)*3 + 1);
1385 for (f = s, t = r; *f; f++) {
1387 /* Escape everything that is not a-zA-Z0-9. We also
1388 * escape 0-9 if it's the first character */
1390 if (!(*f >= 'A' && *f <= 'Z') &&
1391 !(*f >= 'a' && *f <= 'z') &&
1392 !(f > s && *f >= '0' && *f <= '9')) {
1394 *(t++) = hexchar(*f >> 4);
1395 *(t++) = hexchar(*f);
1405 char *bus_path_unescape(const char *f) {
1410 /* Special case for the empty string */
1414 r = new(char, strlen(f) + 1);
1418 for (t = r; *f; f++) {
1423 if ((a = unhexchar(f[1])) < 0 ||
1424 (b = unhexchar(f[2])) < 0) {
1425 /* Invalid escape code, let's take it literal then */
1428 *(t++) = (char) ((a << 4) | b);
1440 char *ascii_strlower(char *t) {
1445 for (p = t; *p; p++)
1446 if (*p >= 'A' && *p <= 'Z')
1447 *p = *p - 'A' + 'a';
1452 _pure_ static bool ignore_file_allow_backup(const char *filename) {
1456 filename[0] == '.' ||
1457 streq(filename, "lost+found") ||
1458 streq(filename, "aquota.user") ||
1459 streq(filename, "aquota.group") ||
1460 endswith(filename, ".rpmnew") ||
1461 endswith(filename, ".rpmsave") ||
1462 endswith(filename, ".rpmorig") ||
1463 endswith(filename, ".dpkg-old") ||
1464 endswith(filename, ".dpkg-new") ||
1465 endswith(filename, ".swp");
1468 bool ignore_file(const char *filename) {
1471 if (endswith(filename, "~"))
1474 return ignore_file_allow_backup(filename);
1477 int fd_nonblock(int fd, bool nonblock) {
1482 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1486 flags |= O_NONBLOCK;
1488 flags &= ~O_NONBLOCK;
1490 if (fcntl(fd, F_SETFL, flags) < 0)
1496 int fd_cloexec(int fd, bool cloexec) {
1501 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1505 flags |= FD_CLOEXEC;
1507 flags &= ~FD_CLOEXEC;
1509 if (fcntl(fd, F_SETFD, flags) < 0)
1515 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1518 assert(n_fdset == 0 || fdset);
1520 for (i = 0; i < n_fdset; i++)
1527 int close_all_fds(const int except[], unsigned n_except) {
1532 assert(n_except == 0 || except);
1534 d = opendir("/proc/self/fd");
1539 /* When /proc isn't available (for example in chroots)
1540 * the fallback is brute forcing through the fd
1543 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1544 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1546 if (fd_in_set(fd, except, n_except))
1549 if (close_nointr(fd) < 0)
1550 if (errno != EBADF && r == 0)
1557 while ((de = readdir(d))) {
1560 if (ignore_file(de->d_name))
1563 if (safe_atoi(de->d_name, &fd) < 0)
1564 /* Let's better ignore this, just in case */
1573 if (fd_in_set(fd, except, n_except))
1576 if (close_nointr(fd) < 0) {
1577 /* Valgrind has its own FD and doesn't want to have it closed */
1578 if (errno != EBADF && r == 0)
1587 bool chars_intersect(const char *a, const char *b) {
1590 /* Returns true if any of the chars in a are in b. */
1591 for (p = a; *p; p++)
1598 bool fstype_is_network(const char *fstype) {
1599 static const char table[] =
1608 return nulstr_contains(table, fstype);
1612 _cleanup_close_ int fd;
1614 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1620 TIOCL_GETKMSGREDIRECT,
1624 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1627 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1630 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1636 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1637 struct termios old_termios, new_termios;
1639 char line[LINE_MAX];
1644 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1645 new_termios = old_termios;
1647 new_termios.c_lflag &= ~ICANON;
1648 new_termios.c_cc[VMIN] = 1;
1649 new_termios.c_cc[VTIME] = 0;
1651 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1654 if (t != (usec_t) -1) {
1655 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1656 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1661 k = fread(&c, 1, 1, f);
1663 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1669 *need_nl = c != '\n';
1676 if (t != (usec_t) -1)
1677 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1680 if (!fgets(line, sizeof(line), f))
1685 if (strlen(line) != 1)
1695 int ask(char *ret, const char *replies, const char *text, ...) {
1705 bool need_nl = true;
1708 fputs(ANSI_HIGHLIGHT_ON, stdout);
1715 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1719 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1722 if (r == -EBADMSG) {
1723 puts("Bad input, please try again.");
1734 if (strchr(replies, c)) {
1739 puts("Read unexpected character, please try again.");
1743 int reset_terminal_fd(int fd, bool switch_to_text) {
1744 struct termios termios;
1747 /* Set terminal to some sane defaults */
1751 /* We leave locked terminal attributes untouched, so that
1752 * Plymouth may set whatever it wants to set, and we don't
1753 * interfere with that. */
1755 /* Disable exclusive mode, just in case */
1756 ioctl(fd, TIOCNXCL);
1758 /* Switch to text mode */
1760 ioctl(fd, KDSETMODE, KD_TEXT);
1762 /* Enable console unicode mode */
1763 ioctl(fd, KDSKBMODE, K_UNICODE);
1765 if (tcgetattr(fd, &termios) < 0) {
1770 /* We only reset the stuff that matters to the software. How
1771 * hardware is set up we don't touch assuming that somebody
1772 * else will do that for us */
1774 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1775 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1776 termios.c_oflag |= ONLCR;
1777 termios.c_cflag |= CREAD;
1778 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1780 termios.c_cc[VINTR] = 03; /* ^C */
1781 termios.c_cc[VQUIT] = 034; /* ^\ */
1782 termios.c_cc[VERASE] = 0177;
1783 termios.c_cc[VKILL] = 025; /* ^X */
1784 termios.c_cc[VEOF] = 04; /* ^D */
1785 termios.c_cc[VSTART] = 021; /* ^Q */
1786 termios.c_cc[VSTOP] = 023; /* ^S */
1787 termios.c_cc[VSUSP] = 032; /* ^Z */
1788 termios.c_cc[VLNEXT] = 026; /* ^V */
1789 termios.c_cc[VWERASE] = 027; /* ^W */
1790 termios.c_cc[VREPRINT] = 022; /* ^R */
1791 termios.c_cc[VEOL] = 0;
1792 termios.c_cc[VEOL2] = 0;
1794 termios.c_cc[VTIME] = 0;
1795 termios.c_cc[VMIN] = 1;
1797 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1801 /* Just in case, flush all crap out */
1802 tcflush(fd, TCIOFLUSH);
1807 int reset_terminal(const char *name) {
1810 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1814 r = reset_terminal_fd(fd, true);
1815 close_nointr_nofail(fd);
1820 int open_terminal(const char *name, int mode) {
1825 * If a TTY is in the process of being closed opening it might
1826 * cause EIO. This is horribly awful, but unlikely to be
1827 * changed in the kernel. Hence we work around this problem by
1828 * retrying a couple of times.
1830 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1834 fd = open(name, mode);
1841 /* Max 1s in total */
1845 usleep(50 * USEC_PER_MSEC);
1854 close_nointr_nofail(fd);
1859 close_nointr_nofail(fd);
1866 int flush_fd(int fd) {
1867 struct pollfd pollfd = {
1877 r = poll(&pollfd, 1, 0);
1887 l = read(fd, buf, sizeof(buf));
1893 if (errno == EAGAIN)
1902 int acquire_terminal(
1906 bool ignore_tiocstty_eperm,
1909 int fd = -1, notify = -1, r = 0, wd = -1;
1914 /* We use inotify to be notified when the tty is closed. We
1915 * create the watch before checking if we can actually acquire
1916 * it, so that we don't lose any event.
1918 * Note: strictly speaking this actually watches for the
1919 * device being closed, it does *not* really watch whether a
1920 * tty loses its controlling process. However, unless some
1921 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1922 * its tty otherwise this will not become a problem. As long
1923 * as the administrator makes sure not configure any service
1924 * on the same tty as an untrusted user this should not be a
1925 * problem. (Which he probably should not do anyway.) */
1927 if (timeout != (usec_t) -1)
1928 ts = now(CLOCK_MONOTONIC);
1930 if (!fail && !force) {
1931 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1937 wd = inotify_add_watch(notify, name, IN_CLOSE);
1945 struct sigaction sa_old, sa_new = {
1946 .sa_handler = SIG_IGN,
1947 .sa_flags = SA_RESTART,
1951 r = flush_fd(notify);
1956 /* We pass here O_NOCTTY only so that we can check the return
1957 * value TIOCSCTTY and have a reliable way to figure out if we
1958 * successfully became the controlling process of the tty */
1959 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1963 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1964 * if we already own the tty. */
1965 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1967 /* First, try to get the tty */
1968 if (ioctl(fd, TIOCSCTTY, force) < 0)
1971 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1973 /* Sometimes it makes sense to ignore TIOCSCTTY
1974 * returning EPERM, i.e. when very likely we already
1975 * are have this controlling terminal. */
1976 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1979 if (r < 0 && (force || fail || r != -EPERM)) {
1988 assert(notify >= 0);
1991 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1993 struct inotify_event *e;
1995 if (timeout != (usec_t) -1) {
1998 n = now(CLOCK_MONOTONIC);
1999 if (ts + timeout < n) {
2004 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2014 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2017 if (errno == EINTR || errno == EAGAIN)
2024 e = (struct inotify_event*) inotify_buffer;
2029 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2034 step = sizeof(struct inotify_event) + e->len;
2035 assert(step <= (size_t) l);
2037 e = (struct inotify_event*) ((uint8_t*) e + step);
2044 /* We close the tty fd here since if the old session
2045 * ended our handle will be dead. It's important that
2046 * we do this after sleeping, so that we don't enter
2047 * an endless loop. */
2048 close_nointr_nofail(fd);
2052 close_nointr_nofail(notify);
2054 r = reset_terminal_fd(fd, true);
2056 log_warning("Failed to reset terminal: %s", strerror(-r));
2062 close_nointr_nofail(fd);
2065 close_nointr_nofail(notify);
2070 int release_terminal(void) {
2072 struct sigaction sa_old, sa_new = {
2073 .sa_handler = SIG_IGN,
2074 .sa_flags = SA_RESTART,
2076 _cleanup_close_ int fd;
2078 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2082 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2083 * by our own TIOCNOTTY */
2084 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2086 if (ioctl(fd, TIOCNOTTY) < 0)
2089 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2094 int sigaction_many(const struct sigaction *sa, ...) {
2099 while ((sig = va_arg(ap, int)) > 0)
2100 if (sigaction(sig, sa, NULL) < 0)
2107 int ignore_signals(int sig, ...) {
2108 struct sigaction sa = {
2109 .sa_handler = SIG_IGN,
2110 .sa_flags = SA_RESTART,
2116 if (sigaction(sig, &sa, NULL) < 0)
2120 while ((sig = va_arg(ap, int)) > 0)
2121 if (sigaction(sig, &sa, NULL) < 0)
2128 int default_signals(int sig, ...) {
2129 struct sigaction sa = {
2130 .sa_handler = SIG_DFL,
2131 .sa_flags = SA_RESTART,
2136 if (sigaction(sig, &sa, NULL) < 0)
2140 while ((sig = va_arg(ap, int)) > 0)
2141 if (sigaction(sig, &sa, NULL) < 0)
2148 int close_pipe(int p[]) {
2154 a = close_nointr(p[0]);
2159 b = close_nointr(p[1]);
2163 return a < 0 ? a : b;
2166 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2175 while (nbytes > 0) {
2178 if ((k = read(fd, p, nbytes)) <= 0) {
2180 if (k < 0 && errno == EINTR)
2183 if (k < 0 && errno == EAGAIN && do_poll) {
2184 struct pollfd pollfd = {
2189 if (poll(&pollfd, 1, -1) < 0) {
2193 return n > 0 ? n : -errno;
2196 if (pollfd.revents != POLLIN)
2197 return n > 0 ? n : -EIO;
2202 return n > 0 ? n : (k < 0 ? -errno : 0);
2213 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2222 while (nbytes > 0) {
2225 k = write(fd, p, nbytes);
2228 if (k < 0 && errno == EINTR)
2231 if (k < 0 && errno == EAGAIN && do_poll) {
2232 struct pollfd pollfd = {
2237 if (poll(&pollfd, 1, -1) < 0) {
2241 return n > 0 ? n : -errno;
2244 if (pollfd.revents != POLLOUT)
2245 return n > 0 ? n : -EIO;
2250 return n > 0 ? n : (k < 0 ? -errno : 0);
2261 int parse_bytes(const char *t, off_t *bytes) {
2262 static const struct {
2264 unsigned long long factor;
2268 { "M", 1024ULL*1024ULL },
2269 { "G", 1024ULL*1024ULL*1024ULL },
2270 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2271 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2272 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2277 unsigned long long r = 0;
2289 l = strtoll(p, &e, 10);
2300 e += strspn(e, WHITESPACE);
2302 for (i = 0; i < ELEMENTSOF(table); i++)
2303 if (startswith(e, table[i].suffix)) {
2304 unsigned long long tmp;
2305 if ((unsigned long long) l > ULLONG_MAX / table[i].factor)
2307 tmp = l * table[i].factor;
2308 if (tmp > ULLONG_MAX - r)
2312 if ((unsigned long long) (off_t) r != r)
2315 p = e + strlen(table[i].suffix);
2319 if (i >= ELEMENTSOF(table))
2329 int make_stdio(int fd) {
2334 r = dup3(fd, STDIN_FILENO, 0);
2335 s = dup3(fd, STDOUT_FILENO, 0);
2336 t = dup3(fd, STDERR_FILENO, 0);
2339 close_nointr_nofail(fd);
2341 if (r < 0 || s < 0 || t < 0)
2344 /* We rely here that the new fd has O_CLOEXEC not set */
2349 int make_null_stdio(void) {
2352 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2356 return make_stdio(null_fd);
2359 bool is_device_path(const char *path) {
2361 /* Returns true on paths that refer to a device, either in
2362 * sysfs or in /dev */
2365 path_startswith(path, "/dev/") ||
2366 path_startswith(path, "/sys/");
2369 int dir_is_empty(const char *path) {
2370 _cleanup_closedir_ DIR *d;
2379 union dirent_storage buf;
2381 r = readdir_r(d, &buf.de, &de);
2388 if (!ignore_file(de->d_name))
2393 char* dirname_malloc(const char *path) {
2394 char *d, *dir, *dir2;
2411 unsigned long long random_ull(void) {
2412 _cleanup_close_ int fd;
2416 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2420 r = loop_read(fd, &ull, sizeof(ull), true);
2421 if (r != sizeof(ull))
2427 return random() * RAND_MAX + random();
2430 void rename_process(const char name[8]) {
2433 /* This is a like a poor man's setproctitle(). It changes the
2434 * comm field, argv[0], and also the glibc's internally used
2435 * name of the process. For the first one a limit of 16 chars
2436 * applies, to the second one usually one of 10 (i.e. length
2437 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2438 * "systemd"). If you pass a longer string it will be
2441 prctl(PR_SET_NAME, name);
2443 if (program_invocation_name)
2444 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2446 if (saved_argc > 0) {
2450 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2452 for (i = 1; i < saved_argc; i++) {
2456 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2461 void sigset_add_many(sigset_t *ss, ...) {
2468 while ((sig = va_arg(ap, int)) > 0)
2469 assert_se(sigaddset(ss, sig) == 0);
2473 char* gethostname_malloc(void) {
2476 assert_se(uname(&u) >= 0);
2478 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2479 return strdup(u.nodename);
2481 return strdup(u.sysname);
2484 bool hostname_is_set(void) {
2487 assert_se(uname(&u) >= 0);
2489 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2492 static char *lookup_uid(uid_t uid) {
2495 _cleanup_free_ char *buf = NULL;
2496 struct passwd pwbuf, *pw = NULL;
2498 /* Shortcut things to avoid NSS lookups */
2500 return strdup("root");
2502 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2506 buf = malloc(bufsize);
2510 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2511 return strdup(pw->pw_name);
2513 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2519 char* getlogname_malloc(void) {
2523 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2528 return lookup_uid(uid);
2531 char *getusername_malloc(void) {
2538 return lookup_uid(getuid());
2541 int getttyname_malloc(int fd, char **r) {
2542 char path[PATH_MAX], *c;
2547 k = ttyname_r(fd, path, sizeof(path));
2553 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2561 int getttyname_harder(int fd, char **r) {
2565 k = getttyname_malloc(fd, &s);
2569 if (streq(s, "tty")) {
2571 return get_ctty(0, NULL, r);
2578 int get_ctty_devnr(pid_t pid, dev_t *d) {
2579 _cleanup_fclose_ FILE *f = NULL;
2580 char line[LINE_MAX], *p;
2581 unsigned long ttynr;
2589 fn = "/proc/self/stat";
2591 fn = procfs_file_alloca(pid, "stat");
2593 f = fopen(fn, "re");
2597 if (!fgets(line, sizeof(line), f)) {
2598 k = feof(f) ? -EIO : -errno;
2602 p = strrchr(line, ')');
2612 "%*d " /* session */
2617 if (major(ttynr) == 0 && minor(ttynr) == 0)
2624 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2626 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *s, *b, *p;
2631 k = get_ctty_devnr(pid, &devnr);
2635 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2637 k = readlink_malloc(fn, &s);
2643 /* This is an ugly hack */
2644 if (major(devnr) == 136) {
2645 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2655 /* Probably something like the ptys which have no
2656 * symlink in /dev/char. Let's return something
2657 * vaguely useful. */
2670 if (startswith(s, "/dev/"))
2672 else if (startswith(s, "../"))
2690 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2696 /* This returns the first error we run into, but nevertheless
2697 * tries to go on. This closes the passed fd. */
2701 close_nointr_nofail(fd);
2703 return errno == ENOENT ? 0 : -errno;
2708 union dirent_storage buf;
2709 bool is_dir, keep_around;
2713 r = readdir_r(d, &buf.de, &de);
2714 if (r != 0 && ret == 0) {
2722 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2725 if (de->d_type == DT_UNKNOWN ||
2727 (de->d_type == DT_DIR && root_dev)) {
2728 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2729 if (ret == 0 && errno != ENOENT)
2734 is_dir = S_ISDIR(st.st_mode);
2737 (st.st_uid == 0 || st.st_uid == getuid()) &&
2738 (st.st_mode & S_ISVTX);
2740 is_dir = de->d_type == DT_DIR;
2741 keep_around = false;
2747 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2748 if (root_dev && st.st_dev != root_dev->st_dev)
2751 subdir_fd = openat(fd, de->d_name,
2752 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2753 if (subdir_fd < 0) {
2754 if (ret == 0 && errno != ENOENT)
2759 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2760 if (r < 0 && ret == 0)
2764 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2765 if (ret == 0 && errno != ENOENT)
2769 } else if (!only_dirs && !keep_around) {
2771 if (unlinkat(fd, de->d_name, 0) < 0) {
2772 if (ret == 0 && errno != ENOENT)
2783 _pure_ static int is_temporary_fs(struct statfs *s) {
2786 F_TYPE_CMP(s->f_type, TMPFS_MAGIC) ||
2787 F_TYPE_CMP(s->f_type, RAMFS_MAGIC);
2790 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2795 if (fstatfs(fd, &s) < 0) {
2796 close_nointr_nofail(fd);
2800 /* We refuse to clean disk file systems with this call. This
2801 * is extra paranoia just to be sure we never ever remove
2803 if (!is_temporary_fs(&s)) {
2804 log_error("Attempted to remove disk file system, and we can't allow that.");
2805 close_nointr_nofail(fd);
2809 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2812 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2818 /* We refuse to clean the root file system with this
2819 * call. This is extra paranoia to never cause a really
2820 * seriously broken system. */
2821 if (path_equal(path, "/")) {
2822 log_error("Attempted to remove entire root file system, and we can't allow that.");
2826 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2829 if (errno != ENOTDIR)
2833 if (statfs(path, &s) < 0)
2836 if (!is_temporary_fs(&s)) {
2837 log_error("Attempted to remove disk file system, and we can't allow that.");
2842 if (delete_root && !only_dirs)
2843 if (unlink(path) < 0 && errno != ENOENT)
2850 if (fstatfs(fd, &s) < 0) {
2851 close_nointr_nofail(fd);
2855 if (!is_temporary_fs(&s)) {
2856 log_error("Attempted to remove disk file system, and we can't allow that.");
2857 close_nointr_nofail(fd);
2862 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2865 if (honour_sticky && file_is_priv_sticky(path) > 0)
2868 if (rmdir(path) < 0 && errno != ENOENT) {
2877 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2878 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2881 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2882 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2885 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2888 /* Under the assumption that we are running privileged we
2889 * first change the access mode and only then hand out
2890 * ownership to avoid a window where access is too open. */
2892 if (mode != (mode_t) -1)
2893 if (chmod(path, mode) < 0)
2896 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2897 if (chown(path, uid, gid) < 0)
2903 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2906 /* Under the assumption that we are running privileged we
2907 * first change the access mode and only then hand out
2908 * ownership to avoid a window where access is too open. */
2910 if (fchmod(fd, mode) < 0)
2913 if (fchown(fd, uid, gid) < 0)
2919 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2923 /* Allocates the cpuset in the right size */
2926 if (!(r = CPU_ALLOC(n)))
2929 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2930 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2940 if (errno != EINVAL)
2947 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2948 static const char status_indent[] = " "; /* "[" STATUS "] " */
2949 _cleanup_free_ char *s = NULL;
2950 _cleanup_close_ int fd = -1;
2951 struct iovec iovec[6] = {};
2953 static bool prev_ephemeral;
2957 /* This is independent of logging, as status messages are
2958 * optional and go exclusively to the console. */
2960 if (vasprintf(&s, format, ap) < 0)
2963 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2976 sl = status ? sizeof(status_indent)-1 : 0;
2982 e = ellipsize(s, emax, 75);
2990 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2991 prev_ephemeral = ephemeral;
2994 if (!isempty(status)) {
2995 IOVEC_SET_STRING(iovec[n++], "[");
2996 IOVEC_SET_STRING(iovec[n++], status);
2997 IOVEC_SET_STRING(iovec[n++], "] ");
2999 IOVEC_SET_STRING(iovec[n++], status_indent);
3002 IOVEC_SET_STRING(iovec[n++], s);
3004 IOVEC_SET_STRING(iovec[n++], "\n");
3006 if (writev(fd, iovec, n) < 0)
3012 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
3018 va_start(ap, format);
3019 r = status_vprintf(status, ellipse, ephemeral, format, ap);
3025 int status_welcome(void) {
3027 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
3029 r = parse_env_file("/etc/os-release", NEWLINE,
3030 "PRETTY_NAME", &pretty_name,
3031 "ANSI_COLOR", &ansi_color,
3033 if (r < 0 && r != -ENOENT)
3034 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3036 return status_printf(NULL, false, false,
3037 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3038 isempty(ansi_color) ? "1" : ansi_color,
3039 isempty(pretty_name) ? "Linux" : pretty_name);
3042 char *replace_env(const char *format, char **env) {
3049 const char *e, *word = format;
3054 for (e = format; *e; e ++) {
3065 if (!(k = strnappend(r, word, e-word-1)))
3074 } else if (*e == '$') {
3075 if (!(k = strnappend(r, word, e-word)))
3091 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3093 k = strappend(r, t);
3107 if (!(k = strnappend(r, word, e-word)))
3118 char **replace_env_argv(char **argv, char **env) {
3120 unsigned k = 0, l = 0;
3122 l = strv_length(argv);
3124 if (!(r = new(char*, l+1)))
3127 STRV_FOREACH(i, argv) {
3129 /* If $FOO appears as single word, replace it by the split up variable */
3130 if ((*i)[0] == '$' && (*i)[1] != '{') {
3135 e = strv_env_get(env, *i+1);
3138 if (!(m = strv_split_quoted(e))) {
3149 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3158 memcpy(r + k, m, q * sizeof(char*));
3166 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3167 if (!(r[k++] = replace_env(*i, env))) {
3177 int fd_columns(int fd) {
3178 struct winsize ws = {};
3180 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3189 unsigned columns(void) {
3193 if (_likely_(cached_columns > 0))
3194 return cached_columns;
3197 e = getenv("COLUMNS");
3202 c = fd_columns(STDOUT_FILENO);
3211 int fd_lines(int fd) {
3212 struct winsize ws = {};
3214 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3223 unsigned lines(void) {
3227 if (_likely_(cached_lines > 0))
3228 return cached_lines;
3231 e = getenv("LINES");
3236 l = fd_lines(STDOUT_FILENO);
3242 return cached_lines;
3245 /* intended to be used as a SIGWINCH sighandler */
3246 void columns_lines_cache_reset(int signum) {
3252 static int cached_on_tty = -1;
3254 if (_unlikely_(cached_on_tty < 0))
3255 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3257 return cached_on_tty;
3260 int running_in_chroot(void) {
3261 struct stat a = {}, b = {};
3263 /* Only works as root */
3264 if (stat("/proc/1/root", &a) < 0)
3267 if (stat("/", &b) < 0)
3271 a.st_dev != b.st_dev ||
3272 a.st_ino != b.st_ino;
3275 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3280 assert(percent <= 100);
3281 assert(new_length >= 3);
3283 if (old_length <= 3 || old_length <= new_length)
3284 return strndup(s, old_length);
3286 r = new0(char, new_length+1);
3290 x = (new_length * percent) / 100;
3292 if (x > new_length - 3)
3300 s + old_length - (new_length - x - 3),
3301 new_length - x - 3);
3306 char *ellipsize(const char *s, size_t length, unsigned percent) {
3307 return ellipsize_mem(s, strlen(s), length, percent);
3310 int touch(const char *path) {
3315 /* This just opens the file for writing, ensuring it
3316 * exists. It doesn't call utimensat() the way /usr/bin/touch
3319 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3323 close_nointr_nofail(fd);
3327 char *unquote(const char *s, const char* quotes) {
3331 /* This is rather stupid, simply removes the heading and
3332 * trailing quotes if there is one. Doesn't care about
3333 * escaping or anything. We should make this smarter one
3340 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3341 return strndup(s+1, l-2);
3346 char *normalize_env_assignment(const char *s) {
3347 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3350 eq = strchr(s, '=');
3362 memmove(r, t, strlen(t) + 1);
3366 name = strndup(s, eq - s);
3374 value = unquote(strstrip(p), QUOTES);
3378 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3384 int wait_for_terminate(pid_t pid, siginfo_t *status) {