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 usec_t timespec_load(const struct timespec *ts) {
79 (usec_t) ts->tv_sec * USEC_PER_SEC +
80 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
83 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
86 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
87 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
92 usec_t timeval_load(const struct timeval *tv) {
96 (usec_t) tv->tv_sec * USEC_PER_SEC +
100 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
103 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
104 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
109 bool endswith(const char *s, const char *postfix) {
116 pl = strlen(postfix);
124 return memcmp(s + sl - pl, postfix, pl) == 0;
127 bool startswith(const char *s, const char *prefix) {
142 return memcmp(s, prefix, pl) == 0;
145 bool startswith_no_case(const char *s, const char *prefix) {
161 for(i = 0; i < pl; ++i) {
162 if (tolower(s[i]) != tolower(prefix[i]))
169 bool first_word(const char *s, const char *word) {
184 if (memcmp(s, word, wl) != 0)
188 strchr(WHITESPACE, s[wl]);
191 int close_nointr(int fd) {
197 if ((r = close(fd)) >= 0)
205 void close_nointr_nofail(int fd) {
206 int saved_errno = errno;
208 /* like close_nointr() but cannot fail, and guarantees errno
211 assert_se(close_nointr(fd) == 0);
216 int parse_boolean(const char *v) {
219 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
221 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
227 int safe_atou(const char *s, unsigned *ret_u) {
235 l = strtoul(s, &x, 0);
237 if (!x || *x || errno)
238 return errno ? -errno : -EINVAL;
240 if ((unsigned long) (unsigned) l != l)
243 *ret_u = (unsigned) l;
247 int safe_atoi(const char *s, int *ret_i) {
255 l = strtol(s, &x, 0);
257 if (!x || *x || errno)
258 return errno ? -errno : -EINVAL;
260 if ((long) (int) l != l)
267 int safe_atolu(const char *s, long unsigned *ret_lu) {
275 l = strtoul(s, &x, 0);
277 if (!x || *x || errno)
278 return errno ? -errno : -EINVAL;
284 int safe_atoli(const char *s, long int *ret_li) {
292 l = strtol(s, &x, 0);
294 if (!x || *x || errno)
295 return errno ? -errno : -EINVAL;
301 int safe_atollu(const char *s, long long unsigned *ret_llu) {
303 unsigned long long l;
309 l = strtoull(s, &x, 0);
311 if (!x || *x || errno)
312 return errno ? -errno : -EINVAL;
318 int safe_atolli(const char *s, long long int *ret_lli) {
326 l = strtoll(s, &x, 0);
328 if (!x || *x || errno)
329 return errno ? -errno : -EINVAL;
335 /* Split a string into words. */
336 char *split(const char *c, size_t *l, const char *separator, char **state) {
339 current = *state ? *state : (char*) c;
341 if (!*current || *c == 0)
344 current += strspn(current, separator);
345 *l = strcspn(current, separator);
348 return (char*) current;
351 /* Split a string into words, but consider strings enclosed in '' and
352 * "" as words even if they include spaces. */
353 char *split_quoted(const char *c, size_t *l, char **state) {
356 current = *state ? *state : (char*) c;
358 if (!*current || *c == 0)
361 current += strspn(current, WHITESPACE);
363 if (*current == '\'') {
365 *l = strcspn(current, "'");
370 } else if (*current == '\"') {
372 *l = strcspn(current, "\"");
378 *l = strcspn(current, WHITESPACE);
382 /* FIXME: Cannot deal with strings that have spaces AND ticks
385 return (char*) current;
388 char **split_path_and_make_absolute(const char *p) {
392 if (!(l = strv_split(p, ":")))
395 if (!strv_path_make_absolute_cwd(l)) {
403 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
406 char fn[132], line[256], *p;
407 long long unsigned ppid;
412 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
413 fn[sizeof(fn)-1] = 0;
415 if (!(f = fopen(fn, "r")))
418 if (!(fgets(line, sizeof(line), f))) {
426 /* Let's skip the pid and comm fields. The latter is enclosed
427 * in () but does not escape any () in its value, so let's
428 * skip over it manually */
430 if (!(p = strrchr(line, ')')))
441 if ((long long unsigned) (pid_t) ppid != ppid)
444 *_ppid = (pid_t) ppid;
449 int write_one_line_file(const char *fn, const char *line) {
456 if (!(f = fopen(fn, "we")))
459 if (fputs(line, f) < 0) {
470 int read_one_line_file(const char *fn, char **line) {
478 if (!(f = fopen(fn, "re")))
481 if (!(fgets(t, sizeof(t), f))) {
486 if (!(c = strdup(t))) {
499 char *truncate_nl(char *s) {
502 s[strcspn(s, NEWLINE)] = 0;
506 int get_process_name(pid_t pid, char **name) {
513 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
516 r = read_one_line_file(p, name);
526 char *strappend(const char *s, const char *suffix) {
536 if (!(r = new(char, a+b+1)))
540 memcpy(r+a, suffix, b);
546 int readlink_malloc(const char *p, char **r) {
556 if (!(c = new(char, l)))
559 if ((n = readlink(p, c, l-1)) < 0) {
565 if ((size_t) n < l-1) {
576 char *file_name_from_path(const char *p) {
581 if ((r = strrchr(p, '/')))
587 bool path_is_absolute(const char *p) {
593 bool is_path(const char *p) {
595 return !!strchr(p, '/');
598 char *path_make_absolute(const char *p, const char *prefix) {
603 /* Makes every item in the list an absolute path by prepending
604 * the prefix, if specified and necessary */
606 if (path_is_absolute(p) || !prefix)
609 if (asprintf(&r, "%s/%s", prefix, p) < 0)
615 char *path_make_absolute_cwd(const char *p) {
620 /* Similar to path_make_absolute(), but prefixes with the
621 * current working directory. */
623 if (path_is_absolute(p))
626 if (!(cwd = get_current_dir_name()))
629 r = path_make_absolute(p, cwd);
635 char **strv_path_make_absolute_cwd(char **l) {
638 /* Goes through every item in the string list and makes it
639 * absolute. This works in place and won't rollback any
640 * changes on failure. */
645 if (!(t = path_make_absolute_cwd(*s)))
655 char **strv_path_canonicalize(char **l) {
663 /* Goes through every item in the string list and canonicalize
664 * the path. This works in place and won't rollback any
665 * changes on failure. */
670 t = path_make_absolute_cwd(*s);
679 u = canonicalize_file_name(t);
683 if (errno == ENOMEM || !errno)
700 int reset_all_signal_handlers(void) {
703 for (sig = 1; sig < _NSIG; sig++) {
706 if (sig == SIGKILL || sig == SIGSTOP)
710 sa.sa_handler = SIG_DFL;
711 sa.sa_flags = SA_RESTART;
713 /* On Linux the first two RT signals are reserved by
714 * glibc, and sigaction() will return EINVAL for them. */
715 if ((sigaction(sig, &sa, NULL) < 0))
723 char *strstrip(char *s) {
726 /* Drops trailing whitespace. Modifies the string in
727 * place. Returns pointer to first non-space character */
729 s += strspn(s, WHITESPACE);
732 if (!strchr(WHITESPACE, *e))
743 char *delete_chars(char *s, const char *bad) {
746 /* Drops all whitespace, regardless where in the string */
748 for (f = s, t = s; *f; f++) {
760 char *file_in_same_dir(const char *path, const char *filename) {
767 /* This removes the last component of path and appends
768 * filename, unless the latter is absolute anyway or the
771 if (path_is_absolute(filename))
772 return strdup(filename);
774 if (!(e = strrchr(path, '/')))
775 return strdup(filename);
777 k = strlen(filename);
778 if (!(r = new(char, e-path+1+k+1)))
781 memcpy(r, path, e-path+1);
782 memcpy(r+(e-path)+1, filename, k+1);
787 int mkdir_parents(const char *path, mode_t mode) {
792 /* Creates every parent directory in the path except the last
795 p = path + strspn(path, "/");
800 e = p + strcspn(p, "/");
801 p = e + strspn(e, "/");
803 /* Is this the last component? If so, then we're
808 if (!(t = strndup(path, e - path)))
815 if (r < 0 && errno != EEXIST)
820 int mkdir_p(const char *path, mode_t mode) {
825 if ((r = mkdir_parents(path, mode)) < 0)
828 if (mkdir(path, mode) < 0)
834 char hexchar(int x) {
835 static const char table[16] = "0123456789abcdef";
837 return table[x & 15];
840 int unhexchar(char c) {
842 if (c >= '0' && c <= '9')
845 if (c >= 'a' && c <= 'f')
848 if (c >= 'A' && c <= 'F')
854 char octchar(int x) {
855 return '0' + (x & 7);
858 int unoctchar(char c) {
860 if (c >= '0' && c <= '7')
866 char decchar(int x) {
867 return '0' + (x % 10);
870 int undecchar(char c) {
872 if (c >= '0' && c <= '9')
878 char *cescape(const char *s) {
884 /* Does C style string escaping. */
886 if (!(r = new(char, strlen(s)*4 + 1)))
889 for (f = s, t = r; *f; f++)
935 /* For special chars we prefer octal over
936 * hexadecimal encoding, simply because glib's
937 * g_strescape() does the same */
938 if ((*f < ' ') || (*f >= 127)) {
940 *(t++) = octchar((unsigned char) *f >> 6);
941 *(t++) = octchar((unsigned char) *f >> 3);
942 *(t++) = octchar((unsigned char) *f);
953 char *cunescape(const char *s) {
959 /* Undoes C style string escaping */
961 if (!(r = new(char, strlen(s)+1)))
964 for (f = s, t = r; *f; f++) {
1007 /* hexadecimal encoding */
1010 if ((a = unhexchar(f[1])) < 0 ||
1011 (b = unhexchar(f[2])) < 0) {
1012 /* Invalid escape code, let's take it literal then */
1016 *(t++) = (char) ((a << 4) | b);
1031 /* octal encoding */
1034 if ((a = unoctchar(f[0])) < 0 ||
1035 (b = unoctchar(f[1])) < 0 ||
1036 (c = unoctchar(f[2])) < 0) {
1037 /* Invalid escape code, let's take it literal then */
1041 *(t++) = (char) ((a << 6) | (b << 3) | c);
1049 /* premature end of string.*/
1054 /* Invalid escape code, let's take it literal then */
1067 char *xescape(const char *s, const char *bad) {
1071 /* Escapes all chars in bad, in addition to \ and all special
1072 * chars, in \xFF style escaping. May be reversed with
1075 if (!(r = new(char, strlen(s)*4+1)))
1078 for (f = s, t = r; *f; f++) {
1080 if ((*f < ' ') || (*f >= 127) ||
1081 (*f == '\\') || strchr(bad, *f)) {
1084 *(t++) = hexchar(*f >> 4);
1085 *(t++) = hexchar(*f);
1095 char *bus_path_escape(const char *s) {
1101 /* Escapes all chars that D-Bus' object path cannot deal
1102 * with. Can be reverse with bus_path_unescape() */
1104 if (!(r = new(char, strlen(s)*3+1)))
1107 for (f = s, t = r; *f; f++) {
1109 if (!(*f >= 'A' && *f <= 'Z') &&
1110 !(*f >= 'a' && *f <= 'z') &&
1111 !(*f >= '0' && *f <= '9')) {
1113 *(t++) = hexchar(*f >> 4);
1114 *(t++) = hexchar(*f);
1124 char *bus_path_unescape(const char *f) {
1129 if (!(r = strdup(f)))
1132 for (t = r; *f; f++) {
1137 if ((a = unhexchar(f[1])) < 0 ||
1138 (b = unhexchar(f[2])) < 0) {
1139 /* Invalid escape code, let's take it literal then */
1142 *(t++) = (char) ((a << 4) | b);
1154 char *path_kill_slashes(char *path) {
1158 /* Removes redundant inner and trailing slashes. Modifies the
1159 * passed string in-place.
1161 * ///foo///bar/ becomes /foo/bar
1164 for (f = path, t = path; *f; f++) {
1179 /* Special rule, if we are talking of the root directory, a
1180 trailing slash is good */
1182 if (t == path && slash)
1189 bool path_startswith(const char *path, const char *prefix) {
1193 if ((path[0] == '/') != (prefix[0] == '/'))
1199 path += strspn(path, "/");
1200 prefix += strspn(prefix, "/");
1208 a = strcspn(path, "/");
1209 b = strcspn(prefix, "/");
1214 if (memcmp(path, prefix, a) != 0)
1222 bool path_equal(const char *a, const char *b) {
1226 if ((a[0] == '/') != (b[0] == '/'))
1232 a += strspn(a, "/");
1233 b += strspn(b, "/");
1235 if (*a == 0 && *b == 0)
1238 if (*a == 0 || *b == 0)
1241 j = strcspn(a, "/");
1242 k = strcspn(b, "/");
1247 if (memcmp(a, b, j) != 0)
1255 char *ascii_strlower(char *t) {
1260 for (p = t; *p; p++)
1261 if (*p >= 'A' && *p <= 'Z')
1262 *p = *p - 'A' + 'a';
1267 bool ignore_file(const char *filename) {
1271 filename[0] == '.' ||
1272 streq(filename, "lost+found") ||
1273 endswith(filename, "~") ||
1274 endswith(filename, ".rpmnew") ||
1275 endswith(filename, ".rpmsave") ||
1276 endswith(filename, ".rpmorig") ||
1277 endswith(filename, ".dpkg-old") ||
1278 endswith(filename, ".dpkg-new") ||
1279 endswith(filename, ".swp");
1282 int fd_nonblock(int fd, bool nonblock) {
1287 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1291 flags |= O_NONBLOCK;
1293 flags &= ~O_NONBLOCK;
1295 if (fcntl(fd, F_SETFL, flags) < 0)
1301 int fd_cloexec(int fd, bool cloexec) {
1306 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1310 flags |= FD_CLOEXEC;
1312 flags &= ~FD_CLOEXEC;
1314 if (fcntl(fd, F_SETFD, flags) < 0)
1320 int close_all_fds(const int except[], unsigned n_except) {
1325 if (!(d = opendir("/proc/self/fd")))
1328 while ((de = readdir(d))) {
1331 if (ignore_file(de->d_name))
1334 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1348 for (i = 0; i < n_except; i++)
1349 if (except[i] == fd) {
1358 if ((r = close_nointr(fd)) < 0) {
1359 /* Valgrind has its own FD and doesn't want to have it closed */
1372 bool chars_intersect(const char *a, const char *b) {
1375 /* Returns true if any of the chars in a are in b. */
1376 for (p = a; *p; p++)
1383 char *format_timestamp(char *buf, size_t l, usec_t t) {
1393 sec = (time_t) t / USEC_PER_SEC;
1395 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1401 bool fstype_is_network(const char *fstype) {
1402 static const char * const table[] = {
1414 for (i = 0; i < ELEMENTSOF(table); i++)
1415 if (streq(table[i], fstype))
1424 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1429 TIOCL_GETKMSGREDIRECT,
1433 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1436 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1439 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1442 close_nointr_nofail(r);
1446 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1447 struct termios old_termios, new_termios;
1454 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1455 new_termios = old_termios;
1457 new_termios.c_lflag &= ~ICANON;
1458 new_termios.c_cc[VMIN] = 1;
1459 new_termios.c_cc[VTIME] = 0;
1461 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1464 k = fread(&c, 1, 1, f);
1466 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1472 *need_nl = c != '\n';
1479 if (!(fgets(line, sizeof(line), f)))
1484 if (strlen(line) != 1)
1494 int ask(char *ret, const char *replies, const char *text, ...) {
1503 bool need_nl = true;
1505 fputs("\x1B[1m", stdout);
1511 fputs("\x1B[0m", stdout);
1515 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1517 if (r == -EBADMSG) {
1518 puts("Bad input, please try again.");
1529 if (strchr(replies, c)) {
1534 puts("Read unexpected character, please try again.");
1538 int reset_terminal(int fd) {
1539 struct termios termios;
1544 /* Set terminal to some sane defaults */
1546 if (tcgetattr(fd, &termios) < 0) {
1551 /* We only reset the stuff that matters to the software. How
1552 * hardware is set up we don't touch assuming that somebody
1553 * else will do that for us */
1555 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1556 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1557 termios.c_oflag |= ONLCR;
1558 termios.c_cflag |= CREAD;
1559 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1561 termios.c_cc[VINTR] = 03; /* ^C */
1562 termios.c_cc[VQUIT] = 034; /* ^\ */
1563 termios.c_cc[VERASE] = 0177;
1564 termios.c_cc[VKILL] = 025; /* ^X */
1565 termios.c_cc[VEOF] = 04; /* ^D */
1566 termios.c_cc[VSTART] = 021; /* ^Q */
1567 termios.c_cc[VSTOP] = 023; /* ^S */
1568 termios.c_cc[VSUSP] = 032; /* ^Z */
1569 termios.c_cc[VLNEXT] = 026; /* ^V */
1570 termios.c_cc[VWERASE] = 027; /* ^W */
1571 termios.c_cc[VREPRINT] = 022; /* ^R */
1572 termios.c_cc[VEOL] = 0;
1573 termios.c_cc[VEOL2] = 0;
1575 termios.c_cc[VTIME] = 0;
1576 termios.c_cc[VMIN] = 1;
1578 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1582 /* Just in case, flush all crap out */
1583 tcflush(fd, TCIOFLUSH);
1588 int open_terminal(const char *name, int mode) {
1591 if ((fd = open(name, mode)) < 0)
1594 if ((r = isatty(fd)) < 0) {
1595 close_nointr_nofail(fd);
1600 close_nointr_nofail(fd);
1607 int flush_fd(int fd) {
1608 struct pollfd pollfd;
1612 pollfd.events = POLLIN;
1619 if ((r = poll(&pollfd, 1, 0)) < 0) {
1630 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1635 if (errno == EAGAIN)
1646 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1647 int fd = -1, notify = -1, r, wd = -1;
1651 /* We use inotify to be notified when the tty is closed. We
1652 * create the watch before checking if we can actually acquire
1653 * it, so that we don't lose any event.
1655 * Note: strictly speaking this actually watches for the
1656 * device being closed, it does *not* really watch whether a
1657 * tty loses its controlling process. However, unless some
1658 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1659 * its tty otherwise this will not become a problem. As long
1660 * as the administrator makes sure not configure any service
1661 * on the same tty as an untrusted user this should not be a
1662 * problem. (Which he probably should not do anyway.) */
1664 if (!fail && !force) {
1665 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1670 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1678 if ((r = flush_fd(notify)) < 0)
1681 /* We pass here O_NOCTTY only so that we can check the return
1682 * value TIOCSCTTY and have a reliable way to figure out if we
1683 * successfully became the controlling process of the tty */
1684 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1687 /* First, try to get the tty */
1688 r = ioctl(fd, TIOCSCTTY, force);
1690 /* Sometimes it makes sense to ignore TIOCSCTTY
1691 * returning EPERM, i.e. when very likely we already
1692 * are have this controlling terminal. */
1693 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1696 if (r < 0 && (force || fail || errno != EPERM)) {
1706 assert(notify >= 0);
1709 struct inotify_event e;
1712 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1726 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1734 /* We close the tty fd here since if the old session
1735 * ended our handle will be dead. It's important that
1736 * we do this after sleeping, so that we don't enter
1737 * an endless loop. */
1738 close_nointr_nofail(fd);
1742 close_nointr_nofail(notify);
1744 if ((r = reset_terminal(fd)) < 0)
1745 log_warning("Failed to reset terminal: %s", strerror(-r));
1751 close_nointr_nofail(fd);
1754 close_nointr_nofail(notify);
1759 int release_terminal(void) {
1761 struct sigaction sa_old, sa_new;
1763 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1766 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1767 * by our own TIOCNOTTY */
1770 sa_new.sa_handler = SIG_IGN;
1771 sa_new.sa_flags = SA_RESTART;
1772 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1774 if (ioctl(fd, TIOCNOTTY) < 0)
1777 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1779 close_nointr_nofail(fd);
1783 int sigaction_many(const struct sigaction *sa, ...) {
1788 while ((sig = va_arg(ap, int)) > 0)
1789 if (sigaction(sig, sa, NULL) < 0)
1796 int ignore_signals(int sig, ...) {
1797 struct sigaction sa;
1802 sa.sa_handler = SIG_IGN;
1803 sa.sa_flags = SA_RESTART;
1805 if (sigaction(sig, &sa, NULL) < 0)
1809 while ((sig = va_arg(ap, int)) > 0)
1810 if (sigaction(sig, &sa, NULL) < 0)
1817 int default_signals(int sig, ...) {
1818 struct sigaction sa;
1823 sa.sa_handler = SIG_DFL;
1824 sa.sa_flags = SA_RESTART;
1826 if (sigaction(sig, &sa, NULL) < 0)
1830 while ((sig = va_arg(ap, int)) > 0)
1831 if (sigaction(sig, &sa, NULL) < 0)
1838 int close_pipe(int p[]) {
1844 a = close_nointr(p[0]);
1849 b = close_nointr(p[1]);
1853 return a < 0 ? a : b;
1856 ssize_t loop_read(int fd, void *buf, size_t nbytes) {
1865 while (nbytes > 0) {
1868 if ((k = read(fd, p, nbytes)) <= 0) {
1873 if (errno == EAGAIN) {
1874 struct pollfd pollfd;
1878 pollfd.events = POLLIN;
1880 if (poll(&pollfd, 1, -1) < 0) {
1884 return n > 0 ? n : -errno;
1887 if (pollfd.revents != POLLIN)
1888 return n > 0 ? n : -EIO;
1893 return n > 0 ? n : (k < 0 ? -errno : 0);
1904 int path_is_mount_point(const char *t) {
1908 if (lstat(t, &a) < 0) {
1910 if (errno == ENOENT)
1916 if (!(copy = strdup(t)))
1919 if (lstat(dirname(copy), &b) < 0) {
1926 return a.st_dev != b.st_dev;
1929 int parse_usec(const char *t, usec_t *usec) {
1930 static const struct {
1934 { "sec", USEC_PER_SEC },
1935 { "s", USEC_PER_SEC },
1936 { "min", USEC_PER_MINUTE },
1937 { "hr", USEC_PER_HOUR },
1938 { "h", USEC_PER_HOUR },
1939 { "d", USEC_PER_DAY },
1940 { "w", USEC_PER_WEEK },
1941 { "msec", USEC_PER_MSEC },
1942 { "ms", USEC_PER_MSEC },
1943 { "m", USEC_PER_MINUTE },
1946 { "", USEC_PER_SEC },
1962 l = strtoll(p, &e, 10);
1973 e += strspn(e, WHITESPACE);
1975 for (i = 0; i < ELEMENTSOF(table); i++)
1976 if (startswith(e, table[i].suffix)) {
1977 r += (usec_t) l * table[i].usec;
1978 p = e + strlen(table[i].suffix);
1982 if (i >= ELEMENTSOF(table))
1992 int make_stdio(int fd) {
1997 r = dup2(fd, STDIN_FILENO);
1998 s = dup2(fd, STDOUT_FILENO);
1999 t = dup2(fd, STDERR_FILENO);
2002 close_nointr_nofail(fd);
2004 if (r < 0 || s < 0 || t < 0)
2010 bool is_clean_exit(int code, int status) {
2012 if (code == CLD_EXITED)
2015 /* If a daemon does not implement handlers for some of the
2016 * signals that's not considered an unclean shutdown */
2017 if (code == CLD_KILLED)
2021 status == SIGTERM ||
2027 bool is_device_path(const char *path) {
2029 /* Returns true on paths that refer to a device, either in
2030 * sysfs or in /dev */
2033 path_startswith(path, "/dev/") ||
2034 path_startswith(path, "/sys/");
2037 static const char *const ioprio_class_table[] = {
2038 [IOPRIO_CLASS_NONE] = "none",
2039 [IOPRIO_CLASS_RT] = "realtime",
2040 [IOPRIO_CLASS_BE] = "best-effort",
2041 [IOPRIO_CLASS_IDLE] = "idle"
2044 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2046 static const char *const sigchld_code_table[] = {
2047 [CLD_EXITED] = "exited",
2048 [CLD_KILLED] = "killed",
2049 [CLD_DUMPED] = "dumped",
2050 [CLD_TRAPPED] = "trapped",
2051 [CLD_STOPPED] = "stopped",
2052 [CLD_CONTINUED] = "continued",
2055 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2057 static const char *const log_facility_table[LOG_NFACILITIES] = {
2058 [LOG_FAC(LOG_KERN)] = "kern",
2059 [LOG_FAC(LOG_USER)] = "user",
2060 [LOG_FAC(LOG_MAIL)] = "mail",
2061 [LOG_FAC(LOG_DAEMON)] = "daemon",
2062 [LOG_FAC(LOG_AUTH)] = "auth",
2063 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2064 [LOG_FAC(LOG_LPR)] = "lpr",
2065 [LOG_FAC(LOG_NEWS)] = "news",
2066 [LOG_FAC(LOG_UUCP)] = "uucp",
2067 [LOG_FAC(LOG_CRON)] = "cron",
2068 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2069 [LOG_FAC(LOG_FTP)] = "ftp",
2070 [LOG_FAC(LOG_LOCAL0)] = "local0",
2071 [LOG_FAC(LOG_LOCAL1)] = "local1",
2072 [LOG_FAC(LOG_LOCAL2)] = "local2",
2073 [LOG_FAC(LOG_LOCAL3)] = "local3",
2074 [LOG_FAC(LOG_LOCAL4)] = "local4",
2075 [LOG_FAC(LOG_LOCAL5)] = "local5",
2076 [LOG_FAC(LOG_LOCAL6)] = "local6",
2077 [LOG_FAC(LOG_LOCAL7)] = "local7"
2080 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2082 static const char *const log_level_table[] = {
2083 [LOG_EMERG] = "emerg",
2084 [LOG_ALERT] = "alert",
2085 [LOG_CRIT] = "crit",
2087 [LOG_WARNING] = "warning",
2088 [LOG_NOTICE] = "notice",
2089 [LOG_INFO] = "info",
2090 [LOG_DEBUG] = "debug"
2093 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2095 static const char* const sched_policy_table[] = {
2096 [SCHED_OTHER] = "other",
2097 [SCHED_BATCH] = "batch",
2098 [SCHED_IDLE] = "idle",
2099 [SCHED_FIFO] = "fifo",
2103 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2105 static const char* const rlimit_table[] = {
2106 [RLIMIT_CPU] = "LimitCPU",
2107 [RLIMIT_FSIZE] = "LimitFSIZE",
2108 [RLIMIT_DATA] = "LimitDATA",
2109 [RLIMIT_STACK] = "LimitSTACK",
2110 [RLIMIT_CORE] = "LimitCORE",
2111 [RLIMIT_RSS] = "LimitRSS",
2112 [RLIMIT_NOFILE] = "LimitNOFILE",
2113 [RLIMIT_AS] = "LimitAS",
2114 [RLIMIT_NPROC] = "LimitNPROC",
2115 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2116 [RLIMIT_LOCKS] = "LimitLOCKS",
2117 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2118 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2119 [RLIMIT_NICE] = "LimitNICE",
2120 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2121 [RLIMIT_RTTIME] = "LimitRTTIME"
2124 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);