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>
54 bool streq_ptr(const char *a, const char *b) {
56 /* Like streq(), but tries to make sense of NULL pointers */
67 usec_t now(clockid_t clock_id) {
70 assert_se(clock_gettime(clock_id, &ts) == 0);
72 return timespec_load(&ts);
75 timestamp* timestamp_get(timestamp *ts) {
78 ts->realtime = now(CLOCK_REALTIME);
79 ts->monotonic = now(CLOCK_MONOTONIC);
84 usec_t timespec_load(const struct timespec *ts) {
88 (usec_t) ts->tv_sec * USEC_PER_SEC +
89 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
92 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
95 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
96 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
101 usec_t timeval_load(const struct timeval *tv) {
105 (usec_t) tv->tv_sec * USEC_PER_SEC +
106 (usec_t) tv->tv_usec;
109 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
112 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
113 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
118 bool endswith(const char *s, const char *postfix) {
125 pl = strlen(postfix);
133 return memcmp(s + sl - pl, postfix, pl) == 0;
136 bool startswith(const char *s, const char *prefix) {
151 return memcmp(s, prefix, pl) == 0;
154 bool startswith_no_case(const char *s, const char *prefix) {
170 for(i = 0; i < pl; ++i) {
171 if (tolower(s[i]) != tolower(prefix[i]))
178 bool first_word(const char *s, const char *word) {
193 if (memcmp(s, word, wl) != 0)
197 strchr(WHITESPACE, s[wl]);
200 int close_nointr(int fd) {
206 if ((r = close(fd)) >= 0)
214 void close_nointr_nofail(int fd) {
215 int saved_errno = errno;
217 /* like close_nointr() but cannot fail, and guarantees errno
220 assert_se(close_nointr(fd) == 0);
225 int parse_boolean(const char *v) {
228 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
230 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
236 int safe_atou(const char *s, unsigned *ret_u) {
244 l = strtoul(s, &x, 0);
246 if (!x || *x || errno)
247 return errno ? -errno : -EINVAL;
249 if ((unsigned long) (unsigned) l != l)
252 *ret_u = (unsigned) l;
256 int safe_atoi(const char *s, int *ret_i) {
264 l = strtol(s, &x, 0);
266 if (!x || *x || errno)
267 return errno ? -errno : -EINVAL;
269 if ((long) (int) l != l)
276 int safe_atolu(const char *s, long unsigned *ret_lu) {
284 l = strtoul(s, &x, 0);
286 if (!x || *x || errno)
287 return errno ? -errno : -EINVAL;
293 int safe_atoli(const char *s, long int *ret_li) {
301 l = strtol(s, &x, 0);
303 if (!x || *x || errno)
304 return errno ? -errno : -EINVAL;
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) {
365 current = *state ? *state : (char*) c;
367 if (!*current || *c == 0)
370 current += strspn(current, WHITESPACE);
372 if (*current == '\'') {
374 *l = strcspn(current, "'");
379 } else if (*current == '\"') {
381 *l = strcspn(current, "\"");
387 *l = strcspn(current, WHITESPACE);
391 /* FIXME: Cannot deal with strings that have spaces AND ticks
394 return (char*) current;
397 char **split_path_and_make_absolute(const char *p) {
401 if (!(l = strv_split(p, ":")))
404 if (!strv_path_make_absolute_cwd(l)) {
412 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
415 char fn[132], line[256], *p;
416 long long unsigned ppid;
421 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
422 fn[sizeof(fn)-1] = 0;
424 if (!(f = fopen(fn, "r")))
427 if (!(fgets(line, sizeof(line), f))) {
435 /* Let's skip the pid and comm fields. The latter is enclosed
436 * in () but does not escape any () in its value, so let's
437 * skip over it manually */
439 if (!(p = strrchr(line, ')')))
450 if ((long long unsigned) (pid_t) ppid != ppid)
453 *_ppid = (pid_t) ppid;
458 int write_one_line_file(const char *fn, const char *line) {
465 if (!(f = fopen(fn, "we")))
468 if (fputs(line, f) < 0) {
479 int read_one_line_file(const char *fn, char **line) {
487 if (!(f = fopen(fn, "re")))
490 if (!(fgets(t, sizeof(t), f))) {
495 if (!(c = strdup(t))) {
508 char *truncate_nl(char *s) {
511 s[strcspn(s, NEWLINE)] = 0;
515 int get_process_name(pid_t pid, char **name) {
522 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
525 r = read_one_line_file(p, name);
535 char *strappend(const char *s, const char *suffix) {
545 if (!(r = new(char, a+b+1)))
549 memcpy(r+a, suffix, b);
555 int readlink_malloc(const char *p, char **r) {
565 if (!(c = new(char, l)))
568 if ((n = readlink(p, c, l-1)) < 0) {
574 if ((size_t) n < l-1) {
585 int readlink_and_make_absolute(const char *p, char **r) {
592 if ((j = readlink_malloc(p, &target)) < 0)
595 k = file_in_same_dir(p, target);
605 char *file_name_from_path(const char *p) {
610 if ((r = strrchr(p, '/')))
616 bool path_is_absolute(const char *p) {
622 bool is_path(const char *p) {
624 return !!strchr(p, '/');
627 char *path_make_absolute(const char *p, const char *prefix) {
632 /* Makes every item in the list an absolute path by prepending
633 * the prefix, if specified and necessary */
635 if (path_is_absolute(p) || !prefix)
638 if (asprintf(&r, "%s/%s", prefix, p) < 0)
644 char *path_make_absolute_cwd(const char *p) {
649 /* Similar to path_make_absolute(), but prefixes with the
650 * current working directory. */
652 if (path_is_absolute(p))
655 if (!(cwd = get_current_dir_name()))
658 r = path_make_absolute(p, cwd);
664 char **strv_path_make_absolute_cwd(char **l) {
667 /* Goes through every item in the string list and makes it
668 * absolute. This works in place and won't rollback any
669 * changes on failure. */
674 if (!(t = path_make_absolute_cwd(*s)))
684 char **strv_path_canonicalize(char **l) {
692 /* Goes through every item in the string list and canonicalize
693 * the path. This works in place and won't rollback any
694 * changes on failure. */
699 t = path_make_absolute_cwd(*s);
708 u = canonicalize_file_name(t);
712 if (errno == ENOMEM || !errno)
729 int reset_all_signal_handlers(void) {
732 for (sig = 1; sig < _NSIG; sig++) {
735 if (sig == SIGKILL || sig == SIGSTOP)
739 sa.sa_handler = SIG_DFL;
740 sa.sa_flags = SA_RESTART;
742 /* On Linux the first two RT signals are reserved by
743 * glibc, and sigaction() will return EINVAL for them. */
744 if ((sigaction(sig, &sa, NULL) < 0))
752 char *strstrip(char *s) {
755 /* Drops trailing whitespace. Modifies the string in
756 * place. Returns pointer to first non-space character */
758 s += strspn(s, WHITESPACE);
761 if (!strchr(WHITESPACE, *e))
772 char *delete_chars(char *s, const char *bad) {
775 /* Drops all whitespace, regardless where in the string */
777 for (f = s, t = s; *f; f++) {
789 char *file_in_same_dir(const char *path, const char *filename) {
796 /* This removes the last component of path and appends
797 * filename, unless the latter is absolute anyway or the
800 if (path_is_absolute(filename))
801 return strdup(filename);
803 if (!(e = strrchr(path, '/')))
804 return strdup(filename);
806 k = strlen(filename);
807 if (!(r = new(char, e-path+1+k+1)))
810 memcpy(r, path, e-path+1);
811 memcpy(r+(e-path)+1, filename, k+1);
816 int mkdir_parents(const char *path, mode_t mode) {
821 /* Creates every parent directory in the path except the last
824 p = path + strspn(path, "/");
829 e = p + strcspn(p, "/");
830 p = e + strspn(e, "/");
832 /* Is this the last component? If so, then we're
837 if (!(t = strndup(path, e - path)))
844 if (r < 0 && errno != EEXIST)
849 int mkdir_p(const char *path, mode_t mode) {
854 if ((r = mkdir_parents(path, mode)) < 0)
857 if (mkdir(path, mode) < 0)
863 char hexchar(int x) {
864 static const char table[16] = "0123456789abcdef";
866 return table[x & 15];
869 int unhexchar(char c) {
871 if (c >= '0' && c <= '9')
874 if (c >= 'a' && c <= 'f')
877 if (c >= 'A' && c <= 'F')
883 char octchar(int x) {
884 return '0' + (x & 7);
887 int unoctchar(char c) {
889 if (c >= '0' && c <= '7')
895 char decchar(int x) {
896 return '0' + (x % 10);
899 int undecchar(char c) {
901 if (c >= '0' && c <= '9')
907 char *cescape(const char *s) {
913 /* Does C style string escaping. */
915 if (!(r = new(char, strlen(s)*4 + 1)))
918 for (f = s, t = r; *f; f++)
964 /* For special chars we prefer octal over
965 * hexadecimal encoding, simply because glib's
966 * g_strescape() does the same */
967 if ((*f < ' ') || (*f >= 127)) {
969 *(t++) = octchar((unsigned char) *f >> 6);
970 *(t++) = octchar((unsigned char) *f >> 3);
971 *(t++) = octchar((unsigned char) *f);
982 char *cunescape(const char *s) {
988 /* Undoes C style string escaping */
990 if (!(r = new(char, strlen(s)+1)))
993 for (f = s, t = r; *f; f++) {
1036 /* hexadecimal encoding */
1039 if ((a = unhexchar(f[1])) < 0 ||
1040 (b = unhexchar(f[2])) < 0) {
1041 /* Invalid escape code, let's take it literal then */
1045 *(t++) = (char) ((a << 4) | b);
1060 /* octal encoding */
1063 if ((a = unoctchar(f[0])) < 0 ||
1064 (b = unoctchar(f[1])) < 0 ||
1065 (c = unoctchar(f[2])) < 0) {
1066 /* Invalid escape code, let's take it literal then */
1070 *(t++) = (char) ((a << 6) | (b << 3) | c);
1078 /* premature end of string.*/
1083 /* Invalid escape code, let's take it literal then */
1096 char *xescape(const char *s, const char *bad) {
1100 /* Escapes all chars in bad, in addition to \ and all special
1101 * chars, in \xFF style escaping. May be reversed with
1104 if (!(r = new(char, strlen(s)*4+1)))
1107 for (f = s, t = r; *f; f++) {
1109 if ((*f < ' ') || (*f >= 127) ||
1110 (*f == '\\') || strchr(bad, *f)) {
1113 *(t++) = hexchar(*f >> 4);
1114 *(t++) = hexchar(*f);
1124 char *bus_path_escape(const char *s) {
1130 /* Escapes all chars that D-Bus' object path cannot deal
1131 * with. Can be reverse with bus_path_unescape() */
1133 if (!(r = new(char, strlen(s)*3+1)))
1136 for (f = s, t = r; *f; f++) {
1138 if (!(*f >= 'A' && *f <= 'Z') &&
1139 !(*f >= 'a' && *f <= 'z') &&
1140 !(*f >= '0' && *f <= '9')) {
1142 *(t++) = hexchar(*f >> 4);
1143 *(t++) = hexchar(*f);
1153 char *bus_path_unescape(const char *f) {
1158 if (!(r = strdup(f)))
1161 for (t = r; *f; f++) {
1166 if ((a = unhexchar(f[1])) < 0 ||
1167 (b = unhexchar(f[2])) < 0) {
1168 /* Invalid escape code, let's take it literal then */
1171 *(t++) = (char) ((a << 4) | b);
1183 char *path_kill_slashes(char *path) {
1187 /* Removes redundant inner and trailing slashes. Modifies the
1188 * passed string in-place.
1190 * ///foo///bar/ becomes /foo/bar
1193 for (f = path, t = path; *f; f++) {
1208 /* Special rule, if we are talking of the root directory, a
1209 trailing slash is good */
1211 if (t == path && slash)
1218 bool path_startswith(const char *path, const char *prefix) {
1222 if ((path[0] == '/') != (prefix[0] == '/'))
1228 path += strspn(path, "/");
1229 prefix += strspn(prefix, "/");
1237 a = strcspn(path, "/");
1238 b = strcspn(prefix, "/");
1243 if (memcmp(path, prefix, a) != 0)
1251 bool path_equal(const char *a, const char *b) {
1255 if ((a[0] == '/') != (b[0] == '/'))
1261 a += strspn(a, "/");
1262 b += strspn(b, "/");
1264 if (*a == 0 && *b == 0)
1267 if (*a == 0 || *b == 0)
1270 j = strcspn(a, "/");
1271 k = strcspn(b, "/");
1276 if (memcmp(a, b, j) != 0)
1284 char *ascii_strlower(char *t) {
1289 for (p = t; *p; p++)
1290 if (*p >= 'A' && *p <= 'Z')
1291 *p = *p - 'A' + 'a';
1296 bool ignore_file(const char *filename) {
1300 filename[0] == '.' ||
1301 streq(filename, "lost+found") ||
1302 endswith(filename, "~") ||
1303 endswith(filename, ".rpmnew") ||
1304 endswith(filename, ".rpmsave") ||
1305 endswith(filename, ".rpmorig") ||
1306 endswith(filename, ".dpkg-old") ||
1307 endswith(filename, ".dpkg-new") ||
1308 endswith(filename, ".swp");
1311 int fd_nonblock(int fd, bool nonblock) {
1316 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1320 flags |= O_NONBLOCK;
1322 flags &= ~O_NONBLOCK;
1324 if (fcntl(fd, F_SETFL, flags) < 0)
1330 int fd_cloexec(int fd, bool cloexec) {
1335 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1339 flags |= FD_CLOEXEC;
1341 flags &= ~FD_CLOEXEC;
1343 if (fcntl(fd, F_SETFD, flags) < 0)
1349 int close_all_fds(const int except[], unsigned n_except) {
1354 if (!(d = opendir("/proc/self/fd")))
1357 while ((de = readdir(d))) {
1360 if (ignore_file(de->d_name))
1363 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1377 for (i = 0; i < n_except; i++)
1378 if (except[i] == fd) {
1387 if ((r = close_nointr(fd)) < 0) {
1388 /* Valgrind has its own FD and doesn't want to have it closed */
1401 bool chars_intersect(const char *a, const char *b) {
1404 /* Returns true if any of the chars in a are in b. */
1405 for (p = a; *p; p++)
1412 char *format_timestamp(char *buf, size_t l, usec_t t) {
1422 sec = (time_t) t / USEC_PER_SEC;
1424 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1430 char *format_timespan(char *buf, size_t l, usec_t t) {
1431 static const struct {
1435 { "w", USEC_PER_WEEK },
1436 { "d", USEC_PER_DAY },
1437 { "h", USEC_PER_HOUR },
1438 { "min", USEC_PER_MINUTE },
1439 { "s", USEC_PER_SEC },
1440 { "ms", USEC_PER_MSEC },
1450 if (t == (usec_t) -1)
1453 /* The result of this function can be parsed with parse_usec */
1455 for (i = 0; i < ELEMENTSOF(table); i++) {
1459 if (t < table[i].usec)
1465 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1466 n = MIN((size_t) k, l);
1479 bool fstype_is_network(const char *fstype) {
1480 static const char * const table[] = {
1492 for (i = 0; i < ELEMENTSOF(table); i++)
1493 if (streq(table[i], fstype))
1502 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1507 TIOCL_GETKMSGREDIRECT,
1511 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1514 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1517 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1520 close_nointr_nofail(r);
1524 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1525 struct termios old_termios, new_termios;
1532 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1533 new_termios = old_termios;
1535 new_termios.c_lflag &= ~ICANON;
1536 new_termios.c_cc[VMIN] = 1;
1537 new_termios.c_cc[VTIME] = 0;
1539 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1542 k = fread(&c, 1, 1, f);
1544 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1550 *need_nl = c != '\n';
1557 if (!(fgets(line, sizeof(line), f)))
1562 if (strlen(line) != 1)
1572 int ask(char *ret, const char *replies, const char *text, ...) {
1581 bool need_nl = true;
1583 fputs("\x1B[1m", stdout);
1589 fputs("\x1B[0m", stdout);
1593 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1595 if (r == -EBADMSG) {
1596 puts("Bad input, please try again.");
1607 if (strchr(replies, c)) {
1612 puts("Read unexpected character, please try again.");
1616 int reset_terminal(int fd) {
1617 struct termios termios;
1622 /* Set terminal to some sane defaults */
1624 if (tcgetattr(fd, &termios) < 0) {
1629 /* We only reset the stuff that matters to the software. How
1630 * hardware is set up we don't touch assuming that somebody
1631 * else will do that for us */
1633 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1634 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1635 termios.c_oflag |= ONLCR;
1636 termios.c_cflag |= CREAD;
1637 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1639 termios.c_cc[VINTR] = 03; /* ^C */
1640 termios.c_cc[VQUIT] = 034; /* ^\ */
1641 termios.c_cc[VERASE] = 0177;
1642 termios.c_cc[VKILL] = 025; /* ^X */
1643 termios.c_cc[VEOF] = 04; /* ^D */
1644 termios.c_cc[VSTART] = 021; /* ^Q */
1645 termios.c_cc[VSTOP] = 023; /* ^S */
1646 termios.c_cc[VSUSP] = 032; /* ^Z */
1647 termios.c_cc[VLNEXT] = 026; /* ^V */
1648 termios.c_cc[VWERASE] = 027; /* ^W */
1649 termios.c_cc[VREPRINT] = 022; /* ^R */
1650 termios.c_cc[VEOL] = 0;
1651 termios.c_cc[VEOL2] = 0;
1653 termios.c_cc[VTIME] = 0;
1654 termios.c_cc[VMIN] = 1;
1656 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1660 /* Just in case, flush all crap out */
1661 tcflush(fd, TCIOFLUSH);
1666 int open_terminal(const char *name, int mode) {
1669 if ((fd = open(name, mode)) < 0)
1672 if ((r = isatty(fd)) < 0) {
1673 close_nointr_nofail(fd);
1678 close_nointr_nofail(fd);
1685 int flush_fd(int fd) {
1686 struct pollfd pollfd;
1690 pollfd.events = POLLIN;
1697 if ((r = poll(&pollfd, 1, 0)) < 0) {
1708 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1713 if (errno == EAGAIN)
1724 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1725 int fd = -1, notify = -1, r, wd = -1;
1729 /* We use inotify to be notified when the tty is closed. We
1730 * create the watch before checking if we can actually acquire
1731 * it, so that we don't lose any event.
1733 * Note: strictly speaking this actually watches for the
1734 * device being closed, it does *not* really watch whether a
1735 * tty loses its controlling process. However, unless some
1736 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1737 * its tty otherwise this will not become a problem. As long
1738 * as the administrator makes sure not configure any service
1739 * on the same tty as an untrusted user this should not be a
1740 * problem. (Which he probably should not do anyway.) */
1742 if (!fail && !force) {
1743 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1748 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1756 if ((r = flush_fd(notify)) < 0)
1759 /* We pass here O_NOCTTY only so that we can check the return
1760 * value TIOCSCTTY and have a reliable way to figure out if we
1761 * successfully became the controlling process of the tty */
1762 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1765 /* First, try to get the tty */
1766 r = ioctl(fd, TIOCSCTTY, force);
1768 /* Sometimes it makes sense to ignore TIOCSCTTY
1769 * returning EPERM, i.e. when very likely we already
1770 * are have this controlling terminal. */
1771 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1774 if (r < 0 && (force || fail || errno != EPERM)) {
1784 assert(notify >= 0);
1787 struct inotify_event e;
1790 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1804 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1812 /* We close the tty fd here since if the old session
1813 * ended our handle will be dead. It's important that
1814 * we do this after sleeping, so that we don't enter
1815 * an endless loop. */
1816 close_nointr_nofail(fd);
1820 close_nointr_nofail(notify);
1822 if ((r = reset_terminal(fd)) < 0)
1823 log_warning("Failed to reset terminal: %s", strerror(-r));
1829 close_nointr_nofail(fd);
1832 close_nointr_nofail(notify);
1837 int release_terminal(void) {
1839 struct sigaction sa_old, sa_new;
1841 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1844 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1845 * by our own TIOCNOTTY */
1848 sa_new.sa_handler = SIG_IGN;
1849 sa_new.sa_flags = SA_RESTART;
1850 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1852 if (ioctl(fd, TIOCNOTTY) < 0)
1855 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1857 close_nointr_nofail(fd);
1861 int sigaction_many(const struct sigaction *sa, ...) {
1866 while ((sig = va_arg(ap, int)) > 0)
1867 if (sigaction(sig, sa, NULL) < 0)
1874 int ignore_signals(int sig, ...) {
1875 struct sigaction sa;
1880 sa.sa_handler = SIG_IGN;
1881 sa.sa_flags = SA_RESTART;
1883 if (sigaction(sig, &sa, NULL) < 0)
1887 while ((sig = va_arg(ap, int)) > 0)
1888 if (sigaction(sig, &sa, NULL) < 0)
1895 int default_signals(int sig, ...) {
1896 struct sigaction sa;
1901 sa.sa_handler = SIG_DFL;
1902 sa.sa_flags = SA_RESTART;
1904 if (sigaction(sig, &sa, NULL) < 0)
1908 while ((sig = va_arg(ap, int)) > 0)
1909 if (sigaction(sig, &sa, NULL) < 0)
1916 int close_pipe(int p[]) {
1922 a = close_nointr(p[0]);
1927 b = close_nointr(p[1]);
1931 return a < 0 ? a : b;
1934 ssize_t loop_read(int fd, void *buf, size_t nbytes) {
1943 while (nbytes > 0) {
1946 if ((k = read(fd, p, nbytes)) <= 0) {
1951 if (errno == EAGAIN) {
1952 struct pollfd pollfd;
1956 pollfd.events = POLLIN;
1958 if (poll(&pollfd, 1, -1) < 0) {
1962 return n > 0 ? n : -errno;
1965 if (pollfd.revents != POLLIN)
1966 return n > 0 ? n : -EIO;
1971 return n > 0 ? n : (k < 0 ? -errno : 0);
1982 int path_is_mount_point(const char *t) {
1986 if (lstat(t, &a) < 0) {
1988 if (errno == ENOENT)
1994 if (!(copy = strdup(t)))
1997 if (lstat(dirname(copy), &b) < 0) {
2004 return a.st_dev != b.st_dev;
2007 int parse_usec(const char *t, usec_t *usec) {
2008 static const struct {
2012 { "sec", USEC_PER_SEC },
2013 { "s", USEC_PER_SEC },
2014 { "min", USEC_PER_MINUTE },
2015 { "hr", USEC_PER_HOUR },
2016 { "h", USEC_PER_HOUR },
2017 { "d", USEC_PER_DAY },
2018 { "w", USEC_PER_WEEK },
2019 { "msec", USEC_PER_MSEC },
2020 { "ms", USEC_PER_MSEC },
2021 { "m", USEC_PER_MINUTE },
2024 { "", USEC_PER_SEC },
2040 l = strtoll(p, &e, 10);
2051 e += strspn(e, WHITESPACE);
2053 for (i = 0; i < ELEMENTSOF(table); i++)
2054 if (startswith(e, table[i].suffix)) {
2055 r += (usec_t) l * table[i].usec;
2056 p = e + strlen(table[i].suffix);
2060 if (i >= ELEMENTSOF(table))
2070 int make_stdio(int fd) {
2075 r = dup2(fd, STDIN_FILENO);
2076 s = dup2(fd, STDOUT_FILENO);
2077 t = dup2(fd, STDERR_FILENO);
2080 close_nointr_nofail(fd);
2082 if (r < 0 || s < 0 || t < 0)
2088 bool is_clean_exit(int code, int status) {
2090 if (code == CLD_EXITED)
2093 /* If a daemon does not implement handlers for some of the
2094 * signals that's not considered an unclean shutdown */
2095 if (code == CLD_KILLED)
2099 status == SIGTERM ||
2105 bool is_device_path(const char *path) {
2107 /* Returns true on paths that refer to a device, either in
2108 * sysfs or in /dev */
2111 path_startswith(path, "/dev/") ||
2112 path_startswith(path, "/sys/");
2115 int dir_is_empty(const char *path) {
2118 struct dirent buf, *de;
2120 if (!(d = opendir(path)))
2124 if ((r = readdir_r(d, &buf, &de)) > 0) {
2134 if (!ignore_file(de->d_name)) {
2144 unsigned long long random_ull(void) {
2149 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2152 r = loop_read(fd, &ull, sizeof(ull));
2153 close_nointr_nofail(fd);
2155 if (r != sizeof(ull))
2161 return random() * RAND_MAX + random();
2164 static const char *const ioprio_class_table[] = {
2165 [IOPRIO_CLASS_NONE] = "none",
2166 [IOPRIO_CLASS_RT] = "realtime",
2167 [IOPRIO_CLASS_BE] = "best-effort",
2168 [IOPRIO_CLASS_IDLE] = "idle"
2171 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2173 static const char *const sigchld_code_table[] = {
2174 [CLD_EXITED] = "exited",
2175 [CLD_KILLED] = "killed",
2176 [CLD_DUMPED] = "dumped",
2177 [CLD_TRAPPED] = "trapped",
2178 [CLD_STOPPED] = "stopped",
2179 [CLD_CONTINUED] = "continued",
2182 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2184 static const char *const log_facility_table[LOG_NFACILITIES] = {
2185 [LOG_FAC(LOG_KERN)] = "kern",
2186 [LOG_FAC(LOG_USER)] = "user",
2187 [LOG_FAC(LOG_MAIL)] = "mail",
2188 [LOG_FAC(LOG_DAEMON)] = "daemon",
2189 [LOG_FAC(LOG_AUTH)] = "auth",
2190 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2191 [LOG_FAC(LOG_LPR)] = "lpr",
2192 [LOG_FAC(LOG_NEWS)] = "news",
2193 [LOG_FAC(LOG_UUCP)] = "uucp",
2194 [LOG_FAC(LOG_CRON)] = "cron",
2195 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2196 [LOG_FAC(LOG_FTP)] = "ftp",
2197 [LOG_FAC(LOG_LOCAL0)] = "local0",
2198 [LOG_FAC(LOG_LOCAL1)] = "local1",
2199 [LOG_FAC(LOG_LOCAL2)] = "local2",
2200 [LOG_FAC(LOG_LOCAL3)] = "local3",
2201 [LOG_FAC(LOG_LOCAL4)] = "local4",
2202 [LOG_FAC(LOG_LOCAL5)] = "local5",
2203 [LOG_FAC(LOG_LOCAL6)] = "local6",
2204 [LOG_FAC(LOG_LOCAL7)] = "local7"
2207 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2209 static const char *const log_level_table[] = {
2210 [LOG_EMERG] = "emerg",
2211 [LOG_ALERT] = "alert",
2212 [LOG_CRIT] = "crit",
2214 [LOG_WARNING] = "warning",
2215 [LOG_NOTICE] = "notice",
2216 [LOG_INFO] = "info",
2217 [LOG_DEBUG] = "debug"
2220 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2222 static const char* const sched_policy_table[] = {
2223 [SCHED_OTHER] = "other",
2224 [SCHED_BATCH] = "batch",
2225 [SCHED_IDLE] = "idle",
2226 [SCHED_FIFO] = "fifo",
2230 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2232 static const char* const rlimit_table[] = {
2233 [RLIMIT_CPU] = "LimitCPU",
2234 [RLIMIT_FSIZE] = "LimitFSIZE",
2235 [RLIMIT_DATA] = "LimitDATA",
2236 [RLIMIT_STACK] = "LimitSTACK",
2237 [RLIMIT_CORE] = "LimitCORE",
2238 [RLIMIT_RSS] = "LimitRSS",
2239 [RLIMIT_NOFILE] = "LimitNOFILE",
2240 [RLIMIT_AS] = "LimitAS",
2241 [RLIMIT_NPROC] = "LimitNPROC",
2242 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2243 [RLIMIT_LOCKS] = "LimitLOCKS",
2244 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2245 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2246 [RLIMIT_NICE] = "LimitNICE",
2247 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2248 [RLIMIT_RTTIME] = "LimitRTTIME"
2251 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);