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 *strappend(const char *s, const char *suffix) {
626 if (!(r = new(char, a+b+1)))
630 memcpy(r+a, suffix, b);
636 int readlink_malloc(const char *p, char **r) {
646 if (!(c = new(char, l)))
649 if ((n = readlink(p, c, l-1)) < 0) {
655 if ((size_t) n < l-1) {
666 int readlink_and_make_absolute(const char *p, char **r) {
673 if ((j = readlink_malloc(p, &target)) < 0)
676 k = file_in_same_dir(p, target);
686 char *file_name_from_path(const char *p) {
691 if ((r = strrchr(p, '/')))
697 bool path_is_absolute(const char *p) {
703 bool is_path(const char *p) {
705 return !!strchr(p, '/');
708 char *path_make_absolute(const char *p, const char *prefix) {
713 /* Makes every item in the list an absolute path by prepending
714 * the prefix, if specified and necessary */
716 if (path_is_absolute(p) || !prefix)
719 if (asprintf(&r, "%s/%s", prefix, p) < 0)
725 char *path_make_absolute_cwd(const char *p) {
730 /* Similar to path_make_absolute(), but prefixes with the
731 * current working directory. */
733 if (path_is_absolute(p))
736 if (!(cwd = get_current_dir_name()))
739 r = path_make_absolute(p, cwd);
745 char **strv_path_make_absolute_cwd(char **l) {
748 /* Goes through every item in the string list and makes it
749 * absolute. This works in place and won't rollback any
750 * changes on failure. */
755 if (!(t = path_make_absolute_cwd(*s)))
765 char **strv_path_canonicalize(char **l) {
773 /* Goes through every item in the string list and canonicalize
774 * the path. This works in place and won't rollback any
775 * changes on failure. */
780 t = path_make_absolute_cwd(*s);
789 u = canonicalize_file_name(t);
793 if (errno == ENOMEM || !errno)
810 int reset_all_signal_handlers(void) {
813 for (sig = 1; sig < _NSIG; sig++) {
816 if (sig == SIGKILL || sig == SIGSTOP)
820 sa.sa_handler = SIG_DFL;
821 sa.sa_flags = SA_RESTART;
823 /* On Linux the first two RT signals are reserved by
824 * glibc, and sigaction() will return EINVAL for them. */
825 if ((sigaction(sig, &sa, NULL) < 0))
833 char *strstrip(char *s) {
836 /* Drops trailing whitespace. Modifies the string in
837 * place. Returns pointer to first non-space character */
839 s += strspn(s, WHITESPACE);
842 if (!strchr(WHITESPACE, *e))
853 char *delete_chars(char *s, const char *bad) {
856 /* Drops all whitespace, regardless where in the string */
858 for (f = s, t = s; *f; f++) {
870 char *file_in_same_dir(const char *path, const char *filename) {
877 /* This removes the last component of path and appends
878 * filename, unless the latter is absolute anyway or the
881 if (path_is_absolute(filename))
882 return strdup(filename);
884 if (!(e = strrchr(path, '/')))
885 return strdup(filename);
887 k = strlen(filename);
888 if (!(r = new(char, e-path+1+k+1)))
891 memcpy(r, path, e-path+1);
892 memcpy(r+(e-path)+1, filename, k+1);
897 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
900 if (mkdir(path, mode) >= 0)
901 if (chmod_and_chown(path, mode, uid, gid) < 0)
904 if (lstat(path, &st) < 0)
907 if ((st.st_mode & 0777) != mode ||
910 !S_ISDIR(st.st_mode)) {
919 int mkdir_parents(const char *path, mode_t mode) {
924 /* Creates every parent directory in the path except the last
927 p = path + strspn(path, "/");
932 e = p + strcspn(p, "/");
933 p = e + strspn(e, "/");
935 /* Is this the last component? If so, then we're
940 if (!(t = strndup(path, e - path)))
947 if (r < 0 && errno != EEXIST)
952 int mkdir_p(const char *path, mode_t mode) {
957 if ((r = mkdir_parents(path, mode)) < 0)
960 if (mkdir(path, mode) < 0)
966 int rmdir_parents(const char *path, const char *stop) {
975 /* Skip trailing slashes */
976 while (l > 0 && path[l-1] == '/')
982 /* Skip last component */
983 while (l > 0 && path[l-1] != '/')
986 /* Skip trailing slashes */
987 while (l > 0 && path[l-1] == '/')
993 if (!(t = strndup(path, l)))
996 if (path_startswith(stop, t)) {
1005 if (errno != ENOENT)
1013 char hexchar(int x) {
1014 static const char table[16] = "0123456789abcdef";
1016 return table[x & 15];
1019 int unhexchar(char c) {
1021 if (c >= '0' && c <= '9')
1024 if (c >= 'a' && c <= 'f')
1025 return c - 'a' + 10;
1027 if (c >= 'A' && c <= 'F')
1028 return c - 'A' + 10;
1033 char octchar(int x) {
1034 return '0' + (x & 7);
1037 int unoctchar(char c) {
1039 if (c >= '0' && c <= '7')
1045 char decchar(int x) {
1046 return '0' + (x % 10);
1049 int undecchar(char c) {
1051 if (c >= '0' && c <= '9')
1057 char *cescape(const char *s) {
1063 /* Does C style string escaping. */
1065 if (!(r = new(char, strlen(s)*4 + 1)))
1068 for (f = s, t = r; *f; f++)
1114 /* For special chars we prefer octal over
1115 * hexadecimal encoding, simply because glib's
1116 * g_strescape() does the same */
1117 if ((*f < ' ') || (*f >= 127)) {
1119 *(t++) = octchar((unsigned char) *f >> 6);
1120 *(t++) = octchar((unsigned char) *f >> 3);
1121 *(t++) = octchar((unsigned char) *f);
1132 char *cunescape_length(const char *s, size_t length) {
1138 /* Undoes C style string escaping */
1140 if (!(r = new(char, length+1)))
1143 for (f = s, t = r; f < s + length; f++) {
1186 /* This is an extension of the XDG syntax files */
1191 /* hexadecimal encoding */
1194 if ((a = unhexchar(f[1])) < 0 ||
1195 (b = unhexchar(f[2])) < 0) {
1196 /* Invalid escape code, let's take it literal then */
1200 *(t++) = (char) ((a << 4) | b);
1215 /* octal encoding */
1218 if ((a = unoctchar(f[0])) < 0 ||
1219 (b = unoctchar(f[1])) < 0 ||
1220 (c = unoctchar(f[2])) < 0) {
1221 /* Invalid escape code, let's take it literal then */
1225 *(t++) = (char) ((a << 6) | (b << 3) | c);
1233 /* premature end of string.*/
1238 /* Invalid escape code, let's take it literal then */
1250 char *cunescape(const char *s) {
1251 return cunescape_length(s, strlen(s));
1254 char *xescape(const char *s, const char *bad) {
1258 /* Escapes all chars in bad, in addition to \ and all special
1259 * chars, in \xFF style escaping. May be reversed with
1262 if (!(r = new(char, strlen(s)*4+1)))
1265 for (f = s, t = r; *f; f++) {
1267 if ((*f < ' ') || (*f >= 127) ||
1268 (*f == '\\') || strchr(bad, *f)) {
1271 *(t++) = hexchar(*f >> 4);
1272 *(t++) = hexchar(*f);
1282 char *bus_path_escape(const char *s) {
1288 /* Escapes all chars that D-Bus' object path cannot deal
1289 * with. Can be reverse with bus_path_unescape() */
1291 if (!(r = new(char, strlen(s)*3+1)))
1294 for (f = s, t = r; *f; f++) {
1296 if (!(*f >= 'A' && *f <= 'Z') &&
1297 !(*f >= 'a' && *f <= 'z') &&
1298 !(*f >= '0' && *f <= '9')) {
1300 *(t++) = hexchar(*f >> 4);
1301 *(t++) = hexchar(*f);
1311 char *bus_path_unescape(const char *f) {
1316 if (!(r = strdup(f)))
1319 for (t = r; *f; f++) {
1324 if ((a = unhexchar(f[1])) < 0 ||
1325 (b = unhexchar(f[2])) < 0) {
1326 /* Invalid escape code, let's take it literal then */
1329 *(t++) = (char) ((a << 4) | b);
1341 char *path_kill_slashes(char *path) {
1345 /* Removes redundant inner and trailing slashes. Modifies the
1346 * passed string in-place.
1348 * ///foo///bar/ becomes /foo/bar
1351 for (f = path, t = path; *f; f++) {
1366 /* Special rule, if we are talking of the root directory, a
1367 trailing slash is good */
1369 if (t == path && slash)
1376 bool path_startswith(const char *path, const char *prefix) {
1380 if ((path[0] == '/') != (prefix[0] == '/'))
1386 path += strspn(path, "/");
1387 prefix += strspn(prefix, "/");
1395 a = strcspn(path, "/");
1396 b = strcspn(prefix, "/");
1401 if (memcmp(path, prefix, a) != 0)
1409 bool path_equal(const char *a, const char *b) {
1413 if ((a[0] == '/') != (b[0] == '/'))
1419 a += strspn(a, "/");
1420 b += strspn(b, "/");
1422 if (*a == 0 && *b == 0)
1425 if (*a == 0 || *b == 0)
1428 j = strcspn(a, "/");
1429 k = strcspn(b, "/");
1434 if (memcmp(a, b, j) != 0)
1442 char *ascii_strlower(char *t) {
1447 for (p = t; *p; p++)
1448 if (*p >= 'A' && *p <= 'Z')
1449 *p = *p - 'A' + 'a';
1454 bool ignore_file(const char *filename) {
1458 filename[0] == '.' ||
1459 streq(filename, "lost+found") ||
1460 endswith(filename, "~") ||
1461 endswith(filename, ".rpmnew") ||
1462 endswith(filename, ".rpmsave") ||
1463 endswith(filename, ".rpmorig") ||
1464 endswith(filename, ".dpkg-old") ||
1465 endswith(filename, ".dpkg-new") ||
1466 endswith(filename, ".swp");
1469 int fd_nonblock(int fd, bool nonblock) {
1474 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1478 flags |= O_NONBLOCK;
1480 flags &= ~O_NONBLOCK;
1482 if (fcntl(fd, F_SETFL, flags) < 0)
1488 int fd_cloexec(int fd, bool cloexec) {
1493 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1497 flags |= FD_CLOEXEC;
1499 flags &= ~FD_CLOEXEC;
1501 if (fcntl(fd, F_SETFD, flags) < 0)
1507 int close_all_fds(const int except[], unsigned n_except) {
1512 if (!(d = opendir("/proc/self/fd")))
1515 while ((de = readdir(d))) {
1518 if (ignore_file(de->d_name))
1521 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1535 for (i = 0; i < n_except; i++)
1536 if (except[i] == fd) {
1545 if ((r = close_nointr(fd)) < 0) {
1546 /* Valgrind has its own FD and doesn't want to have it closed */
1559 bool chars_intersect(const char *a, const char *b) {
1562 /* Returns true if any of the chars in a are in b. */
1563 for (p = a; *p; p++)
1570 char *format_timestamp(char *buf, size_t l, usec_t t) {
1580 sec = (time_t) (t / USEC_PER_SEC);
1582 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1588 char *format_timespan(char *buf, size_t l, usec_t t) {
1589 static const struct {
1593 { "w", USEC_PER_WEEK },
1594 { "d", USEC_PER_DAY },
1595 { "h", USEC_PER_HOUR },
1596 { "min", USEC_PER_MINUTE },
1597 { "s", USEC_PER_SEC },
1598 { "ms", USEC_PER_MSEC },
1608 if (t == (usec_t) -1)
1611 /* The result of this function can be parsed with parse_usec */
1613 for (i = 0; i < ELEMENTSOF(table); i++) {
1617 if (t < table[i].usec)
1623 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1624 n = MIN((size_t) k, l);
1637 bool fstype_is_network(const char *fstype) {
1638 static const char * const table[] = {
1650 for (i = 0; i < ELEMENTSOF(table); i++)
1651 if (streq(table[i], fstype))
1660 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1665 TIOCL_GETKMSGREDIRECT,
1669 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1672 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1675 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1678 close_nointr_nofail(r);
1682 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1683 struct termios old_termios, new_termios;
1690 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1691 new_termios = old_termios;
1693 new_termios.c_lflag &= ~ICANON;
1694 new_termios.c_cc[VMIN] = 1;
1695 new_termios.c_cc[VTIME] = 0;
1697 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1700 k = fread(&c, 1, 1, f);
1702 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1708 *need_nl = c != '\n';
1715 if (!(fgets(line, sizeof(line), f)))
1720 if (strlen(line) != 1)
1730 int ask(char *ret, const char *replies, const char *text, ...) {
1739 bool need_nl = true;
1741 fputs("\x1B[1m", stdout);
1747 fputs("\x1B[0m", stdout);
1751 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1753 if (r == -EBADMSG) {
1754 puts("Bad input, please try again.");
1765 if (strchr(replies, c)) {
1770 puts("Read unexpected character, please try again.");
1774 int reset_terminal(int fd) {
1775 struct termios termios;
1780 /* Set terminal to some sane defaults */
1782 if (tcgetattr(fd, &termios) < 0) {
1787 /* We only reset the stuff that matters to the software. How
1788 * hardware is set up we don't touch assuming that somebody
1789 * else will do that for us */
1791 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1792 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1793 termios.c_oflag |= ONLCR;
1794 termios.c_cflag |= CREAD;
1795 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1797 termios.c_cc[VINTR] = 03; /* ^C */
1798 termios.c_cc[VQUIT] = 034; /* ^\ */
1799 termios.c_cc[VERASE] = 0177;
1800 termios.c_cc[VKILL] = 025; /* ^X */
1801 termios.c_cc[VEOF] = 04; /* ^D */
1802 termios.c_cc[VSTART] = 021; /* ^Q */
1803 termios.c_cc[VSTOP] = 023; /* ^S */
1804 termios.c_cc[VSUSP] = 032; /* ^Z */
1805 termios.c_cc[VLNEXT] = 026; /* ^V */
1806 termios.c_cc[VWERASE] = 027; /* ^W */
1807 termios.c_cc[VREPRINT] = 022; /* ^R */
1808 termios.c_cc[VEOL] = 0;
1809 termios.c_cc[VEOL2] = 0;
1811 termios.c_cc[VTIME] = 0;
1812 termios.c_cc[VMIN] = 1;
1814 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1818 /* Just in case, flush all crap out */
1819 tcflush(fd, TCIOFLUSH);
1824 int open_terminal(const char *name, int mode) {
1827 if ((fd = open(name, mode)) < 0)
1830 if ((r = isatty(fd)) < 0) {
1831 close_nointr_nofail(fd);
1836 close_nointr_nofail(fd);
1843 int flush_fd(int fd) {
1844 struct pollfd pollfd;
1848 pollfd.events = POLLIN;
1855 if ((r = poll(&pollfd, 1, 0)) < 0) {
1866 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1871 if (errno == EAGAIN)
1882 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1883 int fd = -1, notify = -1, r, wd = -1;
1887 /* We use inotify to be notified when the tty is closed. We
1888 * create the watch before checking if we can actually acquire
1889 * it, so that we don't lose any event.
1891 * Note: strictly speaking this actually watches for the
1892 * device being closed, it does *not* really watch whether a
1893 * tty loses its controlling process. However, unless some
1894 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1895 * its tty otherwise this will not become a problem. As long
1896 * as the administrator makes sure not configure any service
1897 * on the same tty as an untrusted user this should not be a
1898 * problem. (Which he probably should not do anyway.) */
1900 if (!fail && !force) {
1901 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1906 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1914 if ((r = flush_fd(notify)) < 0)
1917 /* We pass here O_NOCTTY only so that we can check the return
1918 * value TIOCSCTTY and have a reliable way to figure out if we
1919 * successfully became the controlling process of the tty */
1920 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1923 /* First, try to get the tty */
1924 r = ioctl(fd, TIOCSCTTY, force);
1926 /* Sometimes it makes sense to ignore TIOCSCTTY
1927 * returning EPERM, i.e. when very likely we already
1928 * are have this controlling terminal. */
1929 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1932 if (r < 0 && (force || fail || errno != EPERM)) {
1942 assert(notify >= 0);
1945 struct inotify_event e;
1948 if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1962 if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1970 /* We close the tty fd here since if the old session
1971 * ended our handle will be dead. It's important that
1972 * we do this after sleeping, so that we don't enter
1973 * an endless loop. */
1974 close_nointr_nofail(fd);
1978 close_nointr_nofail(notify);
1980 if ((r = reset_terminal(fd)) < 0)
1981 log_warning("Failed to reset terminal: %s", strerror(-r));
1987 close_nointr_nofail(fd);
1990 close_nointr_nofail(notify);
1995 int release_terminal(void) {
1997 struct sigaction sa_old, sa_new;
1999 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2002 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2003 * by our own TIOCNOTTY */
2006 sa_new.sa_handler = SIG_IGN;
2007 sa_new.sa_flags = SA_RESTART;
2008 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2010 if (ioctl(fd, TIOCNOTTY) < 0)
2013 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2015 close_nointr_nofail(fd);
2019 int sigaction_many(const struct sigaction *sa, ...) {
2024 while ((sig = va_arg(ap, int)) > 0)
2025 if (sigaction(sig, sa, NULL) < 0)
2032 int ignore_signals(int sig, ...) {
2033 struct sigaction sa;
2038 sa.sa_handler = SIG_IGN;
2039 sa.sa_flags = SA_RESTART;
2041 if (sigaction(sig, &sa, NULL) < 0)
2045 while ((sig = va_arg(ap, int)) > 0)
2046 if (sigaction(sig, &sa, NULL) < 0)
2053 int default_signals(int sig, ...) {
2054 struct sigaction sa;
2059 sa.sa_handler = SIG_DFL;
2060 sa.sa_flags = SA_RESTART;
2062 if (sigaction(sig, &sa, NULL) < 0)
2066 while ((sig = va_arg(ap, int)) > 0)
2067 if (sigaction(sig, &sa, NULL) < 0)
2074 int close_pipe(int p[]) {
2080 a = close_nointr(p[0]);
2085 b = close_nointr(p[1]);
2089 return a < 0 ? a : b;
2092 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2101 while (nbytes > 0) {
2104 if ((k = read(fd, p, nbytes)) <= 0) {
2106 if (k < 0 && errno == EINTR)
2109 if (k < 0 && errno == EAGAIN && do_poll) {
2110 struct pollfd pollfd;
2114 pollfd.events = POLLIN;
2116 if (poll(&pollfd, 1, -1) < 0) {
2120 return n > 0 ? n : -errno;
2123 if (pollfd.revents != POLLIN)
2124 return n > 0 ? n : -EIO;
2129 return n > 0 ? n : (k < 0 ? -errno : 0);
2140 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2149 while (nbytes > 0) {
2152 if ((k = write(fd, p, nbytes)) <= 0) {
2154 if (k < 0 && errno == EINTR)
2157 if (k < 0 && errno == EAGAIN && do_poll) {
2158 struct pollfd pollfd;
2162 pollfd.events = POLLOUT;
2164 if (poll(&pollfd, 1, -1) < 0) {
2168 return n > 0 ? n : -errno;
2171 if (pollfd.revents != POLLOUT)
2172 return n > 0 ? n : -EIO;
2177 return n > 0 ? n : (k < 0 ? -errno : 0);
2188 int path_is_mount_point(const char *t) {
2192 if (lstat(t, &a) < 0) {
2194 if (errno == ENOENT)
2200 if (!(copy = strdup(t)))
2203 if (lstat(dirname(copy), &b) < 0) {
2210 return a.st_dev != b.st_dev;
2213 int parse_usec(const char *t, usec_t *usec) {
2214 static const struct {
2218 { "sec", USEC_PER_SEC },
2219 { "s", USEC_PER_SEC },
2220 { "min", USEC_PER_MINUTE },
2221 { "hr", USEC_PER_HOUR },
2222 { "h", USEC_PER_HOUR },
2223 { "d", USEC_PER_DAY },
2224 { "w", USEC_PER_WEEK },
2225 { "msec", USEC_PER_MSEC },
2226 { "ms", USEC_PER_MSEC },
2227 { "m", USEC_PER_MINUTE },
2230 { "", USEC_PER_SEC },
2246 l = strtoll(p, &e, 10);
2257 e += strspn(e, WHITESPACE);
2259 for (i = 0; i < ELEMENTSOF(table); i++)
2260 if (startswith(e, table[i].suffix)) {
2261 r += (usec_t) l * table[i].usec;
2262 p = e + strlen(table[i].suffix);
2266 if (i >= ELEMENTSOF(table))
2276 int make_stdio(int fd) {
2281 r = dup2(fd, STDIN_FILENO);
2282 s = dup2(fd, STDOUT_FILENO);
2283 t = dup2(fd, STDERR_FILENO);
2286 close_nointr_nofail(fd);
2288 if (r < 0 || s < 0 || t < 0)
2294 bool is_clean_exit(int code, int status) {
2296 if (code == CLD_EXITED)
2299 /* If a daemon does not implement handlers for some of the
2300 * signals that's not considered an unclean shutdown */
2301 if (code == CLD_KILLED)
2305 status == SIGTERM ||
2311 bool is_device_path(const char *path) {
2313 /* Returns true on paths that refer to a device, either in
2314 * sysfs or in /dev */
2317 path_startswith(path, "/dev/") ||
2318 path_startswith(path, "/sys/");
2321 int dir_is_empty(const char *path) {
2324 struct dirent buf, *de;
2326 if (!(d = opendir(path)))
2330 if ((r = readdir_r(d, &buf, &de)) > 0) {
2340 if (!ignore_file(de->d_name)) {
2350 unsigned long long random_ull(void) {
2355 if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2358 r = loop_read(fd, &ull, sizeof(ull), true);
2359 close_nointr_nofail(fd);
2361 if (r != sizeof(ull))
2367 return random() * RAND_MAX + random();
2370 void rename_process(const char name[8]) {
2373 prctl(PR_SET_NAME, name);
2375 /* This is a like a poor man's setproctitle(). The string
2376 * passed should fit in 7 chars (i.e. the length of
2379 if (program_invocation_name)
2380 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2383 void sigset_add_many(sigset_t *ss, ...) {
2390 while ((sig = va_arg(ap, int)) > 0)
2391 assert_se(sigaddset(ss, sig) == 0);
2395 char* gethostname_malloc(void) {
2398 assert_se(uname(&u) >= 0);
2401 return strdup(u.nodename);
2403 return strdup(u.sysname);
2406 int getmachineid_malloc(char **b) {
2411 if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2418 char* getlogname_malloc(void) {
2422 struct passwd pwbuf, *pw = NULL;
2425 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2430 /* Shortcut things to avoid NSS lookups */
2432 return strdup("root");
2434 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2437 if (!(buf = malloc(bufsize)))
2440 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2441 name = strdup(pw->pw_name);
2448 if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2454 int getttyname_malloc(char **r) {
2455 char path[PATH_MAX], *p, *c;
2459 if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2465 if (startswith(path, "/dev/"))
2468 if (!(c = strdup(p)))
2475 static int rm_rf_children(int fd, bool only_dirs) {
2481 /* This returns the first error we run into, but nevertheless
2484 if (!(d = fdopendir(fd))) {
2485 close_nointr_nofail(fd);
2490 struct dirent buf, *de;
2494 if ((r = readdir_r(d, &buf, &de)) != 0) {
2503 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2506 if (de->d_type == DT_UNKNOWN) {
2509 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2515 is_dir = S_ISDIR(st.st_mode);
2517 is_dir = de->d_type == DT_DIR;
2522 if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2528 if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2533 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2537 } else if (!only_dirs) {
2539 if (unlinkat(fd, de->d_name, 0) < 0) {
2551 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2557 if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2559 if (errno != ENOTDIR)
2562 if (delete_root && !only_dirs)
2563 if (unlink(path) < 0)
2569 r = rm_rf_children(fd, only_dirs);
2572 if (rmdir(path) < 0) {
2580 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2583 /* Under the assumption that we are running privileged we
2584 * first change the access mode and only then hand out
2585 * ownership to avoid a window where access is too open. */
2587 if (chmod(path, mode) < 0)
2590 if (chown(path, uid, gid) < 0)
2596 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2600 /* Allocates the cpuset in the right size */
2603 if (!(r = CPU_ALLOC(n)))
2606 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2607 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2617 if (errno != EINVAL)
2624 void status_vprintf(const char *format, va_list ap) {
2630 /* This independent of logging, as status messages are
2631 * optional and go exclusively to the console. */
2633 if (vasprintf(&s, format, ap) < 0)
2636 if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2639 write(fd, s, strlen(s));
2645 close_nointr_nofail(fd);
2648 void status_printf(const char *format, ...) {
2653 va_start(ap, format);
2654 status_vprintf(format, ap);
2658 void status_welcome(void) {
2660 #if defined(TARGET_FEDORA)
2663 if (read_one_line_file("/etc/system-release", &r) < 0)
2668 /* This tries to mimic the color magic the old Red Hat sysinit
2671 if (startswith(r, "Red Hat"))
2672 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
2673 else if (startswith(r, "Fedora"))
2674 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
2676 status_printf("Welcome to %s!\n", r);
2680 #elif defined(TARGET_SUSE)
2683 if (read_one_line_file("/etc/SuSE-release", &r) < 0)
2688 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
2691 #warning "You probably should add a welcome text logic here."
2695 static const char *const ioprio_class_table[] = {
2696 [IOPRIO_CLASS_NONE] = "none",
2697 [IOPRIO_CLASS_RT] = "realtime",
2698 [IOPRIO_CLASS_BE] = "best-effort",
2699 [IOPRIO_CLASS_IDLE] = "idle"
2702 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2704 static const char *const sigchld_code_table[] = {
2705 [CLD_EXITED] = "exited",
2706 [CLD_KILLED] = "killed",
2707 [CLD_DUMPED] = "dumped",
2708 [CLD_TRAPPED] = "trapped",
2709 [CLD_STOPPED] = "stopped",
2710 [CLD_CONTINUED] = "continued",
2713 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2715 static const char *const log_facility_table[LOG_NFACILITIES] = {
2716 [LOG_FAC(LOG_KERN)] = "kern",
2717 [LOG_FAC(LOG_USER)] = "user",
2718 [LOG_FAC(LOG_MAIL)] = "mail",
2719 [LOG_FAC(LOG_DAEMON)] = "daemon",
2720 [LOG_FAC(LOG_AUTH)] = "auth",
2721 [LOG_FAC(LOG_SYSLOG)] = "syslog",
2722 [LOG_FAC(LOG_LPR)] = "lpr",
2723 [LOG_FAC(LOG_NEWS)] = "news",
2724 [LOG_FAC(LOG_UUCP)] = "uucp",
2725 [LOG_FAC(LOG_CRON)] = "cron",
2726 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2727 [LOG_FAC(LOG_FTP)] = "ftp",
2728 [LOG_FAC(LOG_LOCAL0)] = "local0",
2729 [LOG_FAC(LOG_LOCAL1)] = "local1",
2730 [LOG_FAC(LOG_LOCAL2)] = "local2",
2731 [LOG_FAC(LOG_LOCAL3)] = "local3",
2732 [LOG_FAC(LOG_LOCAL4)] = "local4",
2733 [LOG_FAC(LOG_LOCAL5)] = "local5",
2734 [LOG_FAC(LOG_LOCAL6)] = "local6",
2735 [LOG_FAC(LOG_LOCAL7)] = "local7"
2738 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2740 static const char *const log_level_table[] = {
2741 [LOG_EMERG] = "emerg",
2742 [LOG_ALERT] = "alert",
2743 [LOG_CRIT] = "crit",
2745 [LOG_WARNING] = "warning",
2746 [LOG_NOTICE] = "notice",
2747 [LOG_INFO] = "info",
2748 [LOG_DEBUG] = "debug"
2751 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2753 static const char* const sched_policy_table[] = {
2754 [SCHED_OTHER] = "other",
2755 [SCHED_BATCH] = "batch",
2756 [SCHED_IDLE] = "idle",
2757 [SCHED_FIFO] = "fifo",
2761 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2763 static const char* const rlimit_table[] = {
2764 [RLIMIT_CPU] = "LimitCPU",
2765 [RLIMIT_FSIZE] = "LimitFSIZE",
2766 [RLIMIT_DATA] = "LimitDATA",
2767 [RLIMIT_STACK] = "LimitSTACK",
2768 [RLIMIT_CORE] = "LimitCORE",
2769 [RLIMIT_RSS] = "LimitRSS",
2770 [RLIMIT_NOFILE] = "LimitNOFILE",
2771 [RLIMIT_AS] = "LimitAS",
2772 [RLIMIT_NPROC] = "LimitNPROC",
2773 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2774 [RLIMIT_LOCKS] = "LimitLOCKS",
2775 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2776 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2777 [RLIMIT_NICE] = "LimitNICE",
2778 [RLIMIT_RTPRIO] = "LimitRTPRIO",
2779 [RLIMIT_RTTIME] = "LimitRTTIME"
2782 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
2784 static const char* const ip_tos_table[] = {
2785 [IPTOS_LOWDELAY] = "low-delay",
2786 [IPTOS_THROUGHPUT] = "throughput",
2787 [IPTOS_RELIABILITY] = "reliability",
2788 [IPTOS_LOWCOST] = "low-cost",
2791 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);