1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 General Public License as published by
10 the Free Software Foundation; either version 2 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 General Public License for more details.
18 You should have received a copy of the GNU 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 bool streq_ptr(const char *a, const char *b) {
60 /* Like streq(), but tries to make sense of NULL pointers */
71 usec_t now(clockid_t clock_id) {
74 assert_se(clock_gettime(clock_id, &ts) == 0);
76 return timespec_load(&ts);
79 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
82 ts->realtime = now(CLOCK_REALTIME);
83 ts->monotonic = now(CLOCK_MONOTONIC);
88 usec_t timespec_load(const struct timespec *ts) {
92 (usec_t) ts->tv_sec * USEC_PER_SEC +
93 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
96 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
99 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
100 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
105 usec_t timeval_load(const struct timeval *tv) {
109 (usec_t) tv->tv_sec * USEC_PER_SEC +
110 (usec_t) tv->tv_usec;
113 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
116 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
117 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
122 bool endswith(const char *s, const char *postfix) {
129 pl = strlen(postfix);
137 return memcmp(s + sl - pl, postfix, pl) == 0;
140 bool startswith(const char *s, const char *prefix) {
155 return memcmp(s, prefix, pl) == 0;
158 bool startswith_no_case(const char *s, const char *prefix) {
174 for(i = 0; i < pl; ++i) {
175 if (tolower(s[i]) != tolower(prefix[i]))
182 bool first_word(const char *s, const char *word) {
197 if (memcmp(s, word, wl) != 0)
201 strchr(WHITESPACE, s[wl]);
204 int close_nointr(int fd) {
210 if ((r = close(fd)) >= 0)
218 void close_nointr_nofail(int fd) {
219 int saved_errno = errno;
221 /* like close_nointr() but cannot fail, and guarantees errno
224 assert_se(close_nointr(fd) == 0);
229 void close_many(const int fds[], unsigned n_fd) {
232 for (i = 0; i < n_fd; i++)
233 close_nointr_nofail(fds[i]);
236 int parse_boolean(const char *v) {
239 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
241 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
247 int parse_pid(const char *s, pid_t* ret_pid) {
255 if ((r = safe_atolu(s, &ul)) < 0)
260 if ((unsigned long) pid != ul)
270 int safe_atou(const char *s, unsigned *ret_u) {
278 l = strtoul(s, &x, 0);
280 if (!x || *x || errno)
281 return errno ? -errno : -EINVAL;
283 if ((unsigned long) (unsigned) l != l)
286 *ret_u = (unsigned) l;
290 int safe_atoi(const char *s, int *ret_i) {
298 l = strtol(s, &x, 0);
300 if (!x || *x || errno)
301 return errno ? -errno : -EINVAL;
303 if ((long) (int) l != l)
310 int safe_atollu(const char *s, long long unsigned *ret_llu) {
312 unsigned long long l;
318 l = strtoull(s, &x, 0);
320 if (!x || *x || errno)
321 return errno ? -errno : -EINVAL;
327 int safe_atolli(const char *s, long long int *ret_lli) {
335 l = strtoll(s, &x, 0);
337 if (!x || *x || errno)
338 return errno ? -errno : -EINVAL;
344 /* Split a string into words. */
345 char *split(const char *c, size_t *l, const char *separator, char **state) {
348 current = *state ? *state : (char*) c;
350 if (!*current || *c == 0)
353 current += strspn(current, separator);
354 *l = strcspn(current, separator);
357 return (char*) current;
360 /* Split a string into words, but consider strings enclosed in '' and
361 * "" as words even if they include spaces. */
362 char *split_quoted(const char *c, size_t *l, char **state) {
364 bool escaped = false;
366 current = *state ? *state : (char*) c;
368 if (!*current || *c == 0)
371 current += strspn(current, WHITESPACE);
373 if (*current == '\'') {
376 for (e = current; *e; e++) {
386 *state = *e == 0 ? e : e+1;
387 } else if (*current == '\"') {
390 for (e = current; *e; e++) {
400 *state = *e == 0 ? e : e+1;
402 for (e = current; *e; e++) {
407 else if (strchr(WHITESPACE, *e))
414 return (char*) current;
417 char **split_path_and_make_absolute(const char *p) {
421 if (!(l = strv_split(p, ":")))
424 if (!strv_path_make_absolute_cwd(l)) {
432 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
435 char fn[132], line[256], *p;
441 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
442 fn[sizeof(fn)-1] = 0;
444 if (!(f = fopen(fn, "r")))
447 if (!(fgets(line, sizeof(line), f))) {
455 /* Let's skip the pid and comm fields. The latter is enclosed
456 * in () but does not escape any () in its value, so let's
457 * skip over it manually */
459 if (!(p = strrchr(line, ')')))
470 if ((long unsigned) (pid_t) ppid != ppid)
473 *_ppid = (pid_t) ppid;
478 int write_one_line_file(const char *fn, const char *line) {
485 if (!(f = fopen(fn, "we")))
488 if (fputs(line, f) < 0) {
499 int read_one_line_file(const char *fn, char **line) {
507 if (!(f = fopen(fn, "re")))
510 if (!(fgets(t, sizeof(t), f))) {
515 if (!(c = strdup(t))) {
528 char *truncate_nl(char *s) {
531 s[strcspn(s, NEWLINE)] = 0;
535 int get_process_name(pid_t pid, char **name) {
542 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
545 r = read_one_line_file(p, name);
555 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
563 assert(max_length > 0);
566 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
575 if (!(r = new(char, max_length))) {
582 while ((c = getc(f)) != EOF) {
604 size_t n = MIN(left-1, 3U);
612 /* Kernel threads have no argv[] */
619 if ((h = get_process_name(pid, &t)) < 0)
622 h = asprintf(&r, "[%s]", t);
633 char *strnappend(const char *s, const char *suffix, size_t b) {
641 return strndup(suffix, b);
651 if (!(r = new(char, a+b+1)))
655 memcpy(r+a, suffix, b);
661 char *strappend(const char *s, const char *suffix) {
662 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
665 int readlink_malloc(const char *p, char **r) {
675 if (!(c = new(char, l)))
678 if ((n = readlink(p, c, l-1)) < 0) {
684 if ((size_t) n < l-1) {
695 int readlink_and_make_absolute(const char *p, char **r) {
702 if ((j = readlink_malloc(p, &target)) < 0)
705 k = file_in_same_dir(p, target);
715 int parent_of_path(const char *path, char **_r) {
716 const char *e, *a = NULL, *b = NULL, *p;
726 for (e = path; *e; e++) {
728 if (!slash && *e == '/') {
732 } else if (slash && *e != '/')
747 r = strndup(path, p-path);
757 char *file_name_from_path(const char *p) {
762 if ((r = strrchr(p, '/')))
768 bool path_is_absolute(const char *p) {
774 bool is_path(const char *p) {
776 return !!strchr(p, '/');
779 char *path_make_absolute(const char *p, const char *prefix) {
784 /* Makes every item in the list an absolute path by prepending
785 * the prefix, if specified and necessary */
787 if (path_is_absolute(p) || !prefix)
790 if (asprintf(&r, "%s/%s", prefix, p) < 0)
796 char *path_make_absolute_cwd(const char *p) {
801 /* Similar to path_make_absolute(), but prefixes with the
802 * current working directory. */
804 if (path_is_absolute(p))
807 if (!(cwd = get_current_dir_name()))
810 r = path_make_absolute(p, cwd);
816 char **strv_path_make_absolute_cwd(char **l) {
819 /* Goes through every item in the string list and makes it
820 * absolute. This works in place and won't rollback any
821 * changes on failure. */
826 if (!(t = path_make_absolute_cwd(*s)))
836 char **strv_path_canonicalize(char **l) {
844 /* Goes through every item in the string list and canonicalize
845 * the path. This works in place and won't rollback any
846 * changes on failure. */
851 t = path_make_absolute_cwd(*s);
860 u = canonicalize_file_name(t);
864 if (errno == ENOMEM || !errno)
881 int reset_all_signal_handlers(void) {
884 for (sig = 1; sig < _NSIG; sig++) {
887 if (sig == SIGKILL || sig == SIGSTOP)
891 sa.sa_handler = SIG_DFL;
892 sa.sa_flags = SA_RESTART;
894 /* On Linux the first two RT signals are reserved by
895 * glibc, and sigaction() will return EINVAL for them. */
896 if ((sigaction(sig, &sa, NULL) < 0))
904 char *strstrip(char *s) {
907 /* Drops trailing whitespace. Modifies the string in
908 * place. Returns pointer to first non-space character */
910 s += strspn(s, WHITESPACE);
913 if (!strchr(WHITESPACE, *e))
924 char *delete_chars(char *s, const char *bad) {
927 /* Drops all whitespace, regardless where in the string */
929 for (f = s, t = s; *f; f++) {
941 char *file_in_same_dir(const char *path, const char *filename) {
948 /* This removes the last component of path and appends
949 * filename, unless the latter is absolute anyway or the
952 if (path_is_absolute(filename))
953 return strdup(filename);
955 if (!(e = strrchr(path, '/')))
956 return strdup(filename);
958 k = strlen(filename);
959 if (!(r = new(char, e-path+1+k+1)))
962 memcpy(r, path, e-path+1);
963 memcpy(r+(e-path)+1, filename, k+1);
968 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
971 if (mkdir(path, mode) >= 0)
972 if (chmod_and_chown(path, mode, uid, gid) < 0)
975 if (lstat(path, &st) < 0)
978 if ((st.st_mode & 0777) != mode ||
981 !S_ISDIR(st.st_mode)) {
990 int mkdir_parents(const char *path, mode_t mode) {
995 /* Creates every parent directory in the path except the last
998 p = path + strspn(path, "/");
1003 e = p + strcspn(p, "/");
1004 p = e + strspn(e, "/");
1006 /* Is this the last component? If so, then we're
1011 if (!(t = strndup(path, e - path)))
1017 if (r < 0 && errno != EEXIST)
1022 int mkdir_p(const char *path, mode_t mode) {
1027 if ((r = mkdir_parents(path, mode)) < 0)
1030 if (mkdir(path, mode) < 0 && errno != EEXIST)
1036 int rmdir_parents(const char *path, const char *stop) {
1045 /* Skip trailing slashes */
1046 while (l > 0 && path[l-1] == '/')
1052 /* Skip last component */
1053 while (l > 0 && path[l-1] != '/')
1056 /* Skip trailing slashes */
1057 while (l > 0 && path[l-1] == '/')
1063 if (!(t = strndup(path, l)))
1066 if (path_startswith(stop, t)) {
1075 if (errno != ENOENT)
1083 char hexchar(int x) {
1084 static const char table[16] = "0123456789abcdef";
1086 return table[x & 15];
1089 int unhexchar(char c) {
1091 if (c >= '0' && c <= '9')
1094 if (c >= 'a' && c <= 'f')
1095 return c - 'a' + 10;
1097 if (c >= 'A' && c <= 'F')
1098 return c - 'A' + 10;
1103 char octchar(int x) {
1104 return '0' + (x & 7);
1107 int unoctchar(char c) {
1109 if (c >= '0' && c <= '7')
1115 char decchar(int x) {
1116 return '0' + (x % 10);
1119 int undecchar(char c) {
1121 if (c >= '0' && c <= '9')
1127 char *cescape(const char *s) {
1133 /* Does C style string escaping. */
1135 if (!(r = new(char, strlen(s)*4 + 1)))
1138 for (f = s, t = r; *f; f++)
1184 /* For special chars we prefer octal over
1185 * hexadecimal encoding, simply because glib's
1186 * g_strescape() does the same */
1187 if ((*f < ' ') || (*f >= 127)) {
1189 *(t++) = octchar((unsigned char) *f >> 6);
1190 *(t++) = octchar((unsigned char) *f >> 3);
1191 *(t++) = octchar((unsigned char) *f);
1202 char *cunescape_length(const char *s, size_t length) {
1208 /* Undoes C style string escaping */
1210 if (!(r = new(char, length+1)))
1213 for (f = s, t = r; f < s + length; f++) {
1256 /* This is an extension of the XDG syntax files */
1261 /* hexadecimal encoding */
1264 if ((a = unhexchar(f[1])) < 0 ||
1265 (b = unhexchar(f[2])) < 0) {
1266 /* Invalid escape code, let's take it literal then */
1270 *(t++) = (char) ((a << 4) | b);
1285 /* octal encoding */
1288 if ((a = unoctchar(f[0])) < 0 ||
1289 (b = unoctchar(f[1])) < 0 ||
1290 (c = unoctchar(f[2])) < 0) {
1291 /* Invalid escape code, let's take it literal then */
1295 *(t++) = (char) ((a << 6) | (b << 3) | c);
1303 /* premature end of string.*/
1308 /* Invalid escape code, let's take it literal then */
1320 char *cunescape(const char *s) {
1321 return cunescape_length(s, strlen(s));
1324 char *xescape(const char *s, const char *bad) {
1328 /* Escapes all chars in bad, in addition to \ and all special
1329 * chars, in \xFF style escaping. May be reversed with
1332 if (!(r = new(char, strlen(s)*4+1)))
1335 for (f = s, t = r; *f; f++) {
1337 if ((*f < ' ') || (*f >= 127) ||
1338 (*f == '\\') || strchr(bad, *f)) {
1341 *(t++) = hexchar(*f >> 4);
1342 *(t++) = hexchar(*f);
1352 char *bus_path_escape(const char *s) {
1358 /* Escapes all chars that D-Bus' object path cannot deal
1359 * with. Can be reverse with bus_path_unescape() */
1361 if (!(r = new(char, strlen(s)*3+1)))
1364 for (f = s, t = r; *f; f++) {
1366 if (!(*f >= 'A' && *f <= 'Z') &&
1367 !(*f >= 'a' && *f <= 'z') &&
1368 !(*f >= '0' && *f <= '9')) {
1370 *(t++) = hexchar(*f >> 4);
1371 *(t++) = hexchar(*f);
1381 char *bus_path_unescape(const char *f) {
1386 if (!(r = strdup(f)))
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 *path_kill_slashes(char *path) {
1415 /* Removes redundant inner and trailing slashes. Modifies the
1416 * passed string in-place.
1418 * ///foo///bar/ becomes /foo/bar
1421 for (f = path, t = path; *f; f++) {
1436 /* Special rule, if we are talking of the root directory, a
1437 trailing slash is good */
1439 if (t == path && slash)
1446 bool path_startswith(const char *path, const char *prefix) {
1450 if ((path[0] == '/') != (prefix[0] == '/'))
1456 path += strspn(path, "/");
1457 prefix += strspn(prefix, "/");
1465 a = strcspn(path, "/");
1466 b = strcspn(prefix, "/");
1471 if (memcmp(path, prefix, a) != 0)
1479 bool path_equal(const char *a, const char *b) {
1483 if ((a[0] == '/') != (b[0] == '/'))
1489 a += strspn(a, "/");
1490 b += strspn(b, "/");
1492 if (*a == 0 && *b == 0)
1495 if (*a == 0 || *b == 0)
1498 j = strcspn(a, "/");
1499 k = strcspn(b, "/");
1504 if (memcmp(a, b, j) != 0)
1512 char *ascii_strlower(char *t) {
1517 for (p = t; *p; p++)
1518 if (*p >= 'A' && *p <= 'Z')
1519 *p = *p - 'A' + 'a';
1524 bool ignore_file(const char *filename) {
1528 filename[0] == '.' ||
1529 streq(filename, "lost+found") ||
1530 endswith(filename, "~") ||
1531 endswith(filename, ".rpmnew") ||
1532 endswith(filename, ".rpmsave") ||
1533 endswith(filename, ".rpmorig") ||
1534 endswith(filename, ".dpkg-old") ||
1535 endswith(filename, ".dpkg-new") ||
1536 endswith(filename, ".swp");
1539 int fd_nonblock(int fd, bool nonblock) {
1544 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1548 flags |= O_NONBLOCK;
1550 flags &= ~O_NONBLOCK;
1552 if (fcntl(fd, F_SETFL, flags) < 0)
1558 int fd_cloexec(int fd, bool cloexec) {
1563 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1567 flags |= FD_CLOEXEC;
1569 flags &= ~FD_CLOEXEC;
1571 if (fcntl(fd, F_SETFD, flags) < 0)
1577 int close_all_fds(const int except[], unsigned n_except) {
1582 if (!(d = opendir("/proc/self/fd")))
1585 while ((de = readdir(d))) {
1588 if (ignore_file(de->d_name))
1591 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1605 for (i = 0; i < n_except; i++)
1606 if (except[i] == fd) {
1615 if ((r = close_nointr(fd)) < 0) {
1616 /* Valgrind has its own FD and doesn't want to have it closed */
1629 bool chars_intersect(const char *a, const char *b) {
1632 /* Returns true if any of the chars in a are in b. */
1633 for (p = a; *p; p++)
1640 char *format_timestamp(char *buf, size_t l, usec_t t) {
1650 sec = (time_t) (t / USEC_PER_SEC);
1652 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1658 char *format_timespan(char *buf, size_t l, usec_t t) {
1659 static const struct {
1663 { "w", USEC_PER_WEEK },
1664 { "d", USEC_PER_DAY },
1665 { "h", USEC_PER_HOUR },
1666 { "min", USEC_PER_MINUTE },
1667 { "s", USEC_PER_SEC },
1668 { "ms", USEC_PER_MSEC },
1678 if (t == (usec_t) -1)
1681 /* The result of this function can be parsed with parse_usec */
1683 for (i = 0; i < ELEMENTSOF(table); i++) {
1687 if (t < table[i].usec)
1693 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1694 n = MIN((size_t) k, l);
1707 bool fstype_is_network(const char *fstype) {
1708 static const char * const table[] = {
1720 for (i = 0; i < ELEMENTSOF(table); i++)
1721 if (streq(table[i], fstype))
1730 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1735 TIOCL_GETKMSGREDIRECT,
1739 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1742 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1745 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1748 close_nointr_nofail(r);
1752 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1753 struct termios old_termios, new_termios;
1760 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1761 new_termios = old_termios;
1763 new_termios.c_lflag &= ~ICANON;
1764 new_termios.c_cc[VMIN] = 1;
1765 new_termios.c_cc[VTIME] = 0;
1767 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1770 k = fread(&c, 1, 1, f);
1772 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1778 *need_nl = c != '\n';
1785 if (!(fgets(line, sizeof(line), f)))
1790 if (strlen(line) != 1)
1800 int ask(char *ret, const char *replies, const char *text, ...) {
1809 bool need_nl = true;
1811 fputs("\x1B[1m", stdout);
1817 fputs("\x1B[0m", stdout);
1821 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1823 if (r == -EBADMSG) {
1824 puts("Bad input, please try again.");
1835 if (strchr(replies, c)) {
1840 puts("Read unexpected character, please try again.");
1844 int reset_terminal(int fd) {
1845 struct termios termios;
1850 /* Set terminal to some sane defaults */
1852 if (tcgetattr(fd, &termios) < 0) {
1857 /* We only reset the stuff that matters to the software. How
1858 * hardware is set up we don't touch assuming that somebody
1859 * else will do that for us */
1861 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1862 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1863 termios.c_oflag |= ONLCR;
1864 termios.c_cflag |= CREAD;
1865 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1867 termios.c_cc[VINTR] = 03; /* ^C */
1868 termios.c_cc[VQUIT] = 034; /* ^\ */
1869 termios.c_cc[VERASE] = 0177;
1870 termios.c_cc[VKILL] = 025; /* ^X */
1871 termios.c_cc[VEOF] = 04; /* ^D */
1872 termios.c_cc[VSTART] = 021; /* ^Q */
1873 termios.c_cc[VSTOP] = 023; /* ^S */
1874 termios.c_cc[VSUSP] = 032; /* ^Z */
1875 termios.c_cc[VLNEXT] = 026; /* ^V */
1876 termios.c_cc[VWERASE] = 027; /* ^W */
1877 termios.c_cc[VREPRINT] = 022; /* ^R */
1878 termios.c_cc[VEOL] = 0;
1879 termios.c_cc[VEOL2] = 0;
1881 termios.c_cc[VTIME] = 0;
1882 termios.c_cc[VMIN] = 1;
1884 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1888 /* Just in case, flush all crap out */
1889 tcflush(fd, TCIOFLUSH);
1894 int open_terminal(const char *name, int mode) {
1897 if ((fd = open(name, mode)) < 0)
1900 if ((r = isatty(fd)) < 0) {
1901 close_nointr_nofail(fd);
1906 close_nointr_nofail(fd);
1913 int flush_fd(int fd) {
1914 struct pollfd pollfd;
1918 pollfd.events = POLLIN;
1925 if ((r = poll(&pollfd, 1, 0)) < 0) {
1936 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1941 if (errno == EAGAIN)
1952 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1953 int fd = -1, notify = -1, r, wd = -1;
1957 /* We use inotify to be notified when the tty is closed. We
1958 * create the watch before checking if we can actually acquire
1959 * it, so that we don't lose any event.
1961 * Note: strictly speaking this actually watches for the
1962 * device being closed, it does *not* really watch whether a
1963 * tty loses its controlling process. However, unless some
1964 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1965 * its tty otherwise this will not become a problem. As long
1966 * as the administrator makes sure not configure any service
1967 * on the same tty as an untrusted user this should not be a
1968 * problem. (Which he probably should not do anyway.) */
1970 if (!fail && !force) {
1971 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1976 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1984 if ((r = flush_fd(notify)) < 0)
1987 /* We pass here O_NOCTTY only so that we can check the return
1988 * value TIOCSCTTY and have a reliable way to figure out if we
1989 * successfully became the controlling process of the tty */
1990 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1993 /* First, try to get the tty */
1994 r = ioctl(fd, TIOCSCTTY, force);
1996 /* Sometimes it makes sense to ignore TIOCSCTTY
1997 * returning EPERM, i.e. when very likely we already
1998 * are have this controlling terminal. */
1999 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2002 if (r < 0 && (force || fail || errno != EPERM)) {
2012 assert(notify >= 0);
2015 struct inotify_event e;
2018 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
2032 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
2040 /* We close the tty fd here since if the old session
2041 * ended our handle will be dead. It's important that
2042 * we do this after sleeping, so that we don't enter
2043 * an endless loop. */
2044 close_nointr_nofail(fd);
2048 close_nointr_nofail(notify);
2050 if ((r = reset_terminal(fd)) < 0)
2051 log_warning("Failed to reset terminal: %s", strerror(-r));
2057 close_nointr_nofail(fd);
2060 close_nointr_nofail(notify);
2065 int release_terminal(void) {
2067 struct sigaction sa_old, sa_new;
2069 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2072 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2073 * by our own TIOCNOTTY */
2076 sa_new.sa_handler = SIG_IGN;
2077 sa_new.sa_flags = SA_RESTART;
2078 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2080 if (ioctl(fd, TIOCNOTTY) < 0)
2083 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2085 close_nointr_nofail(fd);
2089 int sigaction_many(const struct sigaction *sa, ...) {
2094 while ((sig = va_arg(ap, int)) > 0)
2095 if (sigaction(sig, sa, NULL) < 0)
2102 int ignore_signals(int sig, ...) {
2103 struct sigaction sa;
2108 sa.sa_handler = SIG_IGN;
2109 sa.sa_flags = SA_RESTART;
2111 if (sigaction(sig, &sa, NULL) < 0)
2115 while ((sig = va_arg(ap, int)) > 0)
2116 if (sigaction(sig, &sa, NULL) < 0)
2123 int default_signals(int sig, ...) {
2124 struct sigaction sa;
2129 sa.sa_handler = SIG_DFL;
2130 sa.sa_flags = SA_RESTART;
2132 if (sigaction(sig, &sa, NULL) < 0)
2136 while ((sig = va_arg(ap, int)) > 0)
2137 if (sigaction(sig, &sa, NULL) < 0)
2144 int close_pipe(int p[]) {
2150 a = close_nointr(p[0]);
2155 b = close_nointr(p[1]);
2159 return a < 0 ? a : b;
2162 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2171 while (nbytes > 0) {
2174 if ((k = read(fd, p, nbytes)) <= 0) {
2176 if (k < 0 && errno == EINTR)
2179 if (k < 0 && errno == EAGAIN && do_poll) {
2180 struct pollfd pollfd;
2184 pollfd.events = POLLIN;
2186 if (poll(&pollfd, 1, -1) < 0) {
2190 return n > 0 ? n : -errno;
2193 if (pollfd.revents != POLLIN)
2194 return n > 0 ? n : -EIO;
2199 return n > 0 ? n : (k < 0 ? -errno : 0);
2210 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2219 while (nbytes > 0) {
2222 if ((k = write(fd, p, nbytes)) <= 0) {
2224 if (k < 0 && errno == EINTR)
2227 if (k < 0 && errno == EAGAIN && do_poll) {
2228 struct pollfd pollfd;
2232 pollfd.events = POLLOUT;
2234 if (poll(&pollfd, 1, -1) < 0) {
2238 return n > 0 ? n : -errno;
2241 if (pollfd.revents != POLLOUT)
2242 return n > 0 ? n : -EIO;
2247 return n > 0 ? n : (k < 0 ? -errno : 0);
2258 int path_is_mount_point(const char *t) {
2263 if (lstat(t, &a) < 0) {
2264 if (errno == ENOENT)
2270 if ((r = parent_of_path(t, &parent)) < 0)
2273 r = lstat(parent, &b);
2279 return a.st_dev != b.st_dev;
2282 int parse_usec(const char *t, usec_t *usec) {
2283 static const struct {
2287 { "sec", USEC_PER_SEC },
2288 { "s", USEC_PER_SEC },
2289 { "min", USEC_PER_MINUTE },
2290 { "hr", USEC_PER_HOUR },
2291 { "h", USEC_PER_HOUR },
2292 { "d", USEC_PER_DAY },
2293 { "w", USEC_PER_WEEK },
2294 { "msec", USEC_PER_MSEC },
2295 { "ms", USEC_PER_MSEC },
2296 { "m", USEC_PER_MINUTE },
2299 { "", USEC_PER_SEC },
2315 l = strtoll(p, &e, 10);
2326 e += strspn(e, WHITESPACE);
2328 for (i = 0; i < ELEMENTSOF(table); i++)
2329 if (startswith(e, table[i].suffix)) {
2330 r += (usec_t) l * table[i].usec;
2331 p = e + strlen(table[i].suffix);
2335 if (i >= ELEMENTSOF(table))
2345 int make_stdio(int fd) {
2350 r = dup2(fd, STDIN_FILENO);
2351 s = dup2(fd, STDOUT_FILENO);
2352 t = dup2(fd, STDERR_FILENO);
2355 close_nointr_nofail(fd);
2357 if (r < 0 || s < 0 || t < 0)
2363 bool is_clean_exit(int code, int status) {
2365 if (code == CLD_EXITED)
2368 /* If a daemon does not implement handlers for some of the
2369 * signals that's not considered an unclean shutdown */
2370 if (code == CLD_KILLED)
2374 status == SIGTERM ||
2380 bool is_device_path(const char *path) {
2382 /* Returns true on paths that refer to a device, either in
2383 * sysfs or in /dev */
2386 path_startswith(path, "/dev/") ||
2387 path_startswith(path, "/sys/");
2390 int dir_is_empty(const char *path) {
2393 struct dirent buf, *de;
2395 if (!(d = opendir(path)))
2399 if ((r = readdir_r(d, &buf, &de)) > 0) {
2409 if (!ignore_file(de->d_name)) {
2419 unsigned long long random_ull(void) {
2424 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2427 r = loop_read(fd, &ull, sizeof(ull), true);
2428 close_nointr_nofail(fd);
2430 if (r != sizeof(ull))
2436 return random() * RAND_MAX + random();
2439 void rename_process(const char name[8]) {
2442 prctl(PR_SET_NAME, name);
2444 /* This is a like a poor man's setproctitle(). The string
2445 * passed should fit in 7 chars (i.e. the length of
2448 if (program_invocation_name)
2449 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2452 void sigset_add_many(sigset_t *ss, ...) {
2459 while ((sig = va_arg(ap, int)) > 0)
2460 assert_se(sigaddset(ss, sig) == 0);
2464 char* gethostname_malloc(void) {
2467 assert_se(uname(&u) >= 0);
2470 return strdup(u.nodename);
2472 return strdup(u.sysname);
2475 int getmachineid_malloc(char **b) {
2480 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2487 char* getlogname_malloc(void) {
2491 struct passwd pwbuf, *pw = NULL;
2494 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2499 /* Shortcut things to avoid NSS lookups */
2501 return strdup("root");
2503 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2506 if (!(buf = malloc(bufsize)))
2509 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2510 name = strdup(pw->pw_name);
2517 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2523 int getttyname_malloc(char **r) {
2524 char path[PATH_MAX], *p, *c;
2528 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2534 if (startswith(path, "/dev/"))
2537 if (!(c = strdup(p)))
2544 static int rm_rf_children(int fd, bool only_dirs) {
2550 /* This returns the first error we run into, but nevertheless
2553 if (!(d = fdopendir(fd))) {
2554 close_nointr_nofail(fd);
2559 struct dirent buf, *de;
2563 if ((r = readdir_r(d, &buf, &de)) != 0) {
2572 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2575 if (de->d_type == DT_UNKNOWN) {
2578 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2584 is_dir = S_ISDIR(st.st_mode);
2586 is_dir = de->d_type == DT_DIR;
2591 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2597 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2602 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2606 } else if (!only_dirs) {
2608 if (unlinkat(fd, de->d_name, 0) < 0) {
2620 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2626 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2628 if (errno != ENOTDIR)
2631 if (delete_root && !only_dirs)
2632 if (unlink(path) < 0)
2638 r = rm_rf_children(fd, only_dirs);
2641 if (rmdir(path) < 0) {
2649 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2652 /* Under the assumption that we are running privileged we
2653 * first change the access mode and only then hand out
2654 * ownership to avoid a window where access is too open. */
2656 if (chmod(path, mode) < 0)
2659 if (chown(path, uid, gid) < 0)
2665 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2669 /* Allocates the cpuset in the right size */
2672 if (!(r = CPU_ALLOC(n)))
2675 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2676 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2686 if (errno != EINVAL)
2693 void status_vprintf(const char *format, va_list ap) {
2699 /* This independent of logging, as status messages are
2700 * optional and go exclusively to the console. */
2702 if (vasprintf(&s, format, ap) < 0)
2705 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2708 write(fd, s, strlen(s));
2714 close_nointr_nofail(fd);
2717 void status_printf(const char *format, ...) {
2722 va_start(ap, format);
2723 status_vprintf(format, ap);
2727 void status_welcome(void) {
2729 #if defined(TARGET_FEDORA)
2732 if (read_one_line_file("/etc/system-release", &r) < 0)
2737 /* This tries to mimic the color magic the old Red Hat sysinit
2740 if (startswith(r, "Red Hat"))
2741 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2742 else if (startswith(r, "Fedora"))
2743 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2745 status_printf("Welcome to %s!\n", r);
2749 #elif defined(TARGET_SUSE)
2752 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2757 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2760 #warning "You probably should add a welcome text logic here."
2764 char *replace_env(const char *format, char **env) {
2771 const char *e, *word = format;
2776 for (e = format; *e; e ++) {
2787 if (!(k = strnappend(r, word, e-word-1)))
2796 } else if (*e == '$') {
2797 if (!(k = strnappend(r, word, e-word)))
2813 if ((t = strv_env_get_with_length(env, word+2, e-word-2))) {
2814 if (!(k = strappend(r, t)))
2829 if (!(k = strnappend(r, word, e-word)))
2840 char **replace_env_argv(char **argv, char **env) {
2844 if (!(r = new(char*, strv_length(argv)+1)))
2847 STRV_FOREACH(i, argv) {
2848 if (!(r[k++] = replace_env(*i, env))) {
2859 static __thread int parsed_columns = 0;
2862 if (parsed_columns > 0)
2863 return parsed_columns;
2865 if ((e = getenv("COLUMNS")))
2866 parsed_columns = atoi(e);
2868 if (parsed_columns <= 0) {
2872 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
2873 parsed_columns = ws.ws_col;
2876 if (parsed_columns <= 0)
2877 parsed_columns = 80;
2879 return parsed_columns;
2882 int running_in_chroot(void) {
2888 /* Only works as root */
2890 if (stat("/proc/1/root", &a) < 0)
2893 if (stat("/", &b) < 0)
2897 a.st_dev != b.st_dev ||
2898 a.st_ino != b.st_ino;
2901 static const char *const ioprio_class_table[] = {
2902 [IOPRIO_CLASS_NONE] = "none",
2903 [IOPRIO_CLASS_RT] = "realtime",
2904 [IOPRIO_CLASS_BE] = "best-effort",
2905 [IOPRIO_CLASS_IDLE] = "idle"
2908 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2910 static const char *const sigchld_code_table[] = {
2911 [CLD_EXITED] = "exited",
2912 [CLD_KILLED] = "killed",
2913 [CLD_DUMPED] = "dumped",
2914 [CLD_TRAPPED] = "trapped",
2915 [CLD_STOPPED] = "stopped",
2916 [CLD_CONTINUED] = "continued",
2919 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2921 static const char *const log_facility_table[LOG_NFACILITIES] = {
2922 [LOG_FAC(LOG_KERN)] = "kern",
2923 [LOG_FAC(LOG_USER)] = "user",
2924 [LOG_FAC(LOG_MAIL)] = "mail",
2925 [LOG_FAC(LOG_DAEMON)] = "daemon",
2926 [LOG_FAC(LOG_AUTH)] = "auth",
2927 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2928 [LOG_FAC(LOG_LPR)] = "lpr",
2929 [LOG_FAC(LOG_NEWS)] = "news",
2930 [LOG_FAC(LOG_UUCP)] = "uucp",
2931 [LOG_FAC(LOG_CRON)] = "cron",
2932 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2933 [LOG_FAC(LOG_FTP)] = "ftp",
2934 [LOG_FAC(LOG_LOCAL0)] = "local0",
2935 [LOG_FAC(LOG_LOCAL1)] = "local1",
2936 [LOG_FAC(LOG_LOCAL2)] = "local2",
2937 [LOG_FAC(LOG_LOCAL3)] = "local3",
2938 [LOG_FAC(LOG_LOCAL4)] = "local4",
2939 [LOG_FAC(LOG_LOCAL5)] = "local5",
2940 [LOG_FAC(LOG_LOCAL6)] = "local6",
2941 [LOG_FAC(LOG_LOCAL7)] = "local7"
2944 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2946 static const char *const log_level_table[] = {
2947 [LOG_EMERG] = "emerg",
2948 [LOG_ALERT] = "alert",
2949 [LOG_CRIT] = "crit",
2951 [LOG_WARNING] = "warning",
2952 [LOG_NOTICE] = "notice",
2953 [LOG_INFO] = "info",
2954 [LOG_DEBUG] = "debug"
2957 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2959 static const char* const sched_policy_table[] = {
2960 [SCHED_OTHER] = "other",
2961 [SCHED_BATCH] = "batch",
2962 [SCHED_IDLE] = "idle",
2963 [SCHED_FIFO] = "fifo",
2967 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2969 static const char* const rlimit_table[] = {
2970 [RLIMIT_CPU] = "LimitCPU",
2971 [RLIMIT_FSIZE] = "LimitFSIZE",
2972 [RLIMIT_DATA] = "LimitDATA",
2973 [RLIMIT_STACK] = "LimitSTACK",
2974 [RLIMIT_CORE] = "LimitCORE",
2975 [RLIMIT_RSS] = "LimitRSS",
2976 [RLIMIT_NOFILE] = "LimitNOFILE",
2977 [RLIMIT_AS] = "LimitAS",
2978 [RLIMIT_NPROC] = "LimitNPROC",
2979 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2980 [RLIMIT_LOCKS] = "LimitLOCKS",
2981 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2982 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2983 [RLIMIT_NICE] = "LimitNICE",
2984 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2985 [RLIMIT_RTTIME] = "LimitRTTIME"
2988 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2990 static const char* const ip_tos_table[] = {
2991 [IPTOS_LOWDELAY] = "low-delay",
2992 [IPTOS_THROUGHPUT] = "throughput",
2993 [IPTOS_RELIABILITY] = "reliability",
2994 [IPTOS_LOWCOST] = "low-cost",
2997 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
2999 static const char *const signal_table[] = {
3015 [SIGSTKFLT] = "STKFLT",
3025 [SIGVTALRM] = "VTALRM",
3027 [SIGWINCH] = "WINCH",
3033 DEFINE_STRING_TABLE_LOOKUP(signal, int);