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>
47 #include <sys/utsname.h>
57 bool streq_ptr(const char *a, const char *b) {
59 /* Like streq(), but tries to make sense of NULL pointers */
70 usec_t now(clockid_t clock_id) {
73 assert_se(clock_gettime(clock_id, &ts) == 0);
75 return timespec_load(&ts);
78 timestamp* timestamp_get(timestamp *ts) {
81 ts->realtime = now(CLOCK_REALTIME);
82 ts->monotonic = now(CLOCK_MONOTONIC);
87 usec_t timespec_load(const struct timespec *ts) {
91 (usec_t) ts->tv_sec * USEC_PER_SEC +
92 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
95 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
98 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
99 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
104 usec_t timeval_load(const struct timeval *tv) {
108 (usec_t) tv->tv_sec * USEC_PER_SEC +
109 (usec_t) tv->tv_usec;
112 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
115 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
116 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
121 bool endswith(const char *s, const char *postfix) {
128 pl = strlen(postfix);
136 return memcmp(s + sl - pl, postfix, pl) == 0;
139 bool startswith(const char *s, const char *prefix) {
154 return memcmp(s, prefix, pl) == 0;
157 bool startswith_no_case(const char *s, const char *prefix) {
173 for(i = 0; i < pl; ++i) {
174 if (tolower(s[i]) != tolower(prefix[i]))
181 bool first_word(const char *s, const char *word) {
196 if (memcmp(s, word, wl) != 0)
200 strchr(WHITESPACE, s[wl]);
203 int close_nointr(int fd) {
209 if ((r = close(fd)) >= 0)
217 void close_nointr_nofail(int fd) {
218 int saved_errno = errno;
220 /* like close_nointr() but cannot fail, and guarantees errno
223 assert_se(close_nointr(fd) == 0);
228 void close_many(const int fds[], unsigned n_fd) {
231 for (i = 0; i < n_fd; i++)
232 close_nointr_nofail(fds[i]);
235 int parse_boolean(const char *v) {
238 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
240 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
246 int parse_pid(const char *s, pid_t* ret_pid) {
254 if ((r = safe_atolu(s, &ul)) < 0)
259 if ((unsigned long) pid != ul)
269 int safe_atou(const char *s, unsigned *ret_u) {
277 l = strtoul(s, &x, 0);
279 if (!x || *x || errno)
280 return errno ? -errno : -EINVAL;
282 if ((unsigned long) (unsigned) l != l)
285 *ret_u = (unsigned) l;
289 int safe_atoi(const char *s, int *ret_i) {
297 l = strtol(s, &x, 0);
299 if (!x || *x || errno)
300 return errno ? -errno : -EINVAL;
302 if ((long) (int) l != l)
309 int safe_atolu(const char *s, long unsigned *ret_lu) {
317 l = strtoul(s, &x, 0);
319 if (!x || *x || errno)
320 return errno ? -errno : -EINVAL;
326 int safe_atoli(const char *s, long int *ret_li) {
334 l = strtol(s, &x, 0);
336 if (!x || *x || errno)
337 return errno ? -errno : -EINVAL;
343 int safe_atollu(const char *s, long long unsigned *ret_llu) {
345 unsigned long long l;
351 l = strtoull(s, &x, 0);
353 if (!x || *x || errno)
354 return errno ? -errno : -EINVAL;
360 int safe_atolli(const char *s, long long int *ret_lli) {
368 l = strtoll(s, &x, 0);
370 if (!x || *x || errno)
371 return errno ? -errno : -EINVAL;
377 /* Split a string into words. */
378 char *split(const char *c, size_t *l, const char *separator, char **state) {
381 current = *state ? *state : (char*) c;
383 if (!*current || *c == 0)
386 current += strspn(current, separator);
387 *l = strcspn(current, separator);
390 return (char*) current;
393 /* Split a string into words, but consider strings enclosed in '' and
394 * "" as words even if they include spaces. */
395 char *split_quoted(const char *c, size_t *l, char **state) {
398 current = *state ? *state : (char*) c;
400 if (!*current || *c == 0)
403 current += strspn(current, WHITESPACE);
405 if (*current == '\'') {
407 *l = strcspn(current, "'");
412 } else if (*current == '\"') {
414 *l = strcspn(current, "\"");
420 *l = strcspn(current, WHITESPACE);
424 /* FIXME: Cannot deal with strings that have spaces AND ticks
427 return (char*) current;
430 char **split_path_and_make_absolute(const char *p) {
434 if (!(l = strv_split(p, ":")))
437 if (!strv_path_make_absolute_cwd(l)) {
445 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
448 char fn[132], line[256], *p;
449 long long unsigned ppid;
454 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
455 fn[sizeof(fn)-1] = 0;
457 if (!(f = fopen(fn, "r")))
460 if (!(fgets(line, sizeof(line), f))) {
468 /* Let's skip the pid and comm fields. The latter is enclosed
469 * in () but does not escape any () in its value, so let's
470 * skip over it manually */
472 if (!(p = strrchr(line, ')')))
483 if ((long long unsigned) (pid_t) ppid != ppid)
486 *_ppid = (pid_t) ppid;
491 int write_one_line_file(const char *fn, const char *line) {
498 if (!(f = fopen(fn, "we")))
501 if (fputs(line, f) < 0) {
512 int read_one_line_file(const char *fn, char **line) {
520 if (!(f = fopen(fn, "re")))
523 if (!(fgets(t, sizeof(t), f))) {
528 if (!(c = strdup(t))) {
541 char *truncate_nl(char *s) {
544 s[strcspn(s, NEWLINE)] = 0;
548 int get_process_name(pid_t pid, char **name) {
555 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
558 r = read_one_line_file(p, name);
568 char *strappend(const char *s, const char *suffix) {
578 if (!(r = new(char, a+b+1)))
582 memcpy(r+a, suffix, b);
588 int readlink_malloc(const char *p, char **r) {
598 if (!(c = new(char, l)))
601 if ((n = readlink(p, c, l-1)) < 0) {
607 if ((size_t) n < l-1) {
618 int readlink_and_make_absolute(const char *p, char **r) {
625 if ((j = readlink_malloc(p, &target)) < 0)
628 k = file_in_same_dir(p, target);
638 char *file_name_from_path(const char *p) {
643 if ((r = strrchr(p, '/')))
649 bool path_is_absolute(const char *p) {
655 bool is_path(const char *p) {
657 return !!strchr(p, '/');
660 char *path_make_absolute(const char *p, const char *prefix) {
665 /* Makes every item in the list an absolute path by prepending
666 * the prefix, if specified and necessary */
668 if (path_is_absolute(p) || !prefix)
671 if (asprintf(&r, "%s/%s", prefix, p) < 0)
677 char *path_make_absolute_cwd(const char *p) {
682 /* Similar to path_make_absolute(), but prefixes with the
683 * current working directory. */
685 if (path_is_absolute(p))
688 if (!(cwd = get_current_dir_name()))
691 r = path_make_absolute(p, cwd);
697 char **strv_path_make_absolute_cwd(char **l) {
700 /* Goes through every item in the string list and makes it
701 * absolute. This works in place and won't rollback any
702 * changes on failure. */
707 if (!(t = path_make_absolute_cwd(*s)))
717 char **strv_path_canonicalize(char **l) {
725 /* Goes through every item in the string list and canonicalize
726 * the path. This works in place and won't rollback any
727 * changes on failure. */
732 t = path_make_absolute_cwd(*s);
741 u = canonicalize_file_name(t);
745 if (errno == ENOMEM || !errno)
762 int reset_all_signal_handlers(void) {
765 for (sig = 1; sig < _NSIG; sig++) {
768 if (sig == SIGKILL || sig == SIGSTOP)
772 sa.sa_handler = SIG_DFL;
773 sa.sa_flags = SA_RESTART;
775 /* On Linux the first two RT signals are reserved by
776 * glibc, and sigaction() will return EINVAL for them. */
777 if ((sigaction(sig, &sa, NULL) < 0))
785 char *strstrip(char *s) {
788 /* Drops trailing whitespace. Modifies the string in
789 * place. Returns pointer to first non-space character */
791 s += strspn(s, WHITESPACE);
794 if (!strchr(WHITESPACE, *e))
805 char *delete_chars(char *s, const char *bad) {
808 /* Drops all whitespace, regardless where in the string */
810 for (f = s, t = s; *f; f++) {
822 char *file_in_same_dir(const char *path, const char *filename) {
829 /* This removes the last component of path and appends
830 * filename, unless the latter is absolute anyway or the
833 if (path_is_absolute(filename))
834 return strdup(filename);
836 if (!(e = strrchr(path, '/')))
837 return strdup(filename);
839 k = strlen(filename);
840 if (!(r = new(char, e-path+1+k+1)))
843 memcpy(r, path, e-path+1);
844 memcpy(r+(e-path)+1, filename, k+1);
849 int mkdir_parents(const char *path, mode_t mode) {
854 /* Creates every parent directory in the path except the last
857 p = path + strspn(path, "/");
862 e = p + strcspn(p, "/");
863 p = e + strspn(e, "/");
865 /* Is this the last component? If so, then we're
870 if (!(t = strndup(path, e - path)))
877 if (r < 0 && errno != EEXIST)
882 int mkdir_p(const char *path, mode_t mode) {
887 if ((r = mkdir_parents(path, mode)) < 0)
890 if (mkdir(path, mode) < 0)
896 char hexchar(int x) {
897 static const char table[16] = "0123456789abcdef";
899 return table[x & 15];
902 int unhexchar(char c) {
904 if (c >= '0' && c <= '9')
907 if (c >= 'a' && c <= 'f')
910 if (c >= 'A' && c <= 'F')
916 char octchar(int x) {
917 return '0' + (x & 7);
920 int unoctchar(char c) {
922 if (c >= '0' && c <= '7')
928 char decchar(int x) {
929 return '0' + (x % 10);
932 int undecchar(char c) {
934 if (c >= '0' && c <= '9')
940 char *cescape(const char *s) {
946 /* Does C style string escaping. */
948 if (!(r = new(char, strlen(s)*4 + 1)))
951 for (f = s, t = r; *f; f++)
997 /* For special chars we prefer octal over
998 * hexadecimal encoding, simply because glib's
999 * g_strescape() does the same */
1000 if ((*f < ' ') || (*f >= 127)) {
1002 *(t++) = octchar((unsigned char) *f >> 6);
1003 *(t++) = octchar((unsigned char) *f >> 3);
1004 *(t++) = octchar((unsigned char) *f);
1015 char *cunescape(const char *s) {
1021 /* Undoes C style string escaping */
1023 if (!(r = new(char, strlen(s)+1)))
1026 for (f = s, t = r; *f; f++) {
1069 /* hexadecimal encoding */
1072 if ((a = unhexchar(f[1])) < 0 ||
1073 (b = unhexchar(f[2])) < 0) {
1074 /* Invalid escape code, let's take it literal then */
1078 *(t++) = (char) ((a << 4) | b);
1093 /* octal encoding */
1096 if ((a = unoctchar(f[0])) < 0 ||
1097 (b = unoctchar(f[1])) < 0 ||
1098 (c = unoctchar(f[2])) < 0) {
1099 /* Invalid escape code, let's take it literal then */
1103 *(t++) = (char) ((a << 6) | (b << 3) | c);
1111 /* premature end of string.*/
1116 /* Invalid escape code, let's take it literal then */
1129 char *xescape(const char *s, const char *bad) {
1133 /* Escapes all chars in bad, in addition to \ and all special
1134 * chars, in \xFF style escaping. May be reversed with
1137 if (!(r = new(char, strlen(s)*4+1)))
1140 for (f = s, t = r; *f; f++) {
1142 if ((*f < ' ') || (*f >= 127) ||
1143 (*f == '\\') || strchr(bad, *f)) {
1146 *(t++) = hexchar(*f >> 4);
1147 *(t++) = hexchar(*f);
1157 char *bus_path_escape(const char *s) {
1163 /* Escapes all chars that D-Bus' object path cannot deal
1164 * with. Can be reverse with bus_path_unescape() */
1166 if (!(r = new(char, strlen(s)*3+1)))
1169 for (f = s, t = r; *f; f++) {
1171 if (!(*f >= 'A' && *f <= 'Z') &&
1172 !(*f >= 'a' && *f <= 'z') &&
1173 !(*f >= '0' && *f <= '9')) {
1175 *(t++) = hexchar(*f >> 4);
1176 *(t++) = hexchar(*f);
1186 char *bus_path_unescape(const char *f) {
1191 if (!(r = strdup(f)))
1194 for (t = r; *f; f++) {
1199 if ((a = unhexchar(f[1])) < 0 ||
1200 (b = unhexchar(f[2])) < 0) {
1201 /* Invalid escape code, let's take it literal then */
1204 *(t++) = (char) ((a << 4) | b);
1216 char *path_kill_slashes(char *path) {
1220 /* Removes redundant inner and trailing slashes. Modifies the
1221 * passed string in-place.
1223 * ///foo///bar/ becomes /foo/bar
1226 for (f = path, t = path; *f; f++) {
1241 /* Special rule, if we are talking of the root directory, a
1242 trailing slash is good */
1244 if (t == path && slash)
1251 bool path_startswith(const char *path, const char *prefix) {
1255 if ((path[0] == '/') != (prefix[0] == '/'))
1261 path += strspn(path, "/");
1262 prefix += strspn(prefix, "/");
1270 a = strcspn(path, "/");
1271 b = strcspn(prefix, "/");
1276 if (memcmp(path, prefix, a) != 0)
1284 bool path_equal(const char *a, const char *b) {
1288 if ((a[0] == '/') != (b[0] == '/'))
1294 a += strspn(a, "/");
1295 b += strspn(b, "/");
1297 if (*a == 0 && *b == 0)
1300 if (*a == 0 || *b == 0)
1303 j = strcspn(a, "/");
1304 k = strcspn(b, "/");
1309 if (memcmp(a, b, j) != 0)
1317 char *ascii_strlower(char *t) {
1322 for (p = t; *p; p++)
1323 if (*p >= 'A' && *p <= 'Z')
1324 *p = *p - 'A' + 'a';
1329 bool ignore_file(const char *filename) {
1333 filename[0] == '.' ||
1334 streq(filename, "lost+found") ||
1335 endswith(filename, "~") ||
1336 endswith(filename, ".rpmnew") ||
1337 endswith(filename, ".rpmsave") ||
1338 endswith(filename, ".rpmorig") ||
1339 endswith(filename, ".dpkg-old") ||
1340 endswith(filename, ".dpkg-new") ||
1341 endswith(filename, ".swp");
1344 int fd_nonblock(int fd, bool nonblock) {
1349 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1353 flags |= O_NONBLOCK;
1355 flags &= ~O_NONBLOCK;
1357 if (fcntl(fd, F_SETFL, flags) < 0)
1363 int fd_cloexec(int fd, bool cloexec) {
1368 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1372 flags |= FD_CLOEXEC;
1374 flags &= ~FD_CLOEXEC;
1376 if (fcntl(fd, F_SETFD, flags) < 0)
1382 int close_all_fds(const int except[], unsigned n_except) {
1387 if (!(d = opendir("/proc/self/fd")))
1390 while ((de = readdir(d))) {
1393 if (ignore_file(de->d_name))
1396 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1410 for (i = 0; i < n_except; i++)
1411 if (except[i] == fd) {
1420 if ((r = close_nointr(fd)) < 0) {
1421 /* Valgrind has its own FD and doesn't want to have it closed */
1434 bool chars_intersect(const char *a, const char *b) {
1437 /* Returns true if any of the chars in a are in b. */
1438 for (p = a; *p; p++)
1445 char *format_timestamp(char *buf, size_t l, usec_t t) {
1455 sec = (time_t) t / USEC_PER_SEC;
1457 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1463 char *format_timespan(char *buf, size_t l, usec_t t) {
1464 static const struct {
1468 { "w", USEC_PER_WEEK },
1469 { "d", USEC_PER_DAY },
1470 { "h", USEC_PER_HOUR },
1471 { "min", USEC_PER_MINUTE },
1472 { "s", USEC_PER_SEC },
1473 { "ms", USEC_PER_MSEC },
1483 if (t == (usec_t) -1)
1486 /* The result of this function can be parsed with parse_usec */
1488 for (i = 0; i < ELEMENTSOF(table); i++) {
1492 if (t < table[i].usec)
1498 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1499 n = MIN((size_t) k, l);
1512 bool fstype_is_network(const char *fstype) {
1513 static const char * const table[] = {
1525 for (i = 0; i < ELEMENTSOF(table); i++)
1526 if (streq(table[i], fstype))
1535 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1540 TIOCL_GETKMSGREDIRECT,
1544 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1547 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1550 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1553 close_nointr_nofail(r);
1557 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1558 struct termios old_termios, new_termios;
1565 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1566 new_termios = old_termios;
1568 new_termios.c_lflag &= ~ICANON;
1569 new_termios.c_cc[VMIN] = 1;
1570 new_termios.c_cc[VTIME] = 0;
1572 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1575 k = fread(&c, 1, 1, f);
1577 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1583 *need_nl = c != '\n';
1590 if (!(fgets(line, sizeof(line), f)))
1595 if (strlen(line) != 1)
1605 int ask(char *ret, const char *replies, const char *text, ...) {
1614 bool need_nl = true;
1616 fputs("\x1B[1m", stdout);
1622 fputs("\x1B[0m", stdout);
1626 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1628 if (r == -EBADMSG) {
1629 puts("Bad input, please try again.");
1640 if (strchr(replies, c)) {
1645 puts("Read unexpected character, please try again.");
1649 int reset_terminal(int fd) {
1650 struct termios termios;
1655 /* Set terminal to some sane defaults */
1657 if (tcgetattr(fd, &termios) < 0) {
1662 /* We only reset the stuff that matters to the software. How
1663 * hardware is set up we don't touch assuming that somebody
1664 * else will do that for us */
1666 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1667 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1668 termios.c_oflag |= ONLCR;
1669 termios.c_cflag |= CREAD;
1670 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1672 termios.c_cc[VINTR] = 03; /* ^C */
1673 termios.c_cc[VQUIT] = 034; /* ^\ */
1674 termios.c_cc[VERASE] = 0177;
1675 termios.c_cc[VKILL] = 025; /* ^X */
1676 termios.c_cc[VEOF] = 04; /* ^D */
1677 termios.c_cc[VSTART] = 021; /* ^Q */
1678 termios.c_cc[VSTOP] = 023; /* ^S */
1679 termios.c_cc[VSUSP] = 032; /* ^Z */
1680 termios.c_cc[VLNEXT] = 026; /* ^V */
1681 termios.c_cc[VWERASE] = 027; /* ^W */
1682 termios.c_cc[VREPRINT] = 022; /* ^R */
1683 termios.c_cc[VEOL] = 0;
1684 termios.c_cc[VEOL2] = 0;
1686 termios.c_cc[VTIME] = 0;
1687 termios.c_cc[VMIN] = 1;
1689 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1693 /* Just in case, flush all crap out */
1694 tcflush(fd, TCIOFLUSH);
1699 int open_terminal(const char *name, int mode) {
1702 if ((fd = open(name, mode)) < 0)
1705 if ((r = isatty(fd)) < 0) {
1706 close_nointr_nofail(fd);
1711 close_nointr_nofail(fd);
1718 int flush_fd(int fd) {
1719 struct pollfd pollfd;
1723 pollfd.events = POLLIN;
1730 if ((r = poll(&pollfd, 1, 0)) < 0) {
1741 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1746 if (errno == EAGAIN)
1757 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1758 int fd = -1, notify = -1, r, wd = -1;
1762 /* We use inotify to be notified when the tty is closed. We
1763 * create the watch before checking if we can actually acquire
1764 * it, so that we don't lose any event.
1766 * Note: strictly speaking this actually watches for the
1767 * device being closed, it does *not* really watch whether a
1768 * tty loses its controlling process. However, unless some
1769 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1770 * its tty otherwise this will not become a problem. As long
1771 * as the administrator makes sure not configure any service
1772 * on the same tty as an untrusted user this should not be a
1773 * problem. (Which he probably should not do anyway.) */
1775 if (!fail && !force) {
1776 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1781 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1789 if ((r = flush_fd(notify)) < 0)
1792 /* We pass here O_NOCTTY only so that we can check the return
1793 * value TIOCSCTTY and have a reliable way to figure out if we
1794 * successfully became the controlling process of the tty */
1795 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1798 /* First, try to get the tty */
1799 r = ioctl(fd, TIOCSCTTY, force);
1801 /* Sometimes it makes sense to ignore TIOCSCTTY
1802 * returning EPERM, i.e. when very likely we already
1803 * are have this controlling terminal. */
1804 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1807 if (r < 0 && (force || fail || errno != EPERM)) {
1817 assert(notify >= 0);
1820 struct inotify_event e;
1823 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1837 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1845 /* We close the tty fd here since if the old session
1846 * ended our handle will be dead. It's important that
1847 * we do this after sleeping, so that we don't enter
1848 * an endless loop. */
1849 close_nointr_nofail(fd);
1853 close_nointr_nofail(notify);
1855 if ((r = reset_terminal(fd)) < 0)
1856 log_warning("Failed to reset terminal: %s", strerror(-r));
1862 close_nointr_nofail(fd);
1865 close_nointr_nofail(notify);
1870 int release_terminal(void) {
1872 struct sigaction sa_old, sa_new;
1874 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1877 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1878 * by our own TIOCNOTTY */
1881 sa_new.sa_handler = SIG_IGN;
1882 sa_new.sa_flags = SA_RESTART;
1883 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1885 if (ioctl(fd, TIOCNOTTY) < 0)
1888 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1890 close_nointr_nofail(fd);
1894 int sigaction_many(const struct sigaction *sa, ...) {
1899 while ((sig = va_arg(ap, int)) > 0)
1900 if (sigaction(sig, sa, NULL) < 0)
1907 int ignore_signals(int sig, ...) {
1908 struct sigaction sa;
1913 sa.sa_handler = SIG_IGN;
1914 sa.sa_flags = SA_RESTART;
1916 if (sigaction(sig, &sa, NULL) < 0)
1920 while ((sig = va_arg(ap, int)) > 0)
1921 if (sigaction(sig, &sa, NULL) < 0)
1928 int default_signals(int sig, ...) {
1929 struct sigaction sa;
1934 sa.sa_handler = SIG_DFL;
1935 sa.sa_flags = SA_RESTART;
1937 if (sigaction(sig, &sa, NULL) < 0)
1941 while ((sig = va_arg(ap, int)) > 0)
1942 if (sigaction(sig, &sa, NULL) < 0)
1949 int close_pipe(int p[]) {
1955 a = close_nointr(p[0]);
1960 b = close_nointr(p[1]);
1964 return a < 0 ? a : b;
1967 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
1976 while (nbytes > 0) {
1979 if ((k = read(fd, p, nbytes)) <= 0) {
1981 if (k < 0 && errno == EINTR)
1984 if (k < 0 && errno == EAGAIN && do_poll) {
1985 struct pollfd pollfd;
1989 pollfd.events = POLLIN;
1991 if (poll(&pollfd, 1, -1) < 0) {
1995 return n > 0 ? n : -errno;
1998 if (pollfd.revents != POLLIN)
1999 return n > 0 ? n : -EIO;
2004 return n > 0 ? n : (k < 0 ? -errno : 0);
2015 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2024 while (nbytes > 0) {
2027 if ((k = write(fd, p, nbytes)) <= 0) {
2029 if (k < 0 && errno == EINTR)
2032 if (k < 0 && errno == EAGAIN && do_poll) {
2033 struct pollfd pollfd;
2037 pollfd.events = POLLOUT;
2039 if (poll(&pollfd, 1, -1) < 0) {
2043 return n > 0 ? n : -errno;
2046 if (pollfd.revents != POLLOUT)
2047 return n > 0 ? n : -EIO;
2052 return n > 0 ? n : (k < 0 ? -errno : 0);
2063 int path_is_mount_point(const char *t) {
2067 if (lstat(t, &a) < 0) {
2069 if (errno == ENOENT)
2075 if (!(copy = strdup(t)))
2078 if (lstat(dirname(copy), &b) < 0) {
2085 return a.st_dev != b.st_dev;
2088 int parse_usec(const char *t, usec_t *usec) {
2089 static const struct {
2093 { "sec", USEC_PER_SEC },
2094 { "s", USEC_PER_SEC },
2095 { "min", USEC_PER_MINUTE },
2096 { "hr", USEC_PER_HOUR },
2097 { "h", USEC_PER_HOUR },
2098 { "d", USEC_PER_DAY },
2099 { "w", USEC_PER_WEEK },
2100 { "msec", USEC_PER_MSEC },
2101 { "ms", USEC_PER_MSEC },
2102 { "m", USEC_PER_MINUTE },
2105 { "", USEC_PER_SEC },
2121 l = strtoll(p, &e, 10);
2132 e += strspn(e, WHITESPACE);
2134 for (i = 0; i < ELEMENTSOF(table); i++)
2135 if (startswith(e, table[i].suffix)) {
2136 r += (usec_t) l * table[i].usec;
2137 p = e + strlen(table[i].suffix);
2141 if (i >= ELEMENTSOF(table))
2151 int make_stdio(int fd) {
2156 r = dup2(fd, STDIN_FILENO);
2157 s = dup2(fd, STDOUT_FILENO);
2158 t = dup2(fd, STDERR_FILENO);
2161 close_nointr_nofail(fd);
2163 if (r < 0 || s < 0 || t < 0)
2169 bool is_clean_exit(int code, int status) {
2171 if (code == CLD_EXITED)
2174 /* If a daemon does not implement handlers for some of the
2175 * signals that's not considered an unclean shutdown */
2176 if (code == CLD_KILLED)
2180 status == SIGTERM ||
2186 bool is_device_path(const char *path) {
2188 /* Returns true on paths that refer to a device, either in
2189 * sysfs or in /dev */
2192 path_startswith(path, "/dev/") ||
2193 path_startswith(path, "/sys/");
2196 int dir_is_empty(const char *path) {
2199 struct dirent buf, *de;
2201 if (!(d = opendir(path)))
2205 if ((r = readdir_r(d, &buf, &de)) > 0) {
2215 if (!ignore_file(de->d_name)) {
2225 unsigned long long random_ull(void) {
2230 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2233 r = loop_read(fd, &ull, sizeof(ull), true);
2234 close_nointr_nofail(fd);
2236 if (r != sizeof(ull))
2242 return random() * RAND_MAX + random();
2245 void rename_process(const char name[8]) {
2248 prctl(PR_SET_NAME, name);
2250 /* This is a like a poor man's setproctitle(). The string
2251 * passed should fit in 7 chars (i.e. the length of
2254 if (program_invocation_name)
2255 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2258 void sigset_add_many(sigset_t *ss, ...) {
2265 while ((sig = va_arg(ap, int)) > 0)
2266 assert_se(sigaddset(ss, sig) == 0);
2270 char* gethostname_malloc(void) {
2273 assert_se(uname(&u) >= 0);
2276 return strdup(u.nodename);
2278 return strdup(u.sysname);
2281 char* getlogname_malloc(void) {
2285 struct passwd pwbuf, *pw = NULL;
2288 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2293 /* Shortcut things to avoid NSS lookups */
2295 return strdup("root");
2297 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2300 if (!(buf = malloc(bufsize)))
2303 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2304 name = strdup(pw->pw_name);
2311 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2317 char *getttyname_malloc(void) {
2318 char path[PATH_MAX], *p;
2320 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2321 return strdup("unknown");
2326 if (startswith(path, "/dev/"))
2332 static const char *const ioprio_class_table[] = {
2333 [IOPRIO_CLASS_NONE] = "none",
2334 [IOPRIO_CLASS_RT] = "realtime",
2335 [IOPRIO_CLASS_BE] = "best-effort",
2336 [IOPRIO_CLASS_IDLE] = "idle"
2339 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2341 static const char *const sigchld_code_table[] = {
2342 [CLD_EXITED] = "exited",
2343 [CLD_KILLED] = "killed",
2344 [CLD_DUMPED] = "dumped",
2345 [CLD_TRAPPED] = "trapped",
2346 [CLD_STOPPED] = "stopped",
2347 [CLD_CONTINUED] = "continued",
2350 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2352 static const char *const log_facility_table[LOG_NFACILITIES] = {
2353 [LOG_FAC(LOG_KERN)] = "kern",
2354 [LOG_FAC(LOG_USER)] = "user",
2355 [LOG_FAC(LOG_MAIL)] = "mail",
2356 [LOG_FAC(LOG_DAEMON)] = "daemon",
2357 [LOG_FAC(LOG_AUTH)] = "auth",
2358 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2359 [LOG_FAC(LOG_LPR)] = "lpr",
2360 [LOG_FAC(LOG_NEWS)] = "news",
2361 [LOG_FAC(LOG_UUCP)] = "uucp",
2362 [LOG_FAC(LOG_CRON)] = "cron",
2363 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2364 [LOG_FAC(LOG_FTP)] = "ftp",
2365 [LOG_FAC(LOG_LOCAL0)] = "local0",
2366 [LOG_FAC(LOG_LOCAL1)] = "local1",
2367 [LOG_FAC(LOG_LOCAL2)] = "local2",
2368 [LOG_FAC(LOG_LOCAL3)] = "local3",
2369 [LOG_FAC(LOG_LOCAL4)] = "local4",
2370 [LOG_FAC(LOG_LOCAL5)] = "local5",
2371 [LOG_FAC(LOG_LOCAL6)] = "local6",
2372 [LOG_FAC(LOG_LOCAL7)] = "local7"
2375 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2377 static const char *const log_level_table[] = {
2378 [LOG_EMERG] = "emerg",
2379 [LOG_ALERT] = "alert",
2380 [LOG_CRIT] = "crit",
2382 [LOG_WARNING] = "warning",
2383 [LOG_NOTICE] = "notice",
2384 [LOG_INFO] = "info",
2385 [LOG_DEBUG] = "debug"
2388 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2390 static const char* const sched_policy_table[] = {
2391 [SCHED_OTHER] = "other",
2392 [SCHED_BATCH] = "batch",
2393 [SCHED_IDLE] = "idle",
2394 [SCHED_FIFO] = "fifo",
2398 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2400 static const char* const rlimit_table[] = {
2401 [RLIMIT_CPU] = "LimitCPU",
2402 [RLIMIT_FSIZE] = "LimitFSIZE",
2403 [RLIMIT_DATA] = "LimitDATA",
2404 [RLIMIT_STACK] = "LimitSTACK",
2405 [RLIMIT_CORE] = "LimitCORE",
2406 [RLIMIT_RSS] = "LimitRSS",
2407 [RLIMIT_NOFILE] = "LimitNOFILE",
2408 [RLIMIT_AS] = "LimitAS",
2409 [RLIMIT_NPROC] = "LimitNPROC",
2410 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2411 [RLIMIT_LOCKS] = "LimitLOCKS",
2412 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2413 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2414 [RLIMIT_NICE] = "LimitNICE",
2415 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2416 [RLIMIT_RTTIME] = "LimitRTTIME"
2419 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);