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>
59 bool streq_ptr(const char *a, const char *b) {
61 /* Like streq(), but tries to make sense of NULL pointers */
72 usec_t now(clockid_t clock_id) {
75 assert_se(clock_gettime(clock_id, &ts) == 0);
77 return timespec_load(&ts);
80 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
83 ts->realtime = now(CLOCK_REALTIME);
84 ts->monotonic = now(CLOCK_MONOTONIC);
89 usec_t timespec_load(const struct timespec *ts) {
93 (usec_t) ts->tv_sec * USEC_PER_SEC +
94 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
97 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
100 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
101 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
106 usec_t timeval_load(const struct timeval *tv) {
110 (usec_t) tv->tv_sec * USEC_PER_SEC +
111 (usec_t) tv->tv_usec;
114 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
117 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
118 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
123 bool endswith(const char *s, const char *postfix) {
130 pl = strlen(postfix);
138 return memcmp(s + sl - pl, postfix, pl) == 0;
141 bool startswith(const char *s, const char *prefix) {
156 return memcmp(s, prefix, pl) == 0;
159 bool startswith_no_case(const char *s, const char *prefix) {
175 for(i = 0; i < pl; ++i) {
176 if (tolower(s[i]) != tolower(prefix[i]))
183 bool first_word(const char *s, const char *word) {
198 if (memcmp(s, word, wl) != 0)
202 strchr(WHITESPACE, s[wl]);
205 int close_nointr(int fd) {
211 if ((r = close(fd)) >= 0)
219 void close_nointr_nofail(int fd) {
220 int saved_errno = errno;
222 /* like close_nointr() but cannot fail, and guarantees errno
225 assert_se(close_nointr(fd) == 0);
230 void close_many(const int fds[], unsigned n_fd) {
233 for (i = 0; i < n_fd; i++)
234 close_nointr_nofail(fds[i]);
237 int parse_boolean(const char *v) {
240 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
242 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
248 int parse_pid(const char *s, pid_t* ret_pid) {
256 if ((r = safe_atolu(s, &ul)) < 0)
261 if ((unsigned long) pid != ul)
271 int safe_atou(const char *s, unsigned *ret_u) {
279 l = strtoul(s, &x, 0);
281 if (!x || *x || errno)
282 return errno ? -errno : -EINVAL;
284 if ((unsigned long) (unsigned) l != l)
287 *ret_u = (unsigned) l;
291 int safe_atoi(const char *s, int *ret_i) {
299 l = strtol(s, &x, 0);
301 if (!x || *x || errno)
302 return errno ? -errno : -EINVAL;
304 if ((long) (int) l != l)
311 int safe_atollu(const char *s, long long unsigned *ret_llu) {
313 unsigned long long l;
319 l = strtoull(s, &x, 0);
321 if (!x || *x || errno)
322 return errno ? -errno : -EINVAL;
328 int safe_atolli(const char *s, long long int *ret_lli) {
336 l = strtoll(s, &x, 0);
338 if (!x || *x || errno)
339 return errno ? -errno : -EINVAL;
345 /* Split a string into words. */
346 char *split(const char *c, size_t *l, const char *separator, char **state) {
349 current = *state ? *state : (char*) c;
351 if (!*current || *c == 0)
354 current += strspn(current, separator);
355 *l = strcspn(current, separator);
358 return (char*) current;
361 /* Split a string into words, but consider strings enclosed in '' and
362 * "" as words even if they include spaces. */
363 char *split_quoted(const char *c, size_t *l, char **state) {
365 bool escaped = false;
367 current = *state ? *state : (char*) c;
369 if (!*current || *c == 0)
372 current += strspn(current, WHITESPACE);
374 if (*current == '\'') {
377 for (e = current; *e; e++) {
387 *state = *e == 0 ? e : e+1;
388 } else if (*current == '\"') {
391 for (e = current; *e; e++) {
401 *state = *e == 0 ? e : e+1;
403 for (e = current; *e; e++) {
408 else if (strchr(WHITESPACE, *e))
415 return (char*) current;
418 char **split_path_and_make_absolute(const char *p) {
422 if (!(l = strv_split(p, ":")))
425 if (!strv_path_make_absolute_cwd(l)) {
433 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
436 char fn[132], line[256], *p;
442 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
443 fn[sizeof(fn)-1] = 0;
445 if (!(f = fopen(fn, "r")))
448 if (!(fgets(line, sizeof(line), f))) {
456 /* Let's skip the pid and comm fields. The latter is enclosed
457 * in () but does not escape any () in its value, so let's
458 * skip over it manually */
460 if (!(p = strrchr(line, ')')))
471 if ((long unsigned) (pid_t) ppid != ppid)
474 *_ppid = (pid_t) ppid;
479 int write_one_line_file(const char *fn, const char *line) {
486 if (!(f = fopen(fn, "we")))
489 if (fputs(line, f) < 0) {
500 int read_one_line_file(const char *fn, char **line) {
508 if (!(f = fopen(fn, "re")))
511 if (!(fgets(t, sizeof(t), f))) {
516 if (!(c = strdup(t))) {
529 char *truncate_nl(char *s) {
532 s[strcspn(s, NEWLINE)] = 0;
536 int get_process_name(pid_t pid, char **name) {
543 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
546 r = read_one_line_file(p, name);
556 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
564 assert(max_length > 0);
567 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
576 if (!(r = new(char, max_length))) {
583 while ((c = getc(f)) != EOF) {
605 size_t n = MIN(left-1, 3U);
613 /* Kernel threads have no argv[] */
620 if ((h = get_process_name(pid, &t)) < 0)
623 h = asprintf(&r, "[%s]", t);
634 char *strnappend(const char *s, const char *suffix, size_t b) {
642 return strndup(suffix, b);
652 if (!(r = new(char, a+b+1)))
656 memcpy(r+a, suffix, b);
662 char *strappend(const char *s, const char *suffix) {
663 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
666 int readlink_malloc(const char *p, char **r) {
676 if (!(c = new(char, l)))
679 if ((n = readlink(p, c, l-1)) < 0) {
685 if ((size_t) n < l-1) {
696 int readlink_and_make_absolute(const char *p, char **r) {
703 if ((j = readlink_malloc(p, &target)) < 0)
706 k = file_in_same_dir(p, target);
716 int parent_of_path(const char *path, char **_r) {
717 const char *e, *a = NULL, *b = NULL, *p;
727 for (e = path; *e; e++) {
729 if (!slash && *e == '/') {
733 } else if (slash && *e != '/')
748 r = strndup(path, p-path);
758 char *file_name_from_path(const char *p) {
763 if ((r = strrchr(p, '/')))
769 bool path_is_absolute(const char *p) {
775 bool is_path(const char *p) {
777 return !!strchr(p, '/');
780 char *path_make_absolute(const char *p, const char *prefix) {
785 /* Makes every item in the list an absolute path by prepending
786 * the prefix, if specified and necessary */
788 if (path_is_absolute(p) || !prefix)
791 if (asprintf(&r, "%s/%s", prefix, p) < 0)
797 char *path_make_absolute_cwd(const char *p) {
802 /* Similar to path_make_absolute(), but prefixes with the
803 * current working directory. */
805 if (path_is_absolute(p))
808 if (!(cwd = get_current_dir_name()))
811 r = path_make_absolute(p, cwd);
817 char **strv_path_make_absolute_cwd(char **l) {
820 /* Goes through every item in the string list and makes it
821 * absolute. This works in place and won't rollback any
822 * changes on failure. */
827 if (!(t = path_make_absolute_cwd(*s)))
837 char **strv_path_canonicalize(char **l) {
845 /* Goes through every item in the string list and canonicalize
846 * the path. This works in place and won't rollback any
847 * changes on failure. */
852 t = path_make_absolute_cwd(*s);
861 u = canonicalize_file_name(t);
865 if (errno == ENOMEM || !errno)
882 int reset_all_signal_handlers(void) {
885 for (sig = 1; sig < _NSIG; sig++) {
888 if (sig == SIGKILL || sig == SIGSTOP)
892 sa.sa_handler = SIG_DFL;
893 sa.sa_flags = SA_RESTART;
895 /* On Linux the first two RT signals are reserved by
896 * glibc, and sigaction() will return EINVAL for them. */
897 if ((sigaction(sig, &sa, NULL) < 0))
905 char *strstrip(char *s) {
908 /* Drops trailing whitespace. Modifies the string in
909 * place. Returns pointer to first non-space character */
911 s += strspn(s, WHITESPACE);
914 if (!strchr(WHITESPACE, *e))
925 char *delete_chars(char *s, const char *bad) {
928 /* Drops all whitespace, regardless where in the string */
930 for (f = s, t = s; *f; f++) {
942 char *file_in_same_dir(const char *path, const char *filename) {
949 /* This removes the last component of path and appends
950 * filename, unless the latter is absolute anyway or the
953 if (path_is_absolute(filename))
954 return strdup(filename);
956 if (!(e = strrchr(path, '/')))
957 return strdup(filename);
959 k = strlen(filename);
960 if (!(r = new(char, e-path+1+k+1)))
963 memcpy(r, path, e-path+1);
964 memcpy(r+(e-path)+1, filename, k+1);
969 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
972 if (mkdir(path, mode) >= 0)
973 if (chmod_and_chown(path, mode, uid, gid) < 0)
976 if (lstat(path, &st) < 0)
979 if ((st.st_mode & 0777) != mode ||
982 !S_ISDIR(st.st_mode)) {
991 int mkdir_parents(const char *path, mode_t mode) {
996 /* Creates every parent directory in the path except the last
999 p = path + strspn(path, "/");
1004 e = p + strcspn(p, "/");
1005 p = e + strspn(e, "/");
1007 /* Is this the last component? If so, then we're
1012 if (!(t = strndup(path, e - path)))
1018 if (r < 0 && errno != EEXIST)
1023 int mkdir_p(const char *path, mode_t mode) {
1028 if ((r = mkdir_parents(path, mode)) < 0)
1031 if (mkdir(path, mode) < 0 && errno != EEXIST)
1037 int rmdir_parents(const char *path, const char *stop) {
1046 /* Skip trailing slashes */
1047 while (l > 0 && path[l-1] == '/')
1053 /* Skip last component */
1054 while (l > 0 && path[l-1] != '/')
1057 /* Skip trailing slashes */
1058 while (l > 0 && path[l-1] == '/')
1064 if (!(t = strndup(path, l)))
1067 if (path_startswith(stop, t)) {
1076 if (errno != ENOENT)
1084 char hexchar(int x) {
1085 static const char table[16] = "0123456789abcdef";
1087 return table[x & 15];
1090 int unhexchar(char c) {
1092 if (c >= '0' && c <= '9')
1095 if (c >= 'a' && c <= 'f')
1096 return c - 'a' + 10;
1098 if (c >= 'A' && c <= 'F')
1099 return c - 'A' + 10;
1104 char octchar(int x) {
1105 return '0' + (x & 7);
1108 int unoctchar(char c) {
1110 if (c >= '0' && c <= '7')
1116 char decchar(int x) {
1117 return '0' + (x % 10);
1120 int undecchar(char c) {
1122 if (c >= '0' && c <= '9')
1128 char *cescape(const char *s) {
1134 /* Does C style string escaping. */
1136 if (!(r = new(char, strlen(s)*4 + 1)))
1139 for (f = s, t = r; *f; f++)
1185 /* For special chars we prefer octal over
1186 * hexadecimal encoding, simply because glib's
1187 * g_strescape() does the same */
1188 if ((*f < ' ') || (*f >= 127)) {
1190 *(t++) = octchar((unsigned char) *f >> 6);
1191 *(t++) = octchar((unsigned char) *f >> 3);
1192 *(t++) = octchar((unsigned char) *f);
1203 char *cunescape_length(const char *s, size_t length) {
1209 /* Undoes C style string escaping */
1211 if (!(r = new(char, length+1)))
1214 for (f = s, t = r; f < s + length; f++) {
1257 /* This is an extension of the XDG syntax files */
1262 /* hexadecimal encoding */
1265 if ((a = unhexchar(f[1])) < 0 ||
1266 (b = unhexchar(f[2])) < 0) {
1267 /* Invalid escape code, let's take it literal then */
1271 *(t++) = (char) ((a << 4) | b);
1286 /* octal encoding */
1289 if ((a = unoctchar(f[0])) < 0 ||
1290 (b = unoctchar(f[1])) < 0 ||
1291 (c = unoctchar(f[2])) < 0) {
1292 /* Invalid escape code, let's take it literal then */
1296 *(t++) = (char) ((a << 6) | (b << 3) | c);
1304 /* premature end of string.*/
1309 /* Invalid escape code, let's take it literal then */
1321 char *cunescape(const char *s) {
1322 return cunescape_length(s, strlen(s));
1325 char *xescape(const char *s, const char *bad) {
1329 /* Escapes all chars in bad, in addition to \ and all special
1330 * chars, in \xFF style escaping. May be reversed with
1333 if (!(r = new(char, strlen(s)*4+1)))
1336 for (f = s, t = r; *f; f++) {
1338 if ((*f < ' ') || (*f >= 127) ||
1339 (*f == '\\') || strchr(bad, *f)) {
1342 *(t++) = hexchar(*f >> 4);
1343 *(t++) = hexchar(*f);
1353 char *bus_path_escape(const char *s) {
1359 /* Escapes all chars that D-Bus' object path cannot deal
1360 * with. Can be reverse with bus_path_unescape() */
1362 if (!(r = new(char, strlen(s)*3+1)))
1365 for (f = s, t = r; *f; f++) {
1367 if (!(*f >= 'A' && *f <= 'Z') &&
1368 !(*f >= 'a' && *f <= 'z') &&
1369 !(*f >= '0' && *f <= '9')) {
1371 *(t++) = hexchar(*f >> 4);
1372 *(t++) = hexchar(*f);
1382 char *bus_path_unescape(const char *f) {
1387 if (!(r = strdup(f)))
1390 for (t = r; *f; f++) {
1395 if ((a = unhexchar(f[1])) < 0 ||
1396 (b = unhexchar(f[2])) < 0) {
1397 /* Invalid escape code, let's take it literal then */
1400 *(t++) = (char) ((a << 4) | b);
1412 char *path_kill_slashes(char *path) {
1416 /* Removes redundant inner and trailing slashes. Modifies the
1417 * passed string in-place.
1419 * ///foo///bar/ becomes /foo/bar
1422 for (f = path, t = path; *f; f++) {
1437 /* Special rule, if we are talking of the root directory, a
1438 trailing slash is good */
1440 if (t == path && slash)
1447 bool path_startswith(const char *path, const char *prefix) {
1451 if ((path[0] == '/') != (prefix[0] == '/'))
1457 path += strspn(path, "/");
1458 prefix += strspn(prefix, "/");
1466 a = strcspn(path, "/");
1467 b = strcspn(prefix, "/");
1472 if (memcmp(path, prefix, a) != 0)
1480 bool path_equal(const char *a, const char *b) {
1484 if ((a[0] == '/') != (b[0] == '/'))
1490 a += strspn(a, "/");
1491 b += strspn(b, "/");
1493 if (*a == 0 && *b == 0)
1496 if (*a == 0 || *b == 0)
1499 j = strcspn(a, "/");
1500 k = strcspn(b, "/");
1505 if (memcmp(a, b, j) != 0)
1513 char *ascii_strlower(char *t) {
1518 for (p = t; *p; p++)
1519 if (*p >= 'A' && *p <= 'Z')
1520 *p = *p - 'A' + 'a';
1525 bool ignore_file(const char *filename) {
1529 filename[0] == '.' ||
1530 streq(filename, "lost+found") ||
1531 endswith(filename, "~") ||
1532 endswith(filename, ".rpmnew") ||
1533 endswith(filename, ".rpmsave") ||
1534 endswith(filename, ".rpmorig") ||
1535 endswith(filename, ".dpkg-old") ||
1536 endswith(filename, ".dpkg-new") ||
1537 endswith(filename, ".swp");
1540 int fd_nonblock(int fd, bool nonblock) {
1545 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1549 flags |= O_NONBLOCK;
1551 flags &= ~O_NONBLOCK;
1553 if (fcntl(fd, F_SETFL, flags) < 0)
1559 int fd_cloexec(int fd, bool cloexec) {
1564 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1568 flags |= FD_CLOEXEC;
1570 flags &= ~FD_CLOEXEC;
1572 if (fcntl(fd, F_SETFD, flags) < 0)
1578 int close_all_fds(const int except[], unsigned n_except) {
1583 if (!(d = opendir("/proc/self/fd")))
1586 while ((de = readdir(d))) {
1589 if (ignore_file(de->d_name))
1592 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1606 for (i = 0; i < n_except; i++)
1607 if (except[i] == fd) {
1616 if ((r = close_nointr(fd)) < 0) {
1617 /* Valgrind has its own FD and doesn't want to have it closed */
1630 bool chars_intersect(const char *a, const char *b) {
1633 /* Returns true if any of the chars in a are in b. */
1634 for (p = a; *p; p++)
1641 char *format_timestamp(char *buf, size_t l, usec_t t) {
1651 sec = (time_t) (t / USEC_PER_SEC);
1653 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1659 char *format_timespan(char *buf, size_t l, usec_t t) {
1660 static const struct {
1664 { "w", USEC_PER_WEEK },
1665 { "d", USEC_PER_DAY },
1666 { "h", USEC_PER_HOUR },
1667 { "min", USEC_PER_MINUTE },
1668 { "s", USEC_PER_SEC },
1669 { "ms", USEC_PER_MSEC },
1679 if (t == (usec_t) -1)
1682 /* The result of this function can be parsed with parse_usec */
1684 for (i = 0; i < ELEMENTSOF(table); i++) {
1688 if (t < table[i].usec)
1694 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1695 n = MIN((size_t) k, l);
1708 bool fstype_is_network(const char *fstype) {
1709 static const char * const table[] = {
1721 for (i = 0; i < ELEMENTSOF(table); i++)
1722 if (streq(table[i], fstype))
1731 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1736 TIOCL_GETKMSGREDIRECT,
1740 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1743 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1746 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1749 close_nointr_nofail(r);
1753 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1754 struct termios old_termios, new_termios;
1761 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1762 new_termios = old_termios;
1764 new_termios.c_lflag &= ~ICANON;
1765 new_termios.c_cc[VMIN] = 1;
1766 new_termios.c_cc[VTIME] = 0;
1768 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1771 k = fread(&c, 1, 1, f);
1773 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1779 *need_nl = c != '\n';
1786 if (!(fgets(line, sizeof(line), f)))
1791 if (strlen(line) != 1)
1801 int ask(char *ret, const char *replies, const char *text, ...) {
1810 bool need_nl = true;
1812 fputs("\x1B[1m", stdout);
1818 fputs("\x1B[0m", stdout);
1822 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1824 if (r == -EBADMSG) {
1825 puts("Bad input, please try again.");
1836 if (strchr(replies, c)) {
1841 puts("Read unexpected character, please try again.");
1845 int reset_terminal(int fd) {
1846 struct termios termios;
1850 /* Set terminal to some sane defaults */
1854 /* First, unlock termios */
1856 ioctl(fd, TIOCSLCKTRMIOS, &termios);
1858 /* Disable exclusive mode, just in case */
1859 ioctl(fd, TIOCNXCL);
1861 /* Enable console unicode mode */
1863 ioctl(fd, KDSKBMODE, &arg);
1865 if (tcgetattr(fd, &termios) < 0) {
1870 /* We only reset the stuff that matters to the software. How
1871 * hardware is set up we don't touch assuming that somebody
1872 * else will do that for us */
1874 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1875 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1876 termios.c_oflag |= ONLCR;
1877 termios.c_cflag |= CREAD;
1878 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1880 termios.c_cc[VINTR] = 03; /* ^C */
1881 termios.c_cc[VQUIT] = 034; /* ^\ */
1882 termios.c_cc[VERASE] = 0177;
1883 termios.c_cc[VKILL] = 025; /* ^X */
1884 termios.c_cc[VEOF] = 04; /* ^D */
1885 termios.c_cc[VSTART] = 021; /* ^Q */
1886 termios.c_cc[VSTOP] = 023; /* ^S */
1887 termios.c_cc[VSUSP] = 032; /* ^Z */
1888 termios.c_cc[VLNEXT] = 026; /* ^V */
1889 termios.c_cc[VWERASE] = 027; /* ^W */
1890 termios.c_cc[VREPRINT] = 022; /* ^R */
1891 termios.c_cc[VEOL] = 0;
1892 termios.c_cc[VEOL2] = 0;
1894 termios.c_cc[VTIME] = 0;
1895 termios.c_cc[VMIN] = 1;
1897 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1901 /* Just in case, flush all crap out */
1902 tcflush(fd, TCIOFLUSH);
1907 int open_terminal(const char *name, int mode) {
1910 if ((fd = open(name, mode)) < 0)
1913 if ((r = isatty(fd)) < 0) {
1914 close_nointr_nofail(fd);
1919 close_nointr_nofail(fd);
1926 int flush_fd(int fd) {
1927 struct pollfd pollfd;
1931 pollfd.events = POLLIN;
1938 if ((r = poll(&pollfd, 1, 0)) < 0) {
1949 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1954 if (errno == EAGAIN)
1965 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1966 int fd = -1, notify = -1, r, wd = -1;
1970 /* We use inotify to be notified when the tty is closed. We
1971 * create the watch before checking if we can actually acquire
1972 * it, so that we don't lose any event.
1974 * Note: strictly speaking this actually watches for the
1975 * device being closed, it does *not* really watch whether a
1976 * tty loses its controlling process. However, unless some
1977 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1978 * its tty otherwise this will not become a problem. As long
1979 * as the administrator makes sure not configure any service
1980 * on the same tty as an untrusted user this should not be a
1981 * problem. (Which he probably should not do anyway.) */
1983 if (!fail && !force) {
1984 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1989 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1997 if ((r = flush_fd(notify)) < 0)
2000 /* We pass here O_NOCTTY only so that we can check the return
2001 * value TIOCSCTTY and have a reliable way to figure out if we
2002 * successfully became the controlling process of the tty */
2003 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2006 /* First, try to get the tty */
2007 r = ioctl(fd, TIOCSCTTY, force);
2009 /* Sometimes it makes sense to ignore TIOCSCTTY
2010 * returning EPERM, i.e. when very likely we already
2011 * are have this controlling terminal. */
2012 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2015 if (r < 0 && (force || fail || errno != EPERM)) {
2025 assert(notify >= 0);
2028 struct inotify_event e;
2031 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
2045 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
2053 /* We close the tty fd here since if the old session
2054 * ended our handle will be dead. It's important that
2055 * we do this after sleeping, so that we don't enter
2056 * an endless loop. */
2057 close_nointr_nofail(fd);
2061 close_nointr_nofail(notify);
2063 if ((r = reset_terminal(fd)) < 0)
2064 log_warning("Failed to reset terminal: %s", strerror(-r));
2070 close_nointr_nofail(fd);
2073 close_nointr_nofail(notify);
2078 int release_terminal(void) {
2080 struct sigaction sa_old, sa_new;
2082 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2085 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2086 * by our own TIOCNOTTY */
2089 sa_new.sa_handler = SIG_IGN;
2090 sa_new.sa_flags = SA_RESTART;
2091 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2093 if (ioctl(fd, TIOCNOTTY) < 0)
2096 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2098 close_nointr_nofail(fd);
2102 int sigaction_many(const struct sigaction *sa, ...) {
2107 while ((sig = va_arg(ap, int)) > 0)
2108 if (sigaction(sig, sa, NULL) < 0)
2115 int ignore_signals(int sig, ...) {
2116 struct sigaction sa;
2121 sa.sa_handler = SIG_IGN;
2122 sa.sa_flags = SA_RESTART;
2124 if (sigaction(sig, &sa, NULL) < 0)
2128 while ((sig = va_arg(ap, int)) > 0)
2129 if (sigaction(sig, &sa, NULL) < 0)
2136 int default_signals(int sig, ...) {
2137 struct sigaction sa;
2142 sa.sa_handler = SIG_DFL;
2143 sa.sa_flags = SA_RESTART;
2145 if (sigaction(sig, &sa, NULL) < 0)
2149 while ((sig = va_arg(ap, int)) > 0)
2150 if (sigaction(sig, &sa, NULL) < 0)
2157 int close_pipe(int p[]) {
2163 a = close_nointr(p[0]);
2168 b = close_nointr(p[1]);
2172 return a < 0 ? a : b;
2175 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2184 while (nbytes > 0) {
2187 if ((k = read(fd, p, nbytes)) <= 0) {
2189 if (k < 0 && errno == EINTR)
2192 if (k < 0 && errno == EAGAIN && do_poll) {
2193 struct pollfd pollfd;
2197 pollfd.events = POLLIN;
2199 if (poll(&pollfd, 1, -1) < 0) {
2203 return n > 0 ? n : -errno;
2206 if (pollfd.revents != POLLIN)
2207 return n > 0 ? n : -EIO;
2212 return n > 0 ? n : (k < 0 ? -errno : 0);
2223 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2232 while (nbytes > 0) {
2235 if ((k = write(fd, p, nbytes)) <= 0) {
2237 if (k < 0 && errno == EINTR)
2240 if (k < 0 && errno == EAGAIN && do_poll) {
2241 struct pollfd pollfd;
2245 pollfd.events = POLLOUT;
2247 if (poll(&pollfd, 1, -1) < 0) {
2251 return n > 0 ? n : -errno;
2254 if (pollfd.revents != POLLOUT)
2255 return n > 0 ? n : -EIO;
2260 return n > 0 ? n : (k < 0 ? -errno : 0);
2271 int path_is_mount_point(const char *t) {
2276 if (lstat(t, &a) < 0) {
2277 if (errno == ENOENT)
2283 if ((r = parent_of_path(t, &parent)) < 0)
2286 r = lstat(parent, &b);
2292 return a.st_dev != b.st_dev;
2295 int parse_usec(const char *t, usec_t *usec) {
2296 static const struct {
2300 { "sec", USEC_PER_SEC },
2301 { "s", USEC_PER_SEC },
2302 { "min", USEC_PER_MINUTE },
2303 { "hr", USEC_PER_HOUR },
2304 { "h", USEC_PER_HOUR },
2305 { "d", USEC_PER_DAY },
2306 { "w", USEC_PER_WEEK },
2307 { "msec", USEC_PER_MSEC },
2308 { "ms", USEC_PER_MSEC },
2309 { "m", USEC_PER_MINUTE },
2312 { "", USEC_PER_SEC },
2328 l = strtoll(p, &e, 10);
2339 e += strspn(e, WHITESPACE);
2341 for (i = 0; i < ELEMENTSOF(table); i++)
2342 if (startswith(e, table[i].suffix)) {
2343 r += (usec_t) l * table[i].usec;
2344 p = e + strlen(table[i].suffix);
2348 if (i >= ELEMENTSOF(table))
2358 int make_stdio(int fd) {
2363 r = dup2(fd, STDIN_FILENO);
2364 s = dup2(fd, STDOUT_FILENO);
2365 t = dup2(fd, STDERR_FILENO);
2368 close_nointr_nofail(fd);
2370 if (r < 0 || s < 0 || t < 0)
2376 bool is_clean_exit(int code, int status) {
2378 if (code == CLD_EXITED)
2381 /* If a daemon does not implement handlers for some of the
2382 * signals that's not considered an unclean shutdown */
2383 if (code == CLD_KILLED)
2387 status == SIGTERM ||
2393 bool is_device_path(const char *path) {
2395 /* Returns true on paths that refer to a device, either in
2396 * sysfs or in /dev */
2399 path_startswith(path, "/dev/") ||
2400 path_startswith(path, "/sys/");
2403 int dir_is_empty(const char *path) {
2406 struct dirent buf, *de;
2408 if (!(d = opendir(path)))
2412 if ((r = readdir_r(d, &buf, &de)) > 0) {
2422 if (!ignore_file(de->d_name)) {
2432 unsigned long long random_ull(void) {
2437 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2440 r = loop_read(fd, &ull, sizeof(ull), true);
2441 close_nointr_nofail(fd);
2443 if (r != sizeof(ull))
2449 return random() * RAND_MAX + random();
2452 void rename_process(const char name[8]) {
2455 prctl(PR_SET_NAME, name);
2457 /* This is a like a poor man's setproctitle(). The string
2458 * passed should fit in 7 chars (i.e. the length of
2461 if (program_invocation_name)
2462 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2465 void sigset_add_many(sigset_t *ss, ...) {
2472 while ((sig = va_arg(ap, int)) > 0)
2473 assert_se(sigaddset(ss, sig) == 0);
2477 char* gethostname_malloc(void) {
2480 assert_se(uname(&u) >= 0);
2483 return strdup(u.nodename);
2485 return strdup(u.sysname);
2488 int getmachineid_malloc(char **b) {
2493 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2500 char* getlogname_malloc(void) {
2504 struct passwd pwbuf, *pw = NULL;
2507 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2512 /* Shortcut things to avoid NSS lookups */
2514 return strdup("root");
2516 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2519 if (!(buf = malloc(bufsize)))
2522 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2523 name = strdup(pw->pw_name);
2530 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2536 int getttyname_malloc(char **r) {
2537 char path[PATH_MAX], *p, *c;
2541 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2547 if (startswith(path, "/dev/"))
2550 if (!(c = strdup(p)))
2557 static int rm_rf_children(int fd, bool only_dirs) {
2563 /* This returns the first error we run into, but nevertheless
2566 if (!(d = fdopendir(fd))) {
2567 close_nointr_nofail(fd);
2569 return errno == ENOENT ? 0 : -errno;
2573 struct dirent buf, *de;
2577 if ((r = readdir_r(d, &buf, &de)) != 0) {
2586 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2589 if (de->d_type == DT_UNKNOWN) {
2592 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2593 if (ret == 0 && errno != ENOENT)
2598 is_dir = S_ISDIR(st.st_mode);
2600 is_dir = de->d_type == DT_DIR;
2605 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2606 if (ret == 0 && errno != ENOENT)
2611 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2616 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2617 if (ret == 0 && errno != ENOENT)
2620 } else if (!only_dirs) {
2622 if (unlinkat(fd, de->d_name, 0) < 0) {
2623 if (ret == 0 && errno != ENOENT)
2634 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2640 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2642 if (errno != ENOTDIR)
2645 if (delete_root && !only_dirs)
2646 if (unlink(path) < 0)
2652 r = rm_rf_children(fd, only_dirs);
2655 if (rmdir(path) < 0) {
2663 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2666 /* Under the assumption that we are running privileged we
2667 * first change the access mode and only then hand out
2668 * ownership to avoid a window where access is too open. */
2670 if (chmod(path, mode) < 0)
2673 if (chown(path, uid, gid) < 0)
2679 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2683 /* Allocates the cpuset in the right size */
2686 if (!(r = CPU_ALLOC(n)))
2689 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2690 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2700 if (errno != EINVAL)
2707 void status_vprintf(const char *format, va_list ap) {
2713 /* This independent of logging, as status messages are
2714 * optional and go exclusively to the console. */
2716 if (vasprintf(&s, format, ap) < 0)
2719 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2722 write(fd, s, strlen(s));
2728 close_nointr_nofail(fd);
2731 void status_printf(const char *format, ...) {
2736 va_start(ap, format);
2737 status_vprintf(format, ap);
2741 void status_welcome(void) {
2743 #if defined(TARGET_FEDORA)
2746 if (read_one_line_file("/etc/system-release", &r) < 0)
2751 /* This tries to mimic the color magic the old Red Hat sysinit
2754 if (startswith(r, "Red Hat"))
2755 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2756 else if (startswith(r, "Fedora"))
2757 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2759 status_printf("Welcome to %s!\n", r);
2763 #elif defined(TARGET_SUSE)
2766 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2771 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2774 #warning "You probably should add a welcome text logic here."
2778 char *replace_env(const char *format, char **env) {
2785 const char *e, *word = format;
2790 for (e = format; *e; e ++) {
2801 if (!(k = strnappend(r, word, e-word-1)))
2810 } else if (*e == '$') {
2811 if (!(k = strnappend(r, word, e-word)))
2827 if ((t = strv_env_get_with_length(env, word+2, e-word-2))) {
2828 if (!(k = strappend(r, t)))
2843 if (!(k = strnappend(r, word, e-word)))
2854 char **replace_env_argv(char **argv, char **env) {
2858 if (!(r = new(char*, strv_length(argv)+1)))
2861 STRV_FOREACH(i, argv) {
2862 if (!(r[k++] = replace_env(*i, env))) {
2873 static __thread int parsed_columns = 0;
2876 if (parsed_columns > 0)
2877 return parsed_columns;
2879 if ((e = getenv("COLUMNS")))
2880 parsed_columns = atoi(e);
2882 if (parsed_columns <= 0) {
2886 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
2887 parsed_columns = ws.ws_col;
2890 if (parsed_columns <= 0)
2891 parsed_columns = 80;
2893 return parsed_columns;
2896 int running_in_chroot(void) {
2902 /* Only works as root */
2904 if (stat("/proc/1/root", &a) < 0)
2907 if (stat("/", &b) < 0)
2911 a.st_dev != b.st_dev ||
2912 a.st_ino != b.st_ino;
2915 static const char *const ioprio_class_table[] = {
2916 [IOPRIO_CLASS_NONE] = "none",
2917 [IOPRIO_CLASS_RT] = "realtime",
2918 [IOPRIO_CLASS_BE] = "best-effort",
2919 [IOPRIO_CLASS_IDLE] = "idle"
2922 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2924 static const char *const sigchld_code_table[] = {
2925 [CLD_EXITED] = "exited",
2926 [CLD_KILLED] = "killed",
2927 [CLD_DUMPED] = "dumped",
2928 [CLD_TRAPPED] = "trapped",
2929 [CLD_STOPPED] = "stopped",
2930 [CLD_CONTINUED] = "continued",
2933 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2935 static const char *const log_facility_table[LOG_NFACILITIES] = {
2936 [LOG_FAC(LOG_KERN)] = "kern",
2937 [LOG_FAC(LOG_USER)] = "user",
2938 [LOG_FAC(LOG_MAIL)] = "mail",
2939 [LOG_FAC(LOG_DAEMON)] = "daemon",
2940 [LOG_FAC(LOG_AUTH)] = "auth",
2941 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2942 [LOG_FAC(LOG_LPR)] = "lpr",
2943 [LOG_FAC(LOG_NEWS)] = "news",
2944 [LOG_FAC(LOG_UUCP)] = "uucp",
2945 [LOG_FAC(LOG_CRON)] = "cron",
2946 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2947 [LOG_FAC(LOG_FTP)] = "ftp",
2948 [LOG_FAC(LOG_LOCAL0)] = "local0",
2949 [LOG_FAC(LOG_LOCAL1)] = "local1",
2950 [LOG_FAC(LOG_LOCAL2)] = "local2",
2951 [LOG_FAC(LOG_LOCAL3)] = "local3",
2952 [LOG_FAC(LOG_LOCAL4)] = "local4",
2953 [LOG_FAC(LOG_LOCAL5)] = "local5",
2954 [LOG_FAC(LOG_LOCAL6)] = "local6",
2955 [LOG_FAC(LOG_LOCAL7)] = "local7"
2958 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2960 static const char *const log_level_table[] = {
2961 [LOG_EMERG] = "emerg",
2962 [LOG_ALERT] = "alert",
2963 [LOG_CRIT] = "crit",
2965 [LOG_WARNING] = "warning",
2966 [LOG_NOTICE] = "notice",
2967 [LOG_INFO] = "info",
2968 [LOG_DEBUG] = "debug"
2971 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2973 static const char* const sched_policy_table[] = {
2974 [SCHED_OTHER] = "other",
2975 [SCHED_BATCH] = "batch",
2976 [SCHED_IDLE] = "idle",
2977 [SCHED_FIFO] = "fifo",
2981 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2983 static const char* const rlimit_table[] = {
2984 [RLIMIT_CPU] = "LimitCPU",
2985 [RLIMIT_FSIZE] = "LimitFSIZE",
2986 [RLIMIT_DATA] = "LimitDATA",
2987 [RLIMIT_STACK] = "LimitSTACK",
2988 [RLIMIT_CORE] = "LimitCORE",
2989 [RLIMIT_RSS] = "LimitRSS",
2990 [RLIMIT_NOFILE] = "LimitNOFILE",
2991 [RLIMIT_AS] = "LimitAS",
2992 [RLIMIT_NPROC] = "LimitNPROC",
2993 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2994 [RLIMIT_LOCKS] = "LimitLOCKS",
2995 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2996 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2997 [RLIMIT_NICE] = "LimitNICE",
2998 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2999 [RLIMIT_RTTIME] = "LimitRTTIME"
3002 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3004 static const char* const ip_tos_table[] = {
3005 [IPTOS_LOWDELAY] = "low-delay",
3006 [IPTOS_THROUGHPUT] = "throughput",
3007 [IPTOS_RELIABILITY] = "reliability",
3008 [IPTOS_LOWCOST] = "low-cost",
3011 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3013 static const char *const signal_table[] = {
3029 [SIGSTKFLT] = "STKFLT",
3039 [SIGVTALRM] = "VTALRM",
3041 [SIGWINCH] = "WINCH",
3047 DEFINE_STRING_TABLE_LOOKUP(signal, int);