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) {
364 bool escaped = false;
366 current = *state ? *state : (char*) c;
368 if (!*current || *c == 0)
371 current += strspn(current, WHITESPACE);
373 if (*current == '\'') {
376 for (e = current; *e; e++) {
386 *state = *e == 0 ? e : e+1;
387 } else if (*current == '\"') {
390 for (e = current; *e; e++) {
400 *state = *e == 0 ? e : e+1;
402 for (e = current; *e; e++) {
407 else if (strchr(WHITESPACE, *e))
414 return (char*) current;
417 char **split_path_and_make_absolute(const char *p) {
421 if (!(l = strv_split(p, ":")))
424 if (!strv_path_make_absolute_cwd(l)) {
432 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
435 char fn[132], line[256], *p;
441 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
442 fn[sizeof(fn)-1] = 0;
444 if (!(f = fopen(fn, "r")))
447 if (!(fgets(line, sizeof(line), f))) {
455 /* Let's skip the pid and comm fields. The latter is enclosed
456 * in () but does not escape any () in its value, so let's
457 * skip over it manually */
459 if (!(p = strrchr(line, ')')))
470 if ((long unsigned) (pid_t) ppid != ppid)
473 *_ppid = (pid_t) ppid;
478 int write_one_line_file(const char *fn, const char *line) {
485 if (!(f = fopen(fn, "we")))
488 if (fputs(line, f) < 0) {
499 int read_one_line_file(const char *fn, char **line) {
507 if (!(f = fopen(fn, "re")))
510 if (!(fgets(t, sizeof(t), f))) {
515 if (!(c = strdup(t))) {
528 char *truncate_nl(char *s) {
531 s[strcspn(s, NEWLINE)] = 0;
535 int get_process_name(pid_t pid, char **name) {
542 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
545 r = read_one_line_file(p, name);
555 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
563 assert(max_length > 0);
566 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
575 if (!(r = new(char, max_length))) {
582 while ((c = getc(f)) != EOF) {
604 size_t n = MIN(left-1, 3U);
616 char *strnappend(const char *s, const char *suffix, size_t b) {
624 return strndup(suffix, b);
634 if (!(r = new(char, a+b+1)))
638 memcpy(r+a, suffix, b);
644 char *strappend(const char *s, const char *suffix) {
645 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
648 int readlink_malloc(const char *p, char **r) {
658 if (!(c = new(char, l)))
661 if ((n = readlink(p, c, l-1)) < 0) {
667 if ((size_t) n < l-1) {
678 int readlink_and_make_absolute(const char *p, char **r) {
685 if ((j = readlink_malloc(p, &target)) < 0)
688 k = file_in_same_dir(p, target);
698 char *file_name_from_path(const char *p) {
703 if ((r = strrchr(p, '/')))
709 bool path_is_absolute(const char *p) {
715 bool is_path(const char *p) {
717 return !!strchr(p, '/');
720 char *path_make_absolute(const char *p, const char *prefix) {
725 /* Makes every item in the list an absolute path by prepending
726 * the prefix, if specified and necessary */
728 if (path_is_absolute(p) || !prefix)
731 if (asprintf(&r, "%s/%s", prefix, p) < 0)
737 char *path_make_absolute_cwd(const char *p) {
742 /* Similar to path_make_absolute(), but prefixes with the
743 * current working directory. */
745 if (path_is_absolute(p))
748 if (!(cwd = get_current_dir_name()))
751 r = path_make_absolute(p, cwd);
757 char **strv_path_make_absolute_cwd(char **l) {
760 /* Goes through every item in the string list and makes it
761 * absolute. This works in place and won't rollback any
762 * changes on failure. */
767 if (!(t = path_make_absolute_cwd(*s)))
777 char **strv_path_canonicalize(char **l) {
785 /* Goes through every item in the string list and canonicalize
786 * the path. This works in place and won't rollback any
787 * changes on failure. */
792 t = path_make_absolute_cwd(*s);
801 u = canonicalize_file_name(t);
805 if (errno == ENOMEM || !errno)
822 int reset_all_signal_handlers(void) {
825 for (sig = 1; sig < _NSIG; sig++) {
828 if (sig == SIGKILL || sig == SIGSTOP)
832 sa.sa_handler = SIG_DFL;
833 sa.sa_flags = SA_RESTART;
835 /* On Linux the first two RT signals are reserved by
836 * glibc, and sigaction() will return EINVAL for them. */
837 if ((sigaction(sig, &sa, NULL) < 0))
845 char *strstrip(char *s) {
848 /* Drops trailing whitespace. Modifies the string in
849 * place. Returns pointer to first non-space character */
851 s += strspn(s, WHITESPACE);
854 if (!strchr(WHITESPACE, *e))
865 char *delete_chars(char *s, const char *bad) {
868 /* Drops all whitespace, regardless where in the string */
870 for (f = s, t = s; *f; f++) {
882 char *file_in_same_dir(const char *path, const char *filename) {
889 /* This removes the last component of path and appends
890 * filename, unless the latter is absolute anyway or the
893 if (path_is_absolute(filename))
894 return strdup(filename);
896 if (!(e = strrchr(path, '/')))
897 return strdup(filename);
899 k = strlen(filename);
900 if (!(r = new(char, e-path+1+k+1)))
903 memcpy(r, path, e-path+1);
904 memcpy(r+(e-path)+1, filename, k+1);
909 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
912 if (mkdir(path, mode) >= 0)
913 if (chmod_and_chown(path, mode, uid, gid) < 0)
916 if (lstat(path, &st) < 0)
919 if ((st.st_mode & 0777) != mode ||
922 !S_ISDIR(st.st_mode)) {
931 int mkdir_parents(const char *path, mode_t mode) {
936 /* Creates every parent directory in the path except the last
939 p = path + strspn(path, "/");
944 e = p + strcspn(p, "/");
945 p = e + strspn(e, "/");
947 /* Is this the last component? If so, then we're
952 if (!(t = strndup(path, e - path)))
959 if (r < 0 && errno != EEXIST)
964 int mkdir_p(const char *path, mode_t mode) {
969 if ((r = mkdir_parents(path, mode)) < 0)
972 if (mkdir(path, mode) < 0)
978 int rmdir_parents(const char *path, const char *stop) {
987 /* Skip trailing slashes */
988 while (l > 0 && path[l-1] == '/')
994 /* Skip last component */
995 while (l > 0 && path[l-1] != '/')
998 /* Skip trailing slashes */
999 while (l > 0 && path[l-1] == '/')
1005 if (!(t = strndup(path, l)))
1008 if (path_startswith(stop, t)) {
1017 if (errno != ENOENT)
1025 char hexchar(int x) {
1026 static const char table[16] = "0123456789abcdef";
1028 return table[x & 15];
1031 int unhexchar(char c) {
1033 if (c >= '0' && c <= '9')
1036 if (c >= 'a' && c <= 'f')
1037 return c - 'a' + 10;
1039 if (c >= 'A' && c <= 'F')
1040 return c - 'A' + 10;
1045 char octchar(int x) {
1046 return '0' + (x & 7);
1049 int unoctchar(char c) {
1051 if (c >= '0' && c <= '7')
1057 char decchar(int x) {
1058 return '0' + (x % 10);
1061 int undecchar(char c) {
1063 if (c >= '0' && c <= '9')
1069 char *cescape(const char *s) {
1075 /* Does C style string escaping. */
1077 if (!(r = new(char, strlen(s)*4 + 1)))
1080 for (f = s, t = r; *f; f++)
1126 /* For special chars we prefer octal over
1127 * hexadecimal encoding, simply because glib's
1128 * g_strescape() does the same */
1129 if ((*f < ' ') || (*f >= 127)) {
1131 *(t++) = octchar((unsigned char) *f >> 6);
1132 *(t++) = octchar((unsigned char) *f >> 3);
1133 *(t++) = octchar((unsigned char) *f);
1144 char *cunescape_length(const char *s, size_t length) {
1150 /* Undoes C style string escaping */
1152 if (!(r = new(char, length+1)))
1155 for (f = s, t = r; f < s + length; f++) {
1198 /* This is an extension of the XDG syntax files */
1203 /* hexadecimal encoding */
1206 if ((a = unhexchar(f[1])) < 0 ||
1207 (b = unhexchar(f[2])) < 0) {
1208 /* Invalid escape code, let's take it literal then */
1212 *(t++) = (char) ((a << 4) | b);
1227 /* octal encoding */
1230 if ((a = unoctchar(f[0])) < 0 ||
1231 (b = unoctchar(f[1])) < 0 ||
1232 (c = unoctchar(f[2])) < 0) {
1233 /* Invalid escape code, let's take it literal then */
1237 *(t++) = (char) ((a << 6) | (b << 3) | c);
1245 /* premature end of string.*/
1250 /* Invalid escape code, let's take it literal then */
1262 char *cunescape(const char *s) {
1263 return cunescape_length(s, strlen(s));
1266 char *xescape(const char *s, const char *bad) {
1270 /* Escapes all chars in bad, in addition to \ and all special
1271 * chars, in \xFF style escaping. May be reversed with
1274 if (!(r = new(char, strlen(s)*4+1)))
1277 for (f = s, t = r; *f; f++) {
1279 if ((*f < ' ') || (*f >= 127) ||
1280 (*f == '\\') || strchr(bad, *f)) {
1283 *(t++) = hexchar(*f >> 4);
1284 *(t++) = hexchar(*f);
1294 char *bus_path_escape(const char *s) {
1300 /* Escapes all chars that D-Bus' object path cannot deal
1301 * with. Can be reverse with bus_path_unescape() */
1303 if (!(r = new(char, strlen(s)*3+1)))
1306 for (f = s, t = r; *f; f++) {
1308 if (!(*f >= 'A' && *f <= 'Z') &&
1309 !(*f >= 'a' && *f <= 'z') &&
1310 !(*f >= '0' && *f <= '9')) {
1312 *(t++) = hexchar(*f >> 4);
1313 *(t++) = hexchar(*f);
1323 char *bus_path_unescape(const char *f) {
1328 if (!(r = strdup(f)))
1331 for (t = r; *f; f++) {
1336 if ((a = unhexchar(f[1])) < 0 ||
1337 (b = unhexchar(f[2])) < 0) {
1338 /* Invalid escape code, let's take it literal then */
1341 *(t++) = (char) ((a << 4) | b);
1353 char *path_kill_slashes(char *path) {
1357 /* Removes redundant inner and trailing slashes. Modifies the
1358 * passed string in-place.
1360 * ///foo///bar/ becomes /foo/bar
1363 for (f = path, t = path; *f; f++) {
1378 /* Special rule, if we are talking of the root directory, a
1379 trailing slash is good */
1381 if (t == path && slash)
1388 bool path_startswith(const char *path, const char *prefix) {
1392 if ((path[0] == '/') != (prefix[0] == '/'))
1398 path += strspn(path, "/");
1399 prefix += strspn(prefix, "/");
1407 a = strcspn(path, "/");
1408 b = strcspn(prefix, "/");
1413 if (memcmp(path, prefix, a) != 0)
1421 bool path_equal(const char *a, const char *b) {
1425 if ((a[0] == '/') != (b[0] == '/'))
1431 a += strspn(a, "/");
1432 b += strspn(b, "/");
1434 if (*a == 0 && *b == 0)
1437 if (*a == 0 || *b == 0)
1440 j = strcspn(a, "/");
1441 k = strcspn(b, "/");
1446 if (memcmp(a, b, j) != 0)
1454 char *ascii_strlower(char *t) {
1459 for (p = t; *p; p++)
1460 if (*p >= 'A' && *p <= 'Z')
1461 *p = *p - 'A' + 'a';
1466 bool ignore_file(const char *filename) {
1470 filename[0] == '.' ||
1471 streq(filename, "lost+found") ||
1472 endswith(filename, "~") ||
1473 endswith(filename, ".rpmnew") ||
1474 endswith(filename, ".rpmsave") ||
1475 endswith(filename, ".rpmorig") ||
1476 endswith(filename, ".dpkg-old") ||
1477 endswith(filename, ".dpkg-new") ||
1478 endswith(filename, ".swp");
1481 int fd_nonblock(int fd, bool nonblock) {
1486 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1490 flags |= O_NONBLOCK;
1492 flags &= ~O_NONBLOCK;
1494 if (fcntl(fd, F_SETFL, flags) < 0)
1500 int fd_cloexec(int fd, bool cloexec) {
1505 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1509 flags |= FD_CLOEXEC;
1511 flags &= ~FD_CLOEXEC;
1513 if (fcntl(fd, F_SETFD, flags) < 0)
1519 int close_all_fds(const int except[], unsigned n_except) {
1524 if (!(d = opendir("/proc/self/fd")))
1527 while ((de = readdir(d))) {
1530 if (ignore_file(de->d_name))
1533 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1547 for (i = 0; i < n_except; i++)
1548 if (except[i] == fd) {
1557 if ((r = close_nointr(fd)) < 0) {
1558 /* Valgrind has its own FD and doesn't want to have it closed */
1571 bool chars_intersect(const char *a, const char *b) {
1574 /* Returns true if any of the chars in a are in b. */
1575 for (p = a; *p; p++)
1582 char *format_timestamp(char *buf, size_t l, usec_t t) {
1592 sec = (time_t) (t / USEC_PER_SEC);
1594 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1600 char *format_timespan(char *buf, size_t l, usec_t t) {
1601 static const struct {
1605 { "w", USEC_PER_WEEK },
1606 { "d", USEC_PER_DAY },
1607 { "h", USEC_PER_HOUR },
1608 { "min", USEC_PER_MINUTE },
1609 { "s", USEC_PER_SEC },
1610 { "ms", USEC_PER_MSEC },
1620 if (t == (usec_t) -1)
1623 /* The result of this function can be parsed with parse_usec */
1625 for (i = 0; i < ELEMENTSOF(table); i++) {
1629 if (t < table[i].usec)
1635 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1636 n = MIN((size_t) k, l);
1649 bool fstype_is_network(const char *fstype) {
1650 static const char * const table[] = {
1662 for (i = 0; i < ELEMENTSOF(table); i++)
1663 if (streq(table[i], fstype))
1672 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1677 TIOCL_GETKMSGREDIRECT,
1681 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1684 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1687 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1690 close_nointr_nofail(r);
1694 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1695 struct termios old_termios, new_termios;
1702 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1703 new_termios = old_termios;
1705 new_termios.c_lflag &= ~ICANON;
1706 new_termios.c_cc[VMIN] = 1;
1707 new_termios.c_cc[VTIME] = 0;
1709 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1712 k = fread(&c, 1, 1, f);
1714 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1720 *need_nl = c != '\n';
1727 if (!(fgets(line, sizeof(line), f)))
1732 if (strlen(line) != 1)
1742 int ask(char *ret, const char *replies, const char *text, ...) {
1751 bool need_nl = true;
1753 fputs("\x1B[1m", stdout);
1759 fputs("\x1B[0m", stdout);
1763 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1765 if (r == -EBADMSG) {
1766 puts("Bad input, please try again.");
1777 if (strchr(replies, c)) {
1782 puts("Read unexpected character, please try again.");
1786 int reset_terminal(int fd) {
1787 struct termios termios;
1792 /* Set terminal to some sane defaults */
1794 if (tcgetattr(fd, &termios) < 0) {
1799 /* We only reset the stuff that matters to the software. How
1800 * hardware is set up we don't touch assuming that somebody
1801 * else will do that for us */
1803 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1804 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1805 termios.c_oflag |= ONLCR;
1806 termios.c_cflag |= CREAD;
1807 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1809 termios.c_cc[VINTR] = 03; /* ^C */
1810 termios.c_cc[VQUIT] = 034; /* ^\ */
1811 termios.c_cc[VERASE] = 0177;
1812 termios.c_cc[VKILL] = 025; /* ^X */
1813 termios.c_cc[VEOF] = 04; /* ^D */
1814 termios.c_cc[VSTART] = 021; /* ^Q */
1815 termios.c_cc[VSTOP] = 023; /* ^S */
1816 termios.c_cc[VSUSP] = 032; /* ^Z */
1817 termios.c_cc[VLNEXT] = 026; /* ^V */
1818 termios.c_cc[VWERASE] = 027; /* ^W */
1819 termios.c_cc[VREPRINT] = 022; /* ^R */
1820 termios.c_cc[VEOL] = 0;
1821 termios.c_cc[VEOL2] = 0;
1823 termios.c_cc[VTIME] = 0;
1824 termios.c_cc[VMIN] = 1;
1826 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1830 /* Just in case, flush all crap out */
1831 tcflush(fd, TCIOFLUSH);
1836 int open_terminal(const char *name, int mode) {
1839 if ((fd = open(name, mode)) < 0)
1842 if ((r = isatty(fd)) < 0) {
1843 close_nointr_nofail(fd);
1848 close_nointr_nofail(fd);
1855 int flush_fd(int fd) {
1856 struct pollfd pollfd;
1860 pollfd.events = POLLIN;
1867 if ((r = poll(&pollfd, 1, 0)) < 0) {
1878 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1883 if (errno == EAGAIN)
1894 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1895 int fd = -1, notify = -1, r, wd = -1;
1899 /* We use inotify to be notified when the tty is closed. We
1900 * create the watch before checking if we can actually acquire
1901 * it, so that we don't lose any event.
1903 * Note: strictly speaking this actually watches for the
1904 * device being closed, it does *not* really watch whether a
1905 * tty loses its controlling process. However, unless some
1906 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1907 * its tty otherwise this will not become a problem. As long
1908 * as the administrator makes sure not configure any service
1909 * on the same tty as an untrusted user this should not be a
1910 * problem. (Which he probably should not do anyway.) */
1912 if (!fail && !force) {
1913 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1918 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1926 if ((r = flush_fd(notify)) < 0)
1929 /* We pass here O_NOCTTY only so that we can check the return
1930 * value TIOCSCTTY and have a reliable way to figure out if we
1931 * successfully became the controlling process of the tty */
1932 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1935 /* First, try to get the tty */
1936 r = ioctl(fd, TIOCSCTTY, force);
1938 /* Sometimes it makes sense to ignore TIOCSCTTY
1939 * returning EPERM, i.e. when very likely we already
1940 * are have this controlling terminal. */
1941 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1944 if (r < 0 && (force || fail || errno != EPERM)) {
1954 assert(notify >= 0);
1957 struct inotify_event e;
1960 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1974 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1982 /* We close the tty fd here since if the old session
1983 * ended our handle will be dead. It's important that
1984 * we do this after sleeping, so that we don't enter
1985 * an endless loop. */
1986 close_nointr_nofail(fd);
1990 close_nointr_nofail(notify);
1992 if ((r = reset_terminal(fd)) < 0)
1993 log_warning("Failed to reset terminal: %s", strerror(-r));
1999 close_nointr_nofail(fd);
2002 close_nointr_nofail(notify);
2007 int release_terminal(void) {
2009 struct sigaction sa_old, sa_new;
2011 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2014 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2015 * by our own TIOCNOTTY */
2018 sa_new.sa_handler = SIG_IGN;
2019 sa_new.sa_flags = SA_RESTART;
2020 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2022 if (ioctl(fd, TIOCNOTTY) < 0)
2025 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2027 close_nointr_nofail(fd);
2031 int sigaction_many(const struct sigaction *sa, ...) {
2036 while ((sig = va_arg(ap, int)) > 0)
2037 if (sigaction(sig, sa, NULL) < 0)
2044 int ignore_signals(int sig, ...) {
2045 struct sigaction sa;
2050 sa.sa_handler = SIG_IGN;
2051 sa.sa_flags = SA_RESTART;
2053 if (sigaction(sig, &sa, NULL) < 0)
2057 while ((sig = va_arg(ap, int)) > 0)
2058 if (sigaction(sig, &sa, NULL) < 0)
2065 int default_signals(int sig, ...) {
2066 struct sigaction sa;
2071 sa.sa_handler = SIG_DFL;
2072 sa.sa_flags = SA_RESTART;
2074 if (sigaction(sig, &sa, NULL) < 0)
2078 while ((sig = va_arg(ap, int)) > 0)
2079 if (sigaction(sig, &sa, NULL) < 0)
2086 int close_pipe(int p[]) {
2092 a = close_nointr(p[0]);
2097 b = close_nointr(p[1]);
2101 return a < 0 ? a : b;
2104 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2113 while (nbytes > 0) {
2116 if ((k = read(fd, p, nbytes)) <= 0) {
2118 if (k < 0 && errno == EINTR)
2121 if (k < 0 && errno == EAGAIN && do_poll) {
2122 struct pollfd pollfd;
2126 pollfd.events = POLLIN;
2128 if (poll(&pollfd, 1, -1) < 0) {
2132 return n > 0 ? n : -errno;
2135 if (pollfd.revents != POLLIN)
2136 return n > 0 ? n : -EIO;
2141 return n > 0 ? n : (k < 0 ? -errno : 0);
2152 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2161 while (nbytes > 0) {
2164 if ((k = write(fd, p, nbytes)) <= 0) {
2166 if (k < 0 && errno == EINTR)
2169 if (k < 0 && errno == EAGAIN && do_poll) {
2170 struct pollfd pollfd;
2174 pollfd.events = POLLOUT;
2176 if (poll(&pollfd, 1, -1) < 0) {
2180 return n > 0 ? n : -errno;
2183 if (pollfd.revents != POLLOUT)
2184 return n > 0 ? n : -EIO;
2189 return n > 0 ? n : (k < 0 ? -errno : 0);
2200 int path_is_mount_point(const char *t) {
2204 if (lstat(t, &a) < 0) {
2206 if (errno == ENOENT)
2212 if (!(copy = strdup(t)))
2215 if (lstat(dirname(copy), &b) < 0) {
2222 return a.st_dev != b.st_dev;
2225 int parse_usec(const char *t, usec_t *usec) {
2226 static const struct {
2230 { "sec", USEC_PER_SEC },
2231 { "s", USEC_PER_SEC },
2232 { "min", USEC_PER_MINUTE },
2233 { "hr", USEC_PER_HOUR },
2234 { "h", USEC_PER_HOUR },
2235 { "d", USEC_PER_DAY },
2236 { "w", USEC_PER_WEEK },
2237 { "msec", USEC_PER_MSEC },
2238 { "ms", USEC_PER_MSEC },
2239 { "m", USEC_PER_MINUTE },
2242 { "", USEC_PER_SEC },
2258 l = strtoll(p, &e, 10);
2269 e += strspn(e, WHITESPACE);
2271 for (i = 0; i < ELEMENTSOF(table); i++)
2272 if (startswith(e, table[i].suffix)) {
2273 r += (usec_t) l * table[i].usec;
2274 p = e + strlen(table[i].suffix);
2278 if (i >= ELEMENTSOF(table))
2288 int make_stdio(int fd) {
2293 r = dup2(fd, STDIN_FILENO);
2294 s = dup2(fd, STDOUT_FILENO);
2295 t = dup2(fd, STDERR_FILENO);
2298 close_nointr_nofail(fd);
2300 if (r < 0 || s < 0 || t < 0)
2306 bool is_clean_exit(int code, int status) {
2308 if (code == CLD_EXITED)
2311 /* If a daemon does not implement handlers for some of the
2312 * signals that's not considered an unclean shutdown */
2313 if (code == CLD_KILLED)
2317 status == SIGTERM ||
2323 bool is_device_path(const char *path) {
2325 /* Returns true on paths that refer to a device, either in
2326 * sysfs or in /dev */
2329 path_startswith(path, "/dev/") ||
2330 path_startswith(path, "/sys/");
2333 int dir_is_empty(const char *path) {
2336 struct dirent buf, *de;
2338 if (!(d = opendir(path)))
2342 if ((r = readdir_r(d, &buf, &de)) > 0) {
2352 if (!ignore_file(de->d_name)) {
2362 unsigned long long random_ull(void) {
2367 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2370 r = loop_read(fd, &ull, sizeof(ull), true);
2371 close_nointr_nofail(fd);
2373 if (r != sizeof(ull))
2379 return random() * RAND_MAX + random();
2382 void rename_process(const char name[8]) {
2385 prctl(PR_SET_NAME, name);
2387 /* This is a like a poor man's setproctitle(). The string
2388 * passed should fit in 7 chars (i.e. the length of
2391 if (program_invocation_name)
2392 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2395 void sigset_add_many(sigset_t *ss, ...) {
2402 while ((sig = va_arg(ap, int)) > 0)
2403 assert_se(sigaddset(ss, sig) == 0);
2407 char* gethostname_malloc(void) {
2410 assert_se(uname(&u) >= 0);
2413 return strdup(u.nodename);
2415 return strdup(u.sysname);
2418 int getmachineid_malloc(char **b) {
2423 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2430 char* getlogname_malloc(void) {
2434 struct passwd pwbuf, *pw = NULL;
2437 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2442 /* Shortcut things to avoid NSS lookups */
2444 return strdup("root");
2446 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2449 if (!(buf = malloc(bufsize)))
2452 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2453 name = strdup(pw->pw_name);
2460 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2466 int getttyname_malloc(char **r) {
2467 char path[PATH_MAX], *p, *c;
2471 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2477 if (startswith(path, "/dev/"))
2480 if (!(c = strdup(p)))
2487 static int rm_rf_children(int fd, bool only_dirs) {
2493 /* This returns the first error we run into, but nevertheless
2496 if (!(d = fdopendir(fd))) {
2497 close_nointr_nofail(fd);
2502 struct dirent buf, *de;
2506 if ((r = readdir_r(d, &buf, &de)) != 0) {
2515 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2518 if (de->d_type == DT_UNKNOWN) {
2521 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2527 is_dir = S_ISDIR(st.st_mode);
2529 is_dir = de->d_type == DT_DIR;
2534 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2540 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2545 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2549 } else if (!only_dirs) {
2551 if (unlinkat(fd, de->d_name, 0) < 0) {
2563 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2569 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2571 if (errno != ENOTDIR)
2574 if (delete_root && !only_dirs)
2575 if (unlink(path) < 0)
2581 r = rm_rf_children(fd, only_dirs);
2584 if (rmdir(path) < 0) {
2592 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2595 /* Under the assumption that we are running privileged we
2596 * first change the access mode and only then hand out
2597 * ownership to avoid a window where access is too open. */
2599 if (chmod(path, mode) < 0)
2602 if (chown(path, uid, gid) < 0)
2608 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2612 /* Allocates the cpuset in the right size */
2615 if (!(r = CPU_ALLOC(n)))
2618 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2619 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2629 if (errno != EINVAL)
2636 void status_vprintf(const char *format, va_list ap) {
2642 /* This independent of logging, as status messages are
2643 * optional and go exclusively to the console. */
2645 if (vasprintf(&s, format, ap) < 0)
2648 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2651 write(fd, s, strlen(s));
2657 close_nointr_nofail(fd);
2660 void status_printf(const char *format, ...) {
2665 va_start(ap, format);
2666 status_vprintf(format, ap);
2670 void status_welcome(void) {
2672 #if defined(TARGET_FEDORA)
2675 if (read_one_line_file("/etc/system-release", &r) < 0)
2680 /* This tries to mimic the color magic the old Red Hat sysinit
2683 if (startswith(r, "Red Hat"))
2684 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2685 else if (startswith(r, "Fedora"))
2686 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2688 status_printf("Welcome to %s!\n", r);
2692 #elif defined(TARGET_SUSE)
2695 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2700 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2703 #warning "You probably should add a welcome text logic here."
2707 char *replace_env(const char *format, char **env) {
2714 const char *e, *word = format;
2719 for (e = format; *e; e ++) {
2730 if (!(k = strnappend(r, word, e-word-1)))
2739 } else if (*e == '$') {
2740 if (!(k = strnappend(r, word, e-word)))
2756 if ((t = strv_env_get_with_length(env, word+2, e-word-2))) {
2757 if (!(k = strappend(r, t)))
2772 if (!(k = strnappend(r, word, e-word)))
2783 char **replace_env_argv(char **argv, char **env) {
2787 if (!(r = new(char*, strv_length(argv)+1)))
2790 STRV_FOREACH(i, argv) {
2791 if (!(r[k++] = replace_env(*i, env))) {
2801 static const char *const ioprio_class_table[] = {
2802 [IOPRIO_CLASS_NONE] = "none",
2803 [IOPRIO_CLASS_RT] = "realtime",
2804 [IOPRIO_CLASS_BE] = "best-effort",
2805 [IOPRIO_CLASS_IDLE] = "idle"
2808 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2810 static const char *const sigchld_code_table[] = {
2811 [CLD_EXITED] = "exited",
2812 [CLD_KILLED] = "killed",
2813 [CLD_DUMPED] = "dumped",
2814 [CLD_TRAPPED] = "trapped",
2815 [CLD_STOPPED] = "stopped",
2816 [CLD_CONTINUED] = "continued",
2819 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2821 static const char *const log_facility_table[LOG_NFACILITIES] = {
2822 [LOG_FAC(LOG_KERN)] = "kern",
2823 [LOG_FAC(LOG_USER)] = "user",
2824 [LOG_FAC(LOG_MAIL)] = "mail",
2825 [LOG_FAC(LOG_DAEMON)] = "daemon",
2826 [LOG_FAC(LOG_AUTH)] = "auth",
2827 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2828 [LOG_FAC(LOG_LPR)] = "lpr",
2829 [LOG_FAC(LOG_NEWS)] = "news",
2830 [LOG_FAC(LOG_UUCP)] = "uucp",
2831 [LOG_FAC(LOG_CRON)] = "cron",
2832 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2833 [LOG_FAC(LOG_FTP)] = "ftp",
2834 [LOG_FAC(LOG_LOCAL0)] = "local0",
2835 [LOG_FAC(LOG_LOCAL1)] = "local1",
2836 [LOG_FAC(LOG_LOCAL2)] = "local2",
2837 [LOG_FAC(LOG_LOCAL3)] = "local3",
2838 [LOG_FAC(LOG_LOCAL4)] = "local4",
2839 [LOG_FAC(LOG_LOCAL5)] = "local5",
2840 [LOG_FAC(LOG_LOCAL6)] = "local6",
2841 [LOG_FAC(LOG_LOCAL7)] = "local7"
2844 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2846 static const char *const log_level_table[] = {
2847 [LOG_EMERG] = "emerg",
2848 [LOG_ALERT] = "alert",
2849 [LOG_CRIT] = "crit",
2851 [LOG_WARNING] = "warning",
2852 [LOG_NOTICE] = "notice",
2853 [LOG_INFO] = "info",
2854 [LOG_DEBUG] = "debug"
2857 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2859 static const char* const sched_policy_table[] = {
2860 [SCHED_OTHER] = "other",
2861 [SCHED_BATCH] = "batch",
2862 [SCHED_IDLE] = "idle",
2863 [SCHED_FIFO] = "fifo",
2867 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2869 static const char* const rlimit_table[] = {
2870 [RLIMIT_CPU] = "LimitCPU",
2871 [RLIMIT_FSIZE] = "LimitFSIZE",
2872 [RLIMIT_DATA] = "LimitDATA",
2873 [RLIMIT_STACK] = "LimitSTACK",
2874 [RLIMIT_CORE] = "LimitCORE",
2875 [RLIMIT_RSS] = "LimitRSS",
2876 [RLIMIT_NOFILE] = "LimitNOFILE",
2877 [RLIMIT_AS] = "LimitAS",
2878 [RLIMIT_NPROC] = "LimitNPROC",
2879 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2880 [RLIMIT_LOCKS] = "LimitLOCKS",
2881 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2882 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2883 [RLIMIT_NICE] = "LimitNICE",
2884 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2885 [RLIMIT_RTTIME] = "LimitRTTIME"
2888 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2890 static const char* const ip_tos_table[] = {
2891 [IPTOS_LOWDELAY] = "low-delay",
2892 [IPTOS_THROUGHPUT] = "throughput",
2893 [IPTOS_RELIABILITY] = "reliability",
2894 [IPTOS_LOWCOST] = "low-cost",
2897 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);