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>
49 #include <netinet/ip.h>
58 bool streq_ptr(const char *a, const char *b) {
60 /* Like streq(), but tries to make sense of NULL pointers */
71 usec_t now(clockid_t clock_id) {
74 assert_se(clock_gettime(clock_id, &ts) == 0);
76 return timespec_load(&ts);
79 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
82 ts->realtime = now(CLOCK_REALTIME);
83 ts->monotonic = now(CLOCK_MONOTONIC);
88 usec_t timespec_load(const struct timespec *ts) {
92 (usec_t) ts->tv_sec * USEC_PER_SEC +
93 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
96 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
99 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
100 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
105 usec_t timeval_load(const struct timeval *tv) {
109 (usec_t) tv->tv_sec * USEC_PER_SEC +
110 (usec_t) tv->tv_usec;
113 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
116 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
117 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
122 bool endswith(const char *s, const char *postfix) {
129 pl = strlen(postfix);
137 return memcmp(s + sl - pl, postfix, pl) == 0;
140 bool startswith(const char *s, const char *prefix) {
155 return memcmp(s, prefix, pl) == 0;
158 bool startswith_no_case(const char *s, const char *prefix) {
174 for(i = 0; i < pl; ++i) {
175 if (tolower(s[i]) != tolower(prefix[i]))
182 bool first_word(const char *s, const char *word) {
197 if (memcmp(s, word, wl) != 0)
201 strchr(WHITESPACE, s[wl]);
204 int close_nointr(int fd) {
210 if ((r = close(fd)) >= 0)
218 void close_nointr_nofail(int fd) {
219 int saved_errno = errno;
221 /* like close_nointr() but cannot fail, and guarantees errno
224 assert_se(close_nointr(fd) == 0);
229 void close_many(const int fds[], unsigned n_fd) {
232 for (i = 0; i < n_fd; i++)
233 close_nointr_nofail(fds[i]);
236 int parse_boolean(const char *v) {
239 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
241 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
247 int parse_pid(const char *s, pid_t* ret_pid) {
255 if ((r = safe_atolu(s, &ul)) < 0)
260 if ((unsigned long) pid != ul)
270 int safe_atou(const char *s, unsigned *ret_u) {
278 l = strtoul(s, &x, 0);
280 if (!x || *x || errno)
281 return errno ? -errno : -EINVAL;
283 if ((unsigned long) (unsigned) l != l)
286 *ret_u = (unsigned) l;
290 int safe_atoi(const char *s, int *ret_i) {
298 l = strtol(s, &x, 0);
300 if (!x || *x || errno)
301 return errno ? -errno : -EINVAL;
303 if ((long) (int) l != l)
310 int safe_atolu(const char *s, long unsigned *ret_lu) {
318 l = strtoul(s, &x, 0);
320 if (!x || *x || errno)
321 return errno ? -errno : -EINVAL;
327 int safe_atoli(const char *s, long int *ret_li) {
335 l = strtol(s, &x, 0);
337 if (!x || *x || errno)
338 return errno ? -errno : -EINVAL;
344 int safe_atollu(const char *s, long long unsigned *ret_llu) {
346 unsigned long long l;
352 l = strtoull(s, &x, 0);
354 if (!x || *x || errno)
355 return errno ? -errno : -EINVAL;
361 int safe_atolli(const char *s, long long int *ret_lli) {
369 l = strtoll(s, &x, 0);
371 if (!x || *x || errno)
372 return errno ? -errno : -EINVAL;
378 /* Split a string into words. */
379 char *split(const char *c, size_t *l, const char *separator, char **state) {
382 current = *state ? *state : (char*) c;
384 if (!*current || *c == 0)
387 current += strspn(current, separator);
388 *l = strcspn(current, separator);
391 return (char*) current;
394 /* Split a string into words, but consider strings enclosed in '' and
395 * "" as words even if they include spaces. */
396 char *split_quoted(const char *c, size_t *l, char **state) {
399 current = *state ? *state : (char*) c;
401 if (!*current || *c == 0)
404 current += strspn(current, WHITESPACE);
406 if (*current == '\'') {
408 *l = strcspn(current, "'");
413 } else if (*current == '\"') {
415 *l = strcspn(current, "\"");
421 *l = strcspn(current, WHITESPACE);
425 /* FIXME: Cannot deal with strings that have spaces AND ticks
428 return (char*) current;
431 char **split_path_and_make_absolute(const char *p) {
435 if (!(l = strv_split(p, ":")))
438 if (!strv_path_make_absolute_cwd(l)) {
446 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
449 char fn[132], line[256], *p;
455 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
456 fn[sizeof(fn)-1] = 0;
458 if (!(f = fopen(fn, "r")))
461 if (!(fgets(line, sizeof(line), f))) {
469 /* Let's skip the pid and comm fields. The latter is enclosed
470 * in () but does not escape any () in its value, so let's
471 * skip over it manually */
473 if (!(p = strrchr(line, ')')))
484 if ((long unsigned) (pid_t) ppid != ppid)
487 *_ppid = (pid_t) ppid;
492 int write_one_line_file(const char *fn, const char *line) {
499 if (!(f = fopen(fn, "we")))
502 if (fputs(line, f) < 0) {
513 int read_one_line_file(const char *fn, char **line) {
521 if (!(f = fopen(fn, "re")))
524 if (!(fgets(t, sizeof(t), f))) {
529 if (!(c = strdup(t))) {
542 char *truncate_nl(char *s) {
545 s[strcspn(s, NEWLINE)] = 0;
549 int get_process_name(pid_t pid, char **name) {
556 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
559 r = read_one_line_file(p, name);
569 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
577 assert(max_length > 0);
580 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
589 if (!(r = new(char, max_length))) {
596 while ((c = getc(f)) != EOF) {
616 size_t n = MIN(left-1, 3U);
628 char *strappend(const char *s, const char *suffix) {
638 if (!(r = new(char, a+b+1)))
642 memcpy(r+a, suffix, b);
648 int readlink_malloc(const char *p, char **r) {
658 if (!(c = new(char, l)))
661 if ((n = readlink(p, c, l-1)) < 0) {
667 if ((size_t) n < l-1) {
678 int readlink_and_make_absolute(const char *p, char **r) {
685 if ((j = readlink_malloc(p, &target)) < 0)
688 k = file_in_same_dir(p, target);
698 char *file_name_from_path(const char *p) {
703 if ((r = strrchr(p, '/')))
709 bool path_is_absolute(const char *p) {
715 bool is_path(const char *p) {
717 return !!strchr(p, '/');
720 char *path_make_absolute(const char *p, const char *prefix) {
725 /* Makes every item in the list an absolute path by prepending
726 * the prefix, if specified and necessary */
728 if (path_is_absolute(p) || !prefix)
731 if (asprintf(&r, "%s/%s", prefix, p) < 0)
737 char *path_make_absolute_cwd(const char *p) {
742 /* Similar to path_make_absolute(), but prefixes with the
743 * current working directory. */
745 if (path_is_absolute(p))
748 if (!(cwd = get_current_dir_name()))
751 r = path_make_absolute(p, cwd);
757 char **strv_path_make_absolute_cwd(char **l) {
760 /* Goes through every item in the string list and makes it
761 * absolute. This works in place and won't rollback any
762 * changes on failure. */
767 if (!(t = path_make_absolute_cwd(*s)))
777 char **strv_path_canonicalize(char **l) {
785 /* Goes through every item in the string list and canonicalize
786 * the path. This works in place and won't rollback any
787 * changes on failure. */
792 t = path_make_absolute_cwd(*s);
801 u = canonicalize_file_name(t);
805 if (errno == ENOMEM || !errno)
822 int reset_all_signal_handlers(void) {
825 for (sig = 1; sig < _NSIG; sig++) {
828 if (sig == SIGKILL || sig == SIGSTOP)
832 sa.sa_handler = SIG_DFL;
833 sa.sa_flags = SA_RESTART;
835 /* On Linux the first two RT signals are reserved by
836 * glibc, and sigaction() will return EINVAL for them. */
837 if ((sigaction(sig, &sa, NULL) < 0))
845 char *strstrip(char *s) {
848 /* Drops trailing whitespace. Modifies the string in
849 * place. Returns pointer to first non-space character */
851 s += strspn(s, WHITESPACE);
854 if (!strchr(WHITESPACE, *e))
865 char *delete_chars(char *s, const char *bad) {
868 /* Drops all whitespace, regardless where in the string */
870 for (f = s, t = s; *f; f++) {
882 char *file_in_same_dir(const char *path, const char *filename) {
889 /* This removes the last component of path and appends
890 * filename, unless the latter is absolute anyway or the
893 if (path_is_absolute(filename))
894 return strdup(filename);
896 if (!(e = strrchr(path, '/')))
897 return strdup(filename);
899 k = strlen(filename);
900 if (!(r = new(char, e-path+1+k+1)))
903 memcpy(r, path, e-path+1);
904 memcpy(r+(e-path)+1, filename, k+1);
909 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
912 if (mkdir(path, mode) >= 0)
913 if (chmod_and_chown(path, mode, uid, gid) < 0)
916 if (lstat(path, &st) < 0)
919 if ((st.st_mode & 0777) != mode ||
922 !S_ISDIR(st.st_mode)) {
931 int mkdir_parents(const char *path, mode_t mode) {
936 /* Creates every parent directory in the path except the last
939 p = path + strspn(path, "/");
944 e = p + strcspn(p, "/");
945 p = e + strspn(e, "/");
947 /* Is this the last component? If so, then we're
952 if (!(t = strndup(path, e - path)))
959 if (r < 0 && errno != EEXIST)
964 int mkdir_p(const char *path, mode_t mode) {
969 if ((r = mkdir_parents(path, mode)) < 0)
972 if (mkdir(path, mode) < 0)
978 int rmdir_parents(const char *path, const char *stop) {
987 /* Skip trailing slashes */
988 while (l > 0 && path[l-1] == '/')
994 /* Skip last component */
995 while (l > 0 && path[l-1] != '/')
998 /* Skip trailing slashes */
999 while (l > 0 && path[l-1] == '/')
1005 if (!(t = strndup(path, l)))
1008 if (path_startswith(stop, t)) {
1017 if (errno != ENOENT)
1025 char hexchar(int x) {
1026 static const char table[16] = "0123456789abcdef";
1028 return table[x & 15];
1031 int unhexchar(char c) {
1033 if (c >= '0' && c <= '9')
1036 if (c >= 'a' && c <= 'f')
1037 return c - 'a' + 10;
1039 if (c >= 'A' && c <= 'F')
1040 return c - 'A' + 10;
1045 char octchar(int x) {
1046 return '0' + (x & 7);
1049 int unoctchar(char c) {
1051 if (c >= '0' && c <= '7')
1057 char decchar(int x) {
1058 return '0' + (x % 10);
1061 int undecchar(char c) {
1063 if (c >= '0' && c <= '9')
1069 char *cescape(const char *s) {
1075 /* Does C style string escaping. */
1077 if (!(r = new(char, strlen(s)*4 + 1)))
1080 for (f = s, t = r; *f; f++)
1126 /* For special chars we prefer octal over
1127 * hexadecimal encoding, simply because glib's
1128 * g_strescape() does the same */
1129 if ((*f < ' ') || (*f >= 127)) {
1131 *(t++) = octchar((unsigned char) *f >> 6);
1132 *(t++) = octchar((unsigned char) *f >> 3);
1133 *(t++) = octchar((unsigned char) *f);
1144 char *cunescape(const char *s) {
1150 /* Undoes C style string escaping */
1152 if (!(r = new(char, strlen(s)+1)))
1155 for (f = s, t = r; *f; f++) {
1198 /* hexadecimal encoding */
1201 if ((a = unhexchar(f[1])) < 0 ||
1202 (b = unhexchar(f[2])) < 0) {
1203 /* Invalid escape code, let's take it literal then */
1207 *(t++) = (char) ((a << 4) | b);
1222 /* octal encoding */
1225 if ((a = unoctchar(f[0])) < 0 ||
1226 (b = unoctchar(f[1])) < 0 ||
1227 (c = unoctchar(f[2])) < 0) {
1228 /* Invalid escape code, let's take it literal then */
1232 *(t++) = (char) ((a << 6) | (b << 3) | c);
1240 /* premature end of string.*/
1245 /* Invalid escape code, let's take it literal then */
1258 char *xescape(const char *s, const char *bad) {
1262 /* Escapes all chars in bad, in addition to \ and all special
1263 * chars, in \xFF style escaping. May be reversed with
1266 if (!(r = new(char, strlen(s)*4+1)))
1269 for (f = s, t = r; *f; f++) {
1271 if ((*f < ' ') || (*f >= 127) ||
1272 (*f == '\\') || strchr(bad, *f)) {
1275 *(t++) = hexchar(*f >> 4);
1276 *(t++) = hexchar(*f);
1286 char *bus_path_escape(const char *s) {
1292 /* Escapes all chars that D-Bus' object path cannot deal
1293 * with. Can be reverse with bus_path_unescape() */
1295 if (!(r = new(char, strlen(s)*3+1)))
1298 for (f = s, t = r; *f; f++) {
1300 if (!(*f >= 'A' && *f <= 'Z') &&
1301 !(*f >= 'a' && *f <= 'z') &&
1302 !(*f >= '0' && *f <= '9')) {
1304 *(t++) = hexchar(*f >> 4);
1305 *(t++) = hexchar(*f);
1315 char *bus_path_unescape(const char *f) {
1320 if (!(r = strdup(f)))
1323 for (t = r; *f; f++) {
1328 if ((a = unhexchar(f[1])) < 0 ||
1329 (b = unhexchar(f[2])) < 0) {
1330 /* Invalid escape code, let's take it literal then */
1333 *(t++) = (char) ((a << 4) | b);
1345 char *path_kill_slashes(char *path) {
1349 /* Removes redundant inner and trailing slashes. Modifies the
1350 * passed string in-place.
1352 * ///foo///bar/ becomes /foo/bar
1355 for (f = path, t = path; *f; f++) {
1370 /* Special rule, if we are talking of the root directory, a
1371 trailing slash is good */
1373 if (t == path && slash)
1380 bool path_startswith(const char *path, const char *prefix) {
1384 if ((path[0] == '/') != (prefix[0] == '/'))
1390 path += strspn(path, "/");
1391 prefix += strspn(prefix, "/");
1399 a = strcspn(path, "/");
1400 b = strcspn(prefix, "/");
1405 if (memcmp(path, prefix, a) != 0)
1413 bool path_equal(const char *a, const char *b) {
1417 if ((a[0] == '/') != (b[0] == '/'))
1423 a += strspn(a, "/");
1424 b += strspn(b, "/");
1426 if (*a == 0 && *b == 0)
1429 if (*a == 0 || *b == 0)
1432 j = strcspn(a, "/");
1433 k = strcspn(b, "/");
1438 if (memcmp(a, b, j) != 0)
1446 char *ascii_strlower(char *t) {
1451 for (p = t; *p; p++)
1452 if (*p >= 'A' && *p <= 'Z')
1453 *p = *p - 'A' + 'a';
1458 bool ignore_file(const char *filename) {
1462 filename[0] == '.' ||
1463 streq(filename, "lost+found") ||
1464 endswith(filename, "~") ||
1465 endswith(filename, ".rpmnew") ||
1466 endswith(filename, ".rpmsave") ||
1467 endswith(filename, ".rpmorig") ||
1468 endswith(filename, ".dpkg-old") ||
1469 endswith(filename, ".dpkg-new") ||
1470 endswith(filename, ".swp");
1473 int fd_nonblock(int fd, bool nonblock) {
1478 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1482 flags |= O_NONBLOCK;
1484 flags &= ~O_NONBLOCK;
1486 if (fcntl(fd, F_SETFL, flags) < 0)
1492 int fd_cloexec(int fd, bool cloexec) {
1497 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1501 flags |= FD_CLOEXEC;
1503 flags &= ~FD_CLOEXEC;
1505 if (fcntl(fd, F_SETFD, flags) < 0)
1511 int close_all_fds(const int except[], unsigned n_except) {
1516 if (!(d = opendir("/proc/self/fd")))
1519 while ((de = readdir(d))) {
1522 if (ignore_file(de->d_name))
1525 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1539 for (i = 0; i < n_except; i++)
1540 if (except[i] == fd) {
1549 if ((r = close_nointr(fd)) < 0) {
1550 /* Valgrind has its own FD and doesn't want to have it closed */
1563 bool chars_intersect(const char *a, const char *b) {
1566 /* Returns true if any of the chars in a are in b. */
1567 for (p = a; *p; p++)
1574 char *format_timestamp(char *buf, size_t l, usec_t t) {
1584 sec = (time_t) (t / USEC_PER_SEC);
1586 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1592 char *format_timespan(char *buf, size_t l, usec_t t) {
1593 static const struct {
1597 { "w", USEC_PER_WEEK },
1598 { "d", USEC_PER_DAY },
1599 { "h", USEC_PER_HOUR },
1600 { "min", USEC_PER_MINUTE },
1601 { "s", USEC_PER_SEC },
1602 { "ms", USEC_PER_MSEC },
1612 if (t == (usec_t) -1)
1615 /* The result of this function can be parsed with parse_usec */
1617 for (i = 0; i < ELEMENTSOF(table); i++) {
1621 if (t < table[i].usec)
1627 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1628 n = MIN((size_t) k, l);
1641 bool fstype_is_network(const char *fstype) {
1642 static const char * const table[] = {
1654 for (i = 0; i < ELEMENTSOF(table); i++)
1655 if (streq(table[i], fstype))
1664 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1669 TIOCL_GETKMSGREDIRECT,
1673 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1676 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1679 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1682 close_nointr_nofail(r);
1686 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1687 struct termios old_termios, new_termios;
1694 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1695 new_termios = old_termios;
1697 new_termios.c_lflag &= ~ICANON;
1698 new_termios.c_cc[VMIN] = 1;
1699 new_termios.c_cc[VTIME] = 0;
1701 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1704 k = fread(&c, 1, 1, f);
1706 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1712 *need_nl = c != '\n';
1719 if (!(fgets(line, sizeof(line), f)))
1724 if (strlen(line) != 1)
1734 int ask(char *ret, const char *replies, const char *text, ...) {
1743 bool need_nl = true;
1745 fputs("\x1B[1m", stdout);
1751 fputs("\x1B[0m", stdout);
1755 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1757 if (r == -EBADMSG) {
1758 puts("Bad input, please try again.");
1769 if (strchr(replies, c)) {
1774 puts("Read unexpected character, please try again.");
1778 int reset_terminal(int fd) {
1779 struct termios termios;
1784 /* Set terminal to some sane defaults */
1786 if (tcgetattr(fd, &termios) < 0) {
1791 /* We only reset the stuff that matters to the software. How
1792 * hardware is set up we don't touch assuming that somebody
1793 * else will do that for us */
1795 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1796 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1797 termios.c_oflag |= ONLCR;
1798 termios.c_cflag |= CREAD;
1799 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1801 termios.c_cc[VINTR] = 03; /* ^C */
1802 termios.c_cc[VQUIT] = 034; /* ^\ */
1803 termios.c_cc[VERASE] = 0177;
1804 termios.c_cc[VKILL] = 025; /* ^X */
1805 termios.c_cc[VEOF] = 04; /* ^D */
1806 termios.c_cc[VSTART] = 021; /* ^Q */
1807 termios.c_cc[VSTOP] = 023; /* ^S */
1808 termios.c_cc[VSUSP] = 032; /* ^Z */
1809 termios.c_cc[VLNEXT] = 026; /* ^V */
1810 termios.c_cc[VWERASE] = 027; /* ^W */
1811 termios.c_cc[VREPRINT] = 022; /* ^R */
1812 termios.c_cc[VEOL] = 0;
1813 termios.c_cc[VEOL2] = 0;
1815 termios.c_cc[VTIME] = 0;
1816 termios.c_cc[VMIN] = 1;
1818 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1822 /* Just in case, flush all crap out */
1823 tcflush(fd, TCIOFLUSH);
1828 int open_terminal(const char *name, int mode) {
1831 if ((fd = open(name, mode)) < 0)
1834 if ((r = isatty(fd)) < 0) {
1835 close_nointr_nofail(fd);
1840 close_nointr_nofail(fd);
1847 int flush_fd(int fd) {
1848 struct pollfd pollfd;
1852 pollfd.events = POLLIN;
1859 if ((r = poll(&pollfd, 1, 0)) < 0) {
1870 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1875 if (errno == EAGAIN)
1886 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1887 int fd = -1, notify = -1, r, wd = -1;
1891 /* We use inotify to be notified when the tty is closed. We
1892 * create the watch before checking if we can actually acquire
1893 * it, so that we don't lose any event.
1895 * Note: strictly speaking this actually watches for the
1896 * device being closed, it does *not* really watch whether a
1897 * tty loses its controlling process. However, unless some
1898 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1899 * its tty otherwise this will not become a problem. As long
1900 * as the administrator makes sure not configure any service
1901 * on the same tty as an untrusted user this should not be a
1902 * problem. (Which he probably should not do anyway.) */
1904 if (!fail && !force) {
1905 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1910 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1918 if ((r = flush_fd(notify)) < 0)
1921 /* We pass here O_NOCTTY only so that we can check the return
1922 * value TIOCSCTTY and have a reliable way to figure out if we
1923 * successfully became the controlling process of the tty */
1924 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1927 /* First, try to get the tty */
1928 r = ioctl(fd, TIOCSCTTY, force);
1930 /* Sometimes it makes sense to ignore TIOCSCTTY
1931 * returning EPERM, i.e. when very likely we already
1932 * are have this controlling terminal. */
1933 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1936 if (r < 0 && (force || fail || errno != EPERM)) {
1946 assert(notify >= 0);
1949 struct inotify_event e;
1952 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1966 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1974 /* We close the tty fd here since if the old session
1975 * ended our handle will be dead. It's important that
1976 * we do this after sleeping, so that we don't enter
1977 * an endless loop. */
1978 close_nointr_nofail(fd);
1982 close_nointr_nofail(notify);
1984 if ((r = reset_terminal(fd)) < 0)
1985 log_warning("Failed to reset terminal: %s", strerror(-r));
1991 close_nointr_nofail(fd);
1994 close_nointr_nofail(notify);
1999 int release_terminal(void) {
2001 struct sigaction sa_old, sa_new;
2003 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2006 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2007 * by our own TIOCNOTTY */
2010 sa_new.sa_handler = SIG_IGN;
2011 sa_new.sa_flags = SA_RESTART;
2012 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2014 if (ioctl(fd, TIOCNOTTY) < 0)
2017 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2019 close_nointr_nofail(fd);
2023 int sigaction_many(const struct sigaction *sa, ...) {
2028 while ((sig = va_arg(ap, int)) > 0)
2029 if (sigaction(sig, sa, NULL) < 0)
2036 int ignore_signals(int sig, ...) {
2037 struct sigaction sa;
2042 sa.sa_handler = SIG_IGN;
2043 sa.sa_flags = SA_RESTART;
2045 if (sigaction(sig, &sa, NULL) < 0)
2049 while ((sig = va_arg(ap, int)) > 0)
2050 if (sigaction(sig, &sa, NULL) < 0)
2057 int default_signals(int sig, ...) {
2058 struct sigaction sa;
2063 sa.sa_handler = SIG_DFL;
2064 sa.sa_flags = SA_RESTART;
2066 if (sigaction(sig, &sa, NULL) < 0)
2070 while ((sig = va_arg(ap, int)) > 0)
2071 if (sigaction(sig, &sa, NULL) < 0)
2078 int close_pipe(int p[]) {
2084 a = close_nointr(p[0]);
2089 b = close_nointr(p[1]);
2093 return a < 0 ? a : b;
2096 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2105 while (nbytes > 0) {
2108 if ((k = read(fd, p, nbytes)) <= 0) {
2110 if (k < 0 && errno == EINTR)
2113 if (k < 0 && errno == EAGAIN && do_poll) {
2114 struct pollfd pollfd;
2118 pollfd.events = POLLIN;
2120 if (poll(&pollfd, 1, -1) < 0) {
2124 return n > 0 ? n : -errno;
2127 if (pollfd.revents != POLLIN)
2128 return n > 0 ? n : -EIO;
2133 return n > 0 ? n : (k < 0 ? -errno : 0);
2144 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2153 while (nbytes > 0) {
2156 if ((k = write(fd, p, nbytes)) <= 0) {
2158 if (k < 0 && errno == EINTR)
2161 if (k < 0 && errno == EAGAIN && do_poll) {
2162 struct pollfd pollfd;
2166 pollfd.events = POLLOUT;
2168 if (poll(&pollfd, 1, -1) < 0) {
2172 return n > 0 ? n : -errno;
2175 if (pollfd.revents != POLLOUT)
2176 return n > 0 ? n : -EIO;
2181 return n > 0 ? n : (k < 0 ? -errno : 0);
2192 int path_is_mount_point(const char *t) {
2196 if (lstat(t, &a) < 0) {
2198 if (errno == ENOENT)
2204 if (!(copy = strdup(t)))
2207 if (lstat(dirname(copy), &b) < 0) {
2214 return a.st_dev != b.st_dev;
2217 int parse_usec(const char *t, usec_t *usec) {
2218 static const struct {
2222 { "sec", USEC_PER_SEC },
2223 { "s", USEC_PER_SEC },
2224 { "min", USEC_PER_MINUTE },
2225 { "hr", USEC_PER_HOUR },
2226 { "h", USEC_PER_HOUR },
2227 { "d", USEC_PER_DAY },
2228 { "w", USEC_PER_WEEK },
2229 { "msec", USEC_PER_MSEC },
2230 { "ms", USEC_PER_MSEC },
2231 { "m", USEC_PER_MINUTE },
2234 { "", USEC_PER_SEC },
2250 l = strtoll(p, &e, 10);
2261 e += strspn(e, WHITESPACE);
2263 for (i = 0; i < ELEMENTSOF(table); i++)
2264 if (startswith(e, table[i].suffix)) {
2265 r += (usec_t) l * table[i].usec;
2266 p = e + strlen(table[i].suffix);
2270 if (i >= ELEMENTSOF(table))
2280 int make_stdio(int fd) {
2285 r = dup2(fd, STDIN_FILENO);
2286 s = dup2(fd, STDOUT_FILENO);
2287 t = dup2(fd, STDERR_FILENO);
2290 close_nointr_nofail(fd);
2292 if (r < 0 || s < 0 || t < 0)
2298 bool is_clean_exit(int code, int status) {
2300 if (code == CLD_EXITED)
2303 /* If a daemon does not implement handlers for some of the
2304 * signals that's not considered an unclean shutdown */
2305 if (code == CLD_KILLED)
2309 status == SIGTERM ||
2315 bool is_device_path(const char *path) {
2317 /* Returns true on paths that refer to a device, either in
2318 * sysfs or in /dev */
2321 path_startswith(path, "/dev/") ||
2322 path_startswith(path, "/sys/");
2325 int dir_is_empty(const char *path) {
2328 struct dirent buf, *de;
2330 if (!(d = opendir(path)))
2334 if ((r = readdir_r(d, &buf, &de)) > 0) {
2344 if (!ignore_file(de->d_name)) {
2354 unsigned long long random_ull(void) {
2359 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2362 r = loop_read(fd, &ull, sizeof(ull), true);
2363 close_nointr_nofail(fd);
2365 if (r != sizeof(ull))
2371 return random() * RAND_MAX + random();
2374 void rename_process(const char name[8]) {
2377 prctl(PR_SET_NAME, name);
2379 /* This is a like a poor man's setproctitle(). The string
2380 * passed should fit in 7 chars (i.e. the length of
2383 if (program_invocation_name)
2384 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2387 void sigset_add_many(sigset_t *ss, ...) {
2394 while ((sig = va_arg(ap, int)) > 0)
2395 assert_se(sigaddset(ss, sig) == 0);
2399 char* gethostname_malloc(void) {
2402 assert_se(uname(&u) >= 0);
2405 return strdup(u.nodename);
2407 return strdup(u.sysname);
2410 int getmachineid_malloc(char **b) {
2415 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2422 char* getlogname_malloc(void) {
2426 struct passwd pwbuf, *pw = NULL;
2429 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2434 /* Shortcut things to avoid NSS lookups */
2436 return strdup("root");
2438 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2441 if (!(buf = malloc(bufsize)))
2444 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2445 name = strdup(pw->pw_name);
2452 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2458 int getttyname_malloc(char **r) {
2459 char path[PATH_MAX], *p, *c;
2463 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2469 if (startswith(path, "/dev/"))
2472 if (!(c = strdup(p)))
2479 static int rm_rf_children(int fd, bool only_dirs) {
2485 /* This returns the first error we run into, but nevertheless
2488 if (!(d = fdopendir(fd))) {
2489 close_nointr_nofail(fd);
2494 struct dirent buf, *de;
2498 if ((r = readdir_r(d, &buf, &de)) != 0) {
2507 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2510 if (de->d_type == DT_UNKNOWN) {
2513 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2519 is_dir = S_ISDIR(st.st_mode);
2521 is_dir = de->d_type == DT_DIR;
2526 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2532 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2537 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2541 } else if (!only_dirs) {
2543 if (unlinkat(fd, de->d_name, 0) < 0) {
2555 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2561 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2563 if (errno != ENOTDIR)
2566 if (delete_root && !only_dirs)
2567 if (unlink(path) < 0)
2573 r = rm_rf_children(fd, only_dirs);
2576 if (rmdir(path) < 0) {
2584 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2587 /* Under the assumption that we are running privileged we
2588 * first change the access mode and only then hand out
2589 * ownership to avoid a window where access is too open. */
2591 if (chmod(path, mode) < 0)
2594 if (chown(path, uid, gid) < 0)
2600 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2604 /* Allocates the cpuset in the right size */
2607 if (!(r = CPU_ALLOC(n)))
2610 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2611 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2621 if (errno != EINVAL)
2628 static const char *const ioprio_class_table[] = {
2629 [IOPRIO_CLASS_NONE] = "none",
2630 [IOPRIO_CLASS_RT] = "realtime",
2631 [IOPRIO_CLASS_BE] = "best-effort",
2632 [IOPRIO_CLASS_IDLE] = "idle"
2635 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2637 static const char *const sigchld_code_table[] = {
2638 [CLD_EXITED] = "exited",
2639 [CLD_KILLED] = "killed",
2640 [CLD_DUMPED] = "dumped",
2641 [CLD_TRAPPED] = "trapped",
2642 [CLD_STOPPED] = "stopped",
2643 [CLD_CONTINUED] = "continued",
2646 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2648 static const char *const log_facility_table[LOG_NFACILITIES] = {
2649 [LOG_FAC(LOG_KERN)] = "kern",
2650 [LOG_FAC(LOG_USER)] = "user",
2651 [LOG_FAC(LOG_MAIL)] = "mail",
2652 [LOG_FAC(LOG_DAEMON)] = "daemon",
2653 [LOG_FAC(LOG_AUTH)] = "auth",
2654 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2655 [LOG_FAC(LOG_LPR)] = "lpr",
2656 [LOG_FAC(LOG_NEWS)] = "news",
2657 [LOG_FAC(LOG_UUCP)] = "uucp",
2658 [LOG_FAC(LOG_CRON)] = "cron",
2659 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2660 [LOG_FAC(LOG_FTP)] = "ftp",
2661 [LOG_FAC(LOG_LOCAL0)] = "local0",
2662 [LOG_FAC(LOG_LOCAL1)] = "local1",
2663 [LOG_FAC(LOG_LOCAL2)] = "local2",
2664 [LOG_FAC(LOG_LOCAL3)] = "local3",
2665 [LOG_FAC(LOG_LOCAL4)] = "local4",
2666 [LOG_FAC(LOG_LOCAL5)] = "local5",
2667 [LOG_FAC(LOG_LOCAL6)] = "local6",
2668 [LOG_FAC(LOG_LOCAL7)] = "local7"
2671 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2673 static const char *const log_level_table[] = {
2674 [LOG_EMERG] = "emerg",
2675 [LOG_ALERT] = "alert",
2676 [LOG_CRIT] = "crit",
2678 [LOG_WARNING] = "warning",
2679 [LOG_NOTICE] = "notice",
2680 [LOG_INFO] = "info",
2681 [LOG_DEBUG] = "debug"
2684 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2686 static const char* const sched_policy_table[] = {
2687 [SCHED_OTHER] = "other",
2688 [SCHED_BATCH] = "batch",
2689 [SCHED_IDLE] = "idle",
2690 [SCHED_FIFO] = "fifo",
2694 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2696 static const char* const rlimit_table[] = {
2697 [RLIMIT_CPU] = "LimitCPU",
2698 [RLIMIT_FSIZE] = "LimitFSIZE",
2699 [RLIMIT_DATA] = "LimitDATA",
2700 [RLIMIT_STACK] = "LimitSTACK",
2701 [RLIMIT_CORE] = "LimitCORE",
2702 [RLIMIT_RSS] = "LimitRSS",
2703 [RLIMIT_NOFILE] = "LimitNOFILE",
2704 [RLIMIT_AS] = "LimitAS",
2705 [RLIMIT_NPROC] = "LimitNPROC",
2706 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2707 [RLIMIT_LOCKS] = "LimitLOCKS",
2708 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2709 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2710 [RLIMIT_NICE] = "LimitNICE",
2711 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2712 [RLIMIT_RTTIME] = "LimitRTTIME"
2715 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2717 static const char* const ip_tos_table[] = {
2718 [IPTOS_LOWDELAY] = "low-delay",
2719 [IPTOS_THROUGHPUT] = "throughput",
2720 [IPTOS_RELIABILITY] = "reliability",
2721 [IPTOS_LOWCOST] = "low-cost",
2724 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);