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>
55 bool streq_ptr(const char *a, const char *b) {
57 /* Like streq(), but tries to make sense of NULL pointers */
68 usec_t now(clockid_t clock_id) {
71 assert_se(clock_gettime(clock_id, &ts) == 0);
73 return timespec_load(&ts);
76 timestamp* timestamp_get(timestamp *ts) {
79 ts->realtime = now(CLOCK_REALTIME);
80 ts->monotonic = now(CLOCK_MONOTONIC);
85 usec_t timespec_load(const struct timespec *ts) {
89 (usec_t) ts->tv_sec * USEC_PER_SEC +
90 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
93 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
96 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
97 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
102 usec_t timeval_load(const struct timeval *tv) {
106 (usec_t) tv->tv_sec * USEC_PER_SEC +
107 (usec_t) tv->tv_usec;
110 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
113 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
114 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
119 bool endswith(const char *s, const char *postfix) {
126 pl = strlen(postfix);
134 return memcmp(s + sl - pl, postfix, pl) == 0;
137 bool startswith(const char *s, const char *prefix) {
152 return memcmp(s, prefix, pl) == 0;
155 bool startswith_no_case(const char *s, const char *prefix) {
171 for(i = 0; i < pl; ++i) {
172 if (tolower(s[i]) != tolower(prefix[i]))
179 bool first_word(const char *s, const char *word) {
194 if (memcmp(s, word, wl) != 0)
198 strchr(WHITESPACE, s[wl]);
201 int close_nointr(int fd) {
207 if ((r = close(fd)) >= 0)
215 void close_nointr_nofail(int fd) {
216 int saved_errno = errno;
218 /* like close_nointr() but cannot fail, and guarantees errno
221 assert_se(close_nointr(fd) == 0);
226 void close_many(const int fds[], unsigned n_fd) {
229 for (i = 0; i < n_fd; i++)
230 close_nointr_nofail(fds[i]);
233 int parse_boolean(const char *v) {
236 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
238 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
244 int safe_atou(const char *s, unsigned *ret_u) {
252 l = strtoul(s, &x, 0);
254 if (!x || *x || errno)
255 return errno ? -errno : -EINVAL;
257 if ((unsigned long) (unsigned) l != l)
260 *ret_u = (unsigned) l;
264 int safe_atoi(const char *s, int *ret_i) {
272 l = strtol(s, &x, 0);
274 if (!x || *x || errno)
275 return errno ? -errno : -EINVAL;
277 if ((long) (int) l != l)
284 int safe_atolu(const char *s, long unsigned *ret_lu) {
292 l = strtoul(s, &x, 0);
294 if (!x || *x || errno)
295 return errno ? -errno : -EINVAL;
301 int safe_atoli(const char *s, long int *ret_li) {
309 l = strtol(s, &x, 0);
311 if (!x || *x || errno)
312 return errno ? -errno : -EINVAL;
318 int safe_atollu(const char *s, long long unsigned *ret_llu) {
320 unsigned long long l;
326 l = strtoull(s, &x, 0);
328 if (!x || *x || errno)
329 return errno ? -errno : -EINVAL;
335 int safe_atolli(const char *s, long long int *ret_lli) {
343 l = strtoll(s, &x, 0);
345 if (!x || *x || errno)
346 return errno ? -errno : -EINVAL;
352 /* Split a string into words. */
353 char *split(const char *c, size_t *l, const char *separator, char **state) {
356 current = *state ? *state : (char*) c;
358 if (!*current || *c == 0)
361 current += strspn(current, separator);
362 *l = strcspn(current, separator);
365 return (char*) current;
368 /* Split a string into words, but consider strings enclosed in '' and
369 * "" as words even if they include spaces. */
370 char *split_quoted(const char *c, size_t *l, char **state) {
373 current = *state ? *state : (char*) c;
375 if (!*current || *c == 0)
378 current += strspn(current, WHITESPACE);
380 if (*current == '\'') {
382 *l = strcspn(current, "'");
387 } else if (*current == '\"') {
389 *l = strcspn(current, "\"");
395 *l = strcspn(current, WHITESPACE);
399 /* FIXME: Cannot deal with strings that have spaces AND ticks
402 return (char*) current;
405 char **split_path_and_make_absolute(const char *p) {
409 if (!(l = strv_split(p, ":")))
412 if (!strv_path_make_absolute_cwd(l)) {
420 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
423 char fn[132], line[256], *p;
424 long long unsigned ppid;
429 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
430 fn[sizeof(fn)-1] = 0;
432 if (!(f = fopen(fn, "r")))
435 if (!(fgets(line, sizeof(line), f))) {
443 /* Let's skip the pid and comm fields. The latter is enclosed
444 * in () but does not escape any () in its value, so let's
445 * skip over it manually */
447 if (!(p = strrchr(line, ')')))
458 if ((long long unsigned) (pid_t) ppid != ppid)
461 *_ppid = (pid_t) ppid;
466 int write_one_line_file(const char *fn, const char *line) {
473 if (!(f = fopen(fn, "we")))
476 if (fputs(line, f) < 0) {
487 int read_one_line_file(const char *fn, char **line) {
495 if (!(f = fopen(fn, "re")))
498 if (!(fgets(t, sizeof(t), f))) {
503 if (!(c = strdup(t))) {
516 char *truncate_nl(char *s) {
519 s[strcspn(s, NEWLINE)] = 0;
523 int get_process_name(pid_t pid, char **name) {
530 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
533 r = read_one_line_file(p, name);
543 char *strappend(const char *s, const char *suffix) {
553 if (!(r = new(char, a+b+1)))
557 memcpy(r+a, suffix, b);
563 int readlink_malloc(const char *p, char **r) {
573 if (!(c = new(char, l)))
576 if ((n = readlink(p, c, l-1)) < 0) {
582 if ((size_t) n < l-1) {
593 int readlink_and_make_absolute(const char *p, char **r) {
600 if ((j = readlink_malloc(p, &target)) < 0)
603 k = file_in_same_dir(p, target);
613 char *file_name_from_path(const char *p) {
618 if ((r = strrchr(p, '/')))
624 bool path_is_absolute(const char *p) {
630 bool is_path(const char *p) {
632 return !!strchr(p, '/');
635 char *path_make_absolute(const char *p, const char *prefix) {
640 /* Makes every item in the list an absolute path by prepending
641 * the prefix, if specified and necessary */
643 if (path_is_absolute(p) || !prefix)
646 if (asprintf(&r, "%s/%s", prefix, p) < 0)
652 char *path_make_absolute_cwd(const char *p) {
657 /* Similar to path_make_absolute(), but prefixes with the
658 * current working directory. */
660 if (path_is_absolute(p))
663 if (!(cwd = get_current_dir_name()))
666 r = path_make_absolute(p, cwd);
672 char **strv_path_make_absolute_cwd(char **l) {
675 /* Goes through every item in the string list and makes it
676 * absolute. This works in place and won't rollback any
677 * changes on failure. */
682 if (!(t = path_make_absolute_cwd(*s)))
692 char **strv_path_canonicalize(char **l) {
700 /* Goes through every item in the string list and canonicalize
701 * the path. This works in place and won't rollback any
702 * changes on failure. */
707 t = path_make_absolute_cwd(*s);
716 u = canonicalize_file_name(t);
720 if (errno == ENOMEM || !errno)
737 int reset_all_signal_handlers(void) {
740 for (sig = 1; sig < _NSIG; sig++) {
743 if (sig == SIGKILL || sig == SIGSTOP)
747 sa.sa_handler = SIG_DFL;
748 sa.sa_flags = SA_RESTART;
750 /* On Linux the first two RT signals are reserved by
751 * glibc, and sigaction() will return EINVAL for them. */
752 if ((sigaction(sig, &sa, NULL) < 0))
760 char *strstrip(char *s) {
763 /* Drops trailing whitespace. Modifies the string in
764 * place. Returns pointer to first non-space character */
766 s += strspn(s, WHITESPACE);
769 if (!strchr(WHITESPACE, *e))
780 char *delete_chars(char *s, const char *bad) {
783 /* Drops all whitespace, regardless where in the string */
785 for (f = s, t = s; *f; f++) {
797 char *file_in_same_dir(const char *path, const char *filename) {
804 /* This removes the last component of path and appends
805 * filename, unless the latter is absolute anyway or the
808 if (path_is_absolute(filename))
809 return strdup(filename);
811 if (!(e = strrchr(path, '/')))
812 return strdup(filename);
814 k = strlen(filename);
815 if (!(r = new(char, e-path+1+k+1)))
818 memcpy(r, path, e-path+1);
819 memcpy(r+(e-path)+1, filename, k+1);
824 int mkdir_parents(const char *path, mode_t mode) {
829 /* Creates every parent directory in the path except the last
832 p = path + strspn(path, "/");
837 e = p + strcspn(p, "/");
838 p = e + strspn(e, "/");
840 /* Is this the last component? If so, then we're
845 if (!(t = strndup(path, e - path)))
852 if (r < 0 && errno != EEXIST)
857 int mkdir_p(const char *path, mode_t mode) {
862 if ((r = mkdir_parents(path, mode)) < 0)
865 if (mkdir(path, mode) < 0)
871 char hexchar(int x) {
872 static const char table[16] = "0123456789abcdef";
874 return table[x & 15];
877 int unhexchar(char c) {
879 if (c >= '0' && c <= '9')
882 if (c >= 'a' && c <= 'f')
885 if (c >= 'A' && c <= 'F')
891 char octchar(int x) {
892 return '0' + (x & 7);
895 int unoctchar(char c) {
897 if (c >= '0' && c <= '7')
903 char decchar(int x) {
904 return '0' + (x % 10);
907 int undecchar(char c) {
909 if (c >= '0' && c <= '9')
915 char *cescape(const char *s) {
921 /* Does C style string escaping. */
923 if (!(r = new(char, strlen(s)*4 + 1)))
926 for (f = s, t = r; *f; f++)
972 /* For special chars we prefer octal over
973 * hexadecimal encoding, simply because glib's
974 * g_strescape() does the same */
975 if ((*f < ' ') || (*f >= 127)) {
977 *(t++) = octchar((unsigned char) *f >> 6);
978 *(t++) = octchar((unsigned char) *f >> 3);
979 *(t++) = octchar((unsigned char) *f);
990 char *cunescape(const char *s) {
996 /* Undoes C style string escaping */
998 if (!(r = new(char, strlen(s)+1)))
1001 for (f = s, t = r; *f; f++) {
1044 /* hexadecimal encoding */
1047 if ((a = unhexchar(f[1])) < 0 ||
1048 (b = unhexchar(f[2])) < 0) {
1049 /* Invalid escape code, let's take it literal then */
1053 *(t++) = (char) ((a << 4) | b);
1068 /* octal encoding */
1071 if ((a = unoctchar(f[0])) < 0 ||
1072 (b = unoctchar(f[1])) < 0 ||
1073 (c = unoctchar(f[2])) < 0) {
1074 /* Invalid escape code, let's take it literal then */
1078 *(t++) = (char) ((a << 6) | (b << 3) | c);
1086 /* premature end of string.*/
1091 /* Invalid escape code, let's take it literal then */
1104 char *xescape(const char *s, const char *bad) {
1108 /* Escapes all chars in bad, in addition to \ and all special
1109 * chars, in \xFF style escaping. May be reversed with
1112 if (!(r = new(char, strlen(s)*4+1)))
1115 for (f = s, t = r; *f; f++) {
1117 if ((*f < ' ') || (*f >= 127) ||
1118 (*f == '\\') || strchr(bad, *f)) {
1121 *(t++) = hexchar(*f >> 4);
1122 *(t++) = hexchar(*f);
1132 char *bus_path_escape(const char *s) {
1138 /* Escapes all chars that D-Bus' object path cannot deal
1139 * with. Can be reverse with bus_path_unescape() */
1141 if (!(r = new(char, strlen(s)*3+1)))
1144 for (f = s, t = r; *f; f++) {
1146 if (!(*f >= 'A' && *f <= 'Z') &&
1147 !(*f >= 'a' && *f <= 'z') &&
1148 !(*f >= '0' && *f <= '9')) {
1150 *(t++) = hexchar(*f >> 4);
1151 *(t++) = hexchar(*f);
1161 char *bus_path_unescape(const char *f) {
1166 if (!(r = strdup(f)))
1169 for (t = r; *f; f++) {
1174 if ((a = unhexchar(f[1])) < 0 ||
1175 (b = unhexchar(f[2])) < 0) {
1176 /* Invalid escape code, let's take it literal then */
1179 *(t++) = (char) ((a << 4) | b);
1191 char *path_kill_slashes(char *path) {
1195 /* Removes redundant inner and trailing slashes. Modifies the
1196 * passed string in-place.
1198 * ///foo///bar/ becomes /foo/bar
1201 for (f = path, t = path; *f; f++) {
1216 /* Special rule, if we are talking of the root directory, a
1217 trailing slash is good */
1219 if (t == path && slash)
1226 bool path_startswith(const char *path, const char *prefix) {
1230 if ((path[0] == '/') != (prefix[0] == '/'))
1236 path += strspn(path, "/");
1237 prefix += strspn(prefix, "/");
1245 a = strcspn(path, "/");
1246 b = strcspn(prefix, "/");
1251 if (memcmp(path, prefix, a) != 0)
1259 bool path_equal(const char *a, const char *b) {
1263 if ((a[0] == '/') != (b[0] == '/'))
1269 a += strspn(a, "/");
1270 b += strspn(b, "/");
1272 if (*a == 0 && *b == 0)
1275 if (*a == 0 || *b == 0)
1278 j = strcspn(a, "/");
1279 k = strcspn(b, "/");
1284 if (memcmp(a, b, j) != 0)
1292 char *ascii_strlower(char *t) {
1297 for (p = t; *p; p++)
1298 if (*p >= 'A' && *p <= 'Z')
1299 *p = *p - 'A' + 'a';
1304 bool ignore_file(const char *filename) {
1308 filename[0] == '.' ||
1309 streq(filename, "lost+found") ||
1310 endswith(filename, "~") ||
1311 endswith(filename, ".rpmnew") ||
1312 endswith(filename, ".rpmsave") ||
1313 endswith(filename, ".rpmorig") ||
1314 endswith(filename, ".dpkg-old") ||
1315 endswith(filename, ".dpkg-new") ||
1316 endswith(filename, ".swp");
1319 int fd_nonblock(int fd, bool nonblock) {
1324 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1328 flags |= O_NONBLOCK;
1330 flags &= ~O_NONBLOCK;
1332 if (fcntl(fd, F_SETFL, flags) < 0)
1338 int fd_cloexec(int fd, bool cloexec) {
1343 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1347 flags |= FD_CLOEXEC;
1349 flags &= ~FD_CLOEXEC;
1351 if (fcntl(fd, F_SETFD, flags) < 0)
1357 int close_all_fds(const int except[], unsigned n_except) {
1362 if (!(d = opendir("/proc/self/fd")))
1365 while ((de = readdir(d))) {
1368 if (ignore_file(de->d_name))
1371 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1385 for (i = 0; i < n_except; i++)
1386 if (except[i] == fd) {
1395 if ((r = close_nointr(fd)) < 0) {
1396 /* Valgrind has its own FD and doesn't want to have it closed */
1409 bool chars_intersect(const char *a, const char *b) {
1412 /* Returns true if any of the chars in a are in b. */
1413 for (p = a; *p; p++)
1420 char *format_timestamp(char *buf, size_t l, usec_t t) {
1430 sec = (time_t) t / USEC_PER_SEC;
1432 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1438 char *format_timespan(char *buf, size_t l, usec_t t) {
1439 static const struct {
1443 { "w", USEC_PER_WEEK },
1444 { "d", USEC_PER_DAY },
1445 { "h", USEC_PER_HOUR },
1446 { "min", USEC_PER_MINUTE },
1447 { "s", USEC_PER_SEC },
1448 { "ms", USEC_PER_MSEC },
1458 if (t == (usec_t) -1)
1461 /* The result of this function can be parsed with parse_usec */
1463 for (i = 0; i < ELEMENTSOF(table); i++) {
1467 if (t < table[i].usec)
1473 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1474 n = MIN((size_t) k, l);
1487 bool fstype_is_network(const char *fstype) {
1488 static const char * const table[] = {
1500 for (i = 0; i < ELEMENTSOF(table); i++)
1501 if (streq(table[i], fstype))
1510 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1515 TIOCL_GETKMSGREDIRECT,
1519 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1522 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1525 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1528 close_nointr_nofail(r);
1532 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1533 struct termios old_termios, new_termios;
1540 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1541 new_termios = old_termios;
1543 new_termios.c_lflag &= ~ICANON;
1544 new_termios.c_cc[VMIN] = 1;
1545 new_termios.c_cc[VTIME] = 0;
1547 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1550 k = fread(&c, 1, 1, f);
1552 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1558 *need_nl = c != '\n';
1565 if (!(fgets(line, sizeof(line), f)))
1570 if (strlen(line) != 1)
1580 int ask(char *ret, const char *replies, const char *text, ...) {
1589 bool need_nl = true;
1591 fputs("\x1B[1m", stdout);
1597 fputs("\x1B[0m", stdout);
1601 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1603 if (r == -EBADMSG) {
1604 puts("Bad input, please try again.");
1615 if (strchr(replies, c)) {
1620 puts("Read unexpected character, please try again.");
1624 int reset_terminal(int fd) {
1625 struct termios termios;
1630 /* Set terminal to some sane defaults */
1632 if (tcgetattr(fd, &termios) < 0) {
1637 /* We only reset the stuff that matters to the software. How
1638 * hardware is set up we don't touch assuming that somebody
1639 * else will do that for us */
1641 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1642 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1643 termios.c_oflag |= ONLCR;
1644 termios.c_cflag |= CREAD;
1645 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1647 termios.c_cc[VINTR] = 03; /* ^C */
1648 termios.c_cc[VQUIT] = 034; /* ^\ */
1649 termios.c_cc[VERASE] = 0177;
1650 termios.c_cc[VKILL] = 025; /* ^X */
1651 termios.c_cc[VEOF] = 04; /* ^D */
1652 termios.c_cc[VSTART] = 021; /* ^Q */
1653 termios.c_cc[VSTOP] = 023; /* ^S */
1654 termios.c_cc[VSUSP] = 032; /* ^Z */
1655 termios.c_cc[VLNEXT] = 026; /* ^V */
1656 termios.c_cc[VWERASE] = 027; /* ^W */
1657 termios.c_cc[VREPRINT] = 022; /* ^R */
1658 termios.c_cc[VEOL] = 0;
1659 termios.c_cc[VEOL2] = 0;
1661 termios.c_cc[VTIME] = 0;
1662 termios.c_cc[VMIN] = 1;
1664 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1668 /* Just in case, flush all crap out */
1669 tcflush(fd, TCIOFLUSH);
1674 int open_terminal(const char *name, int mode) {
1677 if ((fd = open(name, mode)) < 0)
1680 if ((r = isatty(fd)) < 0) {
1681 close_nointr_nofail(fd);
1686 close_nointr_nofail(fd);
1693 int flush_fd(int fd) {
1694 struct pollfd pollfd;
1698 pollfd.events = POLLIN;
1705 if ((r = poll(&pollfd, 1, 0)) < 0) {
1716 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1721 if (errno == EAGAIN)
1732 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1733 int fd = -1, notify = -1, r, wd = -1;
1737 /* We use inotify to be notified when the tty is closed. We
1738 * create the watch before checking if we can actually acquire
1739 * it, so that we don't lose any event.
1741 * Note: strictly speaking this actually watches for the
1742 * device being closed, it does *not* really watch whether a
1743 * tty loses its controlling process. However, unless some
1744 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1745 * its tty otherwise this will not become a problem. As long
1746 * as the administrator makes sure not configure any service
1747 * on the same tty as an untrusted user this should not be a
1748 * problem. (Which he probably should not do anyway.) */
1750 if (!fail && !force) {
1751 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1756 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1764 if ((r = flush_fd(notify)) < 0)
1767 /* We pass here O_NOCTTY only so that we can check the return
1768 * value TIOCSCTTY and have a reliable way to figure out if we
1769 * successfully became the controlling process of the tty */
1770 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1773 /* First, try to get the tty */
1774 r = ioctl(fd, TIOCSCTTY, force);
1776 /* Sometimes it makes sense to ignore TIOCSCTTY
1777 * returning EPERM, i.e. when very likely we already
1778 * are have this controlling terminal. */
1779 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1782 if (r < 0 && (force || fail || errno != EPERM)) {
1792 assert(notify >= 0);
1795 struct inotify_event e;
1798 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1812 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1820 /* We close the tty fd here since if the old session
1821 * ended our handle will be dead. It's important that
1822 * we do this after sleeping, so that we don't enter
1823 * an endless loop. */
1824 close_nointr_nofail(fd);
1828 close_nointr_nofail(notify);
1830 if ((r = reset_terminal(fd)) < 0)
1831 log_warning("Failed to reset terminal: %s", strerror(-r));
1837 close_nointr_nofail(fd);
1840 close_nointr_nofail(notify);
1845 int release_terminal(void) {
1847 struct sigaction sa_old, sa_new;
1849 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1852 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1853 * by our own TIOCNOTTY */
1856 sa_new.sa_handler = SIG_IGN;
1857 sa_new.sa_flags = SA_RESTART;
1858 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1860 if (ioctl(fd, TIOCNOTTY) < 0)
1863 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1865 close_nointr_nofail(fd);
1869 int sigaction_many(const struct sigaction *sa, ...) {
1874 while ((sig = va_arg(ap, int)) > 0)
1875 if (sigaction(sig, sa, NULL) < 0)
1882 int ignore_signals(int sig, ...) {
1883 struct sigaction sa;
1888 sa.sa_handler = SIG_IGN;
1889 sa.sa_flags = SA_RESTART;
1891 if (sigaction(sig, &sa, NULL) < 0)
1895 while ((sig = va_arg(ap, int)) > 0)
1896 if (sigaction(sig, &sa, NULL) < 0)
1903 int default_signals(int sig, ...) {
1904 struct sigaction sa;
1909 sa.sa_handler = SIG_DFL;
1910 sa.sa_flags = SA_RESTART;
1912 if (sigaction(sig, &sa, NULL) < 0)
1916 while ((sig = va_arg(ap, int)) > 0)
1917 if (sigaction(sig, &sa, NULL) < 0)
1924 int close_pipe(int p[]) {
1930 a = close_nointr(p[0]);
1935 b = close_nointr(p[1]);
1939 return a < 0 ? a : b;
1942 ssize_t loop_read(int fd, void *buf, size_t nbytes) {
1951 while (nbytes > 0) {
1954 if ((k = read(fd, p, nbytes)) <= 0) {
1959 if (errno == EAGAIN) {
1960 struct pollfd pollfd;
1964 pollfd.events = POLLIN;
1966 if (poll(&pollfd, 1, -1) < 0) {
1970 return n > 0 ? n : -errno;
1973 if (pollfd.revents != POLLIN)
1974 return n > 0 ? n : -EIO;
1979 return n > 0 ? n : (k < 0 ? -errno : 0);
1990 int path_is_mount_point(const char *t) {
1994 if (lstat(t, &a) < 0) {
1996 if (errno == ENOENT)
2002 if (!(copy = strdup(t)))
2005 if (lstat(dirname(copy), &b) < 0) {
2012 return a.st_dev != b.st_dev;
2015 int parse_usec(const char *t, usec_t *usec) {
2016 static const struct {
2020 { "sec", USEC_PER_SEC },
2021 { "s", USEC_PER_SEC },
2022 { "min", USEC_PER_MINUTE },
2023 { "hr", USEC_PER_HOUR },
2024 { "h", USEC_PER_HOUR },
2025 { "d", USEC_PER_DAY },
2026 { "w", USEC_PER_WEEK },
2027 { "msec", USEC_PER_MSEC },
2028 { "ms", USEC_PER_MSEC },
2029 { "m", USEC_PER_MINUTE },
2032 { "", USEC_PER_SEC },
2048 l = strtoll(p, &e, 10);
2059 e += strspn(e, WHITESPACE);
2061 for (i = 0; i < ELEMENTSOF(table); i++)
2062 if (startswith(e, table[i].suffix)) {
2063 r += (usec_t) l * table[i].usec;
2064 p = e + strlen(table[i].suffix);
2068 if (i >= ELEMENTSOF(table))
2078 int make_stdio(int fd) {
2083 r = dup2(fd, STDIN_FILENO);
2084 s = dup2(fd, STDOUT_FILENO);
2085 t = dup2(fd, STDERR_FILENO);
2088 close_nointr_nofail(fd);
2090 if (r < 0 || s < 0 || t < 0)
2096 bool is_clean_exit(int code, int status) {
2098 if (code == CLD_EXITED)
2101 /* If a daemon does not implement handlers for some of the
2102 * signals that's not considered an unclean shutdown */
2103 if (code == CLD_KILLED)
2107 status == SIGTERM ||
2113 bool is_device_path(const char *path) {
2115 /* Returns true on paths that refer to a device, either in
2116 * sysfs or in /dev */
2119 path_startswith(path, "/dev/") ||
2120 path_startswith(path, "/sys/");
2123 int dir_is_empty(const char *path) {
2126 struct dirent buf, *de;
2128 if (!(d = opendir(path)))
2132 if ((r = readdir_r(d, &buf, &de)) > 0) {
2142 if (!ignore_file(de->d_name)) {
2152 unsigned long long random_ull(void) {
2157 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2160 r = loop_read(fd, &ull, sizeof(ull));
2161 close_nointr_nofail(fd);
2163 if (r != sizeof(ull))
2169 return random() * RAND_MAX + random();
2172 void rename_process(const char name[8]) {
2175 prctl(PR_SET_NAME, name);
2177 /* This is a like a poor man's setproctitle(). The string
2178 * passed should fit in 7 chars (i.e. the length of
2181 if (program_invocation_name)
2182 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2185 static const char *const ioprio_class_table[] = {
2186 [IOPRIO_CLASS_NONE] = "none",
2187 [IOPRIO_CLASS_RT] = "realtime",
2188 [IOPRIO_CLASS_BE] = "best-effort",
2189 [IOPRIO_CLASS_IDLE] = "idle"
2192 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2194 static const char *const sigchld_code_table[] = {
2195 [CLD_EXITED] = "exited",
2196 [CLD_KILLED] = "killed",
2197 [CLD_DUMPED] = "dumped",
2198 [CLD_TRAPPED] = "trapped",
2199 [CLD_STOPPED] = "stopped",
2200 [CLD_CONTINUED] = "continued",
2203 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2205 static const char *const log_facility_table[LOG_NFACILITIES] = {
2206 [LOG_FAC(LOG_KERN)] = "kern",
2207 [LOG_FAC(LOG_USER)] = "user",
2208 [LOG_FAC(LOG_MAIL)] = "mail",
2209 [LOG_FAC(LOG_DAEMON)] = "daemon",
2210 [LOG_FAC(LOG_AUTH)] = "auth",
2211 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2212 [LOG_FAC(LOG_LPR)] = "lpr",
2213 [LOG_FAC(LOG_NEWS)] = "news",
2214 [LOG_FAC(LOG_UUCP)] = "uucp",
2215 [LOG_FAC(LOG_CRON)] = "cron",
2216 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2217 [LOG_FAC(LOG_FTP)] = "ftp",
2218 [LOG_FAC(LOG_LOCAL0)] = "local0",
2219 [LOG_FAC(LOG_LOCAL1)] = "local1",
2220 [LOG_FAC(LOG_LOCAL2)] = "local2",
2221 [LOG_FAC(LOG_LOCAL3)] = "local3",
2222 [LOG_FAC(LOG_LOCAL4)] = "local4",
2223 [LOG_FAC(LOG_LOCAL5)] = "local5",
2224 [LOG_FAC(LOG_LOCAL6)] = "local6",
2225 [LOG_FAC(LOG_LOCAL7)] = "local7"
2228 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2230 static const char *const log_level_table[] = {
2231 [LOG_EMERG] = "emerg",
2232 [LOG_ALERT] = "alert",
2233 [LOG_CRIT] = "crit",
2235 [LOG_WARNING] = "warning",
2236 [LOG_NOTICE] = "notice",
2237 [LOG_INFO] = "info",
2238 [LOG_DEBUG] = "debug"
2241 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2243 static const char* const sched_policy_table[] = {
2244 [SCHED_OTHER] = "other",
2245 [SCHED_BATCH] = "batch",
2246 [SCHED_IDLE] = "idle",
2247 [SCHED_FIFO] = "fifo",
2251 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2253 static const char* const rlimit_table[] = {
2254 [RLIMIT_CPU] = "LimitCPU",
2255 [RLIMIT_FSIZE] = "LimitFSIZE",
2256 [RLIMIT_DATA] = "LimitDATA",
2257 [RLIMIT_STACK] = "LimitSTACK",
2258 [RLIMIT_CORE] = "LimitCORE",
2259 [RLIMIT_RSS] = "LimitRSS",
2260 [RLIMIT_NOFILE] = "LimitNOFILE",
2261 [RLIMIT_AS] = "LimitAS",
2262 [RLIMIT_NPROC] = "LimitNPROC",
2263 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2264 [RLIMIT_LOCKS] = "LimitLOCKS",
2265 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2266 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2267 [RLIMIT_NICE] = "LimitNICE",
2268 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2269 [RLIMIT_RTTIME] = "LimitRTTIME"
2272 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);