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>
60 bool streq_ptr(const char *a, const char *b) {
62 /* Like streq(), but tries to make sense of NULL pointers */
73 usec_t now(clockid_t clock_id) {
76 assert_se(clock_gettime(clock_id, &ts) == 0);
78 return timespec_load(&ts);
81 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
84 ts->realtime = now(CLOCK_REALTIME);
85 ts->monotonic = now(CLOCK_MONOTONIC);
90 usec_t timespec_load(const struct timespec *ts) {
94 (usec_t) ts->tv_sec * USEC_PER_SEC +
95 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
98 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
101 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
102 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
107 usec_t timeval_load(const struct timeval *tv) {
111 (usec_t) tv->tv_sec * USEC_PER_SEC +
112 (usec_t) tv->tv_usec;
115 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
118 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
119 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
124 bool endswith(const char *s, const char *postfix) {
131 pl = strlen(postfix);
139 return memcmp(s + sl - pl, postfix, pl) == 0;
142 bool startswith(const char *s, const char *prefix) {
157 return memcmp(s, prefix, pl) == 0;
160 bool startswith_no_case(const char *s, const char *prefix) {
176 for(i = 0; i < pl; ++i) {
177 if (tolower(s[i]) != tolower(prefix[i]))
184 bool first_word(const char *s, const char *word) {
199 if (memcmp(s, word, wl) != 0)
203 strchr(WHITESPACE, s[wl]);
206 int close_nointr(int fd) {
212 if ((r = close(fd)) >= 0)
220 void close_nointr_nofail(int fd) {
221 int saved_errno = errno;
223 /* like close_nointr() but cannot fail, and guarantees errno
226 assert_se(close_nointr(fd) == 0);
231 void close_many(const int fds[], unsigned n_fd) {
234 for (i = 0; i < n_fd; i++)
235 close_nointr_nofail(fds[i]);
238 int parse_boolean(const char *v) {
241 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
243 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
249 int parse_pid(const char *s, pid_t* ret_pid) {
257 if ((r = safe_atolu(s, &ul)) < 0)
262 if ((unsigned long) pid != ul)
272 int safe_atou(const char *s, unsigned *ret_u) {
280 l = strtoul(s, &x, 0);
282 if (!x || *x || errno)
283 return errno ? -errno : -EINVAL;
285 if ((unsigned long) (unsigned) l != l)
288 *ret_u = (unsigned) l;
292 int safe_atoi(const char *s, int *ret_i) {
300 l = strtol(s, &x, 0);
302 if (!x || *x || errno)
303 return errno ? -errno : -EINVAL;
305 if ((long) (int) l != l)
312 int safe_atollu(const char *s, long long unsigned *ret_llu) {
314 unsigned long long l;
320 l = strtoull(s, &x, 0);
322 if (!x || *x || errno)
323 return errno ? -errno : -EINVAL;
329 int safe_atolli(const char *s, long long int *ret_lli) {
337 l = strtoll(s, &x, 0);
339 if (!x || *x || errno)
340 return errno ? -errno : -EINVAL;
346 /* Split a string into words. */
347 char *split(const char *c, size_t *l, const char *separator, char **state) {
350 current = *state ? *state : (char*) c;
352 if (!*current || *c == 0)
355 current += strspn(current, separator);
356 *l = strcspn(current, separator);
359 return (char*) current;
362 /* Split a string into words, but consider strings enclosed in '' and
363 * "" as words even if they include spaces. */
364 char *split_quoted(const char *c, size_t *l, char **state) {
366 bool escaped = false;
368 current = *state ? *state : (char*) c;
370 if (!*current || *c == 0)
373 current += strspn(current, WHITESPACE);
375 if (*current == '\'') {
378 for (e = current; *e; e++) {
388 *state = *e == 0 ? e : e+1;
389 } else if (*current == '\"') {
392 for (e = current; *e; e++) {
402 *state = *e == 0 ? e : e+1;
404 for (e = current; *e; e++) {
409 else if (strchr(WHITESPACE, *e))
416 return (char*) current;
419 char **split_path_and_make_absolute(const char *p) {
423 if (!(l = strv_split(p, ":")))
426 if (!strv_path_make_absolute_cwd(l)) {
434 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
437 char fn[132], line[256], *p;
443 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
444 fn[sizeof(fn)-1] = 0;
446 if (!(f = fopen(fn, "r")))
449 if (!(fgets(line, sizeof(line), f))) {
457 /* Let's skip the pid and comm fields. The latter is enclosed
458 * in () but does not escape any () in its value, so let's
459 * skip over it manually */
461 if (!(p = strrchr(line, ')')))
472 if ((long unsigned) (pid_t) ppid != ppid)
475 *_ppid = (pid_t) ppid;
480 int write_one_line_file(const char *fn, const char *line) {
487 if (!(f = fopen(fn, "we")))
490 if (fputs(line, f) < 0) {
501 int read_one_line_file(const char *fn, char **line) {
509 if (!(f = fopen(fn, "re")))
512 if (!(fgets(t, sizeof(t), f))) {
517 if (!(c = strdup(t))) {
530 char *truncate_nl(char *s) {
533 s[strcspn(s, NEWLINE)] = 0;
537 int get_process_name(pid_t pid, char **name) {
544 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
547 r = read_one_line_file(p, name);
557 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
565 assert(max_length > 0);
568 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
577 if (!(r = new(char, max_length))) {
584 while ((c = getc(f)) != EOF) {
606 size_t n = MIN(left-1, 3U);
614 /* Kernel threads have no argv[] */
621 if ((h = get_process_name(pid, &t)) < 0)
624 h = asprintf(&r, "[%s]", t);
635 char *strnappend(const char *s, const char *suffix, size_t b) {
643 return strndup(suffix, b);
653 if (!(r = new(char, a+b+1)))
657 memcpy(r+a, suffix, b);
663 char *strappend(const char *s, const char *suffix) {
664 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
667 int readlink_malloc(const char *p, char **r) {
677 if (!(c = new(char, l)))
680 if ((n = readlink(p, c, l-1)) < 0) {
686 if ((size_t) n < l-1) {
697 int readlink_and_make_absolute(const char *p, char **r) {
704 if ((j = readlink_malloc(p, &target)) < 0)
707 k = file_in_same_dir(p, target);
717 int parent_of_path(const char *path, char **_r) {
718 const char *e, *a = NULL, *b = NULL, *p;
728 for (e = path; *e; e++) {
730 if (!slash && *e == '/') {
734 } else if (slash && *e != '/')
749 r = strndup(path, p-path);
759 char *file_name_from_path(const char *p) {
764 if ((r = strrchr(p, '/')))
770 bool path_is_absolute(const char *p) {
776 bool is_path(const char *p) {
778 return !!strchr(p, '/');
781 char *path_make_absolute(const char *p, const char *prefix) {
786 /* Makes every item in the list an absolute path by prepending
787 * the prefix, if specified and necessary */
789 if (path_is_absolute(p) || !prefix)
792 if (asprintf(&r, "%s/%s", prefix, p) < 0)
798 char *path_make_absolute_cwd(const char *p) {
803 /* Similar to path_make_absolute(), but prefixes with the
804 * current working directory. */
806 if (path_is_absolute(p))
809 if (!(cwd = get_current_dir_name()))
812 r = path_make_absolute(p, cwd);
818 char **strv_path_make_absolute_cwd(char **l) {
821 /* Goes through every item in the string list and makes it
822 * absolute. This works in place and won't rollback any
823 * changes on failure. */
828 if (!(t = path_make_absolute_cwd(*s)))
838 char **strv_path_canonicalize(char **l) {
846 /* Goes through every item in the string list and canonicalize
847 * the path. This works in place and won't rollback any
848 * changes on failure. */
853 t = path_make_absolute_cwd(*s);
862 u = canonicalize_file_name(t);
866 if (errno == ENOMEM || !errno)
883 int reset_all_signal_handlers(void) {
886 for (sig = 1; sig < _NSIG; sig++) {
889 if (sig == SIGKILL || sig == SIGSTOP)
893 sa.sa_handler = SIG_DFL;
894 sa.sa_flags = SA_RESTART;
896 /* On Linux the first two RT signals are reserved by
897 * glibc, and sigaction() will return EINVAL for them. */
898 if ((sigaction(sig, &sa, NULL) < 0))
906 char *strstrip(char *s) {
909 /* Drops trailing whitespace. Modifies the string in
910 * place. Returns pointer to first non-space character */
912 s += strspn(s, WHITESPACE);
915 if (!strchr(WHITESPACE, *e))
926 char *delete_chars(char *s, const char *bad) {
929 /* Drops all whitespace, regardless where in the string */
931 for (f = s, t = s; *f; f++) {
943 char *file_in_same_dir(const char *path, const char *filename) {
950 /* This removes the last component of path and appends
951 * filename, unless the latter is absolute anyway or the
954 if (path_is_absolute(filename))
955 return strdup(filename);
957 if (!(e = strrchr(path, '/')))
958 return strdup(filename);
960 k = strlen(filename);
961 if (!(r = new(char, e-path+1+k+1)))
964 memcpy(r, path, e-path+1);
965 memcpy(r+(e-path)+1, filename, k+1);
970 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
973 if (label_mkdir(path, mode) >= 0)
974 if (chmod_and_chown(path, mode, uid, gid) < 0)
977 if (lstat(path, &st) < 0)
980 if ((st.st_mode & 0777) != mode ||
983 !S_ISDIR(st.st_mode)) {
992 int mkdir_parents(const char *path, mode_t mode) {
997 /* Creates every parent directory in the path except the last
1000 p = path + strspn(path, "/");
1005 e = p + strcspn(p, "/");
1006 p = e + strspn(e, "/");
1008 /* Is this the last component? If so, then we're
1013 if (!(t = strndup(path, e - path)))
1016 r = label_mkdir(t, mode);
1019 if (r < 0 && errno != EEXIST)
1024 int mkdir_p(const char *path, mode_t mode) {
1029 if ((r = mkdir_parents(path, mode)) < 0)
1032 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1038 int rmdir_parents(const char *path, const char *stop) {
1047 /* Skip trailing slashes */
1048 while (l > 0 && path[l-1] == '/')
1054 /* Skip last component */
1055 while (l > 0 && path[l-1] != '/')
1058 /* Skip trailing slashes */
1059 while (l > 0 && path[l-1] == '/')
1065 if (!(t = strndup(path, l)))
1068 if (path_startswith(stop, t)) {
1077 if (errno != ENOENT)
1085 char hexchar(int x) {
1086 static const char table[16] = "0123456789abcdef";
1088 return table[x & 15];
1091 int unhexchar(char c) {
1093 if (c >= '0' && c <= '9')
1096 if (c >= 'a' && c <= 'f')
1097 return c - 'a' + 10;
1099 if (c >= 'A' && c <= 'F')
1100 return c - 'A' + 10;
1105 char octchar(int x) {
1106 return '0' + (x & 7);
1109 int unoctchar(char c) {
1111 if (c >= '0' && c <= '7')
1117 char decchar(int x) {
1118 return '0' + (x % 10);
1121 int undecchar(char c) {
1123 if (c >= '0' && c <= '9')
1129 char *cescape(const char *s) {
1135 /* Does C style string escaping. */
1137 if (!(r = new(char, strlen(s)*4 + 1)))
1140 for (f = s, t = r; *f; f++)
1186 /* For special chars we prefer octal over
1187 * hexadecimal encoding, simply because glib's
1188 * g_strescape() does the same */
1189 if ((*f < ' ') || (*f >= 127)) {
1191 *(t++) = octchar((unsigned char) *f >> 6);
1192 *(t++) = octchar((unsigned char) *f >> 3);
1193 *(t++) = octchar((unsigned char) *f);
1204 char *cunescape_length(const char *s, size_t length) {
1210 /* Undoes C style string escaping */
1212 if (!(r = new(char, length+1)))
1215 for (f = s, t = r; f < s + length; f++) {
1258 /* This is an extension of the XDG syntax files */
1263 /* hexadecimal encoding */
1266 if ((a = unhexchar(f[1])) < 0 ||
1267 (b = unhexchar(f[2])) < 0) {
1268 /* Invalid escape code, let's take it literal then */
1272 *(t++) = (char) ((a << 4) | b);
1287 /* octal encoding */
1290 if ((a = unoctchar(f[0])) < 0 ||
1291 (b = unoctchar(f[1])) < 0 ||
1292 (c = unoctchar(f[2])) < 0) {
1293 /* Invalid escape code, let's take it literal then */
1297 *(t++) = (char) ((a << 6) | (b << 3) | c);
1305 /* premature end of string.*/
1310 /* Invalid escape code, let's take it literal then */
1322 char *cunescape(const char *s) {
1323 return cunescape_length(s, strlen(s));
1326 char *xescape(const char *s, const char *bad) {
1330 /* Escapes all chars in bad, in addition to \ and all special
1331 * chars, in \xFF style escaping. May be reversed with
1334 if (!(r = new(char, strlen(s)*4+1)))
1337 for (f = s, t = r; *f; f++) {
1339 if ((*f < ' ') || (*f >= 127) ||
1340 (*f == '\\') || strchr(bad, *f)) {
1343 *(t++) = hexchar(*f >> 4);
1344 *(t++) = hexchar(*f);
1354 char *bus_path_escape(const char *s) {
1360 /* Escapes all chars that D-Bus' object path cannot deal
1361 * with. Can be reverse with bus_path_unescape() */
1363 if (!(r = new(char, strlen(s)*3+1)))
1366 for (f = s, t = r; *f; f++) {
1368 if (!(*f >= 'A' && *f <= 'Z') &&
1369 !(*f >= 'a' && *f <= 'z') &&
1370 !(*f >= '0' && *f <= '9')) {
1372 *(t++) = hexchar(*f >> 4);
1373 *(t++) = hexchar(*f);
1383 char *bus_path_unescape(const char *f) {
1388 if (!(r = strdup(f)))
1391 for (t = r; *f; f++) {
1396 if ((a = unhexchar(f[1])) < 0 ||
1397 (b = unhexchar(f[2])) < 0) {
1398 /* Invalid escape code, let's take it literal then */
1401 *(t++) = (char) ((a << 4) | b);
1413 char *path_kill_slashes(char *path) {
1417 /* Removes redundant inner and trailing slashes. Modifies the
1418 * passed string in-place.
1420 * ///foo///bar/ becomes /foo/bar
1423 for (f = path, t = path; *f; f++) {
1438 /* Special rule, if we are talking of the root directory, a
1439 trailing slash is good */
1441 if (t == path && slash)
1448 bool path_startswith(const char *path, const char *prefix) {
1452 if ((path[0] == '/') != (prefix[0] == '/'))
1458 path += strspn(path, "/");
1459 prefix += strspn(prefix, "/");
1467 a = strcspn(path, "/");
1468 b = strcspn(prefix, "/");
1473 if (memcmp(path, prefix, a) != 0)
1481 bool path_equal(const char *a, const char *b) {
1485 if ((a[0] == '/') != (b[0] == '/'))
1491 a += strspn(a, "/");
1492 b += strspn(b, "/");
1494 if (*a == 0 && *b == 0)
1497 if (*a == 0 || *b == 0)
1500 j = strcspn(a, "/");
1501 k = strcspn(b, "/");
1506 if (memcmp(a, b, j) != 0)
1514 char *ascii_strlower(char *t) {
1519 for (p = t; *p; p++)
1520 if (*p >= 'A' && *p <= 'Z')
1521 *p = *p - 'A' + 'a';
1526 bool ignore_file(const char *filename) {
1530 filename[0] == '.' ||
1531 streq(filename, "lost+found") ||
1532 endswith(filename, "~") ||
1533 endswith(filename, ".rpmnew") ||
1534 endswith(filename, ".rpmsave") ||
1535 endswith(filename, ".rpmorig") ||
1536 endswith(filename, ".dpkg-old") ||
1537 endswith(filename, ".dpkg-new") ||
1538 endswith(filename, ".swp");
1541 int fd_nonblock(int fd, bool nonblock) {
1546 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1550 flags |= O_NONBLOCK;
1552 flags &= ~O_NONBLOCK;
1554 if (fcntl(fd, F_SETFL, flags) < 0)
1560 int fd_cloexec(int fd, bool cloexec) {
1565 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1569 flags |= FD_CLOEXEC;
1571 flags &= ~FD_CLOEXEC;
1573 if (fcntl(fd, F_SETFD, flags) < 0)
1579 int close_all_fds(const int except[], unsigned n_except) {
1584 if (!(d = opendir("/proc/self/fd")))
1587 while ((de = readdir(d))) {
1590 if (ignore_file(de->d_name))
1593 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1607 for (i = 0; i < n_except; i++)
1608 if (except[i] == fd) {
1617 if ((r = close_nointr(fd)) < 0) {
1618 /* Valgrind has its own FD and doesn't want to have it closed */
1631 bool chars_intersect(const char *a, const char *b) {
1634 /* Returns true if any of the chars in a are in b. */
1635 for (p = a; *p; p++)
1642 char *format_timestamp(char *buf, size_t l, usec_t t) {
1652 sec = (time_t) (t / USEC_PER_SEC);
1654 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1660 char *format_timespan(char *buf, size_t l, usec_t t) {
1661 static const struct {
1665 { "w", USEC_PER_WEEK },
1666 { "d", USEC_PER_DAY },
1667 { "h", USEC_PER_HOUR },
1668 { "min", USEC_PER_MINUTE },
1669 { "s", USEC_PER_SEC },
1670 { "ms", USEC_PER_MSEC },
1680 if (t == (usec_t) -1)
1684 snprintf(p, l, "0");
1689 /* The result of this function can be parsed with parse_usec */
1691 for (i = 0; i < ELEMENTSOF(table); i++) {
1695 if (t < table[i].usec)
1701 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1702 n = MIN((size_t) k, l);
1715 bool fstype_is_network(const char *fstype) {
1716 static const char * const table[] = {
1728 for (i = 0; i < ELEMENTSOF(table); i++)
1729 if (streq(table[i], fstype))
1738 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1743 TIOCL_GETKMSGREDIRECT,
1747 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1750 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1753 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1756 close_nointr_nofail(r);
1760 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1761 struct termios old_termios, new_termios;
1768 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1769 new_termios = old_termios;
1771 new_termios.c_lflag &= ~ICANON;
1772 new_termios.c_cc[VMIN] = 1;
1773 new_termios.c_cc[VTIME] = 0;
1775 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1778 k = fread(&c, 1, 1, f);
1780 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1786 *need_nl = c != '\n';
1793 if (!(fgets(line, sizeof(line), f)))
1798 if (strlen(line) != 1)
1808 int ask(char *ret, const char *replies, const char *text, ...) {
1817 bool need_nl = true;
1819 fputs("\x1B[1m", stdout);
1825 fputs("\x1B[0m", stdout);
1829 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1831 if (r == -EBADMSG) {
1832 puts("Bad input, please try again.");
1843 if (strchr(replies, c)) {
1848 puts("Read unexpected character, please try again.");
1852 int reset_terminal(int fd) {
1853 struct termios termios;
1857 /* Set terminal to some sane defaults */
1861 /* First, unlock termios */
1863 ioctl(fd, TIOCSLCKTRMIOS, &termios);
1865 /* Disable exclusive mode, just in case */
1866 ioctl(fd, TIOCNXCL);
1868 /* Enable console unicode mode */
1870 ioctl(fd, KDSKBMODE, &arg);
1872 if (tcgetattr(fd, &termios) < 0) {
1877 /* We only reset the stuff that matters to the software. How
1878 * hardware is set up we don't touch assuming that somebody
1879 * else will do that for us */
1881 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1882 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1883 termios.c_oflag |= ONLCR;
1884 termios.c_cflag |= CREAD;
1885 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1887 termios.c_cc[VINTR] = 03; /* ^C */
1888 termios.c_cc[VQUIT] = 034; /* ^\ */
1889 termios.c_cc[VERASE] = 0177;
1890 termios.c_cc[VKILL] = 025; /* ^X */
1891 termios.c_cc[VEOF] = 04; /* ^D */
1892 termios.c_cc[VSTART] = 021; /* ^Q */
1893 termios.c_cc[VSTOP] = 023; /* ^S */
1894 termios.c_cc[VSUSP] = 032; /* ^Z */
1895 termios.c_cc[VLNEXT] = 026; /* ^V */
1896 termios.c_cc[VWERASE] = 027; /* ^W */
1897 termios.c_cc[VREPRINT] = 022; /* ^R */
1898 termios.c_cc[VEOL] = 0;
1899 termios.c_cc[VEOL2] = 0;
1901 termios.c_cc[VTIME] = 0;
1902 termios.c_cc[VMIN] = 1;
1904 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1908 /* Just in case, flush all crap out */
1909 tcflush(fd, TCIOFLUSH);
1914 int open_terminal(const char *name, int mode) {
1917 if ((fd = open(name, mode)) < 0)
1920 if ((r = isatty(fd)) < 0) {
1921 close_nointr_nofail(fd);
1926 close_nointr_nofail(fd);
1933 int flush_fd(int fd) {
1934 struct pollfd pollfd;
1938 pollfd.events = POLLIN;
1945 if ((r = poll(&pollfd, 1, 0)) < 0) {
1956 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1961 if (errno == EAGAIN)
1972 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1973 int fd = -1, notify = -1, r, wd = -1;
1977 /* We use inotify to be notified when the tty is closed. We
1978 * create the watch before checking if we can actually acquire
1979 * it, so that we don't lose any event.
1981 * Note: strictly speaking this actually watches for the
1982 * device being closed, it does *not* really watch whether a
1983 * tty loses its controlling process. However, unless some
1984 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1985 * its tty otherwise this will not become a problem. As long
1986 * as the administrator makes sure not configure any service
1987 * on the same tty as an untrusted user this should not be a
1988 * problem. (Which he probably should not do anyway.) */
1990 if (!fail && !force) {
1991 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1996 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2004 if ((r = flush_fd(notify)) < 0)
2007 /* We pass here O_NOCTTY only so that we can check the return
2008 * value TIOCSCTTY and have a reliable way to figure out if we
2009 * successfully became the controlling process of the tty */
2010 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2013 /* First, try to get the tty */
2014 r = ioctl(fd, TIOCSCTTY, force);
2016 /* Sometimes it makes sense to ignore TIOCSCTTY
2017 * returning EPERM, i.e. when very likely we already
2018 * are have this controlling terminal. */
2019 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2022 if (r < 0 && (force || fail || errno != EPERM)) {
2032 assert(notify >= 0);
2035 struct inotify_event e;
2038 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
2052 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
2060 /* We close the tty fd here since if the old session
2061 * ended our handle will be dead. It's important that
2062 * we do this after sleeping, so that we don't enter
2063 * an endless loop. */
2064 close_nointr_nofail(fd);
2068 close_nointr_nofail(notify);
2070 if ((r = reset_terminal(fd)) < 0)
2071 log_warning("Failed to reset terminal: %s", strerror(-r));
2077 close_nointr_nofail(fd);
2080 close_nointr_nofail(notify);
2085 int release_terminal(void) {
2087 struct sigaction sa_old, sa_new;
2089 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2092 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2093 * by our own TIOCNOTTY */
2096 sa_new.sa_handler = SIG_IGN;
2097 sa_new.sa_flags = SA_RESTART;
2098 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2100 if (ioctl(fd, TIOCNOTTY) < 0)
2103 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2105 close_nointr_nofail(fd);
2109 int sigaction_many(const struct sigaction *sa, ...) {
2114 while ((sig = va_arg(ap, int)) > 0)
2115 if (sigaction(sig, sa, NULL) < 0)
2122 int ignore_signals(int sig, ...) {
2123 struct sigaction sa;
2128 sa.sa_handler = SIG_IGN;
2129 sa.sa_flags = SA_RESTART;
2131 if (sigaction(sig, &sa, NULL) < 0)
2135 while ((sig = va_arg(ap, int)) > 0)
2136 if (sigaction(sig, &sa, NULL) < 0)
2143 int default_signals(int sig, ...) {
2144 struct sigaction sa;
2149 sa.sa_handler = SIG_DFL;
2150 sa.sa_flags = SA_RESTART;
2152 if (sigaction(sig, &sa, NULL) < 0)
2156 while ((sig = va_arg(ap, int)) > 0)
2157 if (sigaction(sig, &sa, NULL) < 0)
2164 int close_pipe(int p[]) {
2170 a = close_nointr(p[0]);
2175 b = close_nointr(p[1]);
2179 return a < 0 ? a : b;
2182 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2191 while (nbytes > 0) {
2194 if ((k = read(fd, p, nbytes)) <= 0) {
2196 if (k < 0 && errno == EINTR)
2199 if (k < 0 && errno == EAGAIN && do_poll) {
2200 struct pollfd pollfd;
2204 pollfd.events = POLLIN;
2206 if (poll(&pollfd, 1, -1) < 0) {
2210 return n > 0 ? n : -errno;
2213 if (pollfd.revents != POLLIN)
2214 return n > 0 ? n : -EIO;
2219 return n > 0 ? n : (k < 0 ? -errno : 0);
2230 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2239 while (nbytes > 0) {
2242 if ((k = write(fd, p, nbytes)) <= 0) {
2244 if (k < 0 && errno == EINTR)
2247 if (k < 0 && errno == EAGAIN && do_poll) {
2248 struct pollfd pollfd;
2252 pollfd.events = POLLOUT;
2254 if (poll(&pollfd, 1, -1) < 0) {
2258 return n > 0 ? n : -errno;
2261 if (pollfd.revents != POLLOUT)
2262 return n > 0 ? n : -EIO;
2267 return n > 0 ? n : (k < 0 ? -errno : 0);
2278 int path_is_mount_point(const char *t) {
2283 if (lstat(t, &a) < 0) {
2284 if (errno == ENOENT)
2290 if ((r = parent_of_path(t, &parent)) < 0)
2293 r = lstat(parent, &b);
2299 return a.st_dev != b.st_dev;
2302 int parse_usec(const char *t, usec_t *usec) {
2303 static const struct {
2307 { "sec", USEC_PER_SEC },
2308 { "s", USEC_PER_SEC },
2309 { "min", USEC_PER_MINUTE },
2310 { "hr", USEC_PER_HOUR },
2311 { "h", USEC_PER_HOUR },
2312 { "d", USEC_PER_DAY },
2313 { "w", USEC_PER_WEEK },
2314 { "msec", USEC_PER_MSEC },
2315 { "ms", USEC_PER_MSEC },
2316 { "m", USEC_PER_MINUTE },
2319 { "", USEC_PER_SEC },
2335 l = strtoll(p, &e, 10);
2346 e += strspn(e, WHITESPACE);
2348 for (i = 0; i < ELEMENTSOF(table); i++)
2349 if (startswith(e, table[i].suffix)) {
2350 r += (usec_t) l * table[i].usec;
2351 p = e + strlen(table[i].suffix);
2355 if (i >= ELEMENTSOF(table))
2365 int make_stdio(int fd) {
2370 r = dup2(fd, STDIN_FILENO);
2371 s = dup2(fd, STDOUT_FILENO);
2372 t = dup2(fd, STDERR_FILENO);
2375 close_nointr_nofail(fd);
2377 if (r < 0 || s < 0 || t < 0)
2383 bool is_clean_exit(int code, int status) {
2385 if (code == CLD_EXITED)
2388 /* If a daemon does not implement handlers for some of the
2389 * signals that's not considered an unclean shutdown */
2390 if (code == CLD_KILLED)
2394 status == SIGTERM ||
2400 bool is_device_path(const char *path) {
2402 /* Returns true on paths that refer to a device, either in
2403 * sysfs or in /dev */
2406 path_startswith(path, "/dev/") ||
2407 path_startswith(path, "/sys/");
2410 int dir_is_empty(const char *path) {
2413 struct dirent buf, *de;
2415 if (!(d = opendir(path)))
2419 if ((r = readdir_r(d, &buf, &de)) > 0) {
2429 if (!ignore_file(de->d_name)) {
2439 unsigned long long random_ull(void) {
2444 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2447 r = loop_read(fd, &ull, sizeof(ull), true);
2448 close_nointr_nofail(fd);
2450 if (r != sizeof(ull))
2456 return random() * RAND_MAX + random();
2459 void rename_process(const char name[8]) {
2462 prctl(PR_SET_NAME, name);
2464 /* This is a like a poor man's setproctitle(). The string
2465 * passed should fit in 7 chars (i.e. the length of
2468 if (program_invocation_name)
2469 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2472 void sigset_add_many(sigset_t *ss, ...) {
2479 while ((sig = va_arg(ap, int)) > 0)
2480 assert_se(sigaddset(ss, sig) == 0);
2484 char* gethostname_malloc(void) {
2487 assert_se(uname(&u) >= 0);
2490 return strdup(u.nodename);
2492 return strdup(u.sysname);
2495 char* getlogname_malloc(void) {
2499 struct passwd pwbuf, *pw = NULL;
2502 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2507 /* Shortcut things to avoid NSS lookups */
2509 return strdup("root");
2511 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2514 if (!(buf = malloc(bufsize)))
2517 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2518 name = strdup(pw->pw_name);
2525 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2531 int getttyname_malloc(char **r) {
2532 char path[PATH_MAX], *p, *c;
2536 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2542 if (startswith(path, "/dev/"))
2545 if (!(c = strdup(p)))
2552 static int rm_rf_children(int fd, bool only_dirs) {
2558 /* This returns the first error we run into, but nevertheless
2561 if (!(d = fdopendir(fd))) {
2562 close_nointr_nofail(fd);
2564 return errno == ENOENT ? 0 : -errno;
2568 struct dirent buf, *de;
2572 if ((r = readdir_r(d, &buf, &de)) != 0) {
2581 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2584 if (de->d_type == DT_UNKNOWN) {
2587 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2588 if (ret == 0 && errno != ENOENT)
2593 is_dir = S_ISDIR(st.st_mode);
2595 is_dir = de->d_type == DT_DIR;
2600 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2601 if (ret == 0 && errno != ENOENT)
2606 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2611 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2612 if (ret == 0 && errno != ENOENT)
2615 } else if (!only_dirs) {
2617 if (unlinkat(fd, de->d_name, 0) < 0) {
2618 if (ret == 0 && errno != ENOENT)
2629 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2635 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2637 if (errno != ENOTDIR)
2640 if (delete_root && !only_dirs)
2641 if (unlink(path) < 0)
2647 r = rm_rf_children(fd, only_dirs);
2650 if (rmdir(path) < 0) {
2658 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2661 /* Under the assumption that we are running privileged we
2662 * first change the access mode and only then hand out
2663 * ownership to avoid a window where access is too open. */
2665 if (chmod(path, mode) < 0)
2668 if (chown(path, uid, gid) < 0)
2674 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2678 /* Allocates the cpuset in the right size */
2681 if (!(r = CPU_ALLOC(n)))
2684 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2685 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2695 if (errno != EINVAL)
2702 void status_vprintf(const char *format, va_list ap) {
2708 /* This independent of logging, as status messages are
2709 * optional and go exclusively to the console. */
2711 if (vasprintf(&s, format, ap) < 0)
2714 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2717 write(fd, s, strlen(s));
2723 close_nointr_nofail(fd);
2726 void status_printf(const char *format, ...) {
2731 va_start(ap, format);
2732 status_vprintf(format, ap);
2736 void status_welcome(void) {
2738 #if defined(TARGET_FEDORA)
2741 if (read_one_line_file("/etc/system-release", &r) < 0)
2746 /* This tries to mimic the color magic the old Red Hat sysinit
2749 if (startswith(r, "Red Hat"))
2750 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2751 else if (startswith(r, "Fedora"))
2752 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2754 status_printf("Welcome to %s!\n", r);
2758 #elif defined(TARGET_SUSE)
2761 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2766 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2769 #warning "You probably should add a welcome text logic here."
2773 char *replace_env(const char *format, char **env) {
2780 const char *e, *word = format;
2785 for (e = format; *e; e ++) {
2796 if (!(k = strnappend(r, word, e-word-1)))
2805 } else if (*e == '$') {
2806 if (!(k = strnappend(r, word, e-word)))
2822 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
2825 if (!(k = strappend(r, t)))
2838 if (!(k = strnappend(r, word, e-word)))
2849 char **replace_env_argv(char **argv, char **env) {
2851 unsigned k = 0, l = 0;
2853 l = strv_length(argv);
2855 if (!(r = new(char*, l+1)))
2858 STRV_FOREACH(i, argv) {
2860 /* If $FOO appears as single word, replace it by the split up variable */
2861 if ((*i)[0] == '$' && (*i)[1] != '{') {
2866 if ((e = strv_env_get(env, *i+1))) {
2868 if (!(m = strv_split_quoted(e))) {
2879 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
2888 memcpy(r + k, m, q * sizeof(char*));
2896 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
2897 if (!(r[k++] = replace_env(*i, env))) {
2908 static __thread int parsed_columns = 0;
2911 if (parsed_columns > 0)
2912 return parsed_columns;
2914 if ((e = getenv("COLUMNS")))
2915 parsed_columns = atoi(e);
2917 if (parsed_columns <= 0) {
2921 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
2922 parsed_columns = ws.ws_col;
2925 if (parsed_columns <= 0)
2926 parsed_columns = 80;
2928 return parsed_columns;
2931 int running_in_chroot(void) {
2937 /* Only works as root */
2939 if (stat("/proc/1/root", &a) < 0)
2942 if (stat("/", &b) < 0)
2946 a.st_dev != b.st_dev ||
2947 a.st_ino != b.st_ino;
2950 char *ellipsize(const char *s, unsigned length, unsigned percent) {
2955 assert(percent <= 100);
2956 assert(length >= 3);
2960 if (l <= 3 || l <= length)
2963 if (!(r = new0(char, length+1)))
2966 x = (length * percent) / 100;
2976 s + l - (length - x - 3),
2982 static const char *const ioprio_class_table[] = {
2983 [IOPRIO_CLASS_NONE] = "none",
2984 [IOPRIO_CLASS_RT] = "realtime",
2985 [IOPRIO_CLASS_BE] = "best-effort",
2986 [IOPRIO_CLASS_IDLE] = "idle"
2989 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2991 static const char *const sigchld_code_table[] = {
2992 [CLD_EXITED] = "exited",
2993 [CLD_KILLED] = "killed",
2994 [CLD_DUMPED] = "dumped",
2995 [CLD_TRAPPED] = "trapped",
2996 [CLD_STOPPED] = "stopped",
2997 [CLD_CONTINUED] = "continued",
3000 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3002 static const char *const log_facility_table[LOG_NFACILITIES] = {
3003 [LOG_FAC(LOG_KERN)] = "kern",
3004 [LOG_FAC(LOG_USER)] = "user",
3005 [LOG_FAC(LOG_MAIL)] = "mail",
3006 [LOG_FAC(LOG_DAEMON)] = "daemon",
3007 [LOG_FAC(LOG_AUTH)] = "auth",
3008 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3009 [LOG_FAC(LOG_LPR)] = "lpr",
3010 [LOG_FAC(LOG_NEWS)] = "news",
3011 [LOG_FAC(LOG_UUCP)] = "uucp",
3012 [LOG_FAC(LOG_CRON)] = "cron",
3013 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3014 [LOG_FAC(LOG_FTP)] = "ftp",
3015 [LOG_FAC(LOG_LOCAL0)] = "local0",
3016 [LOG_FAC(LOG_LOCAL1)] = "local1",
3017 [LOG_FAC(LOG_LOCAL2)] = "local2",
3018 [LOG_FAC(LOG_LOCAL3)] = "local3",
3019 [LOG_FAC(LOG_LOCAL4)] = "local4",
3020 [LOG_FAC(LOG_LOCAL5)] = "local5",
3021 [LOG_FAC(LOG_LOCAL6)] = "local6",
3022 [LOG_FAC(LOG_LOCAL7)] = "local7"
3025 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3027 static const char *const log_level_table[] = {
3028 [LOG_EMERG] = "emerg",
3029 [LOG_ALERT] = "alert",
3030 [LOG_CRIT] = "crit",
3032 [LOG_WARNING] = "warning",
3033 [LOG_NOTICE] = "notice",
3034 [LOG_INFO] = "info",
3035 [LOG_DEBUG] = "debug"
3038 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3040 static const char* const sched_policy_table[] = {
3041 [SCHED_OTHER] = "other",
3042 [SCHED_BATCH] = "batch",
3043 [SCHED_IDLE] = "idle",
3044 [SCHED_FIFO] = "fifo",
3048 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3050 static const char* const rlimit_table[] = {
3051 [RLIMIT_CPU] = "LimitCPU",
3052 [RLIMIT_FSIZE] = "LimitFSIZE",
3053 [RLIMIT_DATA] = "LimitDATA",
3054 [RLIMIT_STACK] = "LimitSTACK",
3055 [RLIMIT_CORE] = "LimitCORE",
3056 [RLIMIT_RSS] = "LimitRSS",
3057 [RLIMIT_NOFILE] = "LimitNOFILE",
3058 [RLIMIT_AS] = "LimitAS",
3059 [RLIMIT_NPROC] = "LimitNPROC",
3060 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3061 [RLIMIT_LOCKS] = "LimitLOCKS",
3062 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3063 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3064 [RLIMIT_NICE] = "LimitNICE",
3065 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3066 [RLIMIT_RTTIME] = "LimitRTTIME"
3069 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3071 static const char* const ip_tos_table[] = {
3072 [IPTOS_LOWDELAY] = "low-delay",
3073 [IPTOS_THROUGHPUT] = "throughput",
3074 [IPTOS_RELIABILITY] = "reliability",
3075 [IPTOS_LOWCOST] = "low-cost",
3078 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3080 static const char *const signal_table[] = {
3096 [SIGSTKFLT] = "STKFLT",
3106 [SIGVTALRM] = "VTALRM",
3108 [SIGWINCH] = "WINCH",
3114 DEFINE_STRING_TABLE_LOOKUP(signal, int);