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_atolu(const char *s, long unsigned *ret_lu) {
318 l = strtoul(s, &x, 0);
320 if (!x || *x || errno)
321 return errno ? -errno : -EINVAL;
327 int safe_atoli(const char *s, long int *ret_li) {
335 l = strtol(s, &x, 0);
337 if (!x || *x || errno)
338 return errno ? -errno : -EINVAL;
344 int safe_atollu(const char *s, long long unsigned *ret_llu) {
346 unsigned long long l;
352 l = strtoull(s, &x, 0);
354 if (!x || *x || errno)
355 return errno ? -errno : -EINVAL;
361 int safe_atolli(const char *s, long long int *ret_lli) {
369 l = strtoll(s, &x, 0);
371 if (!x || *x || errno)
372 return errno ? -errno : -EINVAL;
378 /* Split a string into words. */
379 char *split(const char *c, size_t *l, const char *separator, char **state) {
382 current = *state ? *state : (char*) c;
384 if (!*current || *c == 0)
387 current += strspn(current, separator);
388 *l = strcspn(current, separator);
391 return (char*) current;
394 /* Split a string into words, but consider strings enclosed in '' and
395 * "" as words even if they include spaces. */
396 char *split_quoted(const char *c, size_t *l, char **state) {
399 current = *state ? *state : (char*) c;
401 if (!*current || *c == 0)
404 current += strspn(current, WHITESPACE);
406 if (*current == '\'') {
408 *l = strcspn(current, "'");
413 } else if (*current == '\"') {
415 *l = strcspn(current, "\"");
421 *l = strcspn(current, WHITESPACE);
425 /* FIXME: Cannot deal with strings that have spaces AND ticks
428 return (char*) current;
431 char **split_path_and_make_absolute(const char *p) {
435 if (!(l = strv_split(p, ":")))
438 if (!strv_path_make_absolute_cwd(l)) {
446 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
449 char fn[132], line[256], *p;
455 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
456 fn[sizeof(fn)-1] = 0;
458 if (!(f = fopen(fn, "r")))
461 if (!(fgets(line, sizeof(line), f))) {
469 /* Let's skip the pid and comm fields. The latter is enclosed
470 * in () but does not escape any () in its value, so let's
471 * skip over it manually */
473 if (!(p = strrchr(line, ')')))
484 if ((long unsigned) (pid_t) ppid != ppid)
487 *_ppid = (pid_t) ppid;
492 int write_one_line_file(const char *fn, const char *line) {
499 if (!(f = fopen(fn, "we")))
502 if (fputs(line, f) < 0) {
513 int read_one_line_file(const char *fn, char **line) {
521 if (!(f = fopen(fn, "re")))
524 if (!(fgets(t, sizeof(t), f))) {
529 if (!(c = strdup(t))) {
542 char *truncate_nl(char *s) {
545 s[strcspn(s, NEWLINE)] = 0;
549 int get_process_name(pid_t pid, char **name) {
556 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
559 r = read_one_line_file(p, name);
569 char *strappend(const char *s, const char *suffix) {
579 if (!(r = new(char, a+b+1)))
583 memcpy(r+a, suffix, b);
589 int readlink_malloc(const char *p, char **r) {
599 if (!(c = new(char, l)))
602 if ((n = readlink(p, c, l-1)) < 0) {
608 if ((size_t) n < l-1) {
619 int readlink_and_make_absolute(const char *p, char **r) {
626 if ((j = readlink_malloc(p, &target)) < 0)
629 k = file_in_same_dir(p, target);
639 char *file_name_from_path(const char *p) {
644 if ((r = strrchr(p, '/')))
650 bool path_is_absolute(const char *p) {
656 bool is_path(const char *p) {
658 return !!strchr(p, '/');
661 char *path_make_absolute(const char *p, const char *prefix) {
666 /* Makes every item in the list an absolute path by prepending
667 * the prefix, if specified and necessary */
669 if (path_is_absolute(p) || !prefix)
672 if (asprintf(&r, "%s/%s", prefix, p) < 0)
678 char *path_make_absolute_cwd(const char *p) {
683 /* Similar to path_make_absolute(), but prefixes with the
684 * current working directory. */
686 if (path_is_absolute(p))
689 if (!(cwd = get_current_dir_name()))
692 r = path_make_absolute(p, cwd);
698 char **strv_path_make_absolute_cwd(char **l) {
701 /* Goes through every item in the string list and makes it
702 * absolute. This works in place and won't rollback any
703 * changes on failure. */
708 if (!(t = path_make_absolute_cwd(*s)))
718 char **strv_path_canonicalize(char **l) {
726 /* Goes through every item in the string list and canonicalize
727 * the path. This works in place and won't rollback any
728 * changes on failure. */
733 t = path_make_absolute_cwd(*s);
742 u = canonicalize_file_name(t);
746 if (errno == ENOMEM || !errno)
763 int reset_all_signal_handlers(void) {
766 for (sig = 1; sig < _NSIG; sig++) {
769 if (sig == SIGKILL || sig == SIGSTOP)
773 sa.sa_handler = SIG_DFL;
774 sa.sa_flags = SA_RESTART;
776 /* On Linux the first two RT signals are reserved by
777 * glibc, and sigaction() will return EINVAL for them. */
778 if ((sigaction(sig, &sa, NULL) < 0))
786 char *strstrip(char *s) {
789 /* Drops trailing whitespace. Modifies the string in
790 * place. Returns pointer to first non-space character */
792 s += strspn(s, WHITESPACE);
795 if (!strchr(WHITESPACE, *e))
806 char *delete_chars(char *s, const char *bad) {
809 /* Drops all whitespace, regardless where in the string */
811 for (f = s, t = s; *f; f++) {
823 char *file_in_same_dir(const char *path, const char *filename) {
830 /* This removes the last component of path and appends
831 * filename, unless the latter is absolute anyway or the
834 if (path_is_absolute(filename))
835 return strdup(filename);
837 if (!(e = strrchr(path, '/')))
838 return strdup(filename);
840 k = strlen(filename);
841 if (!(r = new(char, e-path+1+k+1)))
844 memcpy(r, path, e-path+1);
845 memcpy(r+(e-path)+1, filename, k+1);
850 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
853 if (mkdir(path, mode) >= 0)
854 if (chmod_and_chown(path, mode, uid, gid) < 0)
857 if (lstat(path, &st) < 0)
860 if ((st.st_mode & 0777) != mode ||
863 !S_ISDIR(st.st_mode)) {
872 int mkdir_parents(const char *path, mode_t mode) {
877 /* Creates every parent directory in the path except the last
880 p = path + strspn(path, "/");
885 e = p + strcspn(p, "/");
886 p = e + strspn(e, "/");
888 /* Is this the last component? If so, then we're
893 if (!(t = strndup(path, e - path)))
900 if (r < 0 && errno != EEXIST)
905 int mkdir_p(const char *path, mode_t mode) {
910 if ((r = mkdir_parents(path, mode)) < 0)
913 if (mkdir(path, mode) < 0)
919 int rmdir_parents(const char *path, const char *stop) {
928 /* Skip trailing slashes */
929 while (l > 0 && path[l-1] == '/')
935 /* Skip last component */
936 while (l > 0 && path[l-1] != '/')
939 /* Skip trailing slashes */
940 while (l > 0 && path[l-1] == '/')
946 if (!(t = strndup(path, l)))
949 if (path_startswith(stop, t)) {
966 char hexchar(int x) {
967 static const char table[16] = "0123456789abcdef";
969 return table[x & 15];
972 int unhexchar(char c) {
974 if (c >= '0' && c <= '9')
977 if (c >= 'a' && c <= 'f')
980 if (c >= 'A' && c <= 'F')
986 char octchar(int x) {
987 return '0' + (x & 7);
990 int unoctchar(char c) {
992 if (c >= '0' && c <= '7')
998 char decchar(int x) {
999 return '0' + (x % 10);
1002 int undecchar(char c) {
1004 if (c >= '0' && c <= '9')
1010 char *cescape(const char *s) {
1016 /* Does C style string escaping. */
1018 if (!(r = new(char, strlen(s)*4 + 1)))
1021 for (f = s, t = r; *f; f++)
1067 /* For special chars we prefer octal over
1068 * hexadecimal encoding, simply because glib's
1069 * g_strescape() does the same */
1070 if ((*f < ' ') || (*f >= 127)) {
1072 *(t++) = octchar((unsigned char) *f >> 6);
1073 *(t++) = octchar((unsigned char) *f >> 3);
1074 *(t++) = octchar((unsigned char) *f);
1085 char *cunescape(const char *s) {
1091 /* Undoes C style string escaping */
1093 if (!(r = new(char, strlen(s)+1)))
1096 for (f = s, t = r; *f; f++) {
1139 /* hexadecimal encoding */
1142 if ((a = unhexchar(f[1])) < 0 ||
1143 (b = unhexchar(f[2])) < 0) {
1144 /* Invalid escape code, let's take it literal then */
1148 *(t++) = (char) ((a << 4) | b);
1163 /* octal encoding */
1166 if ((a = unoctchar(f[0])) < 0 ||
1167 (b = unoctchar(f[1])) < 0 ||
1168 (c = unoctchar(f[2])) < 0) {
1169 /* Invalid escape code, let's take it literal then */
1173 *(t++) = (char) ((a << 6) | (b << 3) | c);
1181 /* premature end of string.*/
1186 /* Invalid escape code, let's take it literal then */
1199 char *xescape(const char *s, const char *bad) {
1203 /* Escapes all chars in bad, in addition to \ and all special
1204 * chars, in \xFF style escaping. May be reversed with
1207 if (!(r = new(char, strlen(s)*4+1)))
1210 for (f = s, t = r; *f; f++) {
1212 if ((*f < ' ') || (*f >= 127) ||
1213 (*f == '\\') || strchr(bad, *f)) {
1216 *(t++) = hexchar(*f >> 4);
1217 *(t++) = hexchar(*f);
1227 char *bus_path_escape(const char *s) {
1233 /* Escapes all chars that D-Bus' object path cannot deal
1234 * with. Can be reverse with bus_path_unescape() */
1236 if (!(r = new(char, strlen(s)*3+1)))
1239 for (f = s, t = r; *f; f++) {
1241 if (!(*f >= 'A' && *f <= 'Z') &&
1242 !(*f >= 'a' && *f <= 'z') &&
1243 !(*f >= '0' && *f <= '9')) {
1245 *(t++) = hexchar(*f >> 4);
1246 *(t++) = hexchar(*f);
1256 char *bus_path_unescape(const char *f) {
1261 if (!(r = strdup(f)))
1264 for (t = r; *f; f++) {
1269 if ((a = unhexchar(f[1])) < 0 ||
1270 (b = unhexchar(f[2])) < 0) {
1271 /* Invalid escape code, let's take it literal then */
1274 *(t++) = (char) ((a << 4) | b);
1286 char *path_kill_slashes(char *path) {
1290 /* Removes redundant inner and trailing slashes. Modifies the
1291 * passed string in-place.
1293 * ///foo///bar/ becomes /foo/bar
1296 for (f = path, t = path; *f; f++) {
1311 /* Special rule, if we are talking of the root directory, a
1312 trailing slash is good */
1314 if (t == path && slash)
1321 bool path_startswith(const char *path, const char *prefix) {
1325 if ((path[0] == '/') != (prefix[0] == '/'))
1331 path += strspn(path, "/");
1332 prefix += strspn(prefix, "/");
1340 a = strcspn(path, "/");
1341 b = strcspn(prefix, "/");
1346 if (memcmp(path, prefix, a) != 0)
1354 bool path_equal(const char *a, const char *b) {
1358 if ((a[0] == '/') != (b[0] == '/'))
1364 a += strspn(a, "/");
1365 b += strspn(b, "/");
1367 if (*a == 0 && *b == 0)
1370 if (*a == 0 || *b == 0)
1373 j = strcspn(a, "/");
1374 k = strcspn(b, "/");
1379 if (memcmp(a, b, j) != 0)
1387 char *ascii_strlower(char *t) {
1392 for (p = t; *p; p++)
1393 if (*p >= 'A' && *p <= 'Z')
1394 *p = *p - 'A' + 'a';
1399 bool ignore_file(const char *filename) {
1403 filename[0] == '.' ||
1404 streq(filename, "lost+found") ||
1405 endswith(filename, "~") ||
1406 endswith(filename, ".rpmnew") ||
1407 endswith(filename, ".rpmsave") ||
1408 endswith(filename, ".rpmorig") ||
1409 endswith(filename, ".dpkg-old") ||
1410 endswith(filename, ".dpkg-new") ||
1411 endswith(filename, ".swp");
1414 int fd_nonblock(int fd, bool nonblock) {
1419 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1423 flags |= O_NONBLOCK;
1425 flags &= ~O_NONBLOCK;
1427 if (fcntl(fd, F_SETFL, flags) < 0)
1433 int fd_cloexec(int fd, bool cloexec) {
1438 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1442 flags |= FD_CLOEXEC;
1444 flags &= ~FD_CLOEXEC;
1446 if (fcntl(fd, F_SETFD, flags) < 0)
1452 int close_all_fds(const int except[], unsigned n_except) {
1457 if (!(d = opendir("/proc/self/fd")))
1460 while ((de = readdir(d))) {
1463 if (ignore_file(de->d_name))
1466 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1480 for (i = 0; i < n_except; i++)
1481 if (except[i] == fd) {
1490 if ((r = close_nointr(fd)) < 0) {
1491 /* Valgrind has its own FD and doesn't want to have it closed */
1504 bool chars_intersect(const char *a, const char *b) {
1507 /* Returns true if any of the chars in a are in b. */
1508 for (p = a; *p; p++)
1515 char *format_timestamp(char *buf, size_t l, usec_t t) {
1525 sec = (time_t) (t / USEC_PER_SEC);
1527 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1533 char *format_timespan(char *buf, size_t l, usec_t t) {
1534 static const struct {
1538 { "w", USEC_PER_WEEK },
1539 { "d", USEC_PER_DAY },
1540 { "h", USEC_PER_HOUR },
1541 { "min", USEC_PER_MINUTE },
1542 { "s", USEC_PER_SEC },
1543 { "ms", USEC_PER_MSEC },
1553 if (t == (usec_t) -1)
1556 /* The result of this function can be parsed with parse_usec */
1558 for (i = 0; i < ELEMENTSOF(table); i++) {
1562 if (t < table[i].usec)
1568 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1569 n = MIN((size_t) k, l);
1582 bool fstype_is_network(const char *fstype) {
1583 static const char * const table[] = {
1595 for (i = 0; i < ELEMENTSOF(table); i++)
1596 if (streq(table[i], fstype))
1605 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1610 TIOCL_GETKMSGREDIRECT,
1614 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1617 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1620 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1623 close_nointr_nofail(r);
1627 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1628 struct termios old_termios, new_termios;
1635 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1636 new_termios = old_termios;
1638 new_termios.c_lflag &= ~ICANON;
1639 new_termios.c_cc[VMIN] = 1;
1640 new_termios.c_cc[VTIME] = 0;
1642 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1645 k = fread(&c, 1, 1, f);
1647 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1653 *need_nl = c != '\n';
1660 if (!(fgets(line, sizeof(line), f)))
1665 if (strlen(line) != 1)
1675 int ask(char *ret, const char *replies, const char *text, ...) {
1684 bool need_nl = true;
1686 fputs("\x1B[1m", stdout);
1692 fputs("\x1B[0m", stdout);
1696 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1698 if (r == -EBADMSG) {
1699 puts("Bad input, please try again.");
1710 if (strchr(replies, c)) {
1715 puts("Read unexpected character, please try again.");
1719 int reset_terminal(int fd) {
1720 struct termios termios;
1725 /* Set terminal to some sane defaults */
1727 if (tcgetattr(fd, &termios) < 0) {
1732 /* We only reset the stuff that matters to the software. How
1733 * hardware is set up we don't touch assuming that somebody
1734 * else will do that for us */
1736 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1737 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1738 termios.c_oflag |= ONLCR;
1739 termios.c_cflag |= CREAD;
1740 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1742 termios.c_cc[VINTR] = 03; /* ^C */
1743 termios.c_cc[VQUIT] = 034; /* ^\ */
1744 termios.c_cc[VERASE] = 0177;
1745 termios.c_cc[VKILL] = 025; /* ^X */
1746 termios.c_cc[VEOF] = 04; /* ^D */
1747 termios.c_cc[VSTART] = 021; /* ^Q */
1748 termios.c_cc[VSTOP] = 023; /* ^S */
1749 termios.c_cc[VSUSP] = 032; /* ^Z */
1750 termios.c_cc[VLNEXT] = 026; /* ^V */
1751 termios.c_cc[VWERASE] = 027; /* ^W */
1752 termios.c_cc[VREPRINT] = 022; /* ^R */
1753 termios.c_cc[VEOL] = 0;
1754 termios.c_cc[VEOL2] = 0;
1756 termios.c_cc[VTIME] = 0;
1757 termios.c_cc[VMIN] = 1;
1759 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1763 /* Just in case, flush all crap out */
1764 tcflush(fd, TCIOFLUSH);
1769 int open_terminal(const char *name, int mode) {
1772 if ((fd = open(name, mode)) < 0)
1775 if ((r = isatty(fd)) < 0) {
1776 close_nointr_nofail(fd);
1781 close_nointr_nofail(fd);
1788 int flush_fd(int fd) {
1789 struct pollfd pollfd;
1793 pollfd.events = POLLIN;
1800 if ((r = poll(&pollfd, 1, 0)) < 0) {
1811 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1816 if (errno == EAGAIN)
1827 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1828 int fd = -1, notify = -1, r, wd = -1;
1832 /* We use inotify to be notified when the tty is closed. We
1833 * create the watch before checking if we can actually acquire
1834 * it, so that we don't lose any event.
1836 * Note: strictly speaking this actually watches for the
1837 * device being closed, it does *not* really watch whether a
1838 * tty loses its controlling process. However, unless some
1839 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1840 * its tty otherwise this will not become a problem. As long
1841 * as the administrator makes sure not configure any service
1842 * on the same tty as an untrusted user this should not be a
1843 * problem. (Which he probably should not do anyway.) */
1845 if (!fail && !force) {
1846 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1851 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1859 if ((r = flush_fd(notify)) < 0)
1862 /* We pass here O_NOCTTY only so that we can check the return
1863 * value TIOCSCTTY and have a reliable way to figure out if we
1864 * successfully became the controlling process of the tty */
1865 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1868 /* First, try to get the tty */
1869 r = ioctl(fd, TIOCSCTTY, force);
1871 /* Sometimes it makes sense to ignore TIOCSCTTY
1872 * returning EPERM, i.e. when very likely we already
1873 * are have this controlling terminal. */
1874 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1877 if (r < 0 && (force || fail || errno != EPERM)) {
1887 assert(notify >= 0);
1890 struct inotify_event e;
1893 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1907 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1915 /* We close the tty fd here since if the old session
1916 * ended our handle will be dead. It's important that
1917 * we do this after sleeping, so that we don't enter
1918 * an endless loop. */
1919 close_nointr_nofail(fd);
1923 close_nointr_nofail(notify);
1925 if ((r = reset_terminal(fd)) < 0)
1926 log_warning("Failed to reset terminal: %s", strerror(-r));
1932 close_nointr_nofail(fd);
1935 close_nointr_nofail(notify);
1940 int release_terminal(void) {
1942 struct sigaction sa_old, sa_new;
1944 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1947 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1948 * by our own TIOCNOTTY */
1951 sa_new.sa_handler = SIG_IGN;
1952 sa_new.sa_flags = SA_RESTART;
1953 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1955 if (ioctl(fd, TIOCNOTTY) < 0)
1958 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1960 close_nointr_nofail(fd);
1964 int sigaction_many(const struct sigaction *sa, ...) {
1969 while ((sig = va_arg(ap, int)) > 0)
1970 if (sigaction(sig, sa, NULL) < 0)
1977 int ignore_signals(int sig, ...) {
1978 struct sigaction sa;
1983 sa.sa_handler = SIG_IGN;
1984 sa.sa_flags = SA_RESTART;
1986 if (sigaction(sig, &sa, NULL) < 0)
1990 while ((sig = va_arg(ap, int)) > 0)
1991 if (sigaction(sig, &sa, NULL) < 0)
1998 int default_signals(int sig, ...) {
1999 struct sigaction sa;
2004 sa.sa_handler = SIG_DFL;
2005 sa.sa_flags = SA_RESTART;
2007 if (sigaction(sig, &sa, NULL) < 0)
2011 while ((sig = va_arg(ap, int)) > 0)
2012 if (sigaction(sig, &sa, NULL) < 0)
2019 int close_pipe(int p[]) {
2025 a = close_nointr(p[0]);
2030 b = close_nointr(p[1]);
2034 return a < 0 ? a : b;
2037 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2046 while (nbytes > 0) {
2049 if ((k = read(fd, p, nbytes)) <= 0) {
2051 if (k < 0 && errno == EINTR)
2054 if (k < 0 && errno == EAGAIN && do_poll) {
2055 struct pollfd pollfd;
2059 pollfd.events = POLLIN;
2061 if (poll(&pollfd, 1, -1) < 0) {
2065 return n > 0 ? n : -errno;
2068 if (pollfd.revents != POLLIN)
2069 return n > 0 ? n : -EIO;
2074 return n > 0 ? n : (k < 0 ? -errno : 0);
2085 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2094 while (nbytes > 0) {
2097 if ((k = write(fd, p, nbytes)) <= 0) {
2099 if (k < 0 && errno == EINTR)
2102 if (k < 0 && errno == EAGAIN && do_poll) {
2103 struct pollfd pollfd;
2107 pollfd.events = POLLOUT;
2109 if (poll(&pollfd, 1, -1) < 0) {
2113 return n > 0 ? n : -errno;
2116 if (pollfd.revents != POLLOUT)
2117 return n > 0 ? n : -EIO;
2122 return n > 0 ? n : (k < 0 ? -errno : 0);
2133 int path_is_mount_point(const char *t) {
2137 if (lstat(t, &a) < 0) {
2139 if (errno == ENOENT)
2145 if (!(copy = strdup(t)))
2148 if (lstat(dirname(copy), &b) < 0) {
2155 return a.st_dev != b.st_dev;
2158 int parse_usec(const char *t, usec_t *usec) {
2159 static const struct {
2163 { "sec", USEC_PER_SEC },
2164 { "s", USEC_PER_SEC },
2165 { "min", USEC_PER_MINUTE },
2166 { "hr", USEC_PER_HOUR },
2167 { "h", USEC_PER_HOUR },
2168 { "d", USEC_PER_DAY },
2169 { "w", USEC_PER_WEEK },
2170 { "msec", USEC_PER_MSEC },
2171 { "ms", USEC_PER_MSEC },
2172 { "m", USEC_PER_MINUTE },
2175 { "", USEC_PER_SEC },
2191 l = strtoll(p, &e, 10);
2202 e += strspn(e, WHITESPACE);
2204 for (i = 0; i < ELEMENTSOF(table); i++)
2205 if (startswith(e, table[i].suffix)) {
2206 r += (usec_t) l * table[i].usec;
2207 p = e + strlen(table[i].suffix);
2211 if (i >= ELEMENTSOF(table))
2221 int make_stdio(int fd) {
2226 r = dup2(fd, STDIN_FILENO);
2227 s = dup2(fd, STDOUT_FILENO);
2228 t = dup2(fd, STDERR_FILENO);
2231 close_nointr_nofail(fd);
2233 if (r < 0 || s < 0 || t < 0)
2239 bool is_clean_exit(int code, int status) {
2241 if (code == CLD_EXITED)
2244 /* If a daemon does not implement handlers for some of the
2245 * signals that's not considered an unclean shutdown */
2246 if (code == CLD_KILLED)
2250 status == SIGTERM ||
2256 bool is_device_path(const char *path) {
2258 /* Returns true on paths that refer to a device, either in
2259 * sysfs or in /dev */
2262 path_startswith(path, "/dev/") ||
2263 path_startswith(path, "/sys/");
2266 int dir_is_empty(const char *path) {
2269 struct dirent buf, *de;
2271 if (!(d = opendir(path)))
2275 if ((r = readdir_r(d, &buf, &de)) > 0) {
2285 if (!ignore_file(de->d_name)) {
2295 unsigned long long random_ull(void) {
2300 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2303 r = loop_read(fd, &ull, sizeof(ull), true);
2304 close_nointr_nofail(fd);
2306 if (r != sizeof(ull))
2312 return random() * RAND_MAX + random();
2315 void rename_process(const char name[8]) {
2318 prctl(PR_SET_NAME, name);
2320 /* This is a like a poor man's setproctitle(). The string
2321 * passed should fit in 7 chars (i.e. the length of
2324 if (program_invocation_name)
2325 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2328 void sigset_add_many(sigset_t *ss, ...) {
2335 while ((sig = va_arg(ap, int)) > 0)
2336 assert_se(sigaddset(ss, sig) == 0);
2340 char* gethostname_malloc(void) {
2343 assert_se(uname(&u) >= 0);
2346 return strdup(u.nodename);
2348 return strdup(u.sysname);
2351 int getmachineid_malloc(char **b) {
2356 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2363 char* getlogname_malloc(void) {
2367 struct passwd pwbuf, *pw = NULL;
2370 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2375 /* Shortcut things to avoid NSS lookups */
2377 return strdup("root");
2379 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2382 if (!(buf = malloc(bufsize)))
2385 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2386 name = strdup(pw->pw_name);
2393 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2399 int getttyname_malloc(char **r) {
2400 char path[PATH_MAX], *p, *c;
2404 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2410 if (startswith(path, "/dev/"))
2413 if (!(c = strdup(p)))
2420 static int rm_rf_children(int fd, bool only_dirs) {
2426 /* This returns the first error we run into, but nevertheless
2429 if (!(d = fdopendir(fd))) {
2430 close_nointr_nofail(fd);
2435 struct dirent buf, *de;
2439 if ((r = readdir_r(d, &buf, &de)) != 0) {
2448 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2451 if (de->d_type == DT_UNKNOWN) {
2454 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2460 is_dir = S_ISDIR(st.st_mode);
2462 is_dir = de->d_type == DT_DIR;
2467 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2473 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2478 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2482 } else if (!only_dirs) {
2484 if (unlinkat(fd, de->d_name, 0) < 0) {
2496 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2502 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2504 if (errno != ENOTDIR)
2507 if (delete_root && !only_dirs)
2508 if (unlink(path) < 0)
2514 r = rm_rf_children(fd, only_dirs);
2517 if (rmdir(path) < 0) {
2525 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2528 /* Under the assumption that we are running privileged we
2529 * first change the access mode and only then hand out
2530 * ownership to avoid a window where access is too open. */
2532 if (chmod(path, mode) < 0)
2535 if (chown(path, uid, gid) < 0)
2541 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2545 /* Allocates the cpuset in the right size */
2548 if (!(r = CPU_ALLOC(n)))
2551 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2552 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2562 if (errno != EINVAL)
2569 static const char *const ioprio_class_table[] = {
2570 [IOPRIO_CLASS_NONE] = "none",
2571 [IOPRIO_CLASS_RT] = "realtime",
2572 [IOPRIO_CLASS_BE] = "best-effort",
2573 [IOPRIO_CLASS_IDLE] = "idle"
2576 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2578 static const char *const sigchld_code_table[] = {
2579 [CLD_EXITED] = "exited",
2580 [CLD_KILLED] = "killed",
2581 [CLD_DUMPED] = "dumped",
2582 [CLD_TRAPPED] = "trapped",
2583 [CLD_STOPPED] = "stopped",
2584 [CLD_CONTINUED] = "continued",
2587 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2589 static const char *const log_facility_table[LOG_NFACILITIES] = {
2590 [LOG_FAC(LOG_KERN)] = "kern",
2591 [LOG_FAC(LOG_USER)] = "user",
2592 [LOG_FAC(LOG_MAIL)] = "mail",
2593 [LOG_FAC(LOG_DAEMON)] = "daemon",
2594 [LOG_FAC(LOG_AUTH)] = "auth",
2595 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2596 [LOG_FAC(LOG_LPR)] = "lpr",
2597 [LOG_FAC(LOG_NEWS)] = "news",
2598 [LOG_FAC(LOG_UUCP)] = "uucp",
2599 [LOG_FAC(LOG_CRON)] = "cron",
2600 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2601 [LOG_FAC(LOG_FTP)] = "ftp",
2602 [LOG_FAC(LOG_LOCAL0)] = "local0",
2603 [LOG_FAC(LOG_LOCAL1)] = "local1",
2604 [LOG_FAC(LOG_LOCAL2)] = "local2",
2605 [LOG_FAC(LOG_LOCAL3)] = "local3",
2606 [LOG_FAC(LOG_LOCAL4)] = "local4",
2607 [LOG_FAC(LOG_LOCAL5)] = "local5",
2608 [LOG_FAC(LOG_LOCAL6)] = "local6",
2609 [LOG_FAC(LOG_LOCAL7)] = "local7"
2612 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2614 static const char *const log_level_table[] = {
2615 [LOG_EMERG] = "emerg",
2616 [LOG_ALERT] = "alert",
2617 [LOG_CRIT] = "crit",
2619 [LOG_WARNING] = "warning",
2620 [LOG_NOTICE] = "notice",
2621 [LOG_INFO] = "info",
2622 [LOG_DEBUG] = "debug"
2625 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2627 static const char* const sched_policy_table[] = {
2628 [SCHED_OTHER] = "other",
2629 [SCHED_BATCH] = "batch",
2630 [SCHED_IDLE] = "idle",
2631 [SCHED_FIFO] = "fifo",
2635 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2637 static const char* const rlimit_table[] = {
2638 [RLIMIT_CPU] = "LimitCPU",
2639 [RLIMIT_FSIZE] = "LimitFSIZE",
2640 [RLIMIT_DATA] = "LimitDATA",
2641 [RLIMIT_STACK] = "LimitSTACK",
2642 [RLIMIT_CORE] = "LimitCORE",
2643 [RLIMIT_RSS] = "LimitRSS",
2644 [RLIMIT_NOFILE] = "LimitNOFILE",
2645 [RLIMIT_AS] = "LimitAS",
2646 [RLIMIT_NPROC] = "LimitNPROC",
2647 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2648 [RLIMIT_LOCKS] = "LimitLOCKS",
2649 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2650 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2651 [RLIMIT_NICE] = "LimitNICE",
2652 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2653 [RLIMIT_RTTIME] = "LimitRTTIME"
2656 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2658 static const char* const ip_tos_table[] = {
2659 [IPTOS_LOWDELAY] = "low-delay",
2660 [IPTOS_THROUGHPUT] = "throughput",
2661 [IPTOS_RELIABILITY] = "reliability",
2662 [IPTOS_LOWCOST] = "low-cost",
2665 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);