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(). We special
1329 * case the empty string. */
1334 r = new(char, strlen(s)*3 + 1);
1338 for (f = s, t = r; *f; f++) {
1340 /* Escape everything that is not a-zA-Z0-9. We also
1341 * escape 0-9 if it's the first character */
1343 if (!(*f >= 'A' && *f <= 'Z') &&
1344 !(*f >= 'a' && *f <= 'z') &&
1345 !(f > s && *f >= '0' && *f <= '9')) {
1347 *(t++) = hexchar(*f >> 4);
1348 *(t++) = hexchar(*f);
1358 char *bus_path_unescape(const char *f) {
1363 /* Special case for the empty string */
1367 r = new(char, strlen(f) + 1);
1371 for (t = r; *f; f++) {
1376 if ((a = unhexchar(f[1])) < 0 ||
1377 (b = unhexchar(f[2])) < 0) {
1378 /* Invalid escape code, let's take it literal then */
1381 *(t++) = (char) ((a << 4) | b);
1393 char *ascii_strlower(char *t) {
1398 for (p = t; *p; p++)
1399 if (*p >= 'A' && *p <= 'Z')
1400 *p = *p - 'A' + 'a';
1405 static bool ignore_file_allow_backup(const char *filename) {
1409 filename[0] == '.' ||
1410 streq(filename, "lost+found") ||
1411 streq(filename, "aquota.user") ||
1412 streq(filename, "aquota.group") ||
1413 endswith(filename, ".rpmnew") ||
1414 endswith(filename, ".rpmsave") ||
1415 endswith(filename, ".rpmorig") ||
1416 endswith(filename, ".dpkg-old") ||
1417 endswith(filename, ".dpkg-new") ||
1418 endswith(filename, ".swp");
1421 bool ignore_file(const char *filename) {
1424 if (endswith(filename, "~"))
1427 return ignore_file_allow_backup(filename);
1430 int fd_nonblock(int fd, bool nonblock) {
1435 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1439 flags |= O_NONBLOCK;
1441 flags &= ~O_NONBLOCK;
1443 if (fcntl(fd, F_SETFL, flags) < 0)
1449 int fd_cloexec(int fd, bool cloexec) {
1454 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1458 flags |= FD_CLOEXEC;
1460 flags &= ~FD_CLOEXEC;
1462 if (fcntl(fd, F_SETFD, flags) < 0)
1468 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1471 assert(n_fdset == 0 || fdset);
1473 for (i = 0; i < n_fdset; i++)
1480 int close_all_fds(const int except[], unsigned n_except) {
1485 assert(n_except == 0 || except);
1487 d = opendir("/proc/self/fd");
1492 /* When /proc isn't available (for example in chroots)
1493 * the fallback is brute forcing through the fd
1496 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1497 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1499 if (fd_in_set(fd, except, n_except))
1502 if (close_nointr(fd) < 0)
1503 if (errno != EBADF && r == 0)
1510 while ((de = readdir(d))) {
1513 if (ignore_file(de->d_name))
1516 if (safe_atoi(de->d_name, &fd) < 0)
1517 /* Let's better ignore this, just in case */
1526 if (fd_in_set(fd, except, n_except))
1529 if (close_nointr(fd) < 0) {
1530 /* Valgrind has its own FD and doesn't want to have it closed */
1531 if (errno != EBADF && r == 0)
1540 bool chars_intersect(const char *a, const char *b) {
1543 /* Returns true if any of the chars in a are in b. */
1544 for (p = a; *p; p++)
1551 bool fstype_is_network(const char *fstype) {
1552 static const char table[] =
1561 return nulstr_contains(table, fstype);
1565 _cleanup_close_ int fd;
1567 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1573 TIOCL_GETKMSGREDIRECT,
1577 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1580 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1583 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1589 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1590 struct termios old_termios, new_termios;
1592 char line[LINE_MAX];
1597 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1598 new_termios = old_termios;
1600 new_termios.c_lflag &= ~ICANON;
1601 new_termios.c_cc[VMIN] = 1;
1602 new_termios.c_cc[VTIME] = 0;
1604 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1607 if (t != (usec_t) -1) {
1608 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1609 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1614 k = fread(&c, 1, 1, f);
1616 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1622 *need_nl = c != '\n';
1629 if (t != (usec_t) -1)
1630 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1633 if (!fgets(line, sizeof(line), f))
1638 if (strlen(line) != 1)
1648 int ask(char *ret, const char *replies, const char *text, ...) {
1658 bool need_nl = true;
1661 fputs(ANSI_HIGHLIGHT_ON, stdout);
1668 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1672 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
1675 if (r == -EBADMSG) {
1676 puts("Bad input, please try again.");
1687 if (strchr(replies, c)) {
1692 puts("Read unexpected character, please try again.");
1696 int reset_terminal_fd(int fd, bool switch_to_text) {
1697 struct termios termios;
1700 /* Set terminal to some sane defaults */
1704 /* We leave locked terminal attributes untouched, so that
1705 * Plymouth may set whatever it wants to set, and we don't
1706 * interfere with that. */
1708 /* Disable exclusive mode, just in case */
1709 ioctl(fd, TIOCNXCL);
1711 /* Switch to text mode */
1713 ioctl(fd, KDSETMODE, KD_TEXT);
1715 /* Enable console unicode mode */
1716 ioctl(fd, KDSKBMODE, K_UNICODE);
1718 if (tcgetattr(fd, &termios) < 0) {
1723 /* We only reset the stuff that matters to the software. How
1724 * hardware is set up we don't touch assuming that somebody
1725 * else will do that for us */
1727 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1728 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1729 termios.c_oflag |= ONLCR;
1730 termios.c_cflag |= CREAD;
1731 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1733 termios.c_cc[VINTR] = 03; /* ^C */
1734 termios.c_cc[VQUIT] = 034; /* ^\ */
1735 termios.c_cc[VERASE] = 0177;
1736 termios.c_cc[VKILL] = 025; /* ^X */
1737 termios.c_cc[VEOF] = 04; /* ^D */
1738 termios.c_cc[VSTART] = 021; /* ^Q */
1739 termios.c_cc[VSTOP] = 023; /* ^S */
1740 termios.c_cc[VSUSP] = 032; /* ^Z */
1741 termios.c_cc[VLNEXT] = 026; /* ^V */
1742 termios.c_cc[VWERASE] = 027; /* ^W */
1743 termios.c_cc[VREPRINT] = 022; /* ^R */
1744 termios.c_cc[VEOL] = 0;
1745 termios.c_cc[VEOL2] = 0;
1747 termios.c_cc[VTIME] = 0;
1748 termios.c_cc[VMIN] = 1;
1750 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1754 /* Just in case, flush all crap out */
1755 tcflush(fd, TCIOFLUSH);
1760 int reset_terminal(const char *name) {
1763 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1767 r = reset_terminal_fd(fd, true);
1768 close_nointr_nofail(fd);
1773 int open_terminal(const char *name, int mode) {
1778 * If a TTY is in the process of being closed opening it might
1779 * cause EIO. This is horribly awful, but unlikely to be
1780 * changed in the kernel. Hence we work around this problem by
1781 * retrying a couple of times.
1783 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1787 fd = open(name, mode);
1794 /* Max 1s in total */
1798 usleep(50 * USEC_PER_MSEC);
1807 close_nointr_nofail(fd);
1812 close_nointr_nofail(fd);
1819 int flush_fd(int fd) {
1820 struct pollfd pollfd;
1824 pollfd.events = POLLIN;
1831 if ((r = poll(&pollfd, 1, 0)) < 0) {
1842 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1847 if (errno == EAGAIN)
1858 int acquire_terminal(
1862 bool ignore_tiocstty_eperm,
1865 int fd = -1, notify = -1, r = 0, wd = -1;
1867 struct sigaction sa_old, sa_new;
1871 /* We use inotify to be notified when the tty is closed. We
1872 * create the watch before checking if we can actually acquire
1873 * it, so that we don't lose any event.
1875 * Note: strictly speaking this actually watches for the
1876 * device being closed, it does *not* really watch whether a
1877 * tty loses its controlling process. However, unless some
1878 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1879 * its tty otherwise this will not become a problem. As long
1880 * as the administrator makes sure not configure any service
1881 * on the same tty as an untrusted user this should not be a
1882 * problem. (Which he probably should not do anyway.) */
1884 if (timeout != (usec_t) -1)
1885 ts = now(CLOCK_MONOTONIC);
1887 if (!fail && !force) {
1888 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
1894 wd = inotify_add_watch(notify, name, IN_CLOSE);
1903 r = flush_fd(notify);
1908 /* We pass here O_NOCTTY only so that we can check the return
1909 * value TIOCSCTTY and have a reliable way to figure out if we
1910 * successfully became the controlling process of the tty */
1911 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1915 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1916 * if we already own the tty. */
1918 sa_new.sa_handler = SIG_IGN;
1919 sa_new.sa_flags = SA_RESTART;
1920 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1922 /* First, try to get the tty */
1923 if (ioctl(fd, TIOCSCTTY, force) < 0)
1926 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1928 /* Sometimes it makes sense to ignore TIOCSCTTY
1929 * returning EPERM, i.e. when very likely we already
1930 * are have this controlling terminal. */
1931 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1934 if (r < 0 && (force || fail || r != -EPERM)) {
1943 assert(notify >= 0);
1946 uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
1948 struct inotify_event *e;
1950 if (timeout != (usec_t) -1) {
1953 n = now(CLOCK_MONOTONIC);
1954 if (ts + timeout < n) {
1959 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1969 l = read(notify, inotify_buffer, sizeof(inotify_buffer));
1972 if (errno == EINTR || errno == EAGAIN)
1979 e = (struct inotify_event*) inotify_buffer;
1984 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1989 step = sizeof(struct inotify_event) + e->len;
1990 assert(step <= (size_t) l);
1992 e = (struct inotify_event*) ((uint8_t*) e + step);
1999 /* We close the tty fd here since if the old session
2000 * ended our handle will be dead. It's important that
2001 * we do this after sleeping, so that we don't enter
2002 * an endless loop. */
2003 close_nointr_nofail(fd);
2007 close_nointr_nofail(notify);
2009 r = reset_terminal_fd(fd, true);
2011 log_warning("Failed to reset terminal: %s", strerror(-r));
2017 close_nointr_nofail(fd);
2020 close_nointr_nofail(notify);
2025 int release_terminal(void) {
2027 struct sigaction sa_old, sa_new;
2029 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2032 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2033 * by our own TIOCNOTTY */
2036 sa_new.sa_handler = SIG_IGN;
2037 sa_new.sa_flags = SA_RESTART;
2038 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2040 if (ioctl(fd, TIOCNOTTY) < 0)
2043 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2045 close_nointr_nofail(fd);
2049 int sigaction_many(const struct sigaction *sa, ...) {
2054 while ((sig = va_arg(ap, int)) > 0)
2055 if (sigaction(sig, sa, NULL) < 0)
2062 int ignore_signals(int sig, ...) {
2063 struct sigaction sa;
2068 sa.sa_handler = SIG_IGN;
2069 sa.sa_flags = SA_RESTART;
2071 if (sigaction(sig, &sa, NULL) < 0)
2075 while ((sig = va_arg(ap, int)) > 0)
2076 if (sigaction(sig, &sa, NULL) < 0)
2083 int default_signals(int sig, ...) {
2084 struct sigaction sa;
2089 sa.sa_handler = SIG_DFL;
2090 sa.sa_flags = SA_RESTART;
2092 if (sigaction(sig, &sa, NULL) < 0)
2096 while ((sig = va_arg(ap, int)) > 0)
2097 if (sigaction(sig, &sa, NULL) < 0)
2104 int close_pipe(int p[]) {
2110 a = close_nointr(p[0]);
2115 b = close_nointr(p[1]);
2119 return a < 0 ? a : b;
2122 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2131 while (nbytes > 0) {
2134 if ((k = read(fd, p, nbytes)) <= 0) {
2136 if (k < 0 && errno == EINTR)
2139 if (k < 0 && errno == EAGAIN && do_poll) {
2140 struct pollfd pollfd;
2144 pollfd.events = POLLIN;
2146 if (poll(&pollfd, 1, -1) < 0) {
2150 return n > 0 ? n : -errno;
2153 if (pollfd.revents != POLLIN)
2154 return n > 0 ? n : -EIO;
2159 return n > 0 ? n : (k < 0 ? -errno : 0);
2170 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2179 while (nbytes > 0) {
2182 k = write(fd, p, nbytes);
2185 if (k < 0 && errno == EINTR)
2188 if (k < 0 && errno == EAGAIN && do_poll) {
2189 struct pollfd pollfd;
2193 pollfd.events = POLLOUT;
2195 if (poll(&pollfd, 1, -1) < 0) {
2199 return n > 0 ? n : -errno;
2202 if (pollfd.revents != POLLOUT)
2203 return n > 0 ? n : -EIO;
2208 return n > 0 ? n : (k < 0 ? -errno : 0);
2219 int parse_bytes(const char *t, off_t *bytes) {
2220 static const struct {
2226 { "M", 1024ULL*1024ULL },
2227 { "G", 1024ULL*1024ULL*1024ULL },
2228 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2229 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2230 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2247 l = strtoll(p, &e, 10);
2258 e += strspn(e, WHITESPACE);
2260 for (i = 0; i < ELEMENTSOF(table); i++)
2261 if (startswith(e, table[i].suffix)) {
2262 r += (off_t) l * table[i].factor;
2263 p = e + strlen(table[i].suffix);
2267 if (i >= ELEMENTSOF(table))
2277 int make_stdio(int fd) {
2282 r = dup3(fd, STDIN_FILENO, 0);
2283 s = dup3(fd, STDOUT_FILENO, 0);
2284 t = dup3(fd, STDERR_FILENO, 0);
2287 close_nointr_nofail(fd);
2289 if (r < 0 || s < 0 || t < 0)
2292 /* We rely here that the new fd has O_CLOEXEC not set */
2297 int make_null_stdio(void) {
2300 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2304 return make_stdio(null_fd);
2307 bool is_device_path(const char *path) {
2309 /* Returns true on paths that refer to a device, either in
2310 * sysfs or in /dev */
2313 path_startswith(path, "/dev/") ||
2314 path_startswith(path, "/sys/");
2317 int dir_is_empty(const char *path) {
2318 _cleanup_closedir_ DIR *d;
2327 union dirent_storage buf;
2329 r = readdir_r(d, &buf.de, &de);
2336 if (!ignore_file(de->d_name))
2341 unsigned long long random_ull(void) {
2342 _cleanup_close_ int fd;
2346 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2350 r = loop_read(fd, &ull, sizeof(ull), true);
2351 if (r != sizeof(ull))
2357 return random() * RAND_MAX + random();
2360 void rename_process(const char name[8]) {
2363 /* This is a like a poor man's setproctitle(). It changes the
2364 * comm field, argv[0], and also the glibc's internally used
2365 * name of the process. For the first one a limit of 16 chars
2366 * applies, to the second one usually one of 10 (i.e. length
2367 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2368 * "systemd"). If you pass a longer string it will be
2371 prctl(PR_SET_NAME, name);
2373 if (program_invocation_name)
2374 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2376 if (saved_argc > 0) {
2380 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2382 for (i = 1; i < saved_argc; i++) {
2386 memset(saved_argv[i], 0, strlen(saved_argv[i]));
2391 void sigset_add_many(sigset_t *ss, ...) {
2398 while ((sig = va_arg(ap, int)) > 0)
2399 assert_se(sigaddset(ss, sig) == 0);
2403 char* gethostname_malloc(void) {
2406 assert_se(uname(&u) >= 0);
2408 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2409 return strdup(u.nodename);
2411 return strdup(u.sysname);
2414 bool hostname_is_set(void) {
2417 assert_se(uname(&u) >= 0);
2419 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2422 static char *lookup_uid(uid_t uid) {
2425 _cleanup_free_ char *buf = NULL;
2426 struct passwd pwbuf, *pw = NULL;
2428 /* Shortcut things to avoid NSS lookups */
2430 return strdup("root");
2432 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2436 buf = malloc(bufsize);
2440 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2441 return strdup(pw->pw_name);
2443 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2449 char* getlogname_malloc(void) {
2453 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2458 return lookup_uid(uid);
2461 char *getusername_malloc(void) {
2468 return lookup_uid(getuid());
2471 int getttyname_malloc(int fd, char **r) {
2472 char path[PATH_MAX], *c;
2477 k = ttyname_r(fd, path, sizeof(path));
2483 c = strdup(startswith(path, "/dev/") ? path + 5 : path);
2491 int getttyname_harder(int fd, char **r) {
2495 k = getttyname_malloc(fd, &s);
2499 if (streq(s, "tty")) {
2501 return get_ctty(0, NULL, r);
2508 int get_ctty_devnr(pid_t pid, dev_t *d) {
2510 char line[LINE_MAX], *p, *fn;
2511 unsigned long ttynr;
2514 if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
2517 f = fopen(fn, "re");
2522 if (!fgets(line, sizeof(line), f)) {
2523 k = feof(f) ? -EIO : -errno;
2530 p = strrchr(line, ')');
2540 "%*d " /* session */
2545 if (major(ttynr) == 0 && minor(ttynr) == 0)
2552 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2554 char fn[PATH_MAX], *s, *b, *p;
2559 k = get_ctty_devnr(pid, &devnr);
2563 snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
2566 k = readlink_malloc(fn, &s);
2572 /* This is an ugly hack */
2573 if (major(devnr) == 136) {
2574 if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
2584 /* Probably something like the ptys which have no
2585 * symlink in /dev/char. Let's return something
2586 * vaguely useful. */
2599 if (startswith(s, "/dev/"))
2601 else if (startswith(s, "../"))
2619 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2625 /* This returns the first error we run into, but nevertheless
2626 * tries to go on. This closes the passed fd. */
2630 close_nointr_nofail(fd);
2632 return errno == ENOENT ? 0 : -errno;
2637 union dirent_storage buf;
2638 bool is_dir, keep_around;
2642 r = readdir_r(d, &buf.de, &de);
2643 if (r != 0 && ret == 0) {
2651 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2654 if (de->d_type == DT_UNKNOWN ||
2656 (de->d_type == DT_DIR && root_dev)) {
2657 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2658 if (ret == 0 && errno != ENOENT)
2663 is_dir = S_ISDIR(st.st_mode);
2666 (st.st_uid == 0 || st.st_uid == getuid()) &&
2667 (st.st_mode & S_ISVTX);
2669 is_dir = de->d_type == DT_DIR;
2670 keep_around = false;
2676 /* if root_dev is set, remove subdirectories only, if device is same as dir */
2677 if (root_dev && st.st_dev != root_dev->st_dev)
2680 subdir_fd = openat(fd, de->d_name,
2681 O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2682 if (subdir_fd < 0) {
2683 if (ret == 0 && errno != ENOENT)
2688 r = rm_rf_children_dangerous(subdir_fd, only_dirs, honour_sticky, root_dev);
2689 if (r < 0 && ret == 0)
2693 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2694 if (ret == 0 && errno != ENOENT)
2698 } else if (!only_dirs && !keep_around) {
2700 if (unlinkat(fd, de->d_name, 0) < 0) {
2701 if (ret == 0 && errno != ENOENT)
2712 static int is_temporary_fs(struct statfs *s) {
2714 return s->f_type == TMPFS_MAGIC ||
2715 (long)s->f_type == (long)RAMFS_MAGIC;
2718 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
2723 if (fstatfs(fd, &s) < 0) {
2724 close_nointr_nofail(fd);
2728 /* We refuse to clean disk file systems with this call. This
2729 * is extra paranoia just to be sure we never ever remove
2731 if (!is_temporary_fs(&s)) {
2732 log_error("Attempted to remove disk file system, and we can't allow that.");
2733 close_nointr_nofail(fd);
2737 return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
2740 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
2746 /* We refuse to clean the root file system with this
2747 * call. This is extra paranoia to never cause a really
2748 * seriously broken system. */
2749 if (path_equal(path, "/")) {
2750 log_error("Attempted to remove entire root file system, and we can't allow that.");
2754 fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
2757 if (errno != ENOTDIR)
2761 if (statfs(path, &s) < 0)
2764 if (!is_temporary_fs(&s)) {
2765 log_error("Attempted to remove disk file system, and we can't allow that.");
2770 if (delete_root && !only_dirs)
2771 if (unlink(path) < 0 && errno != ENOENT)
2778 if (fstatfs(fd, &s) < 0) {
2779 close_nointr_nofail(fd);
2783 if (!is_temporary_fs(&s)) {
2784 log_error("Attempted to remove disk file system, and we can't allow that.");
2785 close_nointr_nofail(fd);
2790 r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
2793 if (honour_sticky && file_is_priv_sticky(path) > 0)
2796 if (rmdir(path) < 0 && errno != ENOENT) {
2805 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2806 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
2809 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
2810 return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
2813 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2816 /* Under the assumption that we are running privileged we
2817 * first change the access mode and only then hand out
2818 * ownership to avoid a window where access is too open. */
2820 if (mode != (mode_t) -1)
2821 if (chmod(path, mode) < 0)
2824 if (uid != (uid_t) -1 || gid != (gid_t) -1)
2825 if (chown(path, uid, gid) < 0)
2831 int fchmod_and_fchown(int fd, 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 (fchmod(fd, mode) < 0)
2841 if (fchown(fd, uid, gid) < 0)
2847 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2851 /* Allocates the cpuset in the right size */
2854 if (!(r = CPU_ALLOC(n)))
2857 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2858 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2868 if (errno != EINVAL)
2875 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2876 static const char status_indent[] = " "; /* "[" STATUS "] " */
2877 _cleanup_free_ char *s = NULL;
2878 _cleanup_close_ int fd = -1;
2879 struct iovec iovec[6];
2881 static bool prev_ephemeral;
2885 /* This is independent of logging, as status messages are
2886 * optional and go exclusively to the console. */
2888 if (vasprintf(&s, format, ap) < 0)
2891 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2904 sl = status ? sizeof(status_indent)-1 : 0;
2910 e = ellipsize(s, emax, 75);
2920 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2921 prev_ephemeral = ephemeral;
2924 if (!isempty(status)) {
2925 IOVEC_SET_STRING(iovec[n++], "[");
2926 IOVEC_SET_STRING(iovec[n++], status);
2927 IOVEC_SET_STRING(iovec[n++], "] ");
2929 IOVEC_SET_STRING(iovec[n++], status_indent);
2932 IOVEC_SET_STRING(iovec[n++], s);
2934 IOVEC_SET_STRING(iovec[n++], "\n");
2936 if (writev(fd, iovec, n) < 0)
2942 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2948 va_start(ap, format);
2949 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2955 int status_welcome(void) {
2957 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
2959 r = parse_env_file("/etc/os-release", NEWLINE,
2960 "PRETTY_NAME", &pretty_name,
2961 "ANSI_COLOR", &ansi_color,
2963 if (r < 0 && r != -ENOENT)
2964 log_warning("Failed to read /etc/os-release: %s", strerror(-r));
2966 return status_printf(NULL, false,
2967 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
2968 isempty(ansi_color) ? "1" : ansi_color,
2969 isempty(pretty_name) ? "Linux" : pretty_name);
2972 char *replace_env(const char *format, char **env) {
2979 const char *e, *word = format;
2984 for (e = format; *e; e ++) {
2995 if (!(k = strnappend(r, word, e-word-1)))
3004 } else if (*e == '$') {
3005 if (!(k = strnappend(r, word, e-word)))
3021 t = strempty(strv_env_get_n(env, word+2, e-word-2));
3023 k = strappend(r, t);
3037 if (!(k = strnappend(r, word, e-word)))
3048 char **replace_env_argv(char **argv, char **env) {
3050 unsigned k = 0, l = 0;
3052 l = strv_length(argv);
3054 if (!(r = new(char*, l+1)))
3057 STRV_FOREACH(i, argv) {
3059 /* If $FOO appears as single word, replace it by the split up variable */
3060 if ((*i)[0] == '$' && (*i)[1] != '{') {
3065 e = strv_env_get(env, *i+1);
3068 if (!(m = strv_split_quoted(e))) {
3079 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3088 memcpy(r + k, m, q * sizeof(char*));
3096 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3097 if (!(r[k++] = replace_env(*i, env))) {
3107 int fd_columns(int fd) {
3111 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3120 unsigned columns(void) {
3124 if (_likely_(cached_columns > 0))
3125 return cached_columns;
3128 e = getenv("COLUMNS");
3133 c = fd_columns(STDOUT_FILENO);
3142 int fd_lines(int fd) {
3146 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3155 unsigned lines(void) {
3159 if (_likely_(cached_lines > 0))
3160 return cached_lines;
3163 e = getenv("LINES");
3168 l = fd_lines(STDOUT_FILENO);
3174 return cached_lines;
3177 /* intended to be used as a SIGWINCH sighandler */
3178 void columns_lines_cache_reset(int signum) {
3184 static int cached_on_tty = -1;
3186 if (_unlikely_(cached_on_tty < 0))
3187 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3189 return cached_on_tty;
3192 int running_in_chroot(void) {
3198 /* Only works as root */
3200 if (stat("/proc/1/root", &a) < 0)
3203 if (stat("/", &b) < 0)
3207 a.st_dev != b.st_dev ||
3208 a.st_ino != b.st_ino;
3211 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3216 assert(percent <= 100);
3217 assert(new_length >= 3);
3219 if (old_length <= 3 || old_length <= new_length)
3220 return strndup(s, old_length);
3222 r = new0(char, new_length+1);
3226 x = (new_length * percent) / 100;
3228 if (x > new_length - 3)
3236 s + old_length - (new_length - x - 3),
3237 new_length - x - 3);
3242 char *ellipsize(const char *s, size_t length, unsigned percent) {
3243 return ellipsize_mem(s, strlen(s), length, percent);
3246 int touch(const char *path) {
3251 /* This just opens the file for writing, ensuring it
3252 * exists. It doesn't call utimensat() the way /usr/bin/touch
3255 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644);
3259 close_nointr_nofail(fd);
3263 char *unquote(const char *s, const char* quotes) {
3267 /* This is rather stupid, simply removes the heading and
3268 * trailing quotes if there is one. Doesn't care about
3269 * escaping or anything. We should make this smarter one
3276 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3277 return strndup(s+1, l-2);
3282 char *normalize_env_assignment(const char *s) {
3283 _cleanup_free_ char *name = NULL, *value = NULL, *p = NULL;
3286 eq = strchr(s, '=');
3298 memmove(r, t, strlen(t) + 1);
3302 name = strndup(s, eq - s);
3310 value = unquote(strstrip(p), QUOTES);
3314 if (asprintf(&r, "%s=%s", strstrip(name), value) < 0)
3320 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3331 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3343 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3350 r = wait_for_terminate(pid, &status);
3352 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3356 if (status.si_code == CLD_EXITED) {
3357 if (status.si_status != 0) {
3358 log_warning("%s failed with error code %i.", name, status.si_status);
3359 return status.si_status;
3362 log_debug("%s succeeded.", name);
3365 } else if (status.si_code == CLD_KILLED ||
3366 status.si_code == CLD_DUMPED) {
3368 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
3372 log_warning("%s failed due to unknown reason.", name);
3376 _noreturn_ void freeze(void) {
3378 /* Make sure nobody waits for us on a socket anymore */
3379 close_all_fds(NULL, 0);
3387 bool null_or_empty(struct stat *st) {
3390 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3393 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))