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 char *file_name_from_path(const char *p) {
590 if ((r = strrchr(p, '/')))
596 bool path_is_absolute(const char *p) {
602 bool is_path(const char *p) {
604 return !!strchr(p, '/');
607 char *path_make_absolute(const char *p, const char *prefix) {
612 /* Makes every item in the list an absolute path by prepending
613 * the prefix, if specified and necessary */
615 if (path_is_absolute(p) || !prefix)
618 if (asprintf(&r, "%s/%s", prefix, p) < 0)
624 char *path_make_absolute_cwd(const char *p) {
629 /* Similar to path_make_absolute(), but prefixes with the
630 * current working directory. */
632 if (path_is_absolute(p))
635 if (!(cwd = get_current_dir_name()))
638 r = path_make_absolute(p, cwd);
644 char **strv_path_make_absolute_cwd(char **l) {
647 /* Goes through every item in the string list and makes it
648 * absolute. This works in place and won't rollback any
649 * changes on failure. */
654 if (!(t = path_make_absolute_cwd(*s)))
664 char **strv_path_canonicalize(char **l) {
672 /* Goes through every item in the string list and canonicalize
673 * the path. This works in place and won't rollback any
674 * changes on failure. */
679 t = path_make_absolute_cwd(*s);
688 u = canonicalize_file_name(t);
692 if (errno == ENOMEM || !errno)
709 int reset_all_signal_handlers(void) {
712 for (sig = 1; sig < _NSIG; sig++) {
715 if (sig == SIGKILL || sig == SIGSTOP)
719 sa.sa_handler = SIG_DFL;
720 sa.sa_flags = SA_RESTART;
722 /* On Linux the first two RT signals are reserved by
723 * glibc, and sigaction() will return EINVAL for them. */
724 if ((sigaction(sig, &sa, NULL) < 0))
732 char *strstrip(char *s) {
735 /* Drops trailing whitespace. Modifies the string in
736 * place. Returns pointer to first non-space character */
738 s += strspn(s, WHITESPACE);
741 if (!strchr(WHITESPACE, *e))
752 char *delete_chars(char *s, const char *bad) {
755 /* Drops all whitespace, regardless where in the string */
757 for (f = s, t = s; *f; f++) {
769 char *file_in_same_dir(const char *path, const char *filename) {
776 /* This removes the last component of path and appends
777 * filename, unless the latter is absolute anyway or the
780 if (path_is_absolute(filename))
781 return strdup(filename);
783 if (!(e = strrchr(path, '/')))
784 return strdup(filename);
786 k = strlen(filename);
787 if (!(r = new(char, e-path+1+k+1)))
790 memcpy(r, path, e-path+1);
791 memcpy(r+(e-path)+1, filename, k+1);
796 int mkdir_parents(const char *path, mode_t mode) {
801 /* Creates every parent directory in the path except the last
804 p = path + strspn(path, "/");
809 e = p + strcspn(p, "/");
810 p = e + strspn(e, "/");
812 /* Is this the last component? If so, then we're
817 if (!(t = strndup(path, e - path)))
824 if (r < 0 && errno != EEXIST)
829 int mkdir_p(const char *path, mode_t mode) {
834 if ((r = mkdir_parents(path, mode)) < 0)
837 if (mkdir(path, mode) < 0)
843 char hexchar(int x) {
844 static const char table[16] = "0123456789abcdef";
846 return table[x & 15];
849 int unhexchar(char c) {
851 if (c >= '0' && c <= '9')
854 if (c >= 'a' && c <= 'f')
857 if (c >= 'A' && c <= 'F')
863 char octchar(int x) {
864 return '0' + (x & 7);
867 int unoctchar(char c) {
869 if (c >= '0' && c <= '7')
875 char decchar(int x) {
876 return '0' + (x % 10);
879 int undecchar(char c) {
881 if (c >= '0' && c <= '9')
887 char *cescape(const char *s) {
893 /* Does C style string escaping. */
895 if (!(r = new(char, strlen(s)*4 + 1)))
898 for (f = s, t = r; *f; f++)
944 /* For special chars we prefer octal over
945 * hexadecimal encoding, simply because glib's
946 * g_strescape() does the same */
947 if ((*f < ' ') || (*f >= 127)) {
949 *(t++) = octchar((unsigned char) *f >> 6);
950 *(t++) = octchar((unsigned char) *f >> 3);
951 *(t++) = octchar((unsigned char) *f);
962 char *cunescape(const char *s) {
968 /* Undoes C style string escaping */
970 if (!(r = new(char, strlen(s)+1)))
973 for (f = s, t = r; *f; f++) {
1016 /* hexadecimal encoding */
1019 if ((a = unhexchar(f[1])) < 0 ||
1020 (b = unhexchar(f[2])) < 0) {
1021 /* Invalid escape code, let's take it literal then */
1025 *(t++) = (char) ((a << 4) | b);
1040 /* octal encoding */
1043 if ((a = unoctchar(f[0])) < 0 ||
1044 (b = unoctchar(f[1])) < 0 ||
1045 (c = unoctchar(f[2])) < 0) {
1046 /* Invalid escape code, let's take it literal then */
1050 *(t++) = (char) ((a << 6) | (b << 3) | c);
1058 /* premature end of string.*/
1063 /* Invalid escape code, let's take it literal then */
1076 char *xescape(const char *s, const char *bad) {
1080 /* Escapes all chars in bad, in addition to \ and all special
1081 * chars, in \xFF style escaping. May be reversed with
1084 if (!(r = new(char, strlen(s)*4+1)))
1087 for (f = s, t = r; *f; f++) {
1089 if ((*f < ' ') || (*f >= 127) ||
1090 (*f == '\\') || strchr(bad, *f)) {
1093 *(t++) = hexchar(*f >> 4);
1094 *(t++) = hexchar(*f);
1104 char *bus_path_escape(const char *s) {
1110 /* Escapes all chars that D-Bus' object path cannot deal
1111 * with. Can be reverse with bus_path_unescape() */
1113 if (!(r = new(char, strlen(s)*3+1)))
1116 for (f = s, t = r; *f; f++) {
1118 if (!(*f >= 'A' && *f <= 'Z') &&
1119 !(*f >= 'a' && *f <= 'z') &&
1120 !(*f >= '0' && *f <= '9')) {
1122 *(t++) = hexchar(*f >> 4);
1123 *(t++) = hexchar(*f);
1133 char *bus_path_unescape(const char *f) {
1138 if (!(r = strdup(f)))
1141 for (t = r; *f; f++) {
1146 if ((a = unhexchar(f[1])) < 0 ||
1147 (b = unhexchar(f[2])) < 0) {
1148 /* Invalid escape code, let's take it literal then */
1151 *(t++) = (char) ((a << 4) | b);
1163 char *path_kill_slashes(char *path) {
1167 /* Removes redundant inner and trailing slashes. Modifies the
1168 * passed string in-place.
1170 * ///foo///bar/ becomes /foo/bar
1173 for (f = path, t = path; *f; f++) {
1188 /* Special rule, if we are talking of the root directory, a
1189 trailing slash is good */
1191 if (t == path && slash)
1198 bool path_startswith(const char *path, const char *prefix) {
1202 if ((path[0] == '/') != (prefix[0] == '/'))
1208 path += strspn(path, "/");
1209 prefix += strspn(prefix, "/");
1217 a = strcspn(path, "/");
1218 b = strcspn(prefix, "/");
1223 if (memcmp(path, prefix, a) != 0)
1231 bool path_equal(const char *a, const char *b) {
1235 if ((a[0] == '/') != (b[0] == '/'))
1241 a += strspn(a, "/");
1242 b += strspn(b, "/");
1244 if (*a == 0 && *b == 0)
1247 if (*a == 0 || *b == 0)
1250 j = strcspn(a, "/");
1251 k = strcspn(b, "/");
1256 if (memcmp(a, b, j) != 0)
1264 char *ascii_strlower(char *t) {
1269 for (p = t; *p; p++)
1270 if (*p >= 'A' && *p <= 'Z')
1271 *p = *p - 'A' + 'a';
1276 bool ignore_file(const char *filename) {
1280 filename[0] == '.' ||
1281 streq(filename, "lost+found") ||
1282 endswith(filename, "~") ||
1283 endswith(filename, ".rpmnew") ||
1284 endswith(filename, ".rpmsave") ||
1285 endswith(filename, ".rpmorig") ||
1286 endswith(filename, ".dpkg-old") ||
1287 endswith(filename, ".dpkg-new") ||
1288 endswith(filename, ".swp");
1291 int fd_nonblock(int fd, bool nonblock) {
1296 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1300 flags |= O_NONBLOCK;
1302 flags &= ~O_NONBLOCK;
1304 if (fcntl(fd, F_SETFL, flags) < 0)
1310 int fd_cloexec(int fd, bool cloexec) {
1315 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1319 flags |= FD_CLOEXEC;
1321 flags &= ~FD_CLOEXEC;
1323 if (fcntl(fd, F_SETFD, flags) < 0)
1329 int close_all_fds(const int except[], unsigned n_except) {
1334 if (!(d = opendir("/proc/self/fd")))
1337 while ((de = readdir(d))) {
1340 if (ignore_file(de->d_name))
1343 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1357 for (i = 0; i < n_except; i++)
1358 if (except[i] == fd) {
1367 if ((r = close_nointr(fd)) < 0) {
1368 /* Valgrind has its own FD and doesn't want to have it closed */
1381 bool chars_intersect(const char *a, const char *b) {
1384 /* Returns true if any of the chars in a are in b. */
1385 for (p = a; *p; p++)
1392 char *format_timestamp(char *buf, size_t l, usec_t t) {
1402 sec = (time_t) t / USEC_PER_SEC;
1404 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1410 char *format_timespan(char *buf, size_t l, usec_t t) {
1411 static const struct {
1415 { "w", USEC_PER_WEEK },
1416 { "d", USEC_PER_DAY },
1417 { "h", USEC_PER_HOUR },
1418 { "min", USEC_PER_MINUTE },
1419 { "s", USEC_PER_SEC },
1420 { "ms", USEC_PER_MSEC },
1430 if (t == (usec_t) -1)
1433 /* The result of this function can be parsed with parse_usec */
1435 for (i = 0; i < ELEMENTSOF(table); i++) {
1439 if (t < table[i].usec)
1445 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1446 n = MIN((size_t) k, l);
1459 bool fstype_is_network(const char *fstype) {
1460 static const char * const table[] = {
1472 for (i = 0; i < ELEMENTSOF(table); i++)
1473 if (streq(table[i], fstype))
1482 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1487 TIOCL_GETKMSGREDIRECT,
1491 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1494 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1497 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1500 close_nointr_nofail(r);
1504 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1505 struct termios old_termios, new_termios;
1512 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1513 new_termios = old_termios;
1515 new_termios.c_lflag &= ~ICANON;
1516 new_termios.c_cc[VMIN] = 1;
1517 new_termios.c_cc[VTIME] = 0;
1519 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1522 k = fread(&c, 1, 1, f);
1524 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1530 *need_nl = c != '\n';
1537 if (!(fgets(line, sizeof(line), f)))
1542 if (strlen(line) != 1)
1552 int ask(char *ret, const char *replies, const char *text, ...) {
1561 bool need_nl = true;
1563 fputs("\x1B[1m", stdout);
1569 fputs("\x1B[0m", stdout);
1573 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1575 if (r == -EBADMSG) {
1576 puts("Bad input, please try again.");
1587 if (strchr(replies, c)) {
1592 puts("Read unexpected character, please try again.");
1596 int reset_terminal(int fd) {
1597 struct termios termios;
1602 /* Set terminal to some sane defaults */
1604 if (tcgetattr(fd, &termios) < 0) {
1609 /* We only reset the stuff that matters to the software. How
1610 * hardware is set up we don't touch assuming that somebody
1611 * else will do that for us */
1613 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1614 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1615 termios.c_oflag |= ONLCR;
1616 termios.c_cflag |= CREAD;
1617 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1619 termios.c_cc[VINTR] = 03; /* ^C */
1620 termios.c_cc[VQUIT] = 034; /* ^\ */
1621 termios.c_cc[VERASE] = 0177;
1622 termios.c_cc[VKILL] = 025; /* ^X */
1623 termios.c_cc[VEOF] = 04; /* ^D */
1624 termios.c_cc[VSTART] = 021; /* ^Q */
1625 termios.c_cc[VSTOP] = 023; /* ^S */
1626 termios.c_cc[VSUSP] = 032; /* ^Z */
1627 termios.c_cc[VLNEXT] = 026; /* ^V */
1628 termios.c_cc[VWERASE] = 027; /* ^W */
1629 termios.c_cc[VREPRINT] = 022; /* ^R */
1630 termios.c_cc[VEOL] = 0;
1631 termios.c_cc[VEOL2] = 0;
1633 termios.c_cc[VTIME] = 0;
1634 termios.c_cc[VMIN] = 1;
1636 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1640 /* Just in case, flush all crap out */
1641 tcflush(fd, TCIOFLUSH);
1646 int open_terminal(const char *name, int mode) {
1649 if ((fd = open(name, mode)) < 0)
1652 if ((r = isatty(fd)) < 0) {
1653 close_nointr_nofail(fd);
1658 close_nointr_nofail(fd);
1665 int flush_fd(int fd) {
1666 struct pollfd pollfd;
1670 pollfd.events = POLLIN;
1677 if ((r = poll(&pollfd, 1, 0)) < 0) {
1688 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1693 if (errno == EAGAIN)
1704 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1705 int fd = -1, notify = -1, r, wd = -1;
1709 /* We use inotify to be notified when the tty is closed. We
1710 * create the watch before checking if we can actually acquire
1711 * it, so that we don't lose any event.
1713 * Note: strictly speaking this actually watches for the
1714 * device being closed, it does *not* really watch whether a
1715 * tty loses its controlling process. However, unless some
1716 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1717 * its tty otherwise this will not become a problem. As long
1718 * as the administrator makes sure not configure any service
1719 * on the same tty as an untrusted user this should not be a
1720 * problem. (Which he probably should not do anyway.) */
1722 if (!fail && !force) {
1723 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1728 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1736 if ((r = flush_fd(notify)) < 0)
1739 /* We pass here O_NOCTTY only so that we can check the return
1740 * value TIOCSCTTY and have a reliable way to figure out if we
1741 * successfully became the controlling process of the tty */
1742 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1745 /* First, try to get the tty */
1746 r = ioctl(fd, TIOCSCTTY, force);
1748 /* Sometimes it makes sense to ignore TIOCSCTTY
1749 * returning EPERM, i.e. when very likely we already
1750 * are have this controlling terminal. */
1751 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1754 if (r < 0 && (force || fail || errno != EPERM)) {
1764 assert(notify >= 0);
1767 struct inotify_event e;
1770 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1784 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1792 /* We close the tty fd here since if the old session
1793 * ended our handle will be dead. It's important that
1794 * we do this after sleeping, so that we don't enter
1795 * an endless loop. */
1796 close_nointr_nofail(fd);
1800 close_nointr_nofail(notify);
1802 if ((r = reset_terminal(fd)) < 0)
1803 log_warning("Failed to reset terminal: %s", strerror(-r));
1809 close_nointr_nofail(fd);
1812 close_nointr_nofail(notify);
1817 int release_terminal(void) {
1819 struct sigaction sa_old, sa_new;
1821 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1824 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1825 * by our own TIOCNOTTY */
1828 sa_new.sa_handler = SIG_IGN;
1829 sa_new.sa_flags = SA_RESTART;
1830 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1832 if (ioctl(fd, TIOCNOTTY) < 0)
1835 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1837 close_nointr_nofail(fd);
1841 int sigaction_many(const struct sigaction *sa, ...) {
1846 while ((sig = va_arg(ap, int)) > 0)
1847 if (sigaction(sig, sa, NULL) < 0)
1854 int ignore_signals(int sig, ...) {
1855 struct sigaction sa;
1860 sa.sa_handler = SIG_IGN;
1861 sa.sa_flags = SA_RESTART;
1863 if (sigaction(sig, &sa, NULL) < 0)
1867 while ((sig = va_arg(ap, int)) > 0)
1868 if (sigaction(sig, &sa, NULL) < 0)
1875 int default_signals(int sig, ...) {
1876 struct sigaction sa;
1881 sa.sa_handler = SIG_DFL;
1882 sa.sa_flags = SA_RESTART;
1884 if (sigaction(sig, &sa, NULL) < 0)
1888 while ((sig = va_arg(ap, int)) > 0)
1889 if (sigaction(sig, &sa, NULL) < 0)
1896 int close_pipe(int p[]) {
1902 a = close_nointr(p[0]);
1907 b = close_nointr(p[1]);
1911 return a < 0 ? a : b;
1914 ssize_t loop_read(int fd, void *buf, size_t nbytes) {
1923 while (nbytes > 0) {
1926 if ((k = read(fd, p, nbytes)) <= 0) {
1931 if (errno == EAGAIN) {
1932 struct pollfd pollfd;
1936 pollfd.events = POLLIN;
1938 if (poll(&pollfd, 1, -1) < 0) {
1942 return n > 0 ? n : -errno;
1945 if (pollfd.revents != POLLIN)
1946 return n > 0 ? n : -EIO;
1951 return n > 0 ? n : (k < 0 ? -errno : 0);
1962 int path_is_mount_point(const char *t) {
1966 if (lstat(t, &a) < 0) {
1968 if (errno == ENOENT)
1974 if (!(copy = strdup(t)))
1977 if (lstat(dirname(copy), &b) < 0) {
1984 return a.st_dev != b.st_dev;
1987 int parse_usec(const char *t, usec_t *usec) {
1988 static const struct {
1992 { "sec", USEC_PER_SEC },
1993 { "s", USEC_PER_SEC },
1994 { "min", USEC_PER_MINUTE },
1995 { "hr", USEC_PER_HOUR },
1996 { "h", USEC_PER_HOUR },
1997 { "d", USEC_PER_DAY },
1998 { "w", USEC_PER_WEEK },
1999 { "msec", USEC_PER_MSEC },
2000 { "ms", USEC_PER_MSEC },
2001 { "m", USEC_PER_MINUTE },
2004 { "", USEC_PER_SEC },
2020 l = strtoll(p, &e, 10);
2031 e += strspn(e, WHITESPACE);
2033 for (i = 0; i < ELEMENTSOF(table); i++)
2034 if (startswith(e, table[i].suffix)) {
2035 r += (usec_t) l * table[i].usec;
2036 p = e + strlen(table[i].suffix);
2040 if (i >= ELEMENTSOF(table))
2050 int make_stdio(int fd) {
2055 r = dup2(fd, STDIN_FILENO);
2056 s = dup2(fd, STDOUT_FILENO);
2057 t = dup2(fd, STDERR_FILENO);
2060 close_nointr_nofail(fd);
2062 if (r < 0 || s < 0 || t < 0)
2068 bool is_clean_exit(int code, int status) {
2070 if (code == CLD_EXITED)
2073 /* If a daemon does not implement handlers for some of the
2074 * signals that's not considered an unclean shutdown */
2075 if (code == CLD_KILLED)
2079 status == SIGTERM ||
2085 bool is_device_path(const char *path) {
2087 /* Returns true on paths that refer to a device, either in
2088 * sysfs or in /dev */
2091 path_startswith(path, "/dev/") ||
2092 path_startswith(path, "/sys/");
2095 int dir_is_empty(const char *path) {
2098 struct dirent buf, *de;
2100 if (!(d = opendir(path)))
2104 if ((r = readdir_r(d, &buf, &de)) > 0) {
2114 if (!ignore_file(de->d_name)) {
2124 static const char *const ioprio_class_table[] = {
2125 [IOPRIO_CLASS_NONE] = "none",
2126 [IOPRIO_CLASS_RT] = "realtime",
2127 [IOPRIO_CLASS_BE] = "best-effort",
2128 [IOPRIO_CLASS_IDLE] = "idle"
2131 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2133 static const char *const sigchld_code_table[] = {
2134 [CLD_EXITED] = "exited",
2135 [CLD_KILLED] = "killed",
2136 [CLD_DUMPED] = "dumped",
2137 [CLD_TRAPPED] = "trapped",
2138 [CLD_STOPPED] = "stopped",
2139 [CLD_CONTINUED] = "continued",
2142 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2144 static const char *const log_facility_table[LOG_NFACILITIES] = {
2145 [LOG_FAC(LOG_KERN)] = "kern",
2146 [LOG_FAC(LOG_USER)] = "user",
2147 [LOG_FAC(LOG_MAIL)] = "mail",
2148 [LOG_FAC(LOG_DAEMON)] = "daemon",
2149 [LOG_FAC(LOG_AUTH)] = "auth",
2150 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2151 [LOG_FAC(LOG_LPR)] = "lpr",
2152 [LOG_FAC(LOG_NEWS)] = "news",
2153 [LOG_FAC(LOG_UUCP)] = "uucp",
2154 [LOG_FAC(LOG_CRON)] = "cron",
2155 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2156 [LOG_FAC(LOG_FTP)] = "ftp",
2157 [LOG_FAC(LOG_LOCAL0)] = "local0",
2158 [LOG_FAC(LOG_LOCAL1)] = "local1",
2159 [LOG_FAC(LOG_LOCAL2)] = "local2",
2160 [LOG_FAC(LOG_LOCAL3)] = "local3",
2161 [LOG_FAC(LOG_LOCAL4)] = "local4",
2162 [LOG_FAC(LOG_LOCAL5)] = "local5",
2163 [LOG_FAC(LOG_LOCAL6)] = "local6",
2164 [LOG_FAC(LOG_LOCAL7)] = "local7"
2167 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2169 static const char *const log_level_table[] = {
2170 [LOG_EMERG] = "emerg",
2171 [LOG_ALERT] = "alert",
2172 [LOG_CRIT] = "crit",
2174 [LOG_WARNING] = "warning",
2175 [LOG_NOTICE] = "notice",
2176 [LOG_INFO] = "info",
2177 [LOG_DEBUG] = "debug"
2180 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2182 static const char* const sched_policy_table[] = {
2183 [SCHED_OTHER] = "other",
2184 [SCHED_BATCH] = "batch",
2185 [SCHED_IDLE] = "idle",
2186 [SCHED_FIFO] = "fifo",
2190 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2192 static const char* const rlimit_table[] = {
2193 [RLIMIT_CPU] = "LimitCPU",
2194 [RLIMIT_FSIZE] = "LimitFSIZE",
2195 [RLIMIT_DATA] = "LimitDATA",
2196 [RLIMIT_STACK] = "LimitSTACK",
2197 [RLIMIT_CORE] = "LimitCORE",
2198 [RLIMIT_RSS] = "LimitRSS",
2199 [RLIMIT_NOFILE] = "LimitNOFILE",
2200 [RLIMIT_AS] = "LimitAS",
2201 [RLIMIT_NPROC] = "LimitNPROC",
2202 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2203 [RLIMIT_LOCKS] = "LimitLOCKS",
2204 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2205 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2206 [RLIMIT_NICE] = "LimitNICE",
2207 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2208 [RLIMIT_RTTIME] = "LimitRTTIME"
2211 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);