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;
454 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned 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 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/%lu/comm", (unsigned 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 safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
852 if (mkdir(path, mode) >= 0)
853 if (chmod_and_chown(path, mode, uid, gid) < 0)
856 if (lstat(path, &st) < 0)
859 if ((st.st_mode & 0777) != mode ||
862 !S_ISDIR(st.st_mode)) {
871 int mkdir_parents(const char *path, mode_t mode) {
876 /* Creates every parent directory in the path except the last
879 p = path + strspn(path, "/");
884 e = p + strcspn(p, "/");
885 p = e + strspn(e, "/");
887 /* Is this the last component? If so, then we're
892 if (!(t = strndup(path, e - path)))
899 if (r < 0 && errno != EEXIST)
904 int mkdir_p(const char *path, mode_t mode) {
909 if ((r = mkdir_parents(path, mode)) < 0)
912 if (mkdir(path, mode) < 0)
918 int rmdir_parents(const char *path, const char *stop) {
927 /* Skip trailing slashes */
928 while (l > 0 && path[l-1] == '/')
934 /* Skip last component */
935 while (l > 0 && path[l-1] != '/')
938 /* Skip trailing slashes */
939 while (l > 0 && path[l-1] == '/')
945 if (!(t = strndup(path, l)))
948 if (path_startswith(stop, t)) {
965 char hexchar(int x) {
966 static const char table[16] = "0123456789abcdef";
968 return table[x & 15];
971 int unhexchar(char c) {
973 if (c >= '0' && c <= '9')
976 if (c >= 'a' && c <= 'f')
979 if (c >= 'A' && c <= 'F')
985 char octchar(int x) {
986 return '0' + (x & 7);
989 int unoctchar(char c) {
991 if (c >= '0' && c <= '7')
997 char decchar(int x) {
998 return '0' + (x % 10);
1001 int undecchar(char c) {
1003 if (c >= '0' && c <= '9')
1009 char *cescape(const char *s) {
1015 /* Does C style string escaping. */
1017 if (!(r = new(char, strlen(s)*4 + 1)))
1020 for (f = s, t = r; *f; f++)
1066 /* For special chars we prefer octal over
1067 * hexadecimal encoding, simply because glib's
1068 * g_strescape() does the same */
1069 if ((*f < ' ') || (*f >= 127)) {
1071 *(t++) = octchar((unsigned char) *f >> 6);
1072 *(t++) = octchar((unsigned char) *f >> 3);
1073 *(t++) = octchar((unsigned char) *f);
1084 char *cunescape(const char *s) {
1090 /* Undoes C style string escaping */
1092 if (!(r = new(char, strlen(s)+1)))
1095 for (f = s, t = r; *f; f++) {
1138 /* hexadecimal encoding */
1141 if ((a = unhexchar(f[1])) < 0 ||
1142 (b = unhexchar(f[2])) < 0) {
1143 /* Invalid escape code, let's take it literal then */
1147 *(t++) = (char) ((a << 4) | b);
1162 /* octal encoding */
1165 if ((a = unoctchar(f[0])) < 0 ||
1166 (b = unoctchar(f[1])) < 0 ||
1167 (c = unoctchar(f[2])) < 0) {
1168 /* Invalid escape code, let's take it literal then */
1172 *(t++) = (char) ((a << 6) | (b << 3) | c);
1180 /* premature end of string.*/
1185 /* Invalid escape code, let's take it literal then */
1198 char *xescape(const char *s, const char *bad) {
1202 /* Escapes all chars in bad, in addition to \ and all special
1203 * chars, in \xFF style escaping. May be reversed with
1206 if (!(r = new(char, strlen(s)*4+1)))
1209 for (f = s, t = r; *f; f++) {
1211 if ((*f < ' ') || (*f >= 127) ||
1212 (*f == '\\') || strchr(bad, *f)) {
1215 *(t++) = hexchar(*f >> 4);
1216 *(t++) = hexchar(*f);
1226 char *bus_path_escape(const char *s) {
1232 /* Escapes all chars that D-Bus' object path cannot deal
1233 * with. Can be reverse with bus_path_unescape() */
1235 if (!(r = new(char, strlen(s)*3+1)))
1238 for (f = s, t = r; *f; f++) {
1240 if (!(*f >= 'A' && *f <= 'Z') &&
1241 !(*f >= 'a' && *f <= 'z') &&
1242 !(*f >= '0' && *f <= '9')) {
1244 *(t++) = hexchar(*f >> 4);
1245 *(t++) = hexchar(*f);
1255 char *bus_path_unescape(const char *f) {
1260 if (!(r = strdup(f)))
1263 for (t = r; *f; f++) {
1268 if ((a = unhexchar(f[1])) < 0 ||
1269 (b = unhexchar(f[2])) < 0) {
1270 /* Invalid escape code, let's take it literal then */
1273 *(t++) = (char) ((a << 4) | b);
1285 char *path_kill_slashes(char *path) {
1289 /* Removes redundant inner and trailing slashes. Modifies the
1290 * passed string in-place.
1292 * ///foo///bar/ becomes /foo/bar
1295 for (f = path, t = path; *f; f++) {
1310 /* Special rule, if we are talking of the root directory, a
1311 trailing slash is good */
1313 if (t == path && slash)
1320 bool path_startswith(const char *path, const char *prefix) {
1324 if ((path[0] == '/') != (prefix[0] == '/'))
1330 path += strspn(path, "/");
1331 prefix += strspn(prefix, "/");
1339 a = strcspn(path, "/");
1340 b = strcspn(prefix, "/");
1345 if (memcmp(path, prefix, a) != 0)
1353 bool path_equal(const char *a, const char *b) {
1357 if ((a[0] == '/') != (b[0] == '/'))
1363 a += strspn(a, "/");
1364 b += strspn(b, "/");
1366 if (*a == 0 && *b == 0)
1369 if (*a == 0 || *b == 0)
1372 j = strcspn(a, "/");
1373 k = strcspn(b, "/");
1378 if (memcmp(a, b, j) != 0)
1386 char *ascii_strlower(char *t) {
1391 for (p = t; *p; p++)
1392 if (*p >= 'A' && *p <= 'Z')
1393 *p = *p - 'A' + 'a';
1398 bool ignore_file(const char *filename) {
1402 filename[0] == '.' ||
1403 streq(filename, "lost+found") ||
1404 endswith(filename, "~") ||
1405 endswith(filename, ".rpmnew") ||
1406 endswith(filename, ".rpmsave") ||
1407 endswith(filename, ".rpmorig") ||
1408 endswith(filename, ".dpkg-old") ||
1409 endswith(filename, ".dpkg-new") ||
1410 endswith(filename, ".swp");
1413 int fd_nonblock(int fd, bool nonblock) {
1418 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1422 flags |= O_NONBLOCK;
1424 flags &= ~O_NONBLOCK;
1426 if (fcntl(fd, F_SETFL, flags) < 0)
1432 int fd_cloexec(int fd, bool cloexec) {
1437 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1441 flags |= FD_CLOEXEC;
1443 flags &= ~FD_CLOEXEC;
1445 if (fcntl(fd, F_SETFD, flags) < 0)
1451 int close_all_fds(const int except[], unsigned n_except) {
1456 if (!(d = opendir("/proc/self/fd")))
1459 while ((de = readdir(d))) {
1462 if (ignore_file(de->d_name))
1465 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1479 for (i = 0; i < n_except; i++)
1480 if (except[i] == fd) {
1489 if ((r = close_nointr(fd)) < 0) {
1490 /* Valgrind has its own FD and doesn't want to have it closed */
1503 bool chars_intersect(const char *a, const char *b) {
1506 /* Returns true if any of the chars in a are in b. */
1507 for (p = a; *p; p++)
1514 char *format_timestamp(char *buf, size_t l, usec_t t) {
1524 sec = (time_t) (t / USEC_PER_SEC);
1526 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1532 char *format_timespan(char *buf, size_t l, usec_t t) {
1533 static const struct {
1537 { "w", USEC_PER_WEEK },
1538 { "d", USEC_PER_DAY },
1539 { "h", USEC_PER_HOUR },
1540 { "min", USEC_PER_MINUTE },
1541 { "s", USEC_PER_SEC },
1542 { "ms", USEC_PER_MSEC },
1552 if (t == (usec_t) -1)
1555 /* The result of this function can be parsed with parse_usec */
1557 for (i = 0; i < ELEMENTSOF(table); i++) {
1561 if (t < table[i].usec)
1567 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1568 n = MIN((size_t) k, l);
1581 bool fstype_is_network(const char *fstype) {
1582 static const char * const table[] = {
1594 for (i = 0; i < ELEMENTSOF(table); i++)
1595 if (streq(table[i], fstype))
1604 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1609 TIOCL_GETKMSGREDIRECT,
1613 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1616 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1619 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1622 close_nointr_nofail(r);
1626 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1627 struct termios old_termios, new_termios;
1634 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1635 new_termios = old_termios;
1637 new_termios.c_lflag &= ~ICANON;
1638 new_termios.c_cc[VMIN] = 1;
1639 new_termios.c_cc[VTIME] = 0;
1641 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1644 k = fread(&c, 1, 1, f);
1646 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1652 *need_nl = c != '\n';
1659 if (!(fgets(line, sizeof(line), f)))
1664 if (strlen(line) != 1)
1674 int ask(char *ret, const char *replies, const char *text, ...) {
1683 bool need_nl = true;
1685 fputs("\x1B[1m", stdout);
1691 fputs("\x1B[0m", stdout);
1695 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1697 if (r == -EBADMSG) {
1698 puts("Bad input, please try again.");
1709 if (strchr(replies, c)) {
1714 puts("Read unexpected character, please try again.");
1718 int reset_terminal(int fd) {
1719 struct termios termios;
1724 /* Set terminal to some sane defaults */
1726 if (tcgetattr(fd, &termios) < 0) {
1731 /* We only reset the stuff that matters to the software. How
1732 * hardware is set up we don't touch assuming that somebody
1733 * else will do that for us */
1735 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1736 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1737 termios.c_oflag |= ONLCR;
1738 termios.c_cflag |= CREAD;
1739 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1741 termios.c_cc[VINTR] = 03; /* ^C */
1742 termios.c_cc[VQUIT] = 034; /* ^\ */
1743 termios.c_cc[VERASE] = 0177;
1744 termios.c_cc[VKILL] = 025; /* ^X */
1745 termios.c_cc[VEOF] = 04; /* ^D */
1746 termios.c_cc[VSTART] = 021; /* ^Q */
1747 termios.c_cc[VSTOP] = 023; /* ^S */
1748 termios.c_cc[VSUSP] = 032; /* ^Z */
1749 termios.c_cc[VLNEXT] = 026; /* ^V */
1750 termios.c_cc[VWERASE] = 027; /* ^W */
1751 termios.c_cc[VREPRINT] = 022; /* ^R */
1752 termios.c_cc[VEOL] = 0;
1753 termios.c_cc[VEOL2] = 0;
1755 termios.c_cc[VTIME] = 0;
1756 termios.c_cc[VMIN] = 1;
1758 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1762 /* Just in case, flush all crap out */
1763 tcflush(fd, TCIOFLUSH);
1768 int open_terminal(const char *name, int mode) {
1771 if ((fd = open(name, mode)) < 0)
1774 if ((r = isatty(fd)) < 0) {
1775 close_nointr_nofail(fd);
1780 close_nointr_nofail(fd);
1787 int flush_fd(int fd) {
1788 struct pollfd pollfd;
1792 pollfd.events = POLLIN;
1799 if ((r = poll(&pollfd, 1, 0)) < 0) {
1810 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1815 if (errno == EAGAIN)
1826 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1827 int fd = -1, notify = -1, r, wd = -1;
1831 /* We use inotify to be notified when the tty is closed. We
1832 * create the watch before checking if we can actually acquire
1833 * it, so that we don't lose any event.
1835 * Note: strictly speaking this actually watches for the
1836 * device being closed, it does *not* really watch whether a
1837 * tty loses its controlling process. However, unless some
1838 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1839 * its tty otherwise this will not become a problem. As long
1840 * as the administrator makes sure not configure any service
1841 * on the same tty as an untrusted user this should not be a
1842 * problem. (Which he probably should not do anyway.) */
1844 if (!fail && !force) {
1845 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1850 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1858 if ((r = flush_fd(notify)) < 0)
1861 /* We pass here O_NOCTTY only so that we can check the return
1862 * value TIOCSCTTY and have a reliable way to figure out if we
1863 * successfully became the controlling process of the tty */
1864 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1867 /* First, try to get the tty */
1868 r = ioctl(fd, TIOCSCTTY, force);
1870 /* Sometimes it makes sense to ignore TIOCSCTTY
1871 * returning EPERM, i.e. when very likely we already
1872 * are have this controlling terminal. */
1873 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1876 if (r < 0 && (force || fail || errno != EPERM)) {
1886 assert(notify >= 0);
1889 struct inotify_event e;
1892 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1906 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1914 /* We close the tty fd here since if the old session
1915 * ended our handle will be dead. It's important that
1916 * we do this after sleeping, so that we don't enter
1917 * an endless loop. */
1918 close_nointr_nofail(fd);
1922 close_nointr_nofail(notify);
1924 if ((r = reset_terminal(fd)) < 0)
1925 log_warning("Failed to reset terminal: %s", strerror(-r));
1931 close_nointr_nofail(fd);
1934 close_nointr_nofail(notify);
1939 int release_terminal(void) {
1941 struct sigaction sa_old, sa_new;
1943 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1946 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1947 * by our own TIOCNOTTY */
1950 sa_new.sa_handler = SIG_IGN;
1951 sa_new.sa_flags = SA_RESTART;
1952 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1954 if (ioctl(fd, TIOCNOTTY) < 0)
1957 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1959 close_nointr_nofail(fd);
1963 int sigaction_many(const struct sigaction *sa, ...) {
1968 while ((sig = va_arg(ap, int)) > 0)
1969 if (sigaction(sig, sa, NULL) < 0)
1976 int ignore_signals(int sig, ...) {
1977 struct sigaction sa;
1982 sa.sa_handler = SIG_IGN;
1983 sa.sa_flags = SA_RESTART;
1985 if (sigaction(sig, &sa, NULL) < 0)
1989 while ((sig = va_arg(ap, int)) > 0)
1990 if (sigaction(sig, &sa, NULL) < 0)
1997 int default_signals(int sig, ...) {
1998 struct sigaction sa;
2003 sa.sa_handler = SIG_DFL;
2004 sa.sa_flags = SA_RESTART;
2006 if (sigaction(sig, &sa, NULL) < 0)
2010 while ((sig = va_arg(ap, int)) > 0)
2011 if (sigaction(sig, &sa, NULL) < 0)
2018 int close_pipe(int p[]) {
2024 a = close_nointr(p[0]);
2029 b = close_nointr(p[1]);
2033 return a < 0 ? a : b;
2036 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2045 while (nbytes > 0) {
2048 if ((k = read(fd, p, nbytes)) <= 0) {
2050 if (k < 0 && errno == EINTR)
2053 if (k < 0 && errno == EAGAIN && do_poll) {
2054 struct pollfd pollfd;
2058 pollfd.events = POLLIN;
2060 if (poll(&pollfd, 1, -1) < 0) {
2064 return n > 0 ? n : -errno;
2067 if (pollfd.revents != POLLIN)
2068 return n > 0 ? n : -EIO;
2073 return n > 0 ? n : (k < 0 ? -errno : 0);
2084 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2093 while (nbytes > 0) {
2096 if ((k = write(fd, p, nbytes)) <= 0) {
2098 if (k < 0 && errno == EINTR)
2101 if (k < 0 && errno == EAGAIN && do_poll) {
2102 struct pollfd pollfd;
2106 pollfd.events = POLLOUT;
2108 if (poll(&pollfd, 1, -1) < 0) {
2112 return n > 0 ? n : -errno;
2115 if (pollfd.revents != POLLOUT)
2116 return n > 0 ? n : -EIO;
2121 return n > 0 ? n : (k < 0 ? -errno : 0);
2132 int path_is_mount_point(const char *t) {
2136 if (lstat(t, &a) < 0) {
2138 if (errno == ENOENT)
2144 if (!(copy = strdup(t)))
2147 if (lstat(dirname(copy), &b) < 0) {
2154 return a.st_dev != b.st_dev;
2157 int parse_usec(const char *t, usec_t *usec) {
2158 static const struct {
2162 { "sec", USEC_PER_SEC },
2163 { "s", USEC_PER_SEC },
2164 { "min", USEC_PER_MINUTE },
2165 { "hr", USEC_PER_HOUR },
2166 { "h", USEC_PER_HOUR },
2167 { "d", USEC_PER_DAY },
2168 { "w", USEC_PER_WEEK },
2169 { "msec", USEC_PER_MSEC },
2170 { "ms", USEC_PER_MSEC },
2171 { "m", USEC_PER_MINUTE },
2174 { "", USEC_PER_SEC },
2190 l = strtoll(p, &e, 10);
2201 e += strspn(e, WHITESPACE);
2203 for (i = 0; i < ELEMENTSOF(table); i++)
2204 if (startswith(e, table[i].suffix)) {
2205 r += (usec_t) l * table[i].usec;
2206 p = e + strlen(table[i].suffix);
2210 if (i >= ELEMENTSOF(table))
2220 int make_stdio(int fd) {
2225 r = dup2(fd, STDIN_FILENO);
2226 s = dup2(fd, STDOUT_FILENO);
2227 t = dup2(fd, STDERR_FILENO);
2230 close_nointr_nofail(fd);
2232 if (r < 0 || s < 0 || t < 0)
2238 bool is_clean_exit(int code, int status) {
2240 if (code == CLD_EXITED)
2243 /* If a daemon does not implement handlers for some of the
2244 * signals that's not considered an unclean shutdown */
2245 if (code == CLD_KILLED)
2249 status == SIGTERM ||
2255 bool is_device_path(const char *path) {
2257 /* Returns true on paths that refer to a device, either in
2258 * sysfs or in /dev */
2261 path_startswith(path, "/dev/") ||
2262 path_startswith(path, "/sys/");
2265 int dir_is_empty(const char *path) {
2268 struct dirent buf, *de;
2270 if (!(d = opendir(path)))
2274 if ((r = readdir_r(d, &buf, &de)) > 0) {
2284 if (!ignore_file(de->d_name)) {
2294 unsigned long long random_ull(void) {
2299 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2302 r = loop_read(fd, &ull, sizeof(ull), true);
2303 close_nointr_nofail(fd);
2305 if (r != sizeof(ull))
2311 return random() * RAND_MAX + random();
2314 void rename_process(const char name[8]) {
2317 prctl(PR_SET_NAME, name);
2319 /* This is a like a poor man's setproctitle(). The string
2320 * passed should fit in 7 chars (i.e. the length of
2323 if (program_invocation_name)
2324 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2327 void sigset_add_many(sigset_t *ss, ...) {
2334 while ((sig = va_arg(ap, int)) > 0)
2335 assert_se(sigaddset(ss, sig) == 0);
2339 char* gethostname_malloc(void) {
2342 assert_se(uname(&u) >= 0);
2345 return strdup(u.nodename);
2347 return strdup(u.sysname);
2350 int getmachineid_malloc(char **b) {
2355 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2362 char* getlogname_malloc(void) {
2366 struct passwd pwbuf, *pw = NULL;
2369 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2374 /* Shortcut things to avoid NSS lookups */
2376 return strdup("root");
2378 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2381 if (!(buf = malloc(bufsize)))
2384 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2385 name = strdup(pw->pw_name);
2392 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2398 int getttyname_malloc(char **r) {
2399 char path[PATH_MAX], *p, *c;
2403 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2409 if (startswith(path, "/dev/"))
2412 if (!(c = strdup(p)))
2419 static int rm_rf_children(int fd, bool only_dirs) {
2425 /* This returns the first error we run into, but nevertheless
2428 if (!(d = fdopendir(fd))) {
2429 close_nointr_nofail(fd);
2434 struct dirent buf, *de;
2438 if ((r = readdir_r(d, &buf, &de)) != 0) {
2447 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2450 if (de->d_type == DT_UNKNOWN) {
2453 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2459 is_dir = S_ISDIR(st.st_mode);
2461 is_dir = de->d_type == DT_DIR;
2466 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2472 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2477 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2481 } else if (!only_dirs) {
2483 if (unlinkat(fd, de->d_name, 0) < 0) {
2495 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2501 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2503 if (errno != ENOTDIR)
2506 if (delete_root && !only_dirs)
2507 if (unlink(path) < 0)
2513 r = rm_rf_children(fd, only_dirs);
2516 if (rmdir(path) < 0) {
2524 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2527 /* Under the assumption that we are running privileged we
2528 * first change the access mode and only then hand out
2529 * ownership to avoid a window where access is too open. */
2531 if (chmod(path, mode) < 0)
2534 if (chown(path, uid, gid) < 0)
2540 static const char *const ioprio_class_table[] = {
2541 [IOPRIO_CLASS_NONE] = "none",
2542 [IOPRIO_CLASS_RT] = "realtime",
2543 [IOPRIO_CLASS_BE] = "best-effort",
2544 [IOPRIO_CLASS_IDLE] = "idle"
2547 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2549 static const char *const sigchld_code_table[] = {
2550 [CLD_EXITED] = "exited",
2551 [CLD_KILLED] = "killed",
2552 [CLD_DUMPED] = "dumped",
2553 [CLD_TRAPPED] = "trapped",
2554 [CLD_STOPPED] = "stopped",
2555 [CLD_CONTINUED] = "continued",
2558 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2560 static const char *const log_facility_table[LOG_NFACILITIES] = {
2561 [LOG_FAC(LOG_KERN)] = "kern",
2562 [LOG_FAC(LOG_USER)] = "user",
2563 [LOG_FAC(LOG_MAIL)] = "mail",
2564 [LOG_FAC(LOG_DAEMON)] = "daemon",
2565 [LOG_FAC(LOG_AUTH)] = "auth",
2566 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2567 [LOG_FAC(LOG_LPR)] = "lpr",
2568 [LOG_FAC(LOG_NEWS)] = "news",
2569 [LOG_FAC(LOG_UUCP)] = "uucp",
2570 [LOG_FAC(LOG_CRON)] = "cron",
2571 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2572 [LOG_FAC(LOG_FTP)] = "ftp",
2573 [LOG_FAC(LOG_LOCAL0)] = "local0",
2574 [LOG_FAC(LOG_LOCAL1)] = "local1",
2575 [LOG_FAC(LOG_LOCAL2)] = "local2",
2576 [LOG_FAC(LOG_LOCAL3)] = "local3",
2577 [LOG_FAC(LOG_LOCAL4)] = "local4",
2578 [LOG_FAC(LOG_LOCAL5)] = "local5",
2579 [LOG_FAC(LOG_LOCAL6)] = "local6",
2580 [LOG_FAC(LOG_LOCAL7)] = "local7"
2583 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2585 static const char *const log_level_table[] = {
2586 [LOG_EMERG] = "emerg",
2587 [LOG_ALERT] = "alert",
2588 [LOG_CRIT] = "crit",
2590 [LOG_WARNING] = "warning",
2591 [LOG_NOTICE] = "notice",
2592 [LOG_INFO] = "info",
2593 [LOG_DEBUG] = "debug"
2596 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2598 static const char* const sched_policy_table[] = {
2599 [SCHED_OTHER] = "other",
2600 [SCHED_BATCH] = "batch",
2601 [SCHED_IDLE] = "idle",
2602 [SCHED_FIFO] = "fifo",
2606 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2608 static const char* const rlimit_table[] = {
2609 [RLIMIT_CPU] = "LimitCPU",
2610 [RLIMIT_FSIZE] = "LimitFSIZE",
2611 [RLIMIT_DATA] = "LimitDATA",
2612 [RLIMIT_STACK] = "LimitSTACK",
2613 [RLIMIT_CORE] = "LimitCORE",
2614 [RLIMIT_RSS] = "LimitRSS",
2615 [RLIMIT_NOFILE] = "LimitNOFILE",
2616 [RLIMIT_AS] = "LimitAS",
2617 [RLIMIT_NPROC] = "LimitNPROC",
2618 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2619 [RLIMIT_LOCKS] = "LimitLOCKS",
2620 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2621 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2622 [RLIMIT_NICE] = "LimitNICE",
2623 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2624 [RLIMIT_RTTIME] = "LimitRTTIME"
2627 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);