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);
613 return get_process_name(pid, line);
619 char *strnappend(const char *s, const char *suffix, size_t b) {
627 return strndup(suffix, b);
637 if (!(r = new(char, a+b+1)))
641 memcpy(r+a, suffix, b);
647 char *strappend(const char *s, const char *suffix) {
648 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
651 int readlink_malloc(const char *p, char **r) {
661 if (!(c = new(char, l)))
664 if ((n = readlink(p, c, l-1)) < 0) {
670 if ((size_t) n < l-1) {
681 int readlink_and_make_absolute(const char *p, char **r) {
688 if ((j = readlink_malloc(p, &target)) < 0)
691 k = file_in_same_dir(p, target);
701 char *file_name_from_path(const char *p) {
706 if ((r = strrchr(p, '/')))
712 bool path_is_absolute(const char *p) {
718 bool is_path(const char *p) {
720 return !!strchr(p, '/');
723 char *path_make_absolute(const char *p, const char *prefix) {
728 /* Makes every item in the list an absolute path by prepending
729 * the prefix, if specified and necessary */
731 if (path_is_absolute(p) || !prefix)
734 if (asprintf(&r, "%s/%s", prefix, p) < 0)
740 char *path_make_absolute_cwd(const char *p) {
745 /* Similar to path_make_absolute(), but prefixes with the
746 * current working directory. */
748 if (path_is_absolute(p))
751 if (!(cwd = get_current_dir_name()))
754 r = path_make_absolute(p, cwd);
760 char **strv_path_make_absolute_cwd(char **l) {
763 /* Goes through every item in the string list and makes it
764 * absolute. This works in place and won't rollback any
765 * changes on failure. */
770 if (!(t = path_make_absolute_cwd(*s)))
780 char **strv_path_canonicalize(char **l) {
788 /* Goes through every item in the string list and canonicalize
789 * the path. This works in place and won't rollback any
790 * changes on failure. */
795 t = path_make_absolute_cwd(*s);
804 u = canonicalize_file_name(t);
808 if (errno == ENOMEM || !errno)
825 int reset_all_signal_handlers(void) {
828 for (sig = 1; sig < _NSIG; sig++) {
831 if (sig == SIGKILL || sig == SIGSTOP)
835 sa.sa_handler = SIG_DFL;
836 sa.sa_flags = SA_RESTART;
838 /* On Linux the first two RT signals are reserved by
839 * glibc, and sigaction() will return EINVAL for them. */
840 if ((sigaction(sig, &sa, NULL) < 0))
848 char *strstrip(char *s) {
851 /* Drops trailing whitespace. Modifies the string in
852 * place. Returns pointer to first non-space character */
854 s += strspn(s, WHITESPACE);
857 if (!strchr(WHITESPACE, *e))
868 char *delete_chars(char *s, const char *bad) {
871 /* Drops all whitespace, regardless where in the string */
873 for (f = s, t = s; *f; f++) {
885 char *file_in_same_dir(const char *path, const char *filename) {
892 /* This removes the last component of path and appends
893 * filename, unless the latter is absolute anyway or the
896 if (path_is_absolute(filename))
897 return strdup(filename);
899 if (!(e = strrchr(path, '/')))
900 return strdup(filename);
902 k = strlen(filename);
903 if (!(r = new(char, e-path+1+k+1)))
906 memcpy(r, path, e-path+1);
907 memcpy(r+(e-path)+1, filename, k+1);
912 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
915 if (mkdir(path, mode) >= 0)
916 if (chmod_and_chown(path, mode, uid, gid) < 0)
919 if (lstat(path, &st) < 0)
922 if ((st.st_mode & 0777) != mode ||
925 !S_ISDIR(st.st_mode)) {
934 int mkdir_parents(const char *path, mode_t mode) {
939 /* Creates every parent directory in the path except the last
942 p = path + strspn(path, "/");
947 e = p + strcspn(p, "/");
948 p = e + strspn(e, "/");
950 /* Is this the last component? If so, then we're
955 if (!(t = strndup(path, e - path)))
961 if (r < 0 && errno != EEXIST)
966 int mkdir_p(const char *path, mode_t mode) {
971 if ((r = mkdir_parents(path, mode)) < 0)
974 if (mkdir(path, mode) < 0 && errno != EEXIST)
980 int rmdir_parents(const char *path, const char *stop) {
989 /* Skip trailing slashes */
990 while (l > 0 && path[l-1] == '/')
996 /* Skip last component */
997 while (l > 0 && path[l-1] != '/')
1000 /* Skip trailing slashes */
1001 while (l > 0 && path[l-1] == '/')
1007 if (!(t = strndup(path, l)))
1010 if (path_startswith(stop, t)) {
1019 if (errno != ENOENT)
1027 char hexchar(int x) {
1028 static const char table[16] = "0123456789abcdef";
1030 return table[x & 15];
1033 int unhexchar(char c) {
1035 if (c >= '0' && c <= '9')
1038 if (c >= 'a' && c <= 'f')
1039 return c - 'a' + 10;
1041 if (c >= 'A' && c <= 'F')
1042 return c - 'A' + 10;
1047 char octchar(int x) {
1048 return '0' + (x & 7);
1051 int unoctchar(char c) {
1053 if (c >= '0' && c <= '7')
1059 char decchar(int x) {
1060 return '0' + (x % 10);
1063 int undecchar(char c) {
1065 if (c >= '0' && c <= '9')
1071 char *cescape(const char *s) {
1077 /* Does C style string escaping. */
1079 if (!(r = new(char, strlen(s)*4 + 1)))
1082 for (f = s, t = r; *f; f++)
1128 /* For special chars we prefer octal over
1129 * hexadecimal encoding, simply because glib's
1130 * g_strescape() does the same */
1131 if ((*f < ' ') || (*f >= 127)) {
1133 *(t++) = octchar((unsigned char) *f >> 6);
1134 *(t++) = octchar((unsigned char) *f >> 3);
1135 *(t++) = octchar((unsigned char) *f);
1146 char *cunescape_length(const char *s, size_t length) {
1152 /* Undoes C style string escaping */
1154 if (!(r = new(char, length+1)))
1157 for (f = s, t = r; f < s + length; f++) {
1200 /* This is an extension of the XDG syntax files */
1205 /* hexadecimal encoding */
1208 if ((a = unhexchar(f[1])) < 0 ||
1209 (b = unhexchar(f[2])) < 0) {
1210 /* Invalid escape code, let's take it literal then */
1214 *(t++) = (char) ((a << 4) | b);
1229 /* octal encoding */
1232 if ((a = unoctchar(f[0])) < 0 ||
1233 (b = unoctchar(f[1])) < 0 ||
1234 (c = unoctchar(f[2])) < 0) {
1235 /* Invalid escape code, let's take it literal then */
1239 *(t++) = (char) ((a << 6) | (b << 3) | c);
1247 /* premature end of string.*/
1252 /* Invalid escape code, let's take it literal then */
1264 char *cunescape(const char *s) {
1265 return cunescape_length(s, strlen(s));
1268 char *xescape(const char *s, const char *bad) {
1272 /* Escapes all chars in bad, in addition to \ and all special
1273 * chars, in \xFF style escaping. May be reversed with
1276 if (!(r = new(char, strlen(s)*4+1)))
1279 for (f = s, t = r; *f; f++) {
1281 if ((*f < ' ') || (*f >= 127) ||
1282 (*f == '\\') || strchr(bad, *f)) {
1285 *(t++) = hexchar(*f >> 4);
1286 *(t++) = hexchar(*f);
1296 char *bus_path_escape(const char *s) {
1302 /* Escapes all chars that D-Bus' object path cannot deal
1303 * with. Can be reverse with bus_path_unescape() */
1305 if (!(r = new(char, strlen(s)*3+1)))
1308 for (f = s, t = r; *f; f++) {
1310 if (!(*f >= 'A' && *f <= 'Z') &&
1311 !(*f >= 'a' && *f <= 'z') &&
1312 !(*f >= '0' && *f <= '9')) {
1314 *(t++) = hexchar(*f >> 4);
1315 *(t++) = hexchar(*f);
1325 char *bus_path_unescape(const char *f) {
1330 if (!(r = strdup(f)))
1333 for (t = r; *f; f++) {
1338 if ((a = unhexchar(f[1])) < 0 ||
1339 (b = unhexchar(f[2])) < 0) {
1340 /* Invalid escape code, let's take it literal then */
1343 *(t++) = (char) ((a << 4) | b);
1355 char *path_kill_slashes(char *path) {
1359 /* Removes redundant inner and trailing slashes. Modifies the
1360 * passed string in-place.
1362 * ///foo///bar/ becomes /foo/bar
1365 for (f = path, t = path; *f; f++) {
1380 /* Special rule, if we are talking of the root directory, a
1381 trailing slash is good */
1383 if (t == path && slash)
1390 bool path_startswith(const char *path, const char *prefix) {
1394 if ((path[0] == '/') != (prefix[0] == '/'))
1400 path += strspn(path, "/");
1401 prefix += strspn(prefix, "/");
1409 a = strcspn(path, "/");
1410 b = strcspn(prefix, "/");
1415 if (memcmp(path, prefix, a) != 0)
1423 bool path_equal(const char *a, const char *b) {
1427 if ((a[0] == '/') != (b[0] == '/'))
1433 a += strspn(a, "/");
1434 b += strspn(b, "/");
1436 if (*a == 0 && *b == 0)
1439 if (*a == 0 || *b == 0)
1442 j = strcspn(a, "/");
1443 k = strcspn(b, "/");
1448 if (memcmp(a, b, j) != 0)
1456 char *ascii_strlower(char *t) {
1461 for (p = t; *p; p++)
1462 if (*p >= 'A' && *p <= 'Z')
1463 *p = *p - 'A' + 'a';
1468 bool ignore_file(const char *filename) {
1472 filename[0] == '.' ||
1473 streq(filename, "lost+found") ||
1474 endswith(filename, "~") ||
1475 endswith(filename, ".rpmnew") ||
1476 endswith(filename, ".rpmsave") ||
1477 endswith(filename, ".rpmorig") ||
1478 endswith(filename, ".dpkg-old") ||
1479 endswith(filename, ".dpkg-new") ||
1480 endswith(filename, ".swp");
1483 int fd_nonblock(int fd, bool nonblock) {
1488 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1492 flags |= O_NONBLOCK;
1494 flags &= ~O_NONBLOCK;
1496 if (fcntl(fd, F_SETFL, flags) < 0)
1502 int fd_cloexec(int fd, bool cloexec) {
1507 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1511 flags |= FD_CLOEXEC;
1513 flags &= ~FD_CLOEXEC;
1515 if (fcntl(fd, F_SETFD, flags) < 0)
1521 int close_all_fds(const int except[], unsigned n_except) {
1526 if (!(d = opendir("/proc/self/fd")))
1529 while ((de = readdir(d))) {
1532 if (ignore_file(de->d_name))
1535 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1549 for (i = 0; i < n_except; i++)
1550 if (except[i] == fd) {
1559 if ((r = close_nointr(fd)) < 0) {
1560 /* Valgrind has its own FD and doesn't want to have it closed */
1573 bool chars_intersect(const char *a, const char *b) {
1576 /* Returns true if any of the chars in a are in b. */
1577 for (p = a; *p; p++)
1584 char *format_timestamp(char *buf, size_t l, usec_t t) {
1594 sec = (time_t) (t / USEC_PER_SEC);
1596 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1602 char *format_timespan(char *buf, size_t l, usec_t t) {
1603 static const struct {
1607 { "w", USEC_PER_WEEK },
1608 { "d", USEC_PER_DAY },
1609 { "h", USEC_PER_HOUR },
1610 { "min", USEC_PER_MINUTE },
1611 { "s", USEC_PER_SEC },
1612 { "ms", USEC_PER_MSEC },
1622 if (t == (usec_t) -1)
1625 /* The result of this function can be parsed with parse_usec */
1627 for (i = 0; i < ELEMENTSOF(table); i++) {
1631 if (t < table[i].usec)
1637 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1638 n = MIN((size_t) k, l);
1651 bool fstype_is_network(const char *fstype) {
1652 static const char * const table[] = {
1664 for (i = 0; i < ELEMENTSOF(table); i++)
1665 if (streq(table[i], fstype))
1674 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1679 TIOCL_GETKMSGREDIRECT,
1683 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1686 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1689 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1692 close_nointr_nofail(r);
1696 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1697 struct termios old_termios, new_termios;
1704 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1705 new_termios = old_termios;
1707 new_termios.c_lflag &= ~ICANON;
1708 new_termios.c_cc[VMIN] = 1;
1709 new_termios.c_cc[VTIME] = 0;
1711 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1714 k = fread(&c, 1, 1, f);
1716 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1722 *need_nl = c != '\n';
1729 if (!(fgets(line, sizeof(line), f)))
1734 if (strlen(line) != 1)
1744 int ask(char *ret, const char *replies, const char *text, ...) {
1753 bool need_nl = true;
1755 fputs("\x1B[1m", stdout);
1761 fputs("\x1B[0m", stdout);
1765 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1767 if (r == -EBADMSG) {
1768 puts("Bad input, please try again.");
1779 if (strchr(replies, c)) {
1784 puts("Read unexpected character, please try again.");
1788 int reset_terminal(int fd) {
1789 struct termios termios;
1794 /* Set terminal to some sane defaults */
1796 if (tcgetattr(fd, &termios) < 0) {
1801 /* We only reset the stuff that matters to the software. How
1802 * hardware is set up we don't touch assuming that somebody
1803 * else will do that for us */
1805 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1806 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1807 termios.c_oflag |= ONLCR;
1808 termios.c_cflag |= CREAD;
1809 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1811 termios.c_cc[VINTR] = 03; /* ^C */
1812 termios.c_cc[VQUIT] = 034; /* ^\ */
1813 termios.c_cc[VERASE] = 0177;
1814 termios.c_cc[VKILL] = 025; /* ^X */
1815 termios.c_cc[VEOF] = 04; /* ^D */
1816 termios.c_cc[VSTART] = 021; /* ^Q */
1817 termios.c_cc[VSTOP] = 023; /* ^S */
1818 termios.c_cc[VSUSP] = 032; /* ^Z */
1819 termios.c_cc[VLNEXT] = 026; /* ^V */
1820 termios.c_cc[VWERASE] = 027; /* ^W */
1821 termios.c_cc[VREPRINT] = 022; /* ^R */
1822 termios.c_cc[VEOL] = 0;
1823 termios.c_cc[VEOL2] = 0;
1825 termios.c_cc[VTIME] = 0;
1826 termios.c_cc[VMIN] = 1;
1828 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1832 /* Just in case, flush all crap out */
1833 tcflush(fd, TCIOFLUSH);
1838 int open_terminal(const char *name, int mode) {
1841 if ((fd = open(name, mode)) < 0)
1844 if ((r = isatty(fd)) < 0) {
1845 close_nointr_nofail(fd);
1850 close_nointr_nofail(fd);
1857 int flush_fd(int fd) {
1858 struct pollfd pollfd;
1862 pollfd.events = POLLIN;
1869 if ((r = poll(&pollfd, 1, 0)) < 0) {
1880 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1885 if (errno == EAGAIN)
1896 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1897 int fd = -1, notify = -1, r, wd = -1;
1901 /* We use inotify to be notified when the tty is closed. We
1902 * create the watch before checking if we can actually acquire
1903 * it, so that we don't lose any event.
1905 * Note: strictly speaking this actually watches for the
1906 * device being closed, it does *not* really watch whether a
1907 * tty loses its controlling process. However, unless some
1908 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1909 * its tty otherwise this will not become a problem. As long
1910 * as the administrator makes sure not configure any service
1911 * on the same tty as an untrusted user this should not be a
1912 * problem. (Which he probably should not do anyway.) */
1914 if (!fail && !force) {
1915 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1920 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1928 if ((r = flush_fd(notify)) < 0)
1931 /* We pass here O_NOCTTY only so that we can check the return
1932 * value TIOCSCTTY and have a reliable way to figure out if we
1933 * successfully became the controlling process of the tty */
1934 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1937 /* First, try to get the tty */
1938 r = ioctl(fd, TIOCSCTTY, force);
1940 /* Sometimes it makes sense to ignore TIOCSCTTY
1941 * returning EPERM, i.e. when very likely we already
1942 * are have this controlling terminal. */
1943 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1946 if (r < 0 && (force || fail || errno != EPERM)) {
1956 assert(notify >= 0);
1959 struct inotify_event e;
1962 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1976 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1984 /* We close the tty fd here since if the old session
1985 * ended our handle will be dead. It's important that
1986 * we do this after sleeping, so that we don't enter
1987 * an endless loop. */
1988 close_nointr_nofail(fd);
1992 close_nointr_nofail(notify);
1994 if ((r = reset_terminal(fd)) < 0)
1995 log_warning("Failed to reset terminal: %s", strerror(-r));
2001 close_nointr_nofail(fd);
2004 close_nointr_nofail(notify);
2009 int release_terminal(void) {
2011 struct sigaction sa_old, sa_new;
2013 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2016 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2017 * by our own TIOCNOTTY */
2020 sa_new.sa_handler = SIG_IGN;
2021 sa_new.sa_flags = SA_RESTART;
2022 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2024 if (ioctl(fd, TIOCNOTTY) < 0)
2027 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2029 close_nointr_nofail(fd);
2033 int sigaction_many(const struct sigaction *sa, ...) {
2038 while ((sig = va_arg(ap, int)) > 0)
2039 if (sigaction(sig, sa, NULL) < 0)
2046 int ignore_signals(int sig, ...) {
2047 struct sigaction sa;
2052 sa.sa_handler = SIG_IGN;
2053 sa.sa_flags = SA_RESTART;
2055 if (sigaction(sig, &sa, NULL) < 0)
2059 while ((sig = va_arg(ap, int)) > 0)
2060 if (sigaction(sig, &sa, NULL) < 0)
2067 int default_signals(int sig, ...) {
2068 struct sigaction sa;
2073 sa.sa_handler = SIG_DFL;
2074 sa.sa_flags = SA_RESTART;
2076 if (sigaction(sig, &sa, NULL) < 0)
2080 while ((sig = va_arg(ap, int)) > 0)
2081 if (sigaction(sig, &sa, NULL) < 0)
2088 int close_pipe(int p[]) {
2094 a = close_nointr(p[0]);
2099 b = close_nointr(p[1]);
2103 return a < 0 ? a : b;
2106 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2115 while (nbytes > 0) {
2118 if ((k = read(fd, p, nbytes)) <= 0) {
2120 if (k < 0 && errno == EINTR)
2123 if (k < 0 && errno == EAGAIN && do_poll) {
2124 struct pollfd pollfd;
2128 pollfd.events = POLLIN;
2130 if (poll(&pollfd, 1, -1) < 0) {
2134 return n > 0 ? n : -errno;
2137 if (pollfd.revents != POLLIN)
2138 return n > 0 ? n : -EIO;
2143 return n > 0 ? n : (k < 0 ? -errno : 0);
2154 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2163 while (nbytes > 0) {
2166 if ((k = write(fd, p, nbytes)) <= 0) {
2168 if (k < 0 && errno == EINTR)
2171 if (k < 0 && errno == EAGAIN && do_poll) {
2172 struct pollfd pollfd;
2176 pollfd.events = POLLOUT;
2178 if (poll(&pollfd, 1, -1) < 0) {
2182 return n > 0 ? n : -errno;
2185 if (pollfd.revents != POLLOUT)
2186 return n > 0 ? n : -EIO;
2191 return n > 0 ? n : (k < 0 ? -errno : 0);
2202 int path_is_mount_point(const char *t) {
2206 if (lstat(t, &a) < 0) {
2208 if (errno == ENOENT)
2214 if (!(copy = strdup(t)))
2217 if (lstat(dirname(copy), &b) < 0) {
2224 return a.st_dev != b.st_dev;
2227 int parse_usec(const char *t, usec_t *usec) {
2228 static const struct {
2232 { "sec", USEC_PER_SEC },
2233 { "s", USEC_PER_SEC },
2234 { "min", USEC_PER_MINUTE },
2235 { "hr", USEC_PER_HOUR },
2236 { "h", USEC_PER_HOUR },
2237 { "d", USEC_PER_DAY },
2238 { "w", USEC_PER_WEEK },
2239 { "msec", USEC_PER_MSEC },
2240 { "ms", USEC_PER_MSEC },
2241 { "m", USEC_PER_MINUTE },
2244 { "", USEC_PER_SEC },
2260 l = strtoll(p, &e, 10);
2271 e += strspn(e, WHITESPACE);
2273 for (i = 0; i < ELEMENTSOF(table); i++)
2274 if (startswith(e, table[i].suffix)) {
2275 r += (usec_t) l * table[i].usec;
2276 p = e + strlen(table[i].suffix);
2280 if (i >= ELEMENTSOF(table))
2290 int make_stdio(int fd) {
2295 r = dup2(fd, STDIN_FILENO);
2296 s = dup2(fd, STDOUT_FILENO);
2297 t = dup2(fd, STDERR_FILENO);
2300 close_nointr_nofail(fd);
2302 if (r < 0 || s < 0 || t < 0)
2308 bool is_clean_exit(int code, int status) {
2310 if (code == CLD_EXITED)
2313 /* If a daemon does not implement handlers for some of the
2314 * signals that's not considered an unclean shutdown */
2315 if (code == CLD_KILLED)
2319 status == SIGTERM ||
2325 bool is_device_path(const char *path) {
2327 /* Returns true on paths that refer to a device, either in
2328 * sysfs or in /dev */
2331 path_startswith(path, "/dev/") ||
2332 path_startswith(path, "/sys/");
2335 int dir_is_empty(const char *path) {
2338 struct dirent buf, *de;
2340 if (!(d = opendir(path)))
2344 if ((r = readdir_r(d, &buf, &de)) > 0) {
2354 if (!ignore_file(de->d_name)) {
2364 unsigned long long random_ull(void) {
2369 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2372 r = loop_read(fd, &ull, sizeof(ull), true);
2373 close_nointr_nofail(fd);
2375 if (r != sizeof(ull))
2381 return random() * RAND_MAX + random();
2384 void rename_process(const char name[8]) {
2387 prctl(PR_SET_NAME, name);
2389 /* This is a like a poor man's setproctitle(). The string
2390 * passed should fit in 7 chars (i.e. the length of
2393 if (program_invocation_name)
2394 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2397 void sigset_add_many(sigset_t *ss, ...) {
2404 while ((sig = va_arg(ap, int)) > 0)
2405 assert_se(sigaddset(ss, sig) == 0);
2409 char* gethostname_malloc(void) {
2412 assert_se(uname(&u) >= 0);
2415 return strdup(u.nodename);
2417 return strdup(u.sysname);
2420 int getmachineid_malloc(char **b) {
2425 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2432 char* getlogname_malloc(void) {
2436 struct passwd pwbuf, *pw = NULL;
2439 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2444 /* Shortcut things to avoid NSS lookups */
2446 return strdup("root");
2448 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2451 if (!(buf = malloc(bufsize)))
2454 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2455 name = strdup(pw->pw_name);
2462 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2468 int getttyname_malloc(char **r) {
2469 char path[PATH_MAX], *p, *c;
2473 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2479 if (startswith(path, "/dev/"))
2482 if (!(c = strdup(p)))
2489 static int rm_rf_children(int fd, bool only_dirs) {
2495 /* This returns the first error we run into, but nevertheless
2498 if (!(d = fdopendir(fd))) {
2499 close_nointr_nofail(fd);
2504 struct dirent buf, *de;
2508 if ((r = readdir_r(d, &buf, &de)) != 0) {
2517 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2520 if (de->d_type == DT_UNKNOWN) {
2523 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2529 is_dir = S_ISDIR(st.st_mode);
2531 is_dir = de->d_type == DT_DIR;
2536 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2542 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2547 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2551 } else if (!only_dirs) {
2553 if (unlinkat(fd, de->d_name, 0) < 0) {
2565 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2571 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2573 if (errno != ENOTDIR)
2576 if (delete_root && !only_dirs)
2577 if (unlink(path) < 0)
2583 r = rm_rf_children(fd, only_dirs);
2586 if (rmdir(path) < 0) {
2594 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2597 /* Under the assumption that we are running privileged we
2598 * first change the access mode and only then hand out
2599 * ownership to avoid a window where access is too open. */
2601 if (chmod(path, mode) < 0)
2604 if (chown(path, uid, gid) < 0)
2610 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2614 /* Allocates the cpuset in the right size */
2617 if (!(r = CPU_ALLOC(n)))
2620 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2621 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2631 if (errno != EINVAL)
2638 void status_vprintf(const char *format, va_list ap) {
2644 /* This independent of logging, as status messages are
2645 * optional and go exclusively to the console. */
2647 if (vasprintf(&s, format, ap) < 0)
2650 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2653 write(fd, s, strlen(s));
2659 close_nointr_nofail(fd);
2662 void status_printf(const char *format, ...) {
2667 va_start(ap, format);
2668 status_vprintf(format, ap);
2672 void status_welcome(void) {
2674 #if defined(TARGET_FEDORA)
2677 if (read_one_line_file("/etc/system-release", &r) < 0)
2682 /* This tries to mimic the color magic the old Red Hat sysinit
2685 if (startswith(r, "Red Hat"))
2686 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2687 else if (startswith(r, "Fedora"))
2688 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2690 status_printf("Welcome to %s!\n", r);
2694 #elif defined(TARGET_SUSE)
2697 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2702 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2705 #warning "You probably should add a welcome text logic here."
2709 char *replace_env(const char *format, char **env) {
2716 const char *e, *word = format;
2721 for (e = format; *e; e ++) {
2732 if (!(k = strnappend(r, word, e-word-1)))
2741 } else if (*e == '$') {
2742 if (!(k = strnappend(r, word, e-word)))
2758 if ((t = strv_env_get_with_length(env, word+2, e-word-2))) {
2759 if (!(k = strappend(r, t)))
2774 if (!(k = strnappend(r, word, e-word)))
2785 char **replace_env_argv(char **argv, char **env) {
2789 if (!(r = new(char*, strv_length(argv)+1)))
2792 STRV_FOREACH(i, argv) {
2793 if (!(r[k++] = replace_env(*i, env))) {
2804 static __thread int parsed_columns = 0;
2807 if (parsed_columns > 0)
2808 return parsed_columns;
2810 if ((e = getenv("COLUMNS")))
2811 parsed_columns = atoi(e);
2813 if (parsed_columns <= 0) {
2817 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
2818 parsed_columns = ws.ws_col;
2821 if (parsed_columns <= 0)
2822 parsed_columns = 80;
2824 return parsed_columns;
2827 int running_in_chroot(void) {
2833 /* Only works as root */
2835 if (stat("/proc/1/root", &a) < 0)
2838 if (stat("/", &b) < 0)
2842 a.st_dev != b.st_dev ||
2843 a.st_ino != b.st_ino;
2846 static const char *const ioprio_class_table[] = {
2847 [IOPRIO_CLASS_NONE] = "none",
2848 [IOPRIO_CLASS_RT] = "realtime",
2849 [IOPRIO_CLASS_BE] = "best-effort",
2850 [IOPRIO_CLASS_IDLE] = "idle"
2853 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2855 static const char *const sigchld_code_table[] = {
2856 [CLD_EXITED] = "exited",
2857 [CLD_KILLED] = "killed",
2858 [CLD_DUMPED] = "dumped",
2859 [CLD_TRAPPED] = "trapped",
2860 [CLD_STOPPED] = "stopped",
2861 [CLD_CONTINUED] = "continued",
2864 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2866 static const char *const log_facility_table[LOG_NFACILITIES] = {
2867 [LOG_FAC(LOG_KERN)] = "kern",
2868 [LOG_FAC(LOG_USER)] = "user",
2869 [LOG_FAC(LOG_MAIL)] = "mail",
2870 [LOG_FAC(LOG_DAEMON)] = "daemon",
2871 [LOG_FAC(LOG_AUTH)] = "auth",
2872 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2873 [LOG_FAC(LOG_LPR)] = "lpr",
2874 [LOG_FAC(LOG_NEWS)] = "news",
2875 [LOG_FAC(LOG_UUCP)] = "uucp",
2876 [LOG_FAC(LOG_CRON)] = "cron",
2877 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2878 [LOG_FAC(LOG_FTP)] = "ftp",
2879 [LOG_FAC(LOG_LOCAL0)] = "local0",
2880 [LOG_FAC(LOG_LOCAL1)] = "local1",
2881 [LOG_FAC(LOG_LOCAL2)] = "local2",
2882 [LOG_FAC(LOG_LOCAL3)] = "local3",
2883 [LOG_FAC(LOG_LOCAL4)] = "local4",
2884 [LOG_FAC(LOG_LOCAL5)] = "local5",
2885 [LOG_FAC(LOG_LOCAL6)] = "local6",
2886 [LOG_FAC(LOG_LOCAL7)] = "local7"
2889 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2891 static const char *const log_level_table[] = {
2892 [LOG_EMERG] = "emerg",
2893 [LOG_ALERT] = "alert",
2894 [LOG_CRIT] = "crit",
2896 [LOG_WARNING] = "warning",
2897 [LOG_NOTICE] = "notice",
2898 [LOG_INFO] = "info",
2899 [LOG_DEBUG] = "debug"
2902 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2904 static const char* const sched_policy_table[] = {
2905 [SCHED_OTHER] = "other",
2906 [SCHED_BATCH] = "batch",
2907 [SCHED_IDLE] = "idle",
2908 [SCHED_FIFO] = "fifo",
2912 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2914 static const char* const rlimit_table[] = {
2915 [RLIMIT_CPU] = "LimitCPU",
2916 [RLIMIT_FSIZE] = "LimitFSIZE",
2917 [RLIMIT_DATA] = "LimitDATA",
2918 [RLIMIT_STACK] = "LimitSTACK",
2919 [RLIMIT_CORE] = "LimitCORE",
2920 [RLIMIT_RSS] = "LimitRSS",
2921 [RLIMIT_NOFILE] = "LimitNOFILE",
2922 [RLIMIT_AS] = "LimitAS",
2923 [RLIMIT_NPROC] = "LimitNPROC",
2924 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2925 [RLIMIT_LOCKS] = "LimitLOCKS",
2926 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2927 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2928 [RLIMIT_NICE] = "LimitNICE",
2929 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2930 [RLIMIT_RTTIME] = "LimitRTTIME"
2933 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2935 static const char* const ip_tos_table[] = {
2936 [IPTOS_LOWDELAY] = "low-delay",
2937 [IPTOS_THROUGHPUT] = "throughput",
2938 [IPTOS_RELIABILITY] = "reliability",
2939 [IPTOS_LOWCOST] = "low-cost",
2942 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
2944 static const char *const signal_table[] = {
2960 [SIGSTKFLT] = "STKFLT",
2970 [SIGVTALRM] = "VTALRM",
2972 [SIGWINCH] = "WINCH",
2978 DEFINE_STRING_TABLE_LOOKUP(signal, int);