1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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>
61 bool streq_ptr(const char *a, const char *b) {
63 /* Like streq(), but tries to make sense of NULL pointers */
74 usec_t now(clockid_t clock_id) {
77 assert_se(clock_gettime(clock_id, &ts) == 0);
79 return timespec_load(&ts);
82 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
85 ts->realtime = now(CLOCK_REALTIME);
86 ts->monotonic = now(CLOCK_MONOTONIC);
91 usec_t timespec_load(const struct timespec *ts) {
95 (usec_t) ts->tv_sec * USEC_PER_SEC +
96 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
99 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
102 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
103 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
108 usec_t timeval_load(const struct timeval *tv) {
112 (usec_t) tv->tv_sec * USEC_PER_SEC +
113 (usec_t) tv->tv_usec;
116 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
119 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
120 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
125 bool endswith(const char *s, const char *postfix) {
132 pl = strlen(postfix);
140 return memcmp(s + sl - pl, postfix, pl) == 0;
143 bool startswith(const char *s, const char *prefix) {
158 return memcmp(s, prefix, pl) == 0;
161 bool startswith_no_case(const char *s, const char *prefix) {
177 for(i = 0; i < pl; ++i) {
178 if (tolower(s[i]) != tolower(prefix[i]))
185 bool first_word(const char *s, const char *word) {
200 if (memcmp(s, word, wl) != 0)
204 strchr(WHITESPACE, s[wl]);
207 int close_nointr(int fd) {
213 if ((r = close(fd)) >= 0)
221 void close_nointr_nofail(int fd) {
222 int saved_errno = errno;
224 /* like close_nointr() but cannot fail, and guarantees errno
227 assert_se(close_nointr(fd) == 0);
232 void close_many(const int fds[], unsigned n_fd) {
235 for (i = 0; i < n_fd; i++)
236 close_nointr_nofail(fds[i]);
239 int parse_boolean(const char *v) {
242 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
244 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
250 int parse_pid(const char *s, pid_t* ret_pid) {
258 if ((r = safe_atolu(s, &ul)) < 0)
263 if ((unsigned long) pid != ul)
273 int safe_atou(const char *s, unsigned *ret_u) {
281 l = strtoul(s, &x, 0);
283 if (!x || *x || errno)
284 return errno ? -errno : -EINVAL;
286 if ((unsigned long) (unsigned) l != l)
289 *ret_u = (unsigned) l;
293 int safe_atoi(const char *s, int *ret_i) {
301 l = strtol(s, &x, 0);
303 if (!x || *x || errno)
304 return errno ? -errno : -EINVAL;
306 if ((long) (int) l != l)
313 int safe_atollu(const char *s, long long unsigned *ret_llu) {
315 unsigned long long l;
321 l = strtoull(s, &x, 0);
323 if (!x || *x || errno)
324 return errno ? -errno : -EINVAL;
330 int safe_atolli(const char *s, long long int *ret_lli) {
338 l = strtoll(s, &x, 0);
340 if (!x || *x || errno)
341 return errno ? -errno : -EINVAL;
347 /* Split a string into words. */
348 char *split(const char *c, size_t *l, const char *separator, char **state) {
351 current = *state ? *state : (char*) c;
353 if (!*current || *c == 0)
356 current += strspn(current, separator);
357 *l = strcspn(current, separator);
360 return (char*) current;
363 /* Split a string into words, but consider strings enclosed in '' and
364 * "" as words even if they include spaces. */
365 char *split_quoted(const char *c, size_t *l, char **state) {
367 bool escaped = false;
369 current = *state ? *state : (char*) c;
371 if (!*current || *c == 0)
374 current += strspn(current, WHITESPACE);
376 if (*current == '\'') {
379 for (e = current; *e; e++) {
389 *state = *e == 0 ? e : e+1;
390 } else if (*current == '\"') {
393 for (e = current; *e; e++) {
403 *state = *e == 0 ? e : e+1;
405 for (e = current; *e; e++) {
410 else if (strchr(WHITESPACE, *e))
417 return (char*) current;
420 char **split_path_and_make_absolute(const char *p) {
424 if (!(l = strv_split(p, ":")))
427 if (!strv_path_make_absolute_cwd(l)) {
435 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
438 char fn[132], line[256], *p;
444 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
445 fn[sizeof(fn)-1] = 0;
447 if (!(f = fopen(fn, "r")))
450 if (!(fgets(line, sizeof(line), f))) {
458 /* Let's skip the pid and comm fields. The latter is enclosed
459 * in () but does not escape any () in its value, so let's
460 * skip over it manually */
462 if (!(p = strrchr(line, ')')))
473 if ((long unsigned) (pid_t) ppid != ppid)
476 *_ppid = (pid_t) ppid;
481 int write_one_line_file(const char *fn, const char *line) {
488 if (!(f = fopen(fn, "we")))
491 if (fputs(line, f) < 0) {
502 int read_one_line_file(const char *fn, char **line) {
510 if (!(f = fopen(fn, "re")))
513 if (!(fgets(t, sizeof(t), f))) {
518 if (!(c = strdup(t))) {
531 char *truncate_nl(char *s) {
534 s[strcspn(s, NEWLINE)] = 0;
538 int get_process_name(pid_t pid, char **name) {
545 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
548 r = read_one_line_file(p, name);
558 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
566 assert(max_length > 0);
569 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
578 if (!(r = new(char, max_length))) {
585 while ((c = getc(f)) != EOF) {
607 size_t n = MIN(left-1, 3U);
615 /* Kernel threads have no argv[] */
622 if ((h = get_process_name(pid, &t)) < 0)
625 h = asprintf(&r, "[%s]", t);
636 char *strnappend(const char *s, const char *suffix, size_t b) {
644 return strndup(suffix, b);
654 if (!(r = new(char, a+b+1)))
658 memcpy(r+a, suffix, b);
664 char *strappend(const char *s, const char *suffix) {
665 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
668 int readlink_malloc(const char *p, char **r) {
678 if (!(c = new(char, l)))
681 if ((n = readlink(p, c, l-1)) < 0) {
687 if ((size_t) n < l-1) {
698 int readlink_and_make_absolute(const char *p, char **r) {
705 if ((j = readlink_malloc(p, &target)) < 0)
708 k = file_in_same_dir(p, target);
718 int parent_of_path(const char *path, char **_r) {
719 const char *e, *a = NULL, *b = NULL, *p;
729 for (e = path; *e; e++) {
731 if (!slash && *e == '/') {
735 } else if (slash && *e != '/')
750 r = strndup(path, p-path);
760 char *file_name_from_path(const char *p) {
765 if ((r = strrchr(p, '/')))
771 bool path_is_absolute(const char *p) {
777 bool is_path(const char *p) {
779 return !!strchr(p, '/');
782 char *path_make_absolute(const char *p, const char *prefix) {
787 /* Makes every item in the list an absolute path by prepending
788 * the prefix, if specified and necessary */
790 if (path_is_absolute(p) || !prefix)
793 if (asprintf(&r, "%s/%s", prefix, p) < 0)
799 char *path_make_absolute_cwd(const char *p) {
804 /* Similar to path_make_absolute(), but prefixes with the
805 * current working directory. */
807 if (path_is_absolute(p))
810 if (!(cwd = get_current_dir_name()))
813 r = path_make_absolute(p, cwd);
819 char **strv_path_make_absolute_cwd(char **l) {
822 /* Goes through every item in the string list and makes it
823 * absolute. This works in place and won't rollback any
824 * changes on failure. */
829 if (!(t = path_make_absolute_cwd(*s)))
839 char **strv_path_canonicalize(char **l) {
847 /* Goes through every item in the string list and canonicalize
848 * the path. This works in place and won't rollback any
849 * changes on failure. */
854 t = path_make_absolute_cwd(*s);
863 u = canonicalize_file_name(t);
867 if (errno == ENOMEM || !errno)
884 int reset_all_signal_handlers(void) {
887 for (sig = 1; sig < _NSIG; sig++) {
890 if (sig == SIGKILL || sig == SIGSTOP)
894 sa.sa_handler = SIG_DFL;
895 sa.sa_flags = SA_RESTART;
897 /* On Linux the first two RT signals are reserved by
898 * glibc, and sigaction() will return EINVAL for them. */
899 if ((sigaction(sig, &sa, NULL) < 0))
907 char *strstrip(char *s) {
910 /* Drops trailing whitespace. Modifies the string in
911 * place. Returns pointer to first non-space character */
913 s += strspn(s, WHITESPACE);
916 if (!strchr(WHITESPACE, *e))
927 char *delete_chars(char *s, const char *bad) {
930 /* Drops all whitespace, regardless where in the string */
932 for (f = s, t = s; *f; f++) {
944 char *file_in_same_dir(const char *path, const char *filename) {
951 /* This removes the last component of path and appends
952 * filename, unless the latter is absolute anyway or the
955 if (path_is_absolute(filename))
956 return strdup(filename);
958 if (!(e = strrchr(path, '/')))
959 return strdup(filename);
961 k = strlen(filename);
962 if (!(r = new(char, e-path+1+k+1)))
965 memcpy(r, path, e-path+1);
966 memcpy(r+(e-path)+1, filename, k+1);
971 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
974 if (label_mkdir(path, mode) >= 0)
975 if (chmod_and_chown(path, mode, uid, gid) < 0)
978 if (lstat(path, &st) < 0)
981 if ((st.st_mode & 0777) != mode ||
984 !S_ISDIR(st.st_mode)) {
993 int mkdir_parents(const char *path, mode_t mode) {
998 /* Creates every parent directory in the path except the last
1001 p = path + strspn(path, "/");
1006 e = p + strcspn(p, "/");
1007 p = e + strspn(e, "/");
1009 /* Is this the last component? If so, then we're
1014 if (!(t = strndup(path, e - path)))
1017 r = label_mkdir(t, mode);
1020 if (r < 0 && errno != EEXIST)
1025 int mkdir_p(const char *path, mode_t mode) {
1030 if ((r = mkdir_parents(path, mode)) < 0)
1033 if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1039 int rmdir_parents(const char *path, const char *stop) {
1048 /* Skip trailing slashes */
1049 while (l > 0 && path[l-1] == '/')
1055 /* Skip last component */
1056 while (l > 0 && path[l-1] != '/')
1059 /* Skip trailing slashes */
1060 while (l > 0 && path[l-1] == '/')
1066 if (!(t = strndup(path, l)))
1069 if (path_startswith(stop, t)) {
1078 if (errno != ENOENT)
1086 char hexchar(int x) {
1087 static const char table[16] = "0123456789abcdef";
1089 return table[x & 15];
1092 int unhexchar(char c) {
1094 if (c >= '0' && c <= '9')
1097 if (c >= 'a' && c <= 'f')
1098 return c - 'a' + 10;
1100 if (c >= 'A' && c <= 'F')
1101 return c - 'A' + 10;
1106 char octchar(int x) {
1107 return '0' + (x & 7);
1110 int unoctchar(char c) {
1112 if (c >= '0' && c <= '7')
1118 char decchar(int x) {
1119 return '0' + (x % 10);
1122 int undecchar(char c) {
1124 if (c >= '0' && c <= '9')
1130 char *cescape(const char *s) {
1136 /* Does C style string escaping. */
1138 if (!(r = new(char, strlen(s)*4 + 1)))
1141 for (f = s, t = r; *f; f++)
1187 /* For special chars we prefer octal over
1188 * hexadecimal encoding, simply because glib's
1189 * g_strescape() does the same */
1190 if ((*f < ' ') || (*f >= 127)) {
1192 *(t++) = octchar((unsigned char) *f >> 6);
1193 *(t++) = octchar((unsigned char) *f >> 3);
1194 *(t++) = octchar((unsigned char) *f);
1205 char *cunescape_length(const char *s, size_t length) {
1211 /* Undoes C style string escaping */
1213 if (!(r = new(char, length+1)))
1216 for (f = s, t = r; f < s + length; f++) {
1259 /* This is an extension of the XDG syntax files */
1264 /* hexadecimal encoding */
1267 if ((a = unhexchar(f[1])) < 0 ||
1268 (b = unhexchar(f[2])) < 0) {
1269 /* Invalid escape code, let's take it literal then */
1273 *(t++) = (char) ((a << 4) | b);
1288 /* octal encoding */
1291 if ((a = unoctchar(f[0])) < 0 ||
1292 (b = unoctchar(f[1])) < 0 ||
1293 (c = unoctchar(f[2])) < 0) {
1294 /* Invalid escape code, let's take it literal then */
1298 *(t++) = (char) ((a << 6) | (b << 3) | c);
1306 /* premature end of string.*/
1311 /* Invalid escape code, let's take it literal then */
1323 char *cunescape(const char *s) {
1324 return cunescape_length(s, strlen(s));
1327 char *xescape(const char *s, const char *bad) {
1331 /* Escapes all chars in bad, in addition to \ and all special
1332 * chars, in \xFF style escaping. May be reversed with
1335 if (!(r = new(char, strlen(s)*4+1)))
1338 for (f = s, t = r; *f; f++) {
1340 if ((*f < ' ') || (*f >= 127) ||
1341 (*f == '\\') || strchr(bad, *f)) {
1344 *(t++) = hexchar(*f >> 4);
1345 *(t++) = hexchar(*f);
1355 char *bus_path_escape(const char *s) {
1361 /* Escapes all chars that D-Bus' object path cannot deal
1362 * with. Can be reverse with bus_path_unescape() */
1364 if (!(r = new(char, strlen(s)*3+1)))
1367 for (f = s, t = r; *f; f++) {
1369 if (!(*f >= 'A' && *f <= 'Z') &&
1370 !(*f >= 'a' && *f <= 'z') &&
1371 !(*f >= '0' && *f <= '9')) {
1373 *(t++) = hexchar(*f >> 4);
1374 *(t++) = hexchar(*f);
1384 char *bus_path_unescape(const char *f) {
1389 if (!(r = strdup(f)))
1392 for (t = r; *f; f++) {
1397 if ((a = unhexchar(f[1])) < 0 ||
1398 (b = unhexchar(f[2])) < 0) {
1399 /* Invalid escape code, let's take it literal then */
1402 *(t++) = (char) ((a << 4) | b);
1414 char *path_kill_slashes(char *path) {
1418 /* Removes redundant inner and trailing slashes. Modifies the
1419 * passed string in-place.
1421 * ///foo///bar/ becomes /foo/bar
1424 for (f = path, t = path; *f; f++) {
1439 /* Special rule, if we are talking of the root directory, a
1440 trailing slash is good */
1442 if (t == path && slash)
1449 bool path_startswith(const char *path, const char *prefix) {
1453 if ((path[0] == '/') != (prefix[0] == '/'))
1459 path += strspn(path, "/");
1460 prefix += strspn(prefix, "/");
1468 a = strcspn(path, "/");
1469 b = strcspn(prefix, "/");
1474 if (memcmp(path, prefix, a) != 0)
1482 bool path_equal(const char *a, const char *b) {
1486 if ((a[0] == '/') != (b[0] == '/'))
1492 a += strspn(a, "/");
1493 b += strspn(b, "/");
1495 if (*a == 0 && *b == 0)
1498 if (*a == 0 || *b == 0)
1501 j = strcspn(a, "/");
1502 k = strcspn(b, "/");
1507 if (memcmp(a, b, j) != 0)
1515 char *ascii_strlower(char *t) {
1520 for (p = t; *p; p++)
1521 if (*p >= 'A' && *p <= 'Z')
1522 *p = *p - 'A' + 'a';
1527 bool ignore_file(const char *filename) {
1531 filename[0] == '.' ||
1532 streq(filename, "lost+found") ||
1533 endswith(filename, "~") ||
1534 endswith(filename, ".rpmnew") ||
1535 endswith(filename, ".rpmsave") ||
1536 endswith(filename, ".rpmorig") ||
1537 endswith(filename, ".dpkg-old") ||
1538 endswith(filename, ".dpkg-new") ||
1539 endswith(filename, ".swp");
1542 int fd_nonblock(int fd, bool nonblock) {
1547 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1551 flags |= O_NONBLOCK;
1553 flags &= ~O_NONBLOCK;
1555 if (fcntl(fd, F_SETFL, flags) < 0)
1561 int fd_cloexec(int fd, bool cloexec) {
1566 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1570 flags |= FD_CLOEXEC;
1572 flags &= ~FD_CLOEXEC;
1574 if (fcntl(fd, F_SETFD, flags) < 0)
1580 int close_all_fds(const int except[], unsigned n_except) {
1585 if (!(d = opendir("/proc/self/fd")))
1588 while ((de = readdir(d))) {
1591 if (ignore_file(de->d_name))
1594 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1608 for (i = 0; i < n_except; i++)
1609 if (except[i] == fd) {
1618 if ((r = close_nointr(fd)) < 0) {
1619 /* Valgrind has its own FD and doesn't want to have it closed */
1632 bool chars_intersect(const char *a, const char *b) {
1635 /* Returns true if any of the chars in a are in b. */
1636 for (p = a; *p; p++)
1643 char *format_timestamp(char *buf, size_t l, usec_t t) {
1653 sec = (time_t) (t / USEC_PER_SEC);
1655 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1661 char *format_timespan(char *buf, size_t l, usec_t t) {
1662 static const struct {
1666 { "w", USEC_PER_WEEK },
1667 { "d", USEC_PER_DAY },
1668 { "h", USEC_PER_HOUR },
1669 { "min", USEC_PER_MINUTE },
1670 { "s", USEC_PER_SEC },
1671 { "ms", USEC_PER_MSEC },
1681 if (t == (usec_t) -1)
1685 snprintf(p, l, "0");
1690 /* The result of this function can be parsed with parse_usec */
1692 for (i = 0; i < ELEMENTSOF(table); i++) {
1696 if (t < table[i].usec)
1702 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1703 n = MIN((size_t) k, l);
1716 bool fstype_is_network(const char *fstype) {
1717 static const char * const table[] = {
1729 for (i = 0; i < ELEMENTSOF(table); i++)
1730 if (streq(table[i], fstype))
1739 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1744 TIOCL_GETKMSGREDIRECT,
1748 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1751 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1754 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1757 close_nointr_nofail(r);
1761 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1762 struct termios old_termios, new_termios;
1769 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1770 new_termios = old_termios;
1772 new_termios.c_lflag &= ~ICANON;
1773 new_termios.c_cc[VMIN] = 1;
1774 new_termios.c_cc[VTIME] = 0;
1776 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1779 k = fread(&c, 1, 1, f);
1781 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1787 *need_nl = c != '\n';
1794 if (!(fgets(line, sizeof(line), f)))
1799 if (strlen(line) != 1)
1809 int ask(char *ret, const char *replies, const char *text, ...) {
1818 bool need_nl = true;
1820 fputs("\x1B[1m", stdout);
1826 fputs("\x1B[0m", stdout);
1830 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1832 if (r == -EBADMSG) {
1833 puts("Bad input, please try again.");
1844 if (strchr(replies, c)) {
1849 puts("Read unexpected character, please try again.");
1853 int reset_terminal(int fd) {
1854 struct termios termios;
1858 /* Set terminal to some sane defaults */
1862 /* First, unlock termios */
1864 ioctl(fd, TIOCSLCKTRMIOS, &termios);
1866 /* Disable exclusive mode, just in case */
1867 ioctl(fd, TIOCNXCL);
1869 /* Enable console unicode mode */
1871 ioctl(fd, KDSKBMODE, &arg);
1873 if (tcgetattr(fd, &termios) < 0) {
1878 /* We only reset the stuff that matters to the software. How
1879 * hardware is set up we don't touch assuming that somebody
1880 * else will do that for us */
1882 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1883 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1884 termios.c_oflag |= ONLCR;
1885 termios.c_cflag |= CREAD;
1886 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1888 termios.c_cc[VINTR] = 03; /* ^C */
1889 termios.c_cc[VQUIT] = 034; /* ^\ */
1890 termios.c_cc[VERASE] = 0177;
1891 termios.c_cc[VKILL] = 025; /* ^X */
1892 termios.c_cc[VEOF] = 04; /* ^D */
1893 termios.c_cc[VSTART] = 021; /* ^Q */
1894 termios.c_cc[VSTOP] = 023; /* ^S */
1895 termios.c_cc[VSUSP] = 032; /* ^Z */
1896 termios.c_cc[VLNEXT] = 026; /* ^V */
1897 termios.c_cc[VWERASE] = 027; /* ^W */
1898 termios.c_cc[VREPRINT] = 022; /* ^R */
1899 termios.c_cc[VEOL] = 0;
1900 termios.c_cc[VEOL2] = 0;
1902 termios.c_cc[VTIME] = 0;
1903 termios.c_cc[VMIN] = 1;
1905 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1909 /* Just in case, flush all crap out */
1910 tcflush(fd, TCIOFLUSH);
1915 int open_terminal(const char *name, int mode) {
1918 if ((fd = open(name, mode)) < 0)
1921 if ((r = isatty(fd)) < 0) {
1922 close_nointr_nofail(fd);
1927 close_nointr_nofail(fd);
1934 int flush_fd(int fd) {
1935 struct pollfd pollfd;
1939 pollfd.events = POLLIN;
1946 if ((r = poll(&pollfd, 1, 0)) < 0) {
1957 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1962 if (errno == EAGAIN)
1973 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1974 int fd = -1, notify = -1, r, wd = -1;
1978 /* We use inotify to be notified when the tty is closed. We
1979 * create the watch before checking if we can actually acquire
1980 * it, so that we don't lose any event.
1982 * Note: strictly speaking this actually watches for the
1983 * device being closed, it does *not* really watch whether a
1984 * tty loses its controlling process. However, unless some
1985 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1986 * its tty otherwise this will not become a problem. As long
1987 * as the administrator makes sure not configure any service
1988 * on the same tty as an untrusted user this should not be a
1989 * problem. (Which he probably should not do anyway.) */
1991 if (!fail && !force) {
1992 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1997 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2005 if ((r = flush_fd(notify)) < 0)
2008 /* We pass here O_NOCTTY only so that we can check the return
2009 * value TIOCSCTTY and have a reliable way to figure out if we
2010 * successfully became the controlling process of the tty */
2011 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2014 /* First, try to get the tty */
2015 r = ioctl(fd, TIOCSCTTY, force);
2017 /* Sometimes it makes sense to ignore TIOCSCTTY
2018 * returning EPERM, i.e. when very likely we already
2019 * are have this controlling terminal. */
2020 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2023 if (r < 0 && (force || fail || errno != EPERM)) {
2033 assert(notify >= 0);
2036 struct inotify_event e;
2039 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
2053 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
2061 /* We close the tty fd here since if the old session
2062 * ended our handle will be dead. It's important that
2063 * we do this after sleeping, so that we don't enter
2064 * an endless loop. */
2065 close_nointr_nofail(fd);
2069 close_nointr_nofail(notify);
2071 if ((r = reset_terminal(fd)) < 0)
2072 log_warning("Failed to reset terminal: %s", strerror(-r));
2078 close_nointr_nofail(fd);
2081 close_nointr_nofail(notify);
2086 int release_terminal(void) {
2088 struct sigaction sa_old, sa_new;
2090 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2093 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2094 * by our own TIOCNOTTY */
2097 sa_new.sa_handler = SIG_IGN;
2098 sa_new.sa_flags = SA_RESTART;
2099 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2101 if (ioctl(fd, TIOCNOTTY) < 0)
2104 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2106 close_nointr_nofail(fd);
2110 int sigaction_many(const struct sigaction *sa, ...) {
2115 while ((sig = va_arg(ap, int)) > 0)
2116 if (sigaction(sig, sa, NULL) < 0)
2123 int ignore_signals(int sig, ...) {
2124 struct sigaction sa;
2129 sa.sa_handler = SIG_IGN;
2130 sa.sa_flags = SA_RESTART;
2132 if (sigaction(sig, &sa, NULL) < 0)
2136 while ((sig = va_arg(ap, int)) > 0)
2137 if (sigaction(sig, &sa, NULL) < 0)
2144 int default_signals(int sig, ...) {
2145 struct sigaction sa;
2150 sa.sa_handler = SIG_DFL;
2151 sa.sa_flags = SA_RESTART;
2153 if (sigaction(sig, &sa, NULL) < 0)
2157 while ((sig = va_arg(ap, int)) > 0)
2158 if (sigaction(sig, &sa, NULL) < 0)
2165 int close_pipe(int p[]) {
2171 a = close_nointr(p[0]);
2176 b = close_nointr(p[1]);
2180 return a < 0 ? a : b;
2183 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2192 while (nbytes > 0) {
2195 if ((k = read(fd, p, nbytes)) <= 0) {
2197 if (k < 0 && errno == EINTR)
2200 if (k < 0 && errno == EAGAIN && do_poll) {
2201 struct pollfd pollfd;
2205 pollfd.events = POLLIN;
2207 if (poll(&pollfd, 1, -1) < 0) {
2211 return n > 0 ? n : -errno;
2214 if (pollfd.revents != POLLIN)
2215 return n > 0 ? n : -EIO;
2220 return n > 0 ? n : (k < 0 ? -errno : 0);
2231 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2240 while (nbytes > 0) {
2243 if ((k = write(fd, p, nbytes)) <= 0) {
2245 if (k < 0 && errno == EINTR)
2248 if (k < 0 && errno == EAGAIN && do_poll) {
2249 struct pollfd pollfd;
2253 pollfd.events = POLLOUT;
2255 if (poll(&pollfd, 1, -1) < 0) {
2259 return n > 0 ? n : -errno;
2262 if (pollfd.revents != POLLOUT)
2263 return n > 0 ? n : -EIO;
2268 return n > 0 ? n : (k < 0 ? -errno : 0);
2279 int path_is_mount_point(const char *t) {
2284 if (lstat(t, &a) < 0) {
2285 if (errno == ENOENT)
2291 if ((r = parent_of_path(t, &parent)) < 0)
2294 r = lstat(parent, &b);
2300 return a.st_dev != b.st_dev;
2303 int parse_usec(const char *t, usec_t *usec) {
2304 static const struct {
2308 { "sec", USEC_PER_SEC },
2309 { "s", USEC_PER_SEC },
2310 { "min", USEC_PER_MINUTE },
2311 { "hr", USEC_PER_HOUR },
2312 { "h", USEC_PER_HOUR },
2313 { "d", USEC_PER_DAY },
2314 { "w", USEC_PER_WEEK },
2315 { "msec", USEC_PER_MSEC },
2316 { "ms", USEC_PER_MSEC },
2317 { "m", USEC_PER_MINUTE },
2320 { "", USEC_PER_SEC },
2336 l = strtoll(p, &e, 10);
2347 e += strspn(e, WHITESPACE);
2349 for (i = 0; i < ELEMENTSOF(table); i++)
2350 if (startswith(e, table[i].suffix)) {
2351 r += (usec_t) l * table[i].usec;
2352 p = e + strlen(table[i].suffix);
2356 if (i >= ELEMENTSOF(table))
2366 int make_stdio(int fd) {
2371 r = dup2(fd, STDIN_FILENO);
2372 s = dup2(fd, STDOUT_FILENO);
2373 t = dup2(fd, STDERR_FILENO);
2376 close_nointr_nofail(fd);
2378 if (r < 0 || s < 0 || t < 0)
2384 bool is_clean_exit(int code, int status) {
2386 if (code == CLD_EXITED)
2389 /* If a daemon does not implement handlers for some of the
2390 * signals that's not considered an unclean shutdown */
2391 if (code == CLD_KILLED)
2395 status == SIGTERM ||
2401 bool is_device_path(const char *path) {
2403 /* Returns true on paths that refer to a device, either in
2404 * sysfs or in /dev */
2407 path_startswith(path, "/dev/") ||
2408 path_startswith(path, "/sys/");
2411 int dir_is_empty(const char *path) {
2414 struct dirent buf, *de;
2416 if (!(d = opendir(path)))
2420 if ((r = readdir_r(d, &buf, &de)) > 0) {
2430 if (!ignore_file(de->d_name)) {
2440 unsigned long long random_ull(void) {
2445 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2448 r = loop_read(fd, &ull, sizeof(ull), true);
2449 close_nointr_nofail(fd);
2451 if (r != sizeof(ull))
2457 return random() * RAND_MAX + random();
2460 void rename_process(const char name[8]) {
2463 prctl(PR_SET_NAME, name);
2465 /* This is a like a poor man's setproctitle(). The string
2466 * passed should fit in 7 chars (i.e. the length of
2469 if (program_invocation_name)
2470 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2473 void sigset_add_many(sigset_t *ss, ...) {
2480 while ((sig = va_arg(ap, int)) > 0)
2481 assert_se(sigaddset(ss, sig) == 0);
2485 char* gethostname_malloc(void) {
2488 assert_se(uname(&u) >= 0);
2491 return strdup(u.nodename);
2493 return strdup(u.sysname);
2496 char* getlogname_malloc(void) {
2500 struct passwd pwbuf, *pw = NULL;
2503 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2508 /* Shortcut things to avoid NSS lookups */
2510 return strdup("root");
2512 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2515 if (!(buf = malloc(bufsize)))
2518 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2519 name = strdup(pw->pw_name);
2526 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2532 int getttyname_malloc(char **r) {
2533 char path[PATH_MAX], *p, *c;
2538 if ((k = ttyname_r(STDIN_FILENO, path, sizeof(path))) != 0)
2544 if (startswith(path, "/dev/"))
2547 if (!(c = strdup(p)))
2554 static int rm_rf_children(int fd, bool only_dirs) {
2560 /* This returns the first error we run into, but nevertheless
2563 if (!(d = fdopendir(fd))) {
2564 close_nointr_nofail(fd);
2566 return errno == ENOENT ? 0 : -errno;
2570 struct dirent buf, *de;
2574 if ((r = readdir_r(d, &buf, &de)) != 0) {
2583 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2586 if (de->d_type == DT_UNKNOWN) {
2589 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2590 if (ret == 0 && errno != ENOENT)
2595 is_dir = S_ISDIR(st.st_mode);
2597 is_dir = de->d_type == DT_DIR;
2602 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2603 if (ret == 0 && errno != ENOENT)
2608 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2613 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2614 if (ret == 0 && errno != ENOENT)
2617 } else if (!only_dirs) {
2619 if (unlinkat(fd, de->d_name, 0) < 0) {
2620 if (ret == 0 && errno != ENOENT)
2631 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2637 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2639 if (errno != ENOTDIR)
2642 if (delete_root && !only_dirs)
2643 if (unlink(path) < 0)
2649 r = rm_rf_children(fd, only_dirs);
2652 if (rmdir(path) < 0) {
2660 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2663 /* Under the assumption that we are running privileged we
2664 * first change the access mode and only then hand out
2665 * ownership to avoid a window where access is too open. */
2667 if (chmod(path, mode) < 0)
2670 if (chown(path, uid, gid) < 0)
2676 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2680 /* Allocates the cpuset in the right size */
2683 if (!(r = CPU_ALLOC(n)))
2686 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2687 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2697 if (errno != EINVAL)
2704 void status_vprintf(const char *format, va_list ap) {
2710 /* This independent of logging, as status messages are
2711 * optional and go exclusively to the console. */
2713 if (vasprintf(&s, format, ap) < 0)
2716 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2719 write(fd, s, strlen(s));
2725 close_nointr_nofail(fd);
2728 void status_printf(const char *format, ...) {
2733 va_start(ap, format);
2734 status_vprintf(format, ap);
2738 void status_welcome(void) {
2740 #if defined(TARGET_FEDORA)
2743 if (read_one_line_file("/etc/system-release", &r) < 0)
2748 /* This tries to mimic the color magic the old Red Hat sysinit
2751 if (startswith(r, "Red Hat"))
2752 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2753 else if (startswith(r, "Fedora"))
2754 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2756 status_printf("Welcome to %s!\n", r);
2760 #elif defined(TARGET_SUSE)
2763 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2768 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2771 #warning "You probably should add a welcome text logic here."
2775 char *replace_env(const char *format, char **env) {
2782 const char *e, *word = format;
2787 for (e = format; *e; e ++) {
2798 if (!(k = strnappend(r, word, e-word-1)))
2807 } else if (*e == '$') {
2808 if (!(k = strnappend(r, word, e-word)))
2824 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
2827 if (!(k = strappend(r, t)))
2840 if (!(k = strnappend(r, word, e-word)))
2851 char **replace_env_argv(char **argv, char **env) {
2853 unsigned k = 0, l = 0;
2855 l = strv_length(argv);
2857 if (!(r = new(char*, l+1)))
2860 STRV_FOREACH(i, argv) {
2862 /* If $FOO appears as single word, replace it by the split up variable */
2863 if ((*i)[0] == '$' && (*i)[1] != '{') {
2868 if ((e = strv_env_get(env, *i+1))) {
2870 if (!(m = strv_split_quoted(e))) {
2881 if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
2890 memcpy(r + k, m, q * sizeof(char*));
2898 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
2899 if (!(r[k++] = replace_env(*i, env))) {
2910 static __thread int parsed_columns = 0;
2913 if (parsed_columns > 0)
2914 return parsed_columns;
2916 if ((e = getenv("COLUMNS")))
2917 parsed_columns = atoi(e);
2919 if (parsed_columns <= 0) {
2923 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
2924 parsed_columns = ws.ws_col;
2927 if (parsed_columns <= 0)
2928 parsed_columns = 80;
2930 return parsed_columns;
2933 int running_in_chroot(void) {
2939 /* Only works as root */
2941 if (stat("/proc/1/root", &a) < 0)
2944 if (stat("/", &b) < 0)
2948 a.st_dev != b.st_dev ||
2949 a.st_ino != b.st_ino;
2952 char *ellipsize(const char *s, unsigned length, unsigned percent) {
2957 assert(percent <= 100);
2958 assert(length >= 3);
2962 if (l <= 3 || l <= length)
2965 if (!(r = new0(char, length+1)))
2968 x = (length * percent) / 100;
2978 s + l - (length - x - 3),
2984 int touch(const char *path) {
2989 if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666)) < 0)
2992 close_nointr_nofail(fd);
2996 static const char *const ioprio_class_table[] = {
2997 [IOPRIO_CLASS_NONE] = "none",
2998 [IOPRIO_CLASS_RT] = "realtime",
2999 [IOPRIO_CLASS_BE] = "best-effort",
3000 [IOPRIO_CLASS_IDLE] = "idle"
3003 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3005 static const char *const sigchld_code_table[] = {
3006 [CLD_EXITED] = "exited",
3007 [CLD_KILLED] = "killed",
3008 [CLD_DUMPED] = "dumped",
3009 [CLD_TRAPPED] = "trapped",
3010 [CLD_STOPPED] = "stopped",
3011 [CLD_CONTINUED] = "continued",
3014 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3016 static const char *const log_facility_table[LOG_NFACILITIES] = {
3017 [LOG_FAC(LOG_KERN)] = "kern",
3018 [LOG_FAC(LOG_USER)] = "user",
3019 [LOG_FAC(LOG_MAIL)] = "mail",
3020 [LOG_FAC(LOG_DAEMON)] = "daemon",
3021 [LOG_FAC(LOG_AUTH)] = "auth",
3022 [LOG_FAC(LOG_SYSLOG)] = "syslog",
3023 [LOG_FAC(LOG_LPR)] = "lpr",
3024 [LOG_FAC(LOG_NEWS)] = "news",
3025 [LOG_FAC(LOG_UUCP)] = "uucp",
3026 [LOG_FAC(LOG_CRON)] = "cron",
3027 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3028 [LOG_FAC(LOG_FTP)] = "ftp",
3029 [LOG_FAC(LOG_LOCAL0)] = "local0",
3030 [LOG_FAC(LOG_LOCAL1)] = "local1",
3031 [LOG_FAC(LOG_LOCAL2)] = "local2",
3032 [LOG_FAC(LOG_LOCAL3)] = "local3",
3033 [LOG_FAC(LOG_LOCAL4)] = "local4",
3034 [LOG_FAC(LOG_LOCAL5)] = "local5",
3035 [LOG_FAC(LOG_LOCAL6)] = "local6",
3036 [LOG_FAC(LOG_LOCAL7)] = "local7"
3039 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3041 static const char *const log_level_table[] = {
3042 [LOG_EMERG] = "emerg",
3043 [LOG_ALERT] = "alert",
3044 [LOG_CRIT] = "crit",
3046 [LOG_WARNING] = "warning",
3047 [LOG_NOTICE] = "notice",
3048 [LOG_INFO] = "info",
3049 [LOG_DEBUG] = "debug"
3052 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3054 static const char* const sched_policy_table[] = {
3055 [SCHED_OTHER] = "other",
3056 [SCHED_BATCH] = "batch",
3057 [SCHED_IDLE] = "idle",
3058 [SCHED_FIFO] = "fifo",
3062 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3064 static const char* const rlimit_table[] = {
3065 [RLIMIT_CPU] = "LimitCPU",
3066 [RLIMIT_FSIZE] = "LimitFSIZE",
3067 [RLIMIT_DATA] = "LimitDATA",
3068 [RLIMIT_STACK] = "LimitSTACK",
3069 [RLIMIT_CORE] = "LimitCORE",
3070 [RLIMIT_RSS] = "LimitRSS",
3071 [RLIMIT_NOFILE] = "LimitNOFILE",
3072 [RLIMIT_AS] = "LimitAS",
3073 [RLIMIT_NPROC] = "LimitNPROC",
3074 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3075 [RLIMIT_LOCKS] = "LimitLOCKS",
3076 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3077 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3078 [RLIMIT_NICE] = "LimitNICE",
3079 [RLIMIT_RTPRIO] = "LimitRTPRIO",
3080 [RLIMIT_RTTIME] = "LimitRTTIME"
3083 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3085 static const char* const ip_tos_table[] = {
3086 [IPTOS_LOWDELAY] = "low-delay",
3087 [IPTOS_THROUGHPUT] = "throughput",
3088 [IPTOS_RELIABILITY] = "reliability",
3089 [IPTOS_LOWCOST] = "low-cost",
3092 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3094 static const char *const signal_table[] = {
3110 [SIGSTKFLT] = "STKFLT",
3120 [SIGVTALRM] = "VTALRM",
3122 [SIGWINCH] = "WINCH",
3128 DEFINE_STRING_TABLE_LOOKUP(signal, int);