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 parse_pid(const char *s, pid_t* ret_pid) {
252 if ((r = safe_atolu(s, &ul)) < 0)
257 if ((unsigned long) pid != ul)
267 int safe_atou(const char *s, unsigned *ret_u) {
275 l = strtoul(s, &x, 0);
277 if (!x || *x || errno)
278 return errno ? -errno : -EINVAL;
280 if ((unsigned long) (unsigned) l != l)
283 *ret_u = (unsigned) l;
287 int safe_atoi(const char *s, int *ret_i) {
295 l = strtol(s, &x, 0);
297 if (!x || *x || errno)
298 return errno ? -errno : -EINVAL;
300 if ((long) (int) l != l)
307 int safe_atolu(const char *s, long unsigned *ret_lu) {
315 l = strtoul(s, &x, 0);
317 if (!x || *x || errno)
318 return errno ? -errno : -EINVAL;
324 int safe_atoli(const char *s, long int *ret_li) {
332 l = strtol(s, &x, 0);
334 if (!x || *x || errno)
335 return errno ? -errno : -EINVAL;
341 int safe_atollu(const char *s, long long unsigned *ret_llu) {
343 unsigned long long l;
349 l = strtoull(s, &x, 0);
351 if (!x || *x || errno)
352 return errno ? -errno : -EINVAL;
358 int safe_atolli(const char *s, long long int *ret_lli) {
366 l = strtoll(s, &x, 0);
368 if (!x || *x || errno)
369 return errno ? -errno : -EINVAL;
375 /* Split a string into words. */
376 char *split(const char *c, size_t *l, const char *separator, char **state) {
379 current = *state ? *state : (char*) c;
381 if (!*current || *c == 0)
384 current += strspn(current, separator);
385 *l = strcspn(current, separator);
388 return (char*) current;
391 /* Split a string into words, but consider strings enclosed in '' and
392 * "" as words even if they include spaces. */
393 char *split_quoted(const char *c, size_t *l, char **state) {
396 current = *state ? *state : (char*) c;
398 if (!*current || *c == 0)
401 current += strspn(current, WHITESPACE);
403 if (*current == '\'') {
405 *l = strcspn(current, "'");
410 } else if (*current == '\"') {
412 *l = strcspn(current, "\"");
418 *l = strcspn(current, WHITESPACE);
422 /* FIXME: Cannot deal with strings that have spaces AND ticks
425 return (char*) current;
428 char **split_path_and_make_absolute(const char *p) {
432 if (!(l = strv_split(p, ":")))
435 if (!strv_path_make_absolute_cwd(l)) {
443 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
446 char fn[132], line[256], *p;
447 long long unsigned ppid;
452 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
453 fn[sizeof(fn)-1] = 0;
455 if (!(f = fopen(fn, "r")))
458 if (!(fgets(line, sizeof(line), f))) {
466 /* Let's skip the pid and comm fields. The latter is enclosed
467 * in () but does not escape any () in its value, so let's
468 * skip over it manually */
470 if (!(p = strrchr(line, ')')))
481 if ((long long unsigned) (pid_t) ppid != ppid)
484 *_ppid = (pid_t) ppid;
489 int write_one_line_file(const char *fn, const char *line) {
496 if (!(f = fopen(fn, "we")))
499 if (fputs(line, f) < 0) {
510 int read_one_line_file(const char *fn, char **line) {
518 if (!(f = fopen(fn, "re")))
521 if (!(fgets(t, sizeof(t), f))) {
526 if (!(c = strdup(t))) {
539 char *truncate_nl(char *s) {
542 s[strcspn(s, NEWLINE)] = 0;
546 int get_process_name(pid_t pid, char **name) {
553 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
556 r = read_one_line_file(p, name);
566 char *strappend(const char *s, const char *suffix) {
576 if (!(r = new(char, a+b+1)))
580 memcpy(r+a, suffix, b);
586 int readlink_malloc(const char *p, char **r) {
596 if (!(c = new(char, l)))
599 if ((n = readlink(p, c, l-1)) < 0) {
605 if ((size_t) n < l-1) {
616 int readlink_and_make_absolute(const char *p, char **r) {
623 if ((j = readlink_malloc(p, &target)) < 0)
626 k = file_in_same_dir(p, target);
636 char *file_name_from_path(const char *p) {
641 if ((r = strrchr(p, '/')))
647 bool path_is_absolute(const char *p) {
653 bool is_path(const char *p) {
655 return !!strchr(p, '/');
658 char *path_make_absolute(const char *p, const char *prefix) {
663 /* Makes every item in the list an absolute path by prepending
664 * the prefix, if specified and necessary */
666 if (path_is_absolute(p) || !prefix)
669 if (asprintf(&r, "%s/%s", prefix, p) < 0)
675 char *path_make_absolute_cwd(const char *p) {
680 /* Similar to path_make_absolute(), but prefixes with the
681 * current working directory. */
683 if (path_is_absolute(p))
686 if (!(cwd = get_current_dir_name()))
689 r = path_make_absolute(p, cwd);
695 char **strv_path_make_absolute_cwd(char **l) {
698 /* Goes through every item in the string list and makes it
699 * absolute. This works in place and won't rollback any
700 * changes on failure. */
705 if (!(t = path_make_absolute_cwd(*s)))
715 char **strv_path_canonicalize(char **l) {
723 /* Goes through every item in the string list and canonicalize
724 * the path. This works in place and won't rollback any
725 * changes on failure. */
730 t = path_make_absolute_cwd(*s);
739 u = canonicalize_file_name(t);
743 if (errno == ENOMEM || !errno)
760 int reset_all_signal_handlers(void) {
763 for (sig = 1; sig < _NSIG; sig++) {
766 if (sig == SIGKILL || sig == SIGSTOP)
770 sa.sa_handler = SIG_DFL;
771 sa.sa_flags = SA_RESTART;
773 /* On Linux the first two RT signals are reserved by
774 * glibc, and sigaction() will return EINVAL for them. */
775 if ((sigaction(sig, &sa, NULL) < 0))
783 char *strstrip(char *s) {
786 /* Drops trailing whitespace. Modifies the string in
787 * place. Returns pointer to first non-space character */
789 s += strspn(s, WHITESPACE);
792 if (!strchr(WHITESPACE, *e))
803 char *delete_chars(char *s, const char *bad) {
806 /* Drops all whitespace, regardless where in the string */
808 for (f = s, t = s; *f; f++) {
820 char *file_in_same_dir(const char *path, const char *filename) {
827 /* This removes the last component of path and appends
828 * filename, unless the latter is absolute anyway or the
831 if (path_is_absolute(filename))
832 return strdup(filename);
834 if (!(e = strrchr(path, '/')))
835 return strdup(filename);
837 k = strlen(filename);
838 if (!(r = new(char, e-path+1+k+1)))
841 memcpy(r, path, e-path+1);
842 memcpy(r+(e-path)+1, filename, k+1);
847 int mkdir_parents(const char *path, mode_t mode) {
852 /* Creates every parent directory in the path except the last
855 p = path + strspn(path, "/");
860 e = p + strcspn(p, "/");
861 p = e + strspn(e, "/");
863 /* Is this the last component? If so, then we're
868 if (!(t = strndup(path, e - path)))
875 if (r < 0 && errno != EEXIST)
880 int mkdir_p(const char *path, mode_t mode) {
885 if ((r = mkdir_parents(path, mode)) < 0)
888 if (mkdir(path, mode) < 0)
894 char hexchar(int x) {
895 static const char table[16] = "0123456789abcdef";
897 return table[x & 15];
900 int unhexchar(char c) {
902 if (c >= '0' && c <= '9')
905 if (c >= 'a' && c <= 'f')
908 if (c >= 'A' && c <= 'F')
914 char octchar(int x) {
915 return '0' + (x & 7);
918 int unoctchar(char c) {
920 if (c >= '0' && c <= '7')
926 char decchar(int x) {
927 return '0' + (x % 10);
930 int undecchar(char c) {
932 if (c >= '0' && c <= '9')
938 char *cescape(const char *s) {
944 /* Does C style string escaping. */
946 if (!(r = new(char, strlen(s)*4 + 1)))
949 for (f = s, t = r; *f; f++)
995 /* For special chars we prefer octal over
996 * hexadecimal encoding, simply because glib's
997 * g_strescape() does the same */
998 if ((*f < ' ') || (*f >= 127)) {
1000 *(t++) = octchar((unsigned char) *f >> 6);
1001 *(t++) = octchar((unsigned char) *f >> 3);
1002 *(t++) = octchar((unsigned char) *f);
1013 char *cunescape(const char *s) {
1019 /* Undoes C style string escaping */
1021 if (!(r = new(char, strlen(s)+1)))
1024 for (f = s, t = r; *f; f++) {
1067 /* hexadecimal encoding */
1070 if ((a = unhexchar(f[1])) < 0 ||
1071 (b = unhexchar(f[2])) < 0) {
1072 /* Invalid escape code, let's take it literal then */
1076 *(t++) = (char) ((a << 4) | b);
1091 /* octal encoding */
1094 if ((a = unoctchar(f[0])) < 0 ||
1095 (b = unoctchar(f[1])) < 0 ||
1096 (c = unoctchar(f[2])) < 0) {
1097 /* Invalid escape code, let's take it literal then */
1101 *(t++) = (char) ((a << 6) | (b << 3) | c);
1109 /* premature end of string.*/
1114 /* Invalid escape code, let's take it literal then */
1127 char *xescape(const char *s, const char *bad) {
1131 /* Escapes all chars in bad, in addition to \ and all special
1132 * chars, in \xFF style escaping. May be reversed with
1135 if (!(r = new(char, strlen(s)*4+1)))
1138 for (f = s, t = r; *f; f++) {
1140 if ((*f < ' ') || (*f >= 127) ||
1141 (*f == '\\') || strchr(bad, *f)) {
1144 *(t++) = hexchar(*f >> 4);
1145 *(t++) = hexchar(*f);
1155 char *bus_path_escape(const char *s) {
1161 /* Escapes all chars that D-Bus' object path cannot deal
1162 * with. Can be reverse with bus_path_unescape() */
1164 if (!(r = new(char, strlen(s)*3+1)))
1167 for (f = s, t = r; *f; f++) {
1169 if (!(*f >= 'A' && *f <= 'Z') &&
1170 !(*f >= 'a' && *f <= 'z') &&
1171 !(*f >= '0' && *f <= '9')) {
1173 *(t++) = hexchar(*f >> 4);
1174 *(t++) = hexchar(*f);
1184 char *bus_path_unescape(const char *f) {
1189 if (!(r = strdup(f)))
1192 for (t = r; *f; f++) {
1197 if ((a = unhexchar(f[1])) < 0 ||
1198 (b = unhexchar(f[2])) < 0) {
1199 /* Invalid escape code, let's take it literal then */
1202 *(t++) = (char) ((a << 4) | b);
1214 char *path_kill_slashes(char *path) {
1218 /* Removes redundant inner and trailing slashes. Modifies the
1219 * passed string in-place.
1221 * ///foo///bar/ becomes /foo/bar
1224 for (f = path, t = path; *f; f++) {
1239 /* Special rule, if we are talking of the root directory, a
1240 trailing slash is good */
1242 if (t == path && slash)
1249 bool path_startswith(const char *path, const char *prefix) {
1253 if ((path[0] == '/') != (prefix[0] == '/'))
1259 path += strspn(path, "/");
1260 prefix += strspn(prefix, "/");
1268 a = strcspn(path, "/");
1269 b = strcspn(prefix, "/");
1274 if (memcmp(path, prefix, a) != 0)
1282 bool path_equal(const char *a, const char *b) {
1286 if ((a[0] == '/') != (b[0] == '/'))
1292 a += strspn(a, "/");
1293 b += strspn(b, "/");
1295 if (*a == 0 && *b == 0)
1298 if (*a == 0 || *b == 0)
1301 j = strcspn(a, "/");
1302 k = strcspn(b, "/");
1307 if (memcmp(a, b, j) != 0)
1315 char *ascii_strlower(char *t) {
1320 for (p = t; *p; p++)
1321 if (*p >= 'A' && *p <= 'Z')
1322 *p = *p - 'A' + 'a';
1327 bool ignore_file(const char *filename) {
1331 filename[0] == '.' ||
1332 streq(filename, "lost+found") ||
1333 endswith(filename, "~") ||
1334 endswith(filename, ".rpmnew") ||
1335 endswith(filename, ".rpmsave") ||
1336 endswith(filename, ".rpmorig") ||
1337 endswith(filename, ".dpkg-old") ||
1338 endswith(filename, ".dpkg-new") ||
1339 endswith(filename, ".swp");
1342 int fd_nonblock(int fd, bool nonblock) {
1347 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1351 flags |= O_NONBLOCK;
1353 flags &= ~O_NONBLOCK;
1355 if (fcntl(fd, F_SETFL, flags) < 0)
1361 int fd_cloexec(int fd, bool cloexec) {
1366 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1370 flags |= FD_CLOEXEC;
1372 flags &= ~FD_CLOEXEC;
1374 if (fcntl(fd, F_SETFD, flags) < 0)
1380 int close_all_fds(const int except[], unsigned n_except) {
1385 if (!(d = opendir("/proc/self/fd")))
1388 while ((de = readdir(d))) {
1391 if (ignore_file(de->d_name))
1394 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1408 for (i = 0; i < n_except; i++)
1409 if (except[i] == fd) {
1418 if ((r = close_nointr(fd)) < 0) {
1419 /* Valgrind has its own FD and doesn't want to have it closed */
1432 bool chars_intersect(const char *a, const char *b) {
1435 /* Returns true if any of the chars in a are in b. */
1436 for (p = a; *p; p++)
1443 char *format_timestamp(char *buf, size_t l, usec_t t) {
1453 sec = (time_t) t / USEC_PER_SEC;
1455 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1461 char *format_timespan(char *buf, size_t l, usec_t t) {
1462 static const struct {
1466 { "w", USEC_PER_WEEK },
1467 { "d", USEC_PER_DAY },
1468 { "h", USEC_PER_HOUR },
1469 { "min", USEC_PER_MINUTE },
1470 { "s", USEC_PER_SEC },
1471 { "ms", USEC_PER_MSEC },
1481 if (t == (usec_t) -1)
1484 /* The result of this function can be parsed with parse_usec */
1486 for (i = 0; i < ELEMENTSOF(table); i++) {
1490 if (t < table[i].usec)
1496 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1497 n = MIN((size_t) k, l);
1510 bool fstype_is_network(const char *fstype) {
1511 static const char * const table[] = {
1523 for (i = 0; i < ELEMENTSOF(table); i++)
1524 if (streq(table[i], fstype))
1533 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1538 TIOCL_GETKMSGREDIRECT,
1542 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1545 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1548 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1551 close_nointr_nofail(r);
1555 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1556 struct termios old_termios, new_termios;
1563 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1564 new_termios = old_termios;
1566 new_termios.c_lflag &= ~ICANON;
1567 new_termios.c_cc[VMIN] = 1;
1568 new_termios.c_cc[VTIME] = 0;
1570 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1573 k = fread(&c, 1, 1, f);
1575 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1581 *need_nl = c != '\n';
1588 if (!(fgets(line, sizeof(line), f)))
1593 if (strlen(line) != 1)
1603 int ask(char *ret, const char *replies, const char *text, ...) {
1612 bool need_nl = true;
1614 fputs("\x1B[1m", stdout);
1620 fputs("\x1B[0m", stdout);
1624 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1626 if (r == -EBADMSG) {
1627 puts("Bad input, please try again.");
1638 if (strchr(replies, c)) {
1643 puts("Read unexpected character, please try again.");
1647 int reset_terminal(int fd) {
1648 struct termios termios;
1653 /* Set terminal to some sane defaults */
1655 if (tcgetattr(fd, &termios) < 0) {
1660 /* We only reset the stuff that matters to the software. How
1661 * hardware is set up we don't touch assuming that somebody
1662 * else will do that for us */
1664 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1665 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1666 termios.c_oflag |= ONLCR;
1667 termios.c_cflag |= CREAD;
1668 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1670 termios.c_cc[VINTR] = 03; /* ^C */
1671 termios.c_cc[VQUIT] = 034; /* ^\ */
1672 termios.c_cc[VERASE] = 0177;
1673 termios.c_cc[VKILL] = 025; /* ^X */
1674 termios.c_cc[VEOF] = 04; /* ^D */
1675 termios.c_cc[VSTART] = 021; /* ^Q */
1676 termios.c_cc[VSTOP] = 023; /* ^S */
1677 termios.c_cc[VSUSP] = 032; /* ^Z */
1678 termios.c_cc[VLNEXT] = 026; /* ^V */
1679 termios.c_cc[VWERASE] = 027; /* ^W */
1680 termios.c_cc[VREPRINT] = 022; /* ^R */
1681 termios.c_cc[VEOL] = 0;
1682 termios.c_cc[VEOL2] = 0;
1684 termios.c_cc[VTIME] = 0;
1685 termios.c_cc[VMIN] = 1;
1687 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1691 /* Just in case, flush all crap out */
1692 tcflush(fd, TCIOFLUSH);
1697 int open_terminal(const char *name, int mode) {
1700 if ((fd = open(name, mode)) < 0)
1703 if ((r = isatty(fd)) < 0) {
1704 close_nointr_nofail(fd);
1709 close_nointr_nofail(fd);
1716 int flush_fd(int fd) {
1717 struct pollfd pollfd;
1721 pollfd.events = POLLIN;
1728 if ((r = poll(&pollfd, 1, 0)) < 0) {
1739 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1744 if (errno == EAGAIN)
1755 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1756 int fd = -1, notify = -1, r, wd = -1;
1760 /* We use inotify to be notified when the tty is closed. We
1761 * create the watch before checking if we can actually acquire
1762 * it, so that we don't lose any event.
1764 * Note: strictly speaking this actually watches for the
1765 * device being closed, it does *not* really watch whether a
1766 * tty loses its controlling process. However, unless some
1767 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1768 * its tty otherwise this will not become a problem. As long
1769 * as the administrator makes sure not configure any service
1770 * on the same tty as an untrusted user this should not be a
1771 * problem. (Which he probably should not do anyway.) */
1773 if (!fail && !force) {
1774 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1779 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1787 if ((r = flush_fd(notify)) < 0)
1790 /* We pass here O_NOCTTY only so that we can check the return
1791 * value TIOCSCTTY and have a reliable way to figure out if we
1792 * successfully became the controlling process of the tty */
1793 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1796 /* First, try to get the tty */
1797 r = ioctl(fd, TIOCSCTTY, force);
1799 /* Sometimes it makes sense to ignore TIOCSCTTY
1800 * returning EPERM, i.e. when very likely we already
1801 * are have this controlling terminal. */
1802 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1805 if (r < 0 && (force || fail || errno != EPERM)) {
1815 assert(notify >= 0);
1818 struct inotify_event e;
1821 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1835 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1843 /* We close the tty fd here since if the old session
1844 * ended our handle will be dead. It's important that
1845 * we do this after sleeping, so that we don't enter
1846 * an endless loop. */
1847 close_nointr_nofail(fd);
1851 close_nointr_nofail(notify);
1853 if ((r = reset_terminal(fd)) < 0)
1854 log_warning("Failed to reset terminal: %s", strerror(-r));
1860 close_nointr_nofail(fd);
1863 close_nointr_nofail(notify);
1868 int release_terminal(void) {
1870 struct sigaction sa_old, sa_new;
1872 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1875 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1876 * by our own TIOCNOTTY */
1879 sa_new.sa_handler = SIG_IGN;
1880 sa_new.sa_flags = SA_RESTART;
1881 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1883 if (ioctl(fd, TIOCNOTTY) < 0)
1886 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1888 close_nointr_nofail(fd);
1892 int sigaction_many(const struct sigaction *sa, ...) {
1897 while ((sig = va_arg(ap, int)) > 0)
1898 if (sigaction(sig, sa, NULL) < 0)
1905 int ignore_signals(int sig, ...) {
1906 struct sigaction sa;
1911 sa.sa_handler = SIG_IGN;
1912 sa.sa_flags = SA_RESTART;
1914 if (sigaction(sig, &sa, NULL) < 0)
1918 while ((sig = va_arg(ap, int)) > 0)
1919 if (sigaction(sig, &sa, NULL) < 0)
1926 int default_signals(int sig, ...) {
1927 struct sigaction sa;
1932 sa.sa_handler = SIG_DFL;
1933 sa.sa_flags = SA_RESTART;
1935 if (sigaction(sig, &sa, NULL) < 0)
1939 while ((sig = va_arg(ap, int)) > 0)
1940 if (sigaction(sig, &sa, NULL) < 0)
1947 int close_pipe(int p[]) {
1953 a = close_nointr(p[0]);
1958 b = close_nointr(p[1]);
1962 return a < 0 ? a : b;
1965 ssize_t loop_read(int fd, void *buf, size_t nbytes) {
1974 while (nbytes > 0) {
1977 if ((k = read(fd, p, nbytes)) <= 0) {
1982 if (errno == EAGAIN) {
1983 struct pollfd pollfd;
1987 pollfd.events = POLLIN;
1989 if (poll(&pollfd, 1, -1) < 0) {
1993 return n > 0 ? n : -errno;
1996 if (pollfd.revents != POLLIN)
1997 return n > 0 ? n : -EIO;
2002 return n > 0 ? n : (k < 0 ? -errno : 0);
2013 int path_is_mount_point(const char *t) {
2017 if (lstat(t, &a) < 0) {
2019 if (errno == ENOENT)
2025 if (!(copy = strdup(t)))
2028 if (lstat(dirname(copy), &b) < 0) {
2035 return a.st_dev != b.st_dev;
2038 int parse_usec(const char *t, usec_t *usec) {
2039 static const struct {
2043 { "sec", USEC_PER_SEC },
2044 { "s", USEC_PER_SEC },
2045 { "min", USEC_PER_MINUTE },
2046 { "hr", USEC_PER_HOUR },
2047 { "h", USEC_PER_HOUR },
2048 { "d", USEC_PER_DAY },
2049 { "w", USEC_PER_WEEK },
2050 { "msec", USEC_PER_MSEC },
2051 { "ms", USEC_PER_MSEC },
2052 { "m", USEC_PER_MINUTE },
2055 { "", USEC_PER_SEC },
2071 l = strtoll(p, &e, 10);
2082 e += strspn(e, WHITESPACE);
2084 for (i = 0; i < ELEMENTSOF(table); i++)
2085 if (startswith(e, table[i].suffix)) {
2086 r += (usec_t) l * table[i].usec;
2087 p = e + strlen(table[i].suffix);
2091 if (i >= ELEMENTSOF(table))
2101 int make_stdio(int fd) {
2106 r = dup2(fd, STDIN_FILENO);
2107 s = dup2(fd, STDOUT_FILENO);
2108 t = dup2(fd, STDERR_FILENO);
2111 close_nointr_nofail(fd);
2113 if (r < 0 || s < 0 || t < 0)
2119 bool is_clean_exit(int code, int status) {
2121 if (code == CLD_EXITED)
2124 /* If a daemon does not implement handlers for some of the
2125 * signals that's not considered an unclean shutdown */
2126 if (code == CLD_KILLED)
2130 status == SIGTERM ||
2136 bool is_device_path(const char *path) {
2138 /* Returns true on paths that refer to a device, either in
2139 * sysfs or in /dev */
2142 path_startswith(path, "/dev/") ||
2143 path_startswith(path, "/sys/");
2146 int dir_is_empty(const char *path) {
2149 struct dirent buf, *de;
2151 if (!(d = opendir(path)))
2155 if ((r = readdir_r(d, &buf, &de)) > 0) {
2165 if (!ignore_file(de->d_name)) {
2175 unsigned long long random_ull(void) {
2180 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2183 r = loop_read(fd, &ull, sizeof(ull));
2184 close_nointr_nofail(fd);
2186 if (r != sizeof(ull))
2192 return random() * RAND_MAX + random();
2195 void rename_process(const char name[8]) {
2198 prctl(PR_SET_NAME, name);
2200 /* This is a like a poor man's setproctitle(). The string
2201 * passed should fit in 7 chars (i.e. the length of
2204 if (program_invocation_name)
2205 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2208 void sigset_add_many(sigset_t *ss, ...) {
2215 while ((sig = va_arg(ap, int)) > 0)
2216 assert_se(sigaddset(ss, sig) == 0);
2220 static const char *const ioprio_class_table[] = {
2221 [IOPRIO_CLASS_NONE] = "none",
2222 [IOPRIO_CLASS_RT] = "realtime",
2223 [IOPRIO_CLASS_BE] = "best-effort",
2224 [IOPRIO_CLASS_IDLE] = "idle"
2227 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2229 static const char *const sigchld_code_table[] = {
2230 [CLD_EXITED] = "exited",
2231 [CLD_KILLED] = "killed",
2232 [CLD_DUMPED] = "dumped",
2233 [CLD_TRAPPED] = "trapped",
2234 [CLD_STOPPED] = "stopped",
2235 [CLD_CONTINUED] = "continued",
2238 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2240 static const char *const log_facility_table[LOG_NFACILITIES] = {
2241 [LOG_FAC(LOG_KERN)] = "kern",
2242 [LOG_FAC(LOG_USER)] = "user",
2243 [LOG_FAC(LOG_MAIL)] = "mail",
2244 [LOG_FAC(LOG_DAEMON)] = "daemon",
2245 [LOG_FAC(LOG_AUTH)] = "auth",
2246 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2247 [LOG_FAC(LOG_LPR)] = "lpr",
2248 [LOG_FAC(LOG_NEWS)] = "news",
2249 [LOG_FAC(LOG_UUCP)] = "uucp",
2250 [LOG_FAC(LOG_CRON)] = "cron",
2251 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2252 [LOG_FAC(LOG_FTP)] = "ftp",
2253 [LOG_FAC(LOG_LOCAL0)] = "local0",
2254 [LOG_FAC(LOG_LOCAL1)] = "local1",
2255 [LOG_FAC(LOG_LOCAL2)] = "local2",
2256 [LOG_FAC(LOG_LOCAL3)] = "local3",
2257 [LOG_FAC(LOG_LOCAL4)] = "local4",
2258 [LOG_FAC(LOG_LOCAL5)] = "local5",
2259 [LOG_FAC(LOG_LOCAL6)] = "local6",
2260 [LOG_FAC(LOG_LOCAL7)] = "local7"
2263 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2265 static const char *const log_level_table[] = {
2266 [LOG_EMERG] = "emerg",
2267 [LOG_ALERT] = "alert",
2268 [LOG_CRIT] = "crit",
2270 [LOG_WARNING] = "warning",
2271 [LOG_NOTICE] = "notice",
2272 [LOG_INFO] = "info",
2273 [LOG_DEBUG] = "debug"
2276 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2278 static const char* const sched_policy_table[] = {
2279 [SCHED_OTHER] = "other",
2280 [SCHED_BATCH] = "batch",
2281 [SCHED_IDLE] = "idle",
2282 [SCHED_FIFO] = "fifo",
2286 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2288 static const char* const rlimit_table[] = {
2289 [RLIMIT_CPU] = "LimitCPU",
2290 [RLIMIT_FSIZE] = "LimitFSIZE",
2291 [RLIMIT_DATA] = "LimitDATA",
2292 [RLIMIT_STACK] = "LimitSTACK",
2293 [RLIMIT_CORE] = "LimitCORE",
2294 [RLIMIT_RSS] = "LimitRSS",
2295 [RLIMIT_NOFILE] = "LimitNOFILE",
2296 [RLIMIT_AS] = "LimitAS",
2297 [RLIMIT_NPROC] = "LimitNPROC",
2298 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2299 [RLIMIT_LOCKS] = "LimitLOCKS",
2300 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2301 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2302 [RLIMIT_NICE] = "LimitNICE",
2303 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2304 [RLIMIT_RTTIME] = "LimitRTTIME"
2307 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);