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_atollu(const char *s, long long unsigned *ret_llu) {
312 unsigned long long l;
318 l = strtoull(s, &x, 0);
320 if (!x || *x || errno)
321 return errno ? -errno : -EINVAL;
327 int safe_atolli(const char *s, long long int *ret_lli) {
335 l = strtoll(s, &x, 0);
337 if (!x || *x || errno)
338 return errno ? -errno : -EINVAL;
344 /* Split a string into words. */
345 char *split(const char *c, size_t *l, const char *separator, char **state) {
348 current = *state ? *state : (char*) c;
350 if (!*current || *c == 0)
353 current += strspn(current, separator);
354 *l = strcspn(current, separator);
357 return (char*) current;
360 /* Split a string into words, but consider strings enclosed in '' and
361 * "" as words even if they include spaces. */
362 char *split_quoted(const char *c, size_t *l, char **state) {
365 current = *state ? *state : (char*) c;
367 if (!*current || *c == 0)
370 current += strspn(current, WHITESPACE);
372 if (*current == '\'') {
374 *l = strcspn(current, "'");
379 } else if (*current == '\"') {
381 *l = strcspn(current, "\"");
387 *l = strcspn(current, WHITESPACE);
391 /* FIXME: Cannot deal with strings that have spaces AND ticks
394 return (char*) current;
397 char **split_path_and_make_absolute(const char *p) {
401 if (!(l = strv_split(p, ":")))
404 if (!strv_path_make_absolute_cwd(l)) {
412 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
415 char fn[132], line[256], *p;
421 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
422 fn[sizeof(fn)-1] = 0;
424 if (!(f = fopen(fn, "r")))
427 if (!(fgets(line, sizeof(line), f))) {
435 /* Let's skip the pid and comm fields. The latter is enclosed
436 * in () but does not escape any () in its value, so let's
437 * skip over it manually */
439 if (!(p = strrchr(line, ')')))
450 if ((long unsigned) (pid_t) ppid != ppid)
453 *_ppid = (pid_t) ppid;
458 int write_one_line_file(const char *fn, const char *line) {
465 if (!(f = fopen(fn, "we")))
468 if (fputs(line, f) < 0) {
479 int read_one_line_file(const char *fn, char **line) {
487 if (!(f = fopen(fn, "re")))
490 if (!(fgets(t, sizeof(t), f))) {
495 if (!(c = strdup(t))) {
508 char *truncate_nl(char *s) {
511 s[strcspn(s, NEWLINE)] = 0;
515 int get_process_name(pid_t pid, char **name) {
522 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
525 r = read_one_line_file(p, name);
535 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
543 assert(max_length > 0);
546 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
555 if (!(r = new(char, max_length))) {
562 while ((c = getc(f)) != EOF) {
584 size_t n = MIN(left-1, 3U);
596 char *strappend(const char *s, const char *suffix) {
606 if (!(r = new(char, a+b+1)))
610 memcpy(r+a, suffix, b);
616 int readlink_malloc(const char *p, char **r) {
626 if (!(c = new(char, l)))
629 if ((n = readlink(p, c, l-1)) < 0) {
635 if ((size_t) n < l-1) {
646 int readlink_and_make_absolute(const char *p, char **r) {
653 if ((j = readlink_malloc(p, &target)) < 0)
656 k = file_in_same_dir(p, target);
666 char *file_name_from_path(const char *p) {
671 if ((r = strrchr(p, '/')))
677 bool path_is_absolute(const char *p) {
683 bool is_path(const char *p) {
685 return !!strchr(p, '/');
688 char *path_make_absolute(const char *p, const char *prefix) {
693 /* Makes every item in the list an absolute path by prepending
694 * the prefix, if specified and necessary */
696 if (path_is_absolute(p) || !prefix)
699 if (asprintf(&r, "%s/%s", prefix, p) < 0)
705 char *path_make_absolute_cwd(const char *p) {
710 /* Similar to path_make_absolute(), but prefixes with the
711 * current working directory. */
713 if (path_is_absolute(p))
716 if (!(cwd = get_current_dir_name()))
719 r = path_make_absolute(p, cwd);
725 char **strv_path_make_absolute_cwd(char **l) {
728 /* Goes through every item in the string list and makes it
729 * absolute. This works in place and won't rollback any
730 * changes on failure. */
735 if (!(t = path_make_absolute_cwd(*s)))
745 char **strv_path_canonicalize(char **l) {
753 /* Goes through every item in the string list and canonicalize
754 * the path. This works in place and won't rollback any
755 * changes on failure. */
760 t = path_make_absolute_cwd(*s);
769 u = canonicalize_file_name(t);
773 if (errno == ENOMEM || !errno)
790 int reset_all_signal_handlers(void) {
793 for (sig = 1; sig < _NSIG; sig++) {
796 if (sig == SIGKILL || sig == SIGSTOP)
800 sa.sa_handler = SIG_DFL;
801 sa.sa_flags = SA_RESTART;
803 /* On Linux the first two RT signals are reserved by
804 * glibc, and sigaction() will return EINVAL for them. */
805 if ((sigaction(sig, &sa, NULL) < 0))
813 char *strstrip(char *s) {
816 /* Drops trailing whitespace. Modifies the string in
817 * place. Returns pointer to first non-space character */
819 s += strspn(s, WHITESPACE);
822 if (!strchr(WHITESPACE, *e))
833 char *delete_chars(char *s, const char *bad) {
836 /* Drops all whitespace, regardless where in the string */
838 for (f = s, t = s; *f; f++) {
850 char *file_in_same_dir(const char *path, const char *filename) {
857 /* This removes the last component of path and appends
858 * filename, unless the latter is absolute anyway or the
861 if (path_is_absolute(filename))
862 return strdup(filename);
864 if (!(e = strrchr(path, '/')))
865 return strdup(filename);
867 k = strlen(filename);
868 if (!(r = new(char, e-path+1+k+1)))
871 memcpy(r, path, e-path+1);
872 memcpy(r+(e-path)+1, filename, k+1);
877 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
880 if (mkdir(path, mode) >= 0)
881 if (chmod_and_chown(path, mode, uid, gid) < 0)
884 if (lstat(path, &st) < 0)
887 if ((st.st_mode & 0777) != mode ||
890 !S_ISDIR(st.st_mode)) {
899 int mkdir_parents(const char *path, mode_t mode) {
904 /* Creates every parent directory in the path except the last
907 p = path + strspn(path, "/");
912 e = p + strcspn(p, "/");
913 p = e + strspn(e, "/");
915 /* Is this the last component? If so, then we're
920 if (!(t = strndup(path, e - path)))
927 if (r < 0 && errno != EEXIST)
932 int mkdir_p(const char *path, mode_t mode) {
937 if ((r = mkdir_parents(path, mode)) < 0)
940 if (mkdir(path, mode) < 0)
946 int rmdir_parents(const char *path, const char *stop) {
955 /* Skip trailing slashes */
956 while (l > 0 && path[l-1] == '/')
962 /* Skip last component */
963 while (l > 0 && path[l-1] != '/')
966 /* Skip trailing slashes */
967 while (l > 0 && path[l-1] == '/')
973 if (!(t = strndup(path, l)))
976 if (path_startswith(stop, t)) {
993 char hexchar(int x) {
994 static const char table[16] = "0123456789abcdef";
996 return table[x & 15];
999 int unhexchar(char c) {
1001 if (c >= '0' && c <= '9')
1004 if (c >= 'a' && c <= 'f')
1005 return c - 'a' + 10;
1007 if (c >= 'A' && c <= 'F')
1008 return c - 'A' + 10;
1013 char octchar(int x) {
1014 return '0' + (x & 7);
1017 int unoctchar(char c) {
1019 if (c >= '0' && c <= '7')
1025 char decchar(int x) {
1026 return '0' + (x % 10);
1029 int undecchar(char c) {
1031 if (c >= '0' && c <= '9')
1037 char *cescape(const char *s) {
1043 /* Does C style string escaping. */
1045 if (!(r = new(char, strlen(s)*4 + 1)))
1048 for (f = s, t = r; *f; f++)
1094 /* For special chars we prefer octal over
1095 * hexadecimal encoding, simply because glib's
1096 * g_strescape() does the same */
1097 if ((*f < ' ') || (*f >= 127)) {
1099 *(t++) = octchar((unsigned char) *f >> 6);
1100 *(t++) = octchar((unsigned char) *f >> 3);
1101 *(t++) = octchar((unsigned char) *f);
1112 char *cunescape(const char *s) {
1118 /* Undoes C style string escaping */
1120 if (!(r = new(char, strlen(s)+1)))
1123 for (f = s, t = r; *f; f++) {
1166 /* hexadecimal encoding */
1169 if ((a = unhexchar(f[1])) < 0 ||
1170 (b = unhexchar(f[2])) < 0) {
1171 /* Invalid escape code, let's take it literal then */
1175 *(t++) = (char) ((a << 4) | b);
1190 /* octal encoding */
1193 if ((a = unoctchar(f[0])) < 0 ||
1194 (b = unoctchar(f[1])) < 0 ||
1195 (c = unoctchar(f[2])) < 0) {
1196 /* Invalid escape code, let's take it literal then */
1200 *(t++) = (char) ((a << 6) | (b << 3) | c);
1208 /* premature end of string.*/
1213 /* Invalid escape code, let's take it literal then */
1226 char *xescape(const char *s, const char *bad) {
1230 /* Escapes all chars in bad, in addition to \ and all special
1231 * chars, in \xFF style escaping. May be reversed with
1234 if (!(r = new(char, strlen(s)*4+1)))
1237 for (f = s, t = r; *f; f++) {
1239 if ((*f < ' ') || (*f >= 127) ||
1240 (*f == '\\') || strchr(bad, *f)) {
1243 *(t++) = hexchar(*f >> 4);
1244 *(t++) = hexchar(*f);
1254 char *bus_path_escape(const char *s) {
1260 /* Escapes all chars that D-Bus' object path cannot deal
1261 * with. Can be reverse with bus_path_unescape() */
1263 if (!(r = new(char, strlen(s)*3+1)))
1266 for (f = s, t = r; *f; f++) {
1268 if (!(*f >= 'A' && *f <= 'Z') &&
1269 !(*f >= 'a' && *f <= 'z') &&
1270 !(*f >= '0' && *f <= '9')) {
1272 *(t++) = hexchar(*f >> 4);
1273 *(t++) = hexchar(*f);
1283 char *bus_path_unescape(const char *f) {
1288 if (!(r = strdup(f)))
1291 for (t = r; *f; f++) {
1296 if ((a = unhexchar(f[1])) < 0 ||
1297 (b = unhexchar(f[2])) < 0) {
1298 /* Invalid escape code, let's take it literal then */
1301 *(t++) = (char) ((a << 4) | b);
1313 char *path_kill_slashes(char *path) {
1317 /* Removes redundant inner and trailing slashes. Modifies the
1318 * passed string in-place.
1320 * ///foo///bar/ becomes /foo/bar
1323 for (f = path, t = path; *f; f++) {
1338 /* Special rule, if we are talking of the root directory, a
1339 trailing slash is good */
1341 if (t == path && slash)
1348 bool path_startswith(const char *path, const char *prefix) {
1352 if ((path[0] == '/') != (prefix[0] == '/'))
1358 path += strspn(path, "/");
1359 prefix += strspn(prefix, "/");
1367 a = strcspn(path, "/");
1368 b = strcspn(prefix, "/");
1373 if (memcmp(path, prefix, a) != 0)
1381 bool path_equal(const char *a, const char *b) {
1385 if ((a[0] == '/') != (b[0] == '/'))
1391 a += strspn(a, "/");
1392 b += strspn(b, "/");
1394 if (*a == 0 && *b == 0)
1397 if (*a == 0 || *b == 0)
1400 j = strcspn(a, "/");
1401 k = strcspn(b, "/");
1406 if (memcmp(a, b, j) != 0)
1414 char *ascii_strlower(char *t) {
1419 for (p = t; *p; p++)
1420 if (*p >= 'A' && *p <= 'Z')
1421 *p = *p - 'A' + 'a';
1426 bool ignore_file(const char *filename) {
1430 filename[0] == '.' ||
1431 streq(filename, "lost+found") ||
1432 endswith(filename, "~") ||
1433 endswith(filename, ".rpmnew") ||
1434 endswith(filename, ".rpmsave") ||
1435 endswith(filename, ".rpmorig") ||
1436 endswith(filename, ".dpkg-old") ||
1437 endswith(filename, ".dpkg-new") ||
1438 endswith(filename, ".swp");
1441 int fd_nonblock(int fd, bool nonblock) {
1446 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1450 flags |= O_NONBLOCK;
1452 flags &= ~O_NONBLOCK;
1454 if (fcntl(fd, F_SETFL, flags) < 0)
1460 int fd_cloexec(int fd, bool cloexec) {
1465 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1469 flags |= FD_CLOEXEC;
1471 flags &= ~FD_CLOEXEC;
1473 if (fcntl(fd, F_SETFD, flags) < 0)
1479 int close_all_fds(const int except[], unsigned n_except) {
1484 if (!(d = opendir("/proc/self/fd")))
1487 while ((de = readdir(d))) {
1490 if (ignore_file(de->d_name))
1493 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1507 for (i = 0; i < n_except; i++)
1508 if (except[i] == fd) {
1517 if ((r = close_nointr(fd)) < 0) {
1518 /* Valgrind has its own FD and doesn't want to have it closed */
1531 bool chars_intersect(const char *a, const char *b) {
1534 /* Returns true if any of the chars in a are in b. */
1535 for (p = a; *p; p++)
1542 char *format_timestamp(char *buf, size_t l, usec_t t) {
1552 sec = (time_t) (t / USEC_PER_SEC);
1554 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1560 char *format_timespan(char *buf, size_t l, usec_t t) {
1561 static const struct {
1565 { "w", USEC_PER_WEEK },
1566 { "d", USEC_PER_DAY },
1567 { "h", USEC_PER_HOUR },
1568 { "min", USEC_PER_MINUTE },
1569 { "s", USEC_PER_SEC },
1570 { "ms", USEC_PER_MSEC },
1580 if (t == (usec_t) -1)
1583 /* The result of this function can be parsed with parse_usec */
1585 for (i = 0; i < ELEMENTSOF(table); i++) {
1589 if (t < table[i].usec)
1595 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1596 n = MIN((size_t) k, l);
1609 bool fstype_is_network(const char *fstype) {
1610 static const char * const table[] = {
1622 for (i = 0; i < ELEMENTSOF(table); i++)
1623 if (streq(table[i], fstype))
1632 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1637 TIOCL_GETKMSGREDIRECT,
1641 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1644 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1647 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1650 close_nointr_nofail(r);
1654 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1655 struct termios old_termios, new_termios;
1662 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1663 new_termios = old_termios;
1665 new_termios.c_lflag &= ~ICANON;
1666 new_termios.c_cc[VMIN] = 1;
1667 new_termios.c_cc[VTIME] = 0;
1669 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1672 k = fread(&c, 1, 1, f);
1674 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1680 *need_nl = c != '\n';
1687 if (!(fgets(line, sizeof(line), f)))
1692 if (strlen(line) != 1)
1702 int ask(char *ret, const char *replies, const char *text, ...) {
1711 bool need_nl = true;
1713 fputs("\x1B[1m", stdout);
1719 fputs("\x1B[0m", stdout);
1723 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1725 if (r == -EBADMSG) {
1726 puts("Bad input, please try again.");
1737 if (strchr(replies, c)) {
1742 puts("Read unexpected character, please try again.");
1746 int reset_terminal(int fd) {
1747 struct termios termios;
1752 /* Set terminal to some sane defaults */
1754 if (tcgetattr(fd, &termios) < 0) {
1759 /* We only reset the stuff that matters to the software. How
1760 * hardware is set up we don't touch assuming that somebody
1761 * else will do that for us */
1763 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1764 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1765 termios.c_oflag |= ONLCR;
1766 termios.c_cflag |= CREAD;
1767 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1769 termios.c_cc[VINTR] = 03; /* ^C */
1770 termios.c_cc[VQUIT] = 034; /* ^\ */
1771 termios.c_cc[VERASE] = 0177;
1772 termios.c_cc[VKILL] = 025; /* ^X */
1773 termios.c_cc[VEOF] = 04; /* ^D */
1774 termios.c_cc[VSTART] = 021; /* ^Q */
1775 termios.c_cc[VSTOP] = 023; /* ^S */
1776 termios.c_cc[VSUSP] = 032; /* ^Z */
1777 termios.c_cc[VLNEXT] = 026; /* ^V */
1778 termios.c_cc[VWERASE] = 027; /* ^W */
1779 termios.c_cc[VREPRINT] = 022; /* ^R */
1780 termios.c_cc[VEOL] = 0;
1781 termios.c_cc[VEOL2] = 0;
1783 termios.c_cc[VTIME] = 0;
1784 termios.c_cc[VMIN] = 1;
1786 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1790 /* Just in case, flush all crap out */
1791 tcflush(fd, TCIOFLUSH);
1796 int open_terminal(const char *name, int mode) {
1799 if ((fd = open(name, mode)) < 0)
1802 if ((r = isatty(fd)) < 0) {
1803 close_nointr_nofail(fd);
1808 close_nointr_nofail(fd);
1815 int flush_fd(int fd) {
1816 struct pollfd pollfd;
1820 pollfd.events = POLLIN;
1827 if ((r = poll(&pollfd, 1, 0)) < 0) {
1838 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1843 if (errno == EAGAIN)
1854 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1855 int fd = -1, notify = -1, r, wd = -1;
1859 /* We use inotify to be notified when the tty is closed. We
1860 * create the watch before checking if we can actually acquire
1861 * it, so that we don't lose any event.
1863 * Note: strictly speaking this actually watches for the
1864 * device being closed, it does *not* really watch whether a
1865 * tty loses its controlling process. However, unless some
1866 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1867 * its tty otherwise this will not become a problem. As long
1868 * as the administrator makes sure not configure any service
1869 * on the same tty as an untrusted user this should not be a
1870 * problem. (Which he probably should not do anyway.) */
1872 if (!fail && !force) {
1873 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1878 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1886 if ((r = flush_fd(notify)) < 0)
1889 /* We pass here O_NOCTTY only so that we can check the return
1890 * value TIOCSCTTY and have a reliable way to figure out if we
1891 * successfully became the controlling process of the tty */
1892 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1895 /* First, try to get the tty */
1896 r = ioctl(fd, TIOCSCTTY, force);
1898 /* Sometimes it makes sense to ignore TIOCSCTTY
1899 * returning EPERM, i.e. when very likely we already
1900 * are have this controlling terminal. */
1901 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1904 if (r < 0 && (force || fail || errno != EPERM)) {
1914 assert(notify >= 0);
1917 struct inotify_event e;
1920 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1934 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1942 /* We close the tty fd here since if the old session
1943 * ended our handle will be dead. It's important that
1944 * we do this after sleeping, so that we don't enter
1945 * an endless loop. */
1946 close_nointr_nofail(fd);
1950 close_nointr_nofail(notify);
1952 if ((r = reset_terminal(fd)) < 0)
1953 log_warning("Failed to reset terminal: %s", strerror(-r));
1959 close_nointr_nofail(fd);
1962 close_nointr_nofail(notify);
1967 int release_terminal(void) {
1969 struct sigaction sa_old, sa_new;
1971 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1974 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1975 * by our own TIOCNOTTY */
1978 sa_new.sa_handler = SIG_IGN;
1979 sa_new.sa_flags = SA_RESTART;
1980 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1982 if (ioctl(fd, TIOCNOTTY) < 0)
1985 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1987 close_nointr_nofail(fd);
1991 int sigaction_many(const struct sigaction *sa, ...) {
1996 while ((sig = va_arg(ap, int)) > 0)
1997 if (sigaction(sig, sa, NULL) < 0)
2004 int ignore_signals(int sig, ...) {
2005 struct sigaction sa;
2010 sa.sa_handler = SIG_IGN;
2011 sa.sa_flags = SA_RESTART;
2013 if (sigaction(sig, &sa, NULL) < 0)
2017 while ((sig = va_arg(ap, int)) > 0)
2018 if (sigaction(sig, &sa, NULL) < 0)
2025 int default_signals(int sig, ...) {
2026 struct sigaction sa;
2031 sa.sa_handler = SIG_DFL;
2032 sa.sa_flags = SA_RESTART;
2034 if (sigaction(sig, &sa, NULL) < 0)
2038 while ((sig = va_arg(ap, int)) > 0)
2039 if (sigaction(sig, &sa, NULL) < 0)
2046 int close_pipe(int p[]) {
2052 a = close_nointr(p[0]);
2057 b = close_nointr(p[1]);
2061 return a < 0 ? a : b;
2064 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2073 while (nbytes > 0) {
2076 if ((k = read(fd, p, nbytes)) <= 0) {
2078 if (k < 0 && errno == EINTR)
2081 if (k < 0 && errno == EAGAIN && do_poll) {
2082 struct pollfd pollfd;
2086 pollfd.events = POLLIN;
2088 if (poll(&pollfd, 1, -1) < 0) {
2092 return n > 0 ? n : -errno;
2095 if (pollfd.revents != POLLIN)
2096 return n > 0 ? n : -EIO;
2101 return n > 0 ? n : (k < 0 ? -errno : 0);
2112 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2121 while (nbytes > 0) {
2124 if ((k = write(fd, p, nbytes)) <= 0) {
2126 if (k < 0 && errno == EINTR)
2129 if (k < 0 && errno == EAGAIN && do_poll) {
2130 struct pollfd pollfd;
2134 pollfd.events = POLLOUT;
2136 if (poll(&pollfd, 1, -1) < 0) {
2140 return n > 0 ? n : -errno;
2143 if (pollfd.revents != POLLOUT)
2144 return n > 0 ? n : -EIO;
2149 return n > 0 ? n : (k < 0 ? -errno : 0);
2160 int path_is_mount_point(const char *t) {
2164 if (lstat(t, &a) < 0) {
2166 if (errno == ENOENT)
2172 if (!(copy = strdup(t)))
2175 if (lstat(dirname(copy), &b) < 0) {
2182 return a.st_dev != b.st_dev;
2185 int parse_usec(const char *t, usec_t *usec) {
2186 static const struct {
2190 { "sec", USEC_PER_SEC },
2191 { "s", USEC_PER_SEC },
2192 { "min", USEC_PER_MINUTE },
2193 { "hr", USEC_PER_HOUR },
2194 { "h", USEC_PER_HOUR },
2195 { "d", USEC_PER_DAY },
2196 { "w", USEC_PER_WEEK },
2197 { "msec", USEC_PER_MSEC },
2198 { "ms", USEC_PER_MSEC },
2199 { "m", USEC_PER_MINUTE },
2202 { "", USEC_PER_SEC },
2218 l = strtoll(p, &e, 10);
2229 e += strspn(e, WHITESPACE);
2231 for (i = 0; i < ELEMENTSOF(table); i++)
2232 if (startswith(e, table[i].suffix)) {
2233 r += (usec_t) l * table[i].usec;
2234 p = e + strlen(table[i].suffix);
2238 if (i >= ELEMENTSOF(table))
2248 int make_stdio(int fd) {
2253 r = dup2(fd, STDIN_FILENO);
2254 s = dup2(fd, STDOUT_FILENO);
2255 t = dup2(fd, STDERR_FILENO);
2258 close_nointr_nofail(fd);
2260 if (r < 0 || s < 0 || t < 0)
2266 bool is_clean_exit(int code, int status) {
2268 if (code == CLD_EXITED)
2271 /* If a daemon does not implement handlers for some of the
2272 * signals that's not considered an unclean shutdown */
2273 if (code == CLD_KILLED)
2277 status == SIGTERM ||
2283 bool is_device_path(const char *path) {
2285 /* Returns true on paths that refer to a device, either in
2286 * sysfs or in /dev */
2289 path_startswith(path, "/dev/") ||
2290 path_startswith(path, "/sys/");
2293 int dir_is_empty(const char *path) {
2296 struct dirent buf, *de;
2298 if (!(d = opendir(path)))
2302 if ((r = readdir_r(d, &buf, &de)) > 0) {
2312 if (!ignore_file(de->d_name)) {
2322 unsigned long long random_ull(void) {
2327 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2330 r = loop_read(fd, &ull, sizeof(ull), true);
2331 close_nointr_nofail(fd);
2333 if (r != sizeof(ull))
2339 return random() * RAND_MAX + random();
2342 void rename_process(const char name[8]) {
2345 prctl(PR_SET_NAME, name);
2347 /* This is a like a poor man's setproctitle(). The string
2348 * passed should fit in 7 chars (i.e. the length of
2351 if (program_invocation_name)
2352 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2355 void sigset_add_many(sigset_t *ss, ...) {
2362 while ((sig = va_arg(ap, int)) > 0)
2363 assert_se(sigaddset(ss, sig) == 0);
2367 char* gethostname_malloc(void) {
2370 assert_se(uname(&u) >= 0);
2373 return strdup(u.nodename);
2375 return strdup(u.sysname);
2378 int getmachineid_malloc(char **b) {
2383 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2390 char* getlogname_malloc(void) {
2394 struct passwd pwbuf, *pw = NULL;
2397 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2402 /* Shortcut things to avoid NSS lookups */
2404 return strdup("root");
2406 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2409 if (!(buf = malloc(bufsize)))
2412 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2413 name = strdup(pw->pw_name);
2420 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2426 int getttyname_malloc(char **r) {
2427 char path[PATH_MAX], *p, *c;
2431 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2437 if (startswith(path, "/dev/"))
2440 if (!(c = strdup(p)))
2447 static int rm_rf_children(int fd, bool only_dirs) {
2453 /* This returns the first error we run into, but nevertheless
2456 if (!(d = fdopendir(fd))) {
2457 close_nointr_nofail(fd);
2462 struct dirent buf, *de;
2466 if ((r = readdir_r(d, &buf, &de)) != 0) {
2475 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2478 if (de->d_type == DT_UNKNOWN) {
2481 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2487 is_dir = S_ISDIR(st.st_mode);
2489 is_dir = de->d_type == DT_DIR;
2494 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2500 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2505 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2509 } else if (!only_dirs) {
2511 if (unlinkat(fd, de->d_name, 0) < 0) {
2523 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2529 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2531 if (errno != ENOTDIR)
2534 if (delete_root && !only_dirs)
2535 if (unlink(path) < 0)
2541 r = rm_rf_children(fd, only_dirs);
2544 if (rmdir(path) < 0) {
2552 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2555 /* Under the assumption that we are running privileged we
2556 * first change the access mode and only then hand out
2557 * ownership to avoid a window where access is too open. */
2559 if (chmod(path, mode) < 0)
2562 if (chown(path, uid, gid) < 0)
2568 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2572 /* Allocates the cpuset in the right size */
2575 if (!(r = CPU_ALLOC(n)))
2578 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2579 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2589 if (errno != EINVAL)
2596 void status_vprintf(const char *format, va_list ap) {
2602 /* This independent of logging, as status messages are
2603 * optional and go exclusively to the console. */
2605 if (vasprintf(&s, format, ap) < 0)
2608 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2611 write(fd, s, strlen(s));
2617 close_nointr_nofail(fd);
2620 void status_printf(const char *format, ...) {
2625 va_start(ap, format);
2626 status_vprintf(format, ap);
2630 void status_welcome(void) {
2632 #if defined(TARGET_FEDORA)
2635 if (read_one_line_file("/etc/system-release", &r) < 0)
2640 /* This tries to mimic the color magic the old Red Hat sysinit
2643 if (startswith(r, "Red Hat"))
2644 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2645 else if (startswith(r, "Fedora"))
2646 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2648 status_printf("Welcome to %s!\n", r);
2652 #elif defined(TARGET_SUSE)
2655 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2660 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2663 #warning "You probably should add a welcome text logic here."
2667 static const char *const ioprio_class_table[] = {
2668 [IOPRIO_CLASS_NONE] = "none",
2669 [IOPRIO_CLASS_RT] = "realtime",
2670 [IOPRIO_CLASS_BE] = "best-effort",
2671 [IOPRIO_CLASS_IDLE] = "idle"
2674 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2676 static const char *const sigchld_code_table[] = {
2677 [CLD_EXITED] = "exited",
2678 [CLD_KILLED] = "killed",
2679 [CLD_DUMPED] = "dumped",
2680 [CLD_TRAPPED] = "trapped",
2681 [CLD_STOPPED] = "stopped",
2682 [CLD_CONTINUED] = "continued",
2685 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2687 static const char *const log_facility_table[LOG_NFACILITIES] = {
2688 [LOG_FAC(LOG_KERN)] = "kern",
2689 [LOG_FAC(LOG_USER)] = "user",
2690 [LOG_FAC(LOG_MAIL)] = "mail",
2691 [LOG_FAC(LOG_DAEMON)] = "daemon",
2692 [LOG_FAC(LOG_AUTH)] = "auth",
2693 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2694 [LOG_FAC(LOG_LPR)] = "lpr",
2695 [LOG_FAC(LOG_NEWS)] = "news",
2696 [LOG_FAC(LOG_UUCP)] = "uucp",
2697 [LOG_FAC(LOG_CRON)] = "cron",
2698 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2699 [LOG_FAC(LOG_FTP)] = "ftp",
2700 [LOG_FAC(LOG_LOCAL0)] = "local0",
2701 [LOG_FAC(LOG_LOCAL1)] = "local1",
2702 [LOG_FAC(LOG_LOCAL2)] = "local2",
2703 [LOG_FAC(LOG_LOCAL3)] = "local3",
2704 [LOG_FAC(LOG_LOCAL4)] = "local4",
2705 [LOG_FAC(LOG_LOCAL5)] = "local5",
2706 [LOG_FAC(LOG_LOCAL6)] = "local6",
2707 [LOG_FAC(LOG_LOCAL7)] = "local7"
2710 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2712 static const char *const log_level_table[] = {
2713 [LOG_EMERG] = "emerg",
2714 [LOG_ALERT] = "alert",
2715 [LOG_CRIT] = "crit",
2717 [LOG_WARNING] = "warning",
2718 [LOG_NOTICE] = "notice",
2719 [LOG_INFO] = "info",
2720 [LOG_DEBUG] = "debug"
2723 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2725 static const char* const sched_policy_table[] = {
2726 [SCHED_OTHER] = "other",
2727 [SCHED_BATCH] = "batch",
2728 [SCHED_IDLE] = "idle",
2729 [SCHED_FIFO] = "fifo",
2733 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2735 static const char* const rlimit_table[] = {
2736 [RLIMIT_CPU] = "LimitCPU",
2737 [RLIMIT_FSIZE] = "LimitFSIZE",
2738 [RLIMIT_DATA] = "LimitDATA",
2739 [RLIMIT_STACK] = "LimitSTACK",
2740 [RLIMIT_CORE] = "LimitCORE",
2741 [RLIMIT_RSS] = "LimitRSS",
2742 [RLIMIT_NOFILE] = "LimitNOFILE",
2743 [RLIMIT_AS] = "LimitAS",
2744 [RLIMIT_NPROC] = "LimitNPROC",
2745 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2746 [RLIMIT_LOCKS] = "LimitLOCKS",
2747 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2748 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2749 [RLIMIT_NICE] = "LimitNICE",
2750 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2751 [RLIMIT_RTTIME] = "LimitRTTIME"
2754 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2756 static const char* const ip_tos_table[] = {
2757 [IPTOS_LOWDELAY] = "low-delay",
2758 [IPTOS_THROUGHPUT] = "throughput",
2759 [IPTOS_RELIABILITY] = "reliability",
2760 [IPTOS_LOWCOST] = "low-cost",
2763 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);