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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser 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>
44 #include <sys/prctl.h>
45 #include <sys/utsname.h>
47 #include <netinet/ip.h>
55 #include <sys/mount.h>
56 #include <linux/magic.h>
60 #include <sys/personality.h>
61 #include <sys/xattr.h>
62 #include <sys/statvfs.h>
66 /* When we include libgen.h because we need dirname() we immediately
67 * undefine basename() since libgen.h defines it as a macro to the XDG
68 * version which is really broken. */
72 #ifdef HAVE_SYS_AUXV_H
84 #include "path-util.h"
85 #include "exit-status.h"
89 #include "device-nodes.h"
94 #include "sparse-endian.h"
95 #include "formats-util.h"
96 #include "process-util.h"
98 /* Put this test here for a lack of better place */
99 assert_cc(EAGAIN == EWOULDBLOCK);
102 char **saved_argv = NULL;
104 static volatile unsigned cached_columns = 0;
105 static volatile unsigned cached_lines = 0;
107 size_t page_size(void) {
108 static thread_local size_t pgsz = 0;
111 if (_likely_(pgsz > 0))
114 r = sysconf(_SC_PAGESIZE);
121 bool streq_ptr(const char *a, const char *b) {
123 /* Like streq(), but tries to make sense of NULL pointers */
134 char* endswith(const char *s, const char *postfix) {
141 pl = strlen(postfix);
144 return (char*) s + sl;
149 if (memcmp(s + sl - pl, postfix, pl) != 0)
152 return (char*) s + sl - pl;
155 char* first_word(const char *s, const char *word) {
162 /* Checks if the string starts with the specified word, either
163 * followed by NUL or by whitespace. Returns a pointer to the
164 * NUL or the first character after the whitespace. */
175 if (memcmp(s, word, wl) != 0)
182 if (!strchr(WHITESPACE, *p))
185 p += strspn(p, WHITESPACE);
189 size_t cescape_char(char c, char *buf) {
190 char * buf_old = buf;
236 /* For special chars we prefer octal over
237 * hexadecimal encoding, simply because glib's
238 * g_strescape() does the same */
239 if ((c < ' ') || (c >= 127)) {
241 *(buf++) = octchar((unsigned char) c >> 6);
242 *(buf++) = octchar((unsigned char) c >> 3);
243 *(buf++) = octchar((unsigned char) c);
249 return buf - buf_old;
252 int close_nointr(int fd) {
259 * Just ignore EINTR; a retry loop is the wrong thing to do on
262 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
263 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
264 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
265 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
273 int safe_close(int fd) {
276 * Like close_nointr() but cannot fail. Guarantees errno is
277 * unchanged. Is a NOP with negative fds passed, and returns
278 * -1, so that it can be used in this syntax:
280 * fd = safe_close(fd);
286 /* The kernel might return pretty much any error code
287 * via close(), but the fd will be closed anyway. The
288 * only condition we want to check for here is whether
289 * the fd was invalid at all... */
291 assert_se(close_nointr(fd) != -EBADF);
297 void close_many(const int fds[], unsigned n_fd) {
300 assert(fds || n_fd <= 0);
302 for (i = 0; i < n_fd; i++)
306 int unlink_noerrno(const char *path) {
317 int parse_boolean(const char *v) {
320 if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
322 else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
328 int parse_pid(const char *s, pid_t* ret_pid) {
329 unsigned long ul = 0;
336 r = safe_atolu(s, &ul);
342 if ((unsigned long) pid != ul)
352 int parse_uid(const char *s, uid_t* ret_uid) {
353 unsigned long ul = 0;
360 r = safe_atolu(s, &ul);
366 if ((unsigned long) uid != ul)
369 /* Some libc APIs use UID_INVALID as special placeholder */
370 if (uid == (uid_t) 0xFFFFFFFF)
373 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
374 if (uid == (uid_t) 0xFFFF)
381 int safe_atou(const char *s, unsigned *ret_u) {
389 l = strtoul(s, &x, 0);
391 if (!x || x == s || *x || errno)
392 return errno > 0 ? -errno : -EINVAL;
394 if ((unsigned long) (unsigned) l != l)
397 *ret_u = (unsigned) l;
401 int safe_atoi(const char *s, int *ret_i) {
409 l = strtol(s, &x, 0);
411 if (!x || x == s || *x || errno)
412 return errno > 0 ? -errno : -EINVAL;
414 if ((long) (int) l != l)
421 int safe_atou8(const char *s, uint8_t *ret) {
429 l = strtoul(s, &x, 0);
431 if (!x || x == s || *x || errno)
432 return errno > 0 ? -errno : -EINVAL;
434 if ((unsigned long) (uint8_t) l != l)
441 int safe_atou16(const char *s, uint16_t *ret) {
449 l = strtoul(s, &x, 0);
451 if (!x || x == s || *x || errno)
452 return errno > 0 ? -errno : -EINVAL;
454 if ((unsigned long) (uint16_t) l != l)
461 int safe_atoi16(const char *s, int16_t *ret) {
469 l = strtol(s, &x, 0);
471 if (!x || x == s || *x || errno)
472 return errno > 0 ? -errno : -EINVAL;
474 if ((long) (int16_t) l != l)
481 int safe_atollu(const char *s, long long unsigned *ret_llu) {
483 unsigned long long l;
489 l = strtoull(s, &x, 0);
491 if (!x || x == s || *x || errno)
492 return errno ? -errno : -EINVAL;
498 int safe_atolli(const char *s, long long int *ret_lli) {
506 l = strtoll(s, &x, 0);
508 if (!x || x == s || *x || errno)
509 return errno ? -errno : -EINVAL;
515 int safe_atod(const char *s, double *ret_d) {
523 loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
524 if (loc == (locale_t) 0)
528 d = strtod_l(s, &x, loc);
530 if (!x || x == s || *x || errno) {
532 return errno ? -errno : -EINVAL;
540 static size_t strcspn_escaped(const char *s, const char *reject) {
541 bool escaped = false;
544 for (n=0; s[n]; n++) {
547 else if (s[n] == '\\')
549 else if (strchr(reject, s[n]))
553 /* if s ends in \, return index of previous char */
557 /* Split a string into words. */
558 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
564 assert(**state == '\0');
568 current += strspn(current, separator);
574 if (quoted && strchr("\'\"", *current)) {
575 char quotechars[2] = {*current, '\0'};
577 *l = strcspn_escaped(current + 1, quotechars);
578 if (current[*l + 1] == '\0' ||
579 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
580 /* right quote missing or garbage at the end */
584 assert(current[*l + 1] == quotechars[0]);
585 *state = current++ + *l + 2;
587 *l = strcspn_escaped(current, separator);
588 if (current[*l] && !strchr(separator, current[*l])) {
589 /* unfinished escape */
593 *state = current + *l;
595 *l = strcspn(current, separator);
596 *state = current + *l;
602 int fchmod_umask(int fd, mode_t m) {
607 r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
613 char *truncate_nl(char *s) {
616 s[strcspn(s, NEWLINE)] = 0;
620 char *strnappend(const char *s, const char *suffix, size_t b) {
628 return strndup(suffix, b);
637 if (b > ((size_t) -1) - a)
640 r = new(char, a+b+1);
645 memcpy(r+a, suffix, b);
651 char *strappend(const char *s, const char *suffix) {
652 return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
655 int readlinkat_malloc(int fd, const char *p, char **ret) {
670 n = readlinkat(fd, p, c, l-1);
677 if ((size_t) n < l-1) {
688 int readlink_malloc(const char *p, char **ret) {
689 return readlinkat_malloc(AT_FDCWD, p, ret);
692 int readlink_value(const char *p, char **ret) {
693 _cleanup_free_ char *link = NULL;
697 r = readlink_malloc(p, &link);
701 value = basename(link);
705 value = strdup(value);
714 int readlink_and_make_absolute(const char *p, char **r) {
715 _cleanup_free_ char *target = NULL;
722 j = readlink_malloc(p, &target);
726 k = file_in_same_dir(p, target);
734 int readlink_and_canonicalize(const char *p, char **r) {
741 j = readlink_and_make_absolute(p, &t);
745 s = canonicalize_file_name(t);
752 path_kill_slashes(*r);
757 int reset_all_signal_handlers(void) {
760 for (sig = 1; sig < _NSIG; sig++) {
761 struct sigaction sa = {
762 .sa_handler = SIG_DFL,
763 .sa_flags = SA_RESTART,
766 /* These two cannot be caught... */
767 if (sig == SIGKILL || sig == SIGSTOP)
770 /* On Linux the first two RT signals are reserved by
771 * glibc, and sigaction() will return EINVAL for them. */
772 if ((sigaction(sig, &sa, NULL) < 0))
773 if (errno != EINVAL && r == 0)
780 int reset_signal_mask(void) {
783 if (sigemptyset(&ss) < 0)
786 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
792 char *strstrip(char *s) {
795 /* Drops trailing whitespace. Modifies the string in
796 * place. Returns pointer to first non-space character */
798 s += strspn(s, WHITESPACE);
800 for (e = strchr(s, 0); e > s; e --)
801 if (!strchr(WHITESPACE, e[-1]))
809 char *delete_chars(char *s, const char *bad) {
812 /* Drops all whitespace, regardless where in the string */
814 for (f = s, t = s; *f; f++) {
826 char *file_in_same_dir(const char *path, const char *filename) {
833 /* This removes the last component of path and appends
834 * filename, unless the latter is absolute anyway or the
837 if (path_is_absolute(filename))
838 return strdup(filename);
840 e = strrchr(path, '/');
842 return strdup(filename);
844 k = strlen(filename);
845 ret = new(char, (e + 1 - path) + k + 1);
849 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
853 int rmdir_parents(const char *path, const char *stop) {
862 /* Skip trailing slashes */
863 while (l > 0 && path[l-1] == '/')
869 /* Skip last component */
870 while (l > 0 && path[l-1] != '/')
873 /* Skip trailing slashes */
874 while (l > 0 && path[l-1] == '/')
880 if (!(t = strndup(path, l)))
883 if (path_startswith(stop, t)) {
899 char hexchar(int x) {
900 static const char table[16] = "0123456789abcdef";
902 return table[x & 15];
905 int unhexchar(char c) {
907 if (c >= '0' && c <= '9')
910 if (c >= 'a' && c <= 'f')
913 if (c >= 'A' && c <= 'F')
919 char *hexmem(const void *p, size_t l) {
923 z = r = malloc(l * 2 + 1);
927 for (x = p; x < (const uint8_t*) p + l; x++) {
928 *(z++) = hexchar(*x >> 4);
929 *(z++) = hexchar(*x & 15);
936 void *unhexmem(const char *p, size_t l) {
942 z = r = malloc((l + 1) / 2 + 1);
946 for (x = p; x < p + l; x += 2) {
955 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
962 char octchar(int x) {
963 return '0' + (x & 7);
966 int unoctchar(char c) {
968 if (c >= '0' && c <= '7')
974 char decchar(int x) {
975 return '0' + (x % 10);
978 int undecchar(char c) {
980 if (c >= '0' && c <= '9')
986 char *cescape(const char *s) {
992 /* Does C style string escaping. May be reversed with
995 r = new(char, strlen(s)*4 + 1);
999 for (f = s, t = r; *f; f++)
1000 t += cescape_char(*f, t);
1007 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1014 /* Unescapes C style. Returns the unescaped character in ret,
1015 * unless we encountered a \u sequence in which case the full
1016 * unicode character is returned in ret_unicode, instead. */
1018 if (length != (size_t) -1 && length < 1)
1055 /* This is an extension of the XDG syntax files */
1060 /* hexadecimal encoding */
1063 if (length != (size_t) -1 && length < 3)
1066 a = unhexchar(p[1]);
1070 b = unhexchar(p[2]);
1074 /* Don't allow NUL bytes */
1075 if (a == 0 && b == 0)
1078 *ret = (char) ((a << 4U) | b);
1084 /* C++11 style 16bit unicode */
1090 if (length != (size_t) -1 && length < 5)
1093 for (i = 0; i < 4; i++) {
1094 a[i] = unhexchar(p[1 + i]);
1099 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1101 /* Don't allow 0 chars */
1120 /* C++11 style 32bit unicode */
1126 if (length != (size_t) -1 && length < 9)
1129 for (i = 0; i < 8; i++) {
1130 a[i] = unhexchar(p[1 + i]);
1135 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1136 ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] << 8U) | ((uint32_t) a[6] << 4U) | (uint32_t) a[7];
1138 /* Don't allow 0 chars */
1142 /* Don't allow invalid code points */
1143 if (!unichar_is_valid(c))
1168 /* octal encoding */
1172 if (length != (size_t) -1 && length < 4)
1175 a = unoctchar(p[0]);
1179 b = unoctchar(p[1]);
1183 c = unoctchar(p[2]);
1187 /* don't allow NUL bytes */
1188 if (a == 0 && b == 0 && c == 0)
1191 /* Don't allow bytes above 255 */
1192 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1208 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1216 /* Undoes C style string escaping, and optionally prefixes it. */
1218 pl = prefix ? strlen(prefix) : 0;
1220 r = new(char, pl+length+1);
1225 memcpy(r, prefix, pl);
1227 for (f = s, t = r + pl; f < s + length; f++) {
1233 remaining = s + length - f;
1234 assert(remaining > 0);
1237 /* A literal literal, copy verbatim */
1242 if (remaining == 1) {
1243 if (flags & UNESCAPE_RELAX) {
1244 /* A trailing backslash, copy verbatim */
1253 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1255 if (flags & UNESCAPE_RELAX) {
1256 /* Invalid escape code, let's take it literal then */
1266 /* Non-Unicode? Let's encode this directly */
1269 /* Unicode? Then let's encode this in UTF-8 */
1270 t += utf8_encode_unichar(t, u);
1281 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1282 return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1285 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1286 return cunescape_length(s, strlen(s), flags, ret);
1289 char *xescape(const char *s, const char *bad) {
1293 /* Escapes all chars in bad, in addition to \ and all special
1294 * chars, in \xFF style escaping. May be reversed with
1297 r = new(char, strlen(s) * 4 + 1);
1301 for (f = s, t = r; *f; f++) {
1303 if ((*f < ' ') || (*f >= 127) ||
1304 (*f == '\\') || strchr(bad, *f)) {
1307 *(t++) = hexchar(*f >> 4);
1308 *(t++) = hexchar(*f);
1318 char *ascii_strlower(char *t) {
1323 for (p = t; *p; p++)
1324 if (*p >= 'A' && *p <= 'Z')
1325 *p = *p - 'A' + 'a';
1330 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1334 filename[0] == '.' ||
1335 streq(filename, "lost+found") ||
1336 streq(filename, "aquota.user") ||
1337 streq(filename, "aquota.group") ||
1338 endswith(filename, ".rpmnew") ||
1339 endswith(filename, ".rpmsave") ||
1340 endswith(filename, ".rpmorig") ||
1341 endswith(filename, ".dpkg-old") ||
1342 endswith(filename, ".dpkg-new") ||
1343 endswith(filename, ".dpkg-tmp") ||
1344 endswith(filename, ".dpkg-dist") ||
1345 endswith(filename, ".dpkg-bak") ||
1346 endswith(filename, ".dpkg-backup") ||
1347 endswith(filename, ".dpkg-remove") ||
1348 endswith(filename, ".swp");
1351 bool hidden_file(const char *filename) {
1354 if (endswith(filename, "~"))
1357 return hidden_file_allow_backup(filename);
1360 int fd_nonblock(int fd, bool nonblock) {
1365 flags = fcntl(fd, F_GETFL, 0);
1370 nflags = flags | O_NONBLOCK;
1372 nflags = flags & ~O_NONBLOCK;
1374 if (nflags == flags)
1377 if (fcntl(fd, F_SETFL, nflags) < 0)
1383 int fd_cloexec(int fd, bool cloexec) {
1388 flags = fcntl(fd, F_GETFD, 0);
1393 nflags = flags | FD_CLOEXEC;
1395 nflags = flags & ~FD_CLOEXEC;
1397 if (nflags == flags)
1400 if (fcntl(fd, F_SETFD, nflags) < 0)
1406 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1409 assert(n_fdset == 0 || fdset);
1411 for (i = 0; i < n_fdset; i++)
1418 int close_all_fds(const int except[], unsigned n_except) {
1419 _cleanup_closedir_ DIR *d = NULL;
1423 assert(n_except == 0 || except);
1425 d = opendir("/proc/self/fd");
1430 /* When /proc isn't available (for example in chroots)
1431 * the fallback is brute forcing through the fd
1434 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1435 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1437 if (fd_in_set(fd, except, n_except))
1440 if (close_nointr(fd) < 0)
1441 if (errno != EBADF && r == 0)
1448 while ((de = readdir(d))) {
1451 if (hidden_file(de->d_name))
1454 if (safe_atoi(de->d_name, &fd) < 0)
1455 /* Let's better ignore this, just in case */
1464 if (fd_in_set(fd, except, n_except))
1467 if (close_nointr(fd) < 0) {
1468 /* Valgrind has its own FD and doesn't want to have it closed */
1469 if (errno != EBADF && r == 0)
1477 bool chars_intersect(const char *a, const char *b) {
1480 /* Returns true if any of the chars in a are in b. */
1481 for (p = a; *p; p++)
1488 bool fstype_is_network(const char *fstype) {
1489 static const char table[] =
1504 x = startswith(fstype, "fuse.");
1508 return nulstr_contains(table, fstype);
1512 _cleanup_close_ int fd;
1514 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1520 TIOCL_GETKMSGREDIRECT,
1524 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1527 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1530 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1536 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1537 struct termios old_termios, new_termios;
1538 char c, line[LINE_MAX];
1543 if (tcgetattr(fileno(f), &old_termios) >= 0) {
1544 new_termios = old_termios;
1546 new_termios.c_lflag &= ~ICANON;
1547 new_termios.c_cc[VMIN] = 1;
1548 new_termios.c_cc[VTIME] = 0;
1550 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1553 if (t != USEC_INFINITY) {
1554 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1555 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1560 k = fread(&c, 1, 1, f);
1562 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1568 *need_nl = c != '\n';
1575 if (t != USEC_INFINITY) {
1576 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1581 if (!fgets(line, sizeof(line), f))
1582 return errno ? -errno : -EIO;
1586 if (strlen(line) != 1)
1596 int ask_char(char *ret, const char *replies, const char *text, ...) {
1606 bool need_nl = true;
1609 fputs(ANSI_HIGHLIGHT_ON, stdout);
1616 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1620 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
1623 if (r == -EBADMSG) {
1624 puts("Bad input, please try again.");
1635 if (strchr(replies, c)) {
1640 puts("Read unexpected character, please try again.");
1644 int ask_string(char **ret, const char *text, ...) {
1649 char line[LINE_MAX];
1653 fputs(ANSI_HIGHLIGHT_ON, stdout);
1660 fputs(ANSI_HIGHLIGHT_OFF, stdout);
1665 if (!fgets(line, sizeof(line), stdin))
1666 return errno ? -errno : -EIO;
1668 if (!endswith(line, "\n"))
1687 int reset_terminal_fd(int fd, bool switch_to_text) {
1688 struct termios termios;
1691 /* Set terminal to some sane defaults */
1695 /* We leave locked terminal attributes untouched, so that
1696 * Plymouth may set whatever it wants to set, and we don't
1697 * interfere with that. */
1699 /* Disable exclusive mode, just in case */
1700 ioctl(fd, TIOCNXCL);
1702 /* Switch to text mode */
1704 ioctl(fd, KDSETMODE, KD_TEXT);
1706 /* Enable console unicode mode */
1707 ioctl(fd, KDSKBMODE, K_UNICODE);
1709 if (tcgetattr(fd, &termios) < 0) {
1714 /* We only reset the stuff that matters to the software. How
1715 * hardware is set up we don't touch assuming that somebody
1716 * else will do that for us */
1718 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1719 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1720 termios.c_oflag |= ONLCR;
1721 termios.c_cflag |= CREAD;
1722 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1724 termios.c_cc[VINTR] = 03; /* ^C */
1725 termios.c_cc[VQUIT] = 034; /* ^\ */
1726 termios.c_cc[VERASE] = 0177;
1727 termios.c_cc[VKILL] = 025; /* ^X */
1728 termios.c_cc[VEOF] = 04; /* ^D */
1729 termios.c_cc[VSTART] = 021; /* ^Q */
1730 termios.c_cc[VSTOP] = 023; /* ^S */
1731 termios.c_cc[VSUSP] = 032; /* ^Z */
1732 termios.c_cc[VLNEXT] = 026; /* ^V */
1733 termios.c_cc[VWERASE] = 027; /* ^W */
1734 termios.c_cc[VREPRINT] = 022; /* ^R */
1735 termios.c_cc[VEOL] = 0;
1736 termios.c_cc[VEOL2] = 0;
1738 termios.c_cc[VTIME] = 0;
1739 termios.c_cc[VMIN] = 1;
1741 if (tcsetattr(fd, TCSANOW, &termios) < 0)
1745 /* Just in case, flush all crap out */
1746 tcflush(fd, TCIOFLUSH);
1751 int reset_terminal(const char *name) {
1752 _cleanup_close_ int fd = -1;
1754 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1758 return reset_terminal_fd(fd, true);
1761 int open_terminal(const char *name, int mode) {
1766 * If a TTY is in the process of being closed opening it might
1767 * cause EIO. This is horribly awful, but unlikely to be
1768 * changed in the kernel. Hence we work around this problem by
1769 * retrying a couple of times.
1771 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1774 assert(!(mode & O_CREAT));
1777 fd = open(name, mode, 0);
1784 /* Max 1s in total */
1788 usleep(50 * USEC_PER_MSEC);
1806 int flush_fd(int fd) {
1807 struct pollfd pollfd = {
1817 r = poll(&pollfd, 1, 0);
1827 l = read(fd, buf, sizeof(buf));
1833 if (errno == EAGAIN)
1842 int acquire_terminal(
1846 bool ignore_tiocstty_eperm,
1849 int fd = -1, notify = -1, r = 0, wd = -1;
1854 /* We use inotify to be notified when the tty is closed. We
1855 * create the watch before checking if we can actually acquire
1856 * it, so that we don't lose any event.
1858 * Note: strictly speaking this actually watches for the
1859 * device being closed, it does *not* really watch whether a
1860 * tty loses its controlling process. However, unless some
1861 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1862 * its tty otherwise this will not become a problem. As long
1863 * as the administrator makes sure not configure any service
1864 * on the same tty as an untrusted user this should not be a
1865 * problem. (Which he probably should not do anyway.) */
1867 if (timeout != USEC_INFINITY)
1868 ts = now(CLOCK_MONOTONIC);
1870 if (!fail && !force) {
1871 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
1877 wd = inotify_add_watch(notify, name, IN_CLOSE);
1885 struct sigaction sa_old, sa_new = {
1886 .sa_handler = SIG_IGN,
1887 .sa_flags = SA_RESTART,
1891 r = flush_fd(notify);
1896 /* We pass here O_NOCTTY only so that we can check the return
1897 * value TIOCSCTTY and have a reliable way to figure out if we
1898 * successfully became the controlling process of the tty */
1899 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1903 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1904 * if we already own the tty. */
1905 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1907 /* First, try to get the tty */
1908 if (ioctl(fd, TIOCSCTTY, force) < 0)
1911 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1913 /* Sometimes it makes sense to ignore TIOCSCTTY
1914 * returning EPERM, i.e. when very likely we already
1915 * are have this controlling terminal. */
1916 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1919 if (r < 0 && (force || fail || r != -EPERM)) {
1928 assert(notify >= 0);
1931 union inotify_event_buffer buffer;
1932 struct inotify_event *e;
1935 if (timeout != USEC_INFINITY) {
1938 n = now(CLOCK_MONOTONIC);
1939 if (ts + timeout < n) {
1944 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1954 l = read(notify, &buffer, sizeof(buffer));
1956 if (errno == EINTR || errno == EAGAIN)
1963 FOREACH_INOTIFY_EVENT(e, buffer, l) {
1964 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1973 /* We close the tty fd here since if the old session
1974 * ended our handle will be dead. It's important that
1975 * we do this after sleeping, so that we don't enter
1976 * an endless loop. */
1977 fd = safe_close(fd);
1982 r = reset_terminal_fd(fd, true);
1984 log_warning_errno(r, "Failed to reset terminal: %m");
1995 int release_terminal(void) {
1996 static const struct sigaction sa_new = {
1997 .sa_handler = SIG_IGN,
1998 .sa_flags = SA_RESTART,
2001 _cleanup_close_ int fd = -1;
2002 struct sigaction sa_old;
2005 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2009 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2010 * by our own TIOCNOTTY */
2011 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2013 if (ioctl(fd, TIOCNOTTY) < 0)
2016 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2021 int sigaction_many(const struct sigaction *sa, ...) {
2026 while ((sig = va_arg(ap, int)) > 0)
2027 if (sigaction(sig, sa, NULL) < 0)
2034 int ignore_signals(int sig, ...) {
2035 struct sigaction sa = {
2036 .sa_handler = SIG_IGN,
2037 .sa_flags = SA_RESTART,
2042 if (sigaction(sig, &sa, NULL) < 0)
2046 while ((sig = va_arg(ap, int)) > 0)
2047 if (sigaction(sig, &sa, NULL) < 0)
2054 int default_signals(int sig, ...) {
2055 struct sigaction sa = {
2056 .sa_handler = SIG_DFL,
2057 .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 void safe_close_pair(int p[]) {
2078 /* Special case pairs which use the same fd in both
2080 p[0] = p[1] = safe_close(p[0]);
2084 p[0] = safe_close(p[0]);
2085 p[1] = safe_close(p[1]);
2088 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2095 while (nbytes > 0) {
2098 k = read(fd, p, nbytes);
2103 if (errno == EAGAIN && do_poll) {
2105 /* We knowingly ignore any return value here,
2106 * and expect that any error/EOF is reported
2109 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2113 return n > 0 ? n : -errno;
2127 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
2130 n = loop_read(fd, buf, nbytes, do_poll);
2133 if ((size_t) n != nbytes)
2138 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2139 const uint8_t *p = buf;
2146 while (nbytes > 0) {
2149 k = write(fd, p, nbytes);
2154 if (errno == EAGAIN && do_poll) {
2155 /* We knowingly ignore any return value here,
2156 * and expect that any error/EOF is reported
2159 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2166 if (k == 0) /* Can't really happen */
2176 int parse_size(const char *t, off_t base, off_t *size) {
2178 /* Soo, sometimes we want to parse IEC binary suffxies, and
2179 * sometimes SI decimal suffixes. This function can parse
2180 * both. Which one is the right way depends on the
2181 * context. Wikipedia suggests that SI is customary for
2182 * hardrware metrics and network speeds, while IEC is
2183 * customary for most data sizes used by software and volatile
2184 * (RAM) memory. Hence be careful which one you pick!
2186 * In either case we use just K, M, G as suffix, and not Ki,
2187 * Mi, Gi or so (as IEC would suggest). That's because that's
2188 * frickin' ugly. But this means you really need to make sure
2189 * to document which base you are parsing when you use this
2194 unsigned long long factor;
2197 static const struct table iec[] = {
2198 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2199 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2200 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2201 { "G", 1024ULL*1024ULL*1024ULL },
2202 { "M", 1024ULL*1024ULL },
2208 static const struct table si[] = {
2209 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2210 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2211 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2212 { "G", 1000ULL*1000ULL*1000ULL },
2213 { "M", 1000ULL*1000ULL },
2219 const struct table *table;
2221 unsigned long long r = 0;
2222 unsigned n_entries, start_pos = 0;
2225 assert(base == 1000 || base == 1024);
2230 n_entries = ELEMENTSOF(si);
2233 n_entries = ELEMENTSOF(iec);
2239 unsigned long long l2;
2245 l = strtoll(p, &e, 10);
2258 if (*e >= '0' && *e <= '9') {
2261 /* strotoull itself would accept space/+/- */
2262 l2 = strtoull(e, &e2, 10);
2264 if (errno == ERANGE)
2267 /* Ignore failure. E.g. 10.M is valid */
2274 e += strspn(e, WHITESPACE);
2276 for (i = start_pos; i < n_entries; i++)
2277 if (startswith(e, table[i].suffix)) {
2278 unsigned long long tmp;
2279 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2281 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2282 if (tmp > ULLONG_MAX - r)
2286 if ((unsigned long long) (off_t) r != r)
2289 p = e + strlen(table[i].suffix);
2305 int make_stdio(int fd) {
2310 r = dup2(fd, STDIN_FILENO);
2311 s = dup2(fd, STDOUT_FILENO);
2312 t = dup2(fd, STDERR_FILENO);
2317 if (r < 0 || s < 0 || t < 0)
2320 /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
2321 * dup2() was a NOP and the bit hence possibly set. */
2322 fd_cloexec(STDIN_FILENO, false);
2323 fd_cloexec(STDOUT_FILENO, false);
2324 fd_cloexec(STDERR_FILENO, false);
2329 int make_null_stdio(void) {
2332 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2336 return make_stdio(null_fd);
2339 bool is_device_path(const char *path) {
2341 /* Returns true on paths that refer to a device, either in
2342 * sysfs or in /dev */
2345 path_startswith(path, "/dev/") ||
2346 path_startswith(path, "/sys/");
2349 int dir_is_empty(const char *path) {
2350 _cleanup_closedir_ DIR *d;
2361 if (!de && errno != 0)
2367 if (!hidden_file(de->d_name))
2372 char* dirname_malloc(const char *path) {
2373 char *d, *dir, *dir2;
2390 int dev_urandom(void *p, size_t n) {
2391 static int have_syscall = -1;
2393 _cleanup_close_ int fd = -1;
2396 /* Gathers some randomness from the kernel. This call will
2397 * never block, and will always return some data from the
2398 * kernel, regardless if the random pool is fully initialized
2399 * or not. It thus makes no guarantee for the quality of the
2400 * returned entropy, but is good enough for or usual usecases
2401 * of seeding the hash functions for hashtable */
2403 /* Use the getrandom() syscall unless we know we don't have
2404 * it, or when the requested size is too large for it. */
2405 if (have_syscall != 0 || (size_t) (int) n != n) {
2406 r = getrandom(p, n, GRND_NONBLOCK);
2408 have_syscall = true;
2413 if (errno == ENOSYS)
2414 /* we lack the syscall, continue with
2415 * reading from /dev/urandom */
2416 have_syscall = false;
2417 else if (errno == EAGAIN)
2418 /* not enough entropy for now. Let's
2419 * remember to use the syscall the
2420 * next time, again, but also read
2421 * from /dev/urandom for now, which
2422 * doesn't care about the current
2423 * amount of entropy. */
2424 have_syscall = true;
2428 /* too short read? */
2432 fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2434 return errno == ENOENT ? -ENOSYS : -errno;
2436 return loop_read_exact(fd, p, n, true);
2439 void initialize_srand(void) {
2440 static bool srand_called = false;
2442 #ifdef HAVE_SYS_AUXV_H
2451 #ifdef HAVE_SYS_AUXV_H
2452 /* The kernel provides us with a bit of entropy in auxv, so
2453 * let's try to make use of that to seed the pseudo-random
2454 * generator. It's better than nothing... */
2456 auxv = (void*) getauxval(AT_RANDOM);
2458 x ^= *(unsigned*) auxv;
2461 x ^= (unsigned) now(CLOCK_REALTIME);
2462 x ^= (unsigned) gettid();
2465 srand_called = true;
2468 void random_bytes(void *p, size_t n) {
2472 r = dev_urandom(p, n);
2476 /* If some idiot made /dev/urandom unavailable to us, he'll
2477 * get a PRNG instead. */
2481 for (q = p; q < (uint8_t*) p + n; q ++)
2485 void rename_process(const char name[8]) {
2488 /* This is a like a poor man's setproctitle(). It changes the
2489 * comm field, argv[0], and also the glibc's internally used
2490 * name of the process. For the first one a limit of 16 chars
2491 * applies, to the second one usually one of 10 (i.e. length
2492 * of "/sbin/init"), to the third one one of 7 (i.e. length of
2493 * "systemd"). If you pass a longer string it will be
2496 prctl(PR_SET_NAME, name);
2498 if (program_invocation_name)
2499 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2501 if (saved_argc > 0) {
2505 strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2507 for (i = 1; i < saved_argc; i++) {
2511 memzero(saved_argv[i], strlen(saved_argv[i]));
2516 void sigset_add_many(sigset_t *ss, ...) {
2523 while ((sig = va_arg(ap, int)) > 0)
2524 assert_se(sigaddset(ss, sig) == 0);
2528 int sigprocmask_many(int how, ...) {
2533 assert_se(sigemptyset(&ss) == 0);
2536 while ((sig = va_arg(ap, int)) > 0)
2537 assert_se(sigaddset(&ss, sig) == 0);
2540 if (sigprocmask(how, &ss, NULL) < 0)
2546 char* gethostname_malloc(void) {
2549 assert_se(uname(&u) >= 0);
2551 if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2552 return strdup(u.nodename);
2554 return strdup(u.sysname);
2557 bool hostname_is_set(void) {
2560 assert_se(uname(&u) >= 0);
2562 return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2565 char *lookup_uid(uid_t uid) {
2568 _cleanup_free_ char *buf = NULL;
2569 struct passwd pwbuf, *pw = NULL;
2571 /* Shortcut things to avoid NSS lookups */
2573 return strdup("root");
2575 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2579 buf = malloc(bufsize);
2583 if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2584 return strdup(pw->pw_name);
2586 if (asprintf(&name, UID_FMT, uid) < 0)
2592 char* getlogname_malloc(void) {
2596 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2601 return lookup_uid(uid);
2604 char *getusername_malloc(void) {
2611 return lookup_uid(getuid());
2614 int getttyname_malloc(int fd, char **ret) {
2624 r = ttyname_r(fd, path, sizeof(path));
2629 p = startswith(path, "/dev/");
2630 c = strdup(p ?: path);
2647 int getttyname_harder(int fd, char **r) {
2651 k = getttyname_malloc(fd, &s);
2655 if (streq(s, "tty")) {
2657 return get_ctty(0, NULL, r);
2664 int get_ctty_devnr(pid_t pid, dev_t *d) {
2666 _cleanup_free_ char *line = NULL;
2668 unsigned long ttynr;
2672 p = procfs_file_alloca(pid, "stat");
2673 r = read_one_line_file(p, &line);
2677 p = strrchr(line, ')');
2687 "%*d " /* session */
2692 if (major(ttynr) == 0 && minor(ttynr) == 0)
2701 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2702 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2703 _cleanup_free_ char *s = NULL;
2710 k = get_ctty_devnr(pid, &devnr);
2714 sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
2716 k = readlink_malloc(fn, &s);
2722 /* This is an ugly hack */
2723 if (major(devnr) == 136) {
2724 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
2727 /* Probably something like the ptys which have no
2728 * symlink in /dev/char. Let's return something
2729 * vaguely useful. */
2736 if (startswith(s, "/dev/"))
2738 else if (startswith(s, "../"))
2755 bool is_temporary_fs(const struct statfs *s) {
2758 return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2759 F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2762 int fd_is_temporary_fs(int fd) {
2765 if (fstatfs(fd, &s) < 0)
2768 return is_temporary_fs(&s);
2771 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2774 /* Under the assumption that we are running privileged we
2775 * first change the access mode and only then hand out
2776 * ownership to avoid a window where access is too open. */
2778 if (mode != MODE_INVALID)
2779 if (chmod(path, mode) < 0)
2782 if (uid != UID_INVALID || gid != GID_INVALID)
2783 if (chown(path, uid, gid) < 0)
2789 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2792 /* Under the assumption that we are running privileged we
2793 * first change the access mode and only then hand out
2794 * ownership to avoid a window where access is too open. */
2796 if (mode != MODE_INVALID)
2797 if (fchmod(fd, mode) < 0)
2800 if (uid != UID_INVALID || gid != GID_INVALID)
2801 if (fchown(fd, uid, gid) < 0)
2807 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2811 /* Allocates the cpuset in the right size */
2814 if (!(r = CPU_ALLOC(n)))
2817 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2818 CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2828 if (errno != EINVAL)
2835 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2836 static const char status_indent[] = " "; /* "[" STATUS "] " */
2837 _cleanup_free_ char *s = NULL;
2838 _cleanup_close_ int fd = -1;
2839 struct iovec iovec[6] = {};
2841 static bool prev_ephemeral;
2845 /* This is independent of logging, as status messages are
2846 * optional and go exclusively to the console. */
2848 if (vasprintf(&s, format, ap) < 0)
2851 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2864 sl = status ? sizeof(status_indent)-1 : 0;
2870 e = ellipsize(s, emax, 50);
2878 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2879 prev_ephemeral = ephemeral;
2882 if (!isempty(status)) {
2883 IOVEC_SET_STRING(iovec[n++], "[");
2884 IOVEC_SET_STRING(iovec[n++], status);
2885 IOVEC_SET_STRING(iovec[n++], "] ");
2887 IOVEC_SET_STRING(iovec[n++], status_indent);
2890 IOVEC_SET_STRING(iovec[n++], s);
2892 IOVEC_SET_STRING(iovec[n++], "\n");
2894 if (writev(fd, iovec, n) < 0)
2900 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2906 va_start(ap, format);
2907 r = status_vprintf(status, ellipse, ephemeral, format, ap);
2913 char *replace_env(const char *format, char **env) {
2920 const char *e, *word = format;
2925 for (e = format; *e; e ++) {
2936 k = strnappend(r, word, e-word-1);
2946 } else if (*e == '$') {
2947 k = strnappend(r, word, e-word);
2964 t = strempty(strv_env_get_n(env, word+2, e-word-2));
2966 k = strappend(r, t);
2980 k = strnappend(r, word, e-word);
2992 char **replace_env_argv(char **argv, char **env) {
2994 unsigned k = 0, l = 0;
2996 l = strv_length(argv);
2998 ret = new(char*, l+1);
3002 STRV_FOREACH(i, argv) {
3004 /* If $FOO appears as single word, replace it by the split up variable */
3005 if ((*i)[0] == '$' && (*i)[1] != '{') {
3007 char **w, **m = NULL;
3010 e = strv_env_get(env, *i+1);
3014 r = strv_split_quoted(&m, e, UNQUOTE_RELAX);
3026 w = realloc(ret, sizeof(char*) * (l+1));
3036 memcpy(ret + k, m, q * sizeof(char*));
3044 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3045 ret[k] = replace_env(*i, env);
3057 int fd_columns(int fd) {
3058 struct winsize ws = {};
3060 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3069 unsigned columns(void) {
3073 if (_likely_(cached_columns > 0))
3074 return cached_columns;
3077 e = getenv("COLUMNS");
3079 (void) safe_atoi(e, &c);
3082 c = fd_columns(STDOUT_FILENO);
3088 return cached_columns;
3091 int fd_lines(int fd) {
3092 struct winsize ws = {};
3094 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3103 unsigned lines(void) {
3107 if (_likely_(cached_lines > 0))
3108 return cached_lines;
3111 e = getenv("LINES");
3113 (void) safe_atoi(e, &l);
3116 l = fd_lines(STDOUT_FILENO);
3122 return cached_lines;
3125 /* intended to be used as a SIGWINCH sighandler */
3126 void columns_lines_cache_reset(int signum) {
3132 static int cached_on_tty = -1;
3134 if (_unlikely_(cached_on_tty < 0))
3135 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3137 return cached_on_tty;
3140 int files_same(const char *filea, const char *fileb) {
3143 if (stat(filea, &a) < 0)
3146 if (stat(fileb, &b) < 0)
3149 return a.st_dev == b.st_dev &&
3150 a.st_ino == b.st_ino;
3153 int running_in_chroot(void) {
3156 ret = files_same("/proc/1/root", "/");
3163 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3168 assert(percent <= 100);
3169 assert(new_length >= 3);
3171 if (old_length <= 3 || old_length <= new_length)
3172 return strndup(s, old_length);
3174 r = new0(char, new_length+1);
3178 x = (new_length * percent) / 100;
3180 if (x > new_length - 3)
3188 s + old_length - (new_length - x - 3),
3189 new_length - x - 3);
3194 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3198 unsigned k, len, len2;
3201 assert(percent <= 100);
3202 assert(new_length >= 3);
3204 /* if no multibyte characters use ascii_ellipsize_mem for speed */
3205 if (ascii_is_valid(s))
3206 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3208 if (old_length <= 3 || old_length <= new_length)
3209 return strndup(s, old_length);
3211 x = (new_length * percent) / 100;
3213 if (x > new_length - 3)
3217 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3220 c = utf8_encoded_to_unichar(i);
3223 k += unichar_iswide(c) ? 2 : 1;
3226 if (k > x) /* last character was wide and went over quota */
3229 for (j = s + old_length; k < new_length && j > i; ) {
3232 j = utf8_prev_char(j);
3233 c = utf8_encoded_to_unichar(j);
3236 k += unichar_iswide(c) ? 2 : 1;
3240 /* we don't actually need to ellipsize */
3242 return memdup(s, old_length + 1);
3244 /* make space for ellipsis */
3245 j = utf8_next_char(j);
3248 len2 = s + old_length - j;
3249 e = new(char, len + 3 + len2 + 1);
3254 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3255 old_length, new_length, x, len, len2, k);
3259 e[len] = 0xe2; /* tri-dot ellipsis: … */
3263 memcpy(e + len + 3, j, len2 + 1);
3268 char *ellipsize(const char *s, size_t length, unsigned percent) {
3269 return ellipsize_mem(s, strlen(s), length, percent);
3272 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
3273 _cleanup_close_ int fd;
3279 mkdir_parents(path, 0755);
3281 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
3286 r = fchmod(fd, mode);
3291 if (uid != UID_INVALID || gid != GID_INVALID) {
3292 r = fchown(fd, uid, gid);
3297 if (stamp != USEC_INFINITY) {
3298 struct timespec ts[2];
3300 timespec_store(&ts[0], stamp);
3302 r = futimens(fd, ts);
3304 r = futimens(fd, NULL);
3311 int touch(const char *path) {
3312 return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
3315 static char *unquote(const char *s, const char* quotes) {
3319 /* This is rather stupid, simply removes the heading and
3320 * trailing quotes if there is one. Doesn't care about
3321 * escaping or anything.
3323 * DON'T USE THIS FOR NEW CODE ANYMORE!*/
3329 if (strchr(quotes, s[0]) && s[l-1] == s[0])
3330 return strndup(s+1, l-2);
3335 noreturn void freeze(void) {
3337 /* Make sure nobody waits for us on a socket anymore */
3338 close_all_fds(NULL, 0);
3346 bool null_or_empty(struct stat *st) {
3349 if (S_ISREG(st->st_mode) && st->st_size <= 0)
3352 if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3358 int null_or_empty_path(const char *fn) {
3363 if (stat(fn, &st) < 0)
3366 return null_or_empty(&st);
3369 int null_or_empty_fd(int fd) {
3374 if (fstat(fd, &st) < 0)
3377 return null_or_empty(&st);
3380 DIR *xopendirat(int fd, const char *name, int flags) {
3384 assert(!(flags & O_CREAT));
3386 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3399 int signal_from_string_try_harder(const char *s) {
3403 signo = signal_from_string(s);
3405 if (startswith(s, "SIG"))
3406 return signal_from_string(s+3);
3411 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3412 _cleanup_free_ char *t = NULL, *u = NULL;
3415 u = unquote(tagvalue, QUOTES);
3419 enc_len = strlen(u) * 4 + 1;
3420 t = new(char, enc_len);
3424 if (encode_devnode_name(u, t, enc_len) < 0)
3427 return strjoin("/dev/disk/by-", by, "/", t, NULL);
3430 char *fstab_node_to_udev_node(const char *p) {
3433 if (startswith(p, "LABEL="))
3434 return tag_to_udev_node(p+6, "label");
3436 if (startswith(p, "UUID="))
3437 return tag_to_udev_node(p+5, "uuid");
3439 if (startswith(p, "PARTUUID="))
3440 return tag_to_udev_node(p+9, "partuuid");
3442 if (startswith(p, "PARTLABEL="))
3443 return tag_to_udev_node(p+10, "partlabel");
3448 bool tty_is_vc(const char *tty) {
3451 return vtnr_from_tty(tty) >= 0;
3454 bool tty_is_console(const char *tty) {
3457 if (startswith(tty, "/dev/"))
3460 return streq(tty, "console");
3463 int vtnr_from_tty(const char *tty) {
3468 if (startswith(tty, "/dev/"))
3471 if (!startswith(tty, "tty") )
3474 if (tty[3] < '0' || tty[3] > '9')
3477 r = safe_atoi(tty+3, &i);
3481 if (i < 0 || i > 63)
3487 char *resolve_dev_console(char **active) {
3490 /* Resolve where /dev/console is pointing to, if /sys is actually ours
3491 * (i.e. not read-only-mounted which is a sign for container setups) */
3493 if (path_is_read_only_fs("/sys") > 0)
3496 if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3499 /* If multiple log outputs are configured the last one is what
3500 * /dev/console points to */
3501 tty = strrchr(*active, ' ');
3507 if (streq(tty, "tty0")) {
3510 /* Get the active VC (e.g. tty1) */
3511 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3513 tty = *active = tmp;
3520 bool tty_is_vc_resolve(const char *tty) {
3521 _cleanup_free_ char *active = NULL;
3525 if (startswith(tty, "/dev/"))
3528 if (streq(tty, "console")) {
3529 tty = resolve_dev_console(&active);
3534 return tty_is_vc(tty);
3537 const char *default_term_for_tty(const char *tty) {
3540 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt220";
3543 bool dirent_is_file(const struct dirent *de) {
3546 if (hidden_file(de->d_name))
3549 if (de->d_type != DT_REG &&
3550 de->d_type != DT_LNK &&
3551 de->d_type != DT_UNKNOWN)
3557 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3560 if (de->d_type != DT_REG &&
3561 de->d_type != DT_LNK &&
3562 de->d_type != DT_UNKNOWN)
3565 if (hidden_file_allow_backup(de->d_name))
3568 return endswith(de->d_name, suffix);
3571 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
3572 _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
3573 _cleanup_set_free_free_ Set *seen = NULL;
3576 /* We fork this all off from a child process so that we can
3577 * somewhat cleanly make use of SIGALRM to set a time limit */
3579 reset_all_signal_handlers();
3580 reset_signal_mask();
3582 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
3584 pids = hashmap_new(NULL);
3588 seen = set_new(&string_hash_ops);
3592 STRV_FOREACH(directory, directories) {
3593 _cleanup_closedir_ DIR *d;
3596 d = opendir(*directory);
3598 if (errno == ENOENT)
3601 return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
3604 FOREACH_DIRENT(de, d, break) {
3605 _cleanup_free_ char *path = NULL;
3609 if (!dirent_is_file(de))
3612 if (set_contains(seen, de->d_name)) {
3613 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
3617 r = set_put_strdup(seen, de->d_name);
3621 path = strjoin(*directory, "/", de->d_name, NULL);
3625 if (null_or_empty_path(path)) {
3626 log_debug("%s is empty (a mask).", path);
3632 log_error_errno(errno, "Failed to fork: %m");
3634 } else if (pid == 0) {
3637 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
3647 return log_error_errno(errno, "Failed to execute %s: %m", path);
3650 log_debug("Spawned %s as " PID_FMT ".", path, pid);
3652 r = hashmap_put(pids, UINT_TO_PTR(pid), path);
3659 /* Abort execution of this process after the timout. We simply
3660 * rely on SIGALRM as default action terminating the process,
3661 * and turn on alarm(). */
3663 if (timeout != USEC_INFINITY)
3664 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
3666 while (!hashmap_isempty(pids)) {
3667 _cleanup_free_ char *path = NULL;
3670 pid = PTR_TO_UINT(hashmap_first_key(pids));
3673 path = hashmap_remove(pids, UINT_TO_PTR(pid));
3676 wait_for_terminate_and_warn(path, pid, true);
3682 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
3686 char **dirs = (char**) directories;
3688 assert(!strv_isempty(dirs));
3690 name = basename(dirs[0]);
3691 assert(!isempty(name));
3693 /* Executes all binaries in the directories in parallel and waits
3694 * for them to finish. Optionally a timeout is applied. If a file
3695 * with the same name exists in more than one directory, the
3696 * earliest one wins. */
3698 executor_pid = fork();
3699 if (executor_pid < 0) {
3700 log_error_errno(errno, "Failed to fork: %m");
3703 } else if (executor_pid == 0) {
3704 r = do_execute(dirs, timeout, argv);
3705 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
3708 wait_for_terminate_and_warn(name, executor_pid, true);
3711 bool nulstr_contains(const char*nulstr, const char *needle) {
3717 NULSTR_FOREACH(i, nulstr)
3718 if (streq(i, needle))
3724 bool plymouth_running(void) {
3725 return access("/run/plymouth/pid", F_OK) >= 0;
3728 char* strshorten(char *s, size_t l) {
3737 static bool hostname_valid_char(char c) {
3739 (c >= 'a' && c <= 'z') ||
3740 (c >= 'A' && c <= 'Z') ||
3741 (c >= '0' && c <= '9') ||
3747 bool hostname_is_valid(const char *s) {
3754 /* Doesn't accept empty hostnames, hostnames with trailing or
3755 * leading dots, and hostnames with multiple dots in a
3756 * sequence. Also ensures that the length stays below
3759 for (p = s, dot = true; *p; p++) {
3766 if (!hostname_valid_char(*p))
3776 if (p-s > HOST_NAME_MAX)
3782 char* hostname_cleanup(char *s, bool lowercase) {
3786 for (p = s, d = s, dot = true; *p; p++) {
3793 } else if (hostname_valid_char(*p)) {
3794 *(d++) = lowercase ? tolower(*p) : *p;
3805 strshorten(s, HOST_NAME_MAX);
3810 bool machine_name_is_valid(const char *s) {
3812 if (!hostname_is_valid(s))
3815 /* Machine names should be useful hostnames, but also be
3816 * useful in unit names, hence we enforce a stricter length
3825 int pipe_eof(int fd) {
3826 struct pollfd pollfd = {
3828 .events = POLLIN|POLLHUP,
3833 r = poll(&pollfd, 1, 0);
3840 return pollfd.revents & POLLHUP;
3843 int fd_wait_for_event(int fd, int event, usec_t t) {
3845 struct pollfd pollfd = {
3853 r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
3860 return pollfd.revents;
3863 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3872 r = tempfn_xxxxxx(path, &t);
3876 fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
3882 f = fdopen(fd, "we");
3895 int terminal_vhangup_fd(int fd) {
3898 if (ioctl(fd, TIOCVHANGUP) < 0)
3904 int terminal_vhangup(const char *name) {
3905 _cleanup_close_ int fd;
3907 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3911 return terminal_vhangup_fd(fd);
3914 int vt_disallocate(const char *name) {
3918 /* Deallocate the VT if possible. If not possible
3919 * (i.e. because it is the active one), at least clear it
3920 * entirely (including the scrollback buffer) */
3922 if (!startswith(name, "/dev/"))
3925 if (!tty_is_vc(name)) {
3926 /* So this is not a VT. I guess we cannot deallocate
3927 * it then. But let's at least clear the screen */
3929 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3934 "\033[r" /* clear scrolling region */
3935 "\033[H" /* move home */
3936 "\033[2J", /* clear screen */
3943 if (!startswith(name, "/dev/tty"))
3946 r = safe_atou(name+8, &u);
3953 /* Try to deallocate */
3954 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3958 r = ioctl(fd, VT_DISALLOCATE, u);
3967 /* Couldn't deallocate, so let's clear it fully with
3969 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3974 "\033[r" /* clear scrolling region */
3975 "\033[H" /* move home */
3976 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3983 int symlink_atomic(const char *from, const char *to) {
3984 _cleanup_free_ char *t = NULL;
3990 r = tempfn_random(to, &t);
3994 if (symlink(from, t) < 0)
3997 if (rename(t, to) < 0) {
4005 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4006 _cleanup_free_ char *t = NULL;
4011 r = tempfn_random(path, &t);
4015 if (mknod(t, mode, dev) < 0)
4018 if (rename(t, path) < 0) {
4026 int mkfifo_atomic(const char *path, mode_t mode) {
4027 _cleanup_free_ char *t = NULL;
4032 r = tempfn_random(path, &t);
4036 if (mkfifo(t, mode) < 0)
4039 if (rename(t, path) < 0) {
4047 bool display_is_local(const char *display) {
4051 display[0] == ':' &&
4052 display[1] >= '0' &&
4056 int socket_from_display(const char *display, char **path) {
4063 if (!display_is_local(display))
4066 k = strspn(display+1, "0123456789");
4068 f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4072 c = stpcpy(f, "/tmp/.X11-unix/X");
4073 memcpy(c, display+1, k);
4082 const char **username,
4083 uid_t *uid, gid_t *gid,
4085 const char **shell) {
4093 /* We enforce some special rules for uid=0: in order to avoid
4094 * NSS lookups for root we hardcode its data. */
4096 if (streq(*username, "root") || streq(*username, "0")) {
4114 if (parse_uid(*username, &u) >= 0) {
4118 /* If there are multiple users with the same id, make
4119 * sure to leave $USER to the configured value instead
4120 * of the first occurrence in the database. However if
4121 * the uid was configured by a numeric uid, then let's
4122 * pick the real username from /etc/passwd. */
4124 *username = p->pw_name;
4127 p = getpwnam(*username);
4131 return errno > 0 ? -errno : -ESRCH;
4143 *shell = p->pw_shell;
4148 char* uid_to_name(uid_t uid) {
4153 return strdup("root");
4157 return strdup(p->pw_name);
4159 if (asprintf(&r, UID_FMT, uid) < 0)
4165 char* gid_to_name(gid_t gid) {
4170 return strdup("root");
4174 return strdup(p->gr_name);
4176 if (asprintf(&r, GID_FMT, gid) < 0)
4182 int get_group_creds(const char **groupname, gid_t *gid) {
4188 /* We enforce some special rules for gid=0: in order to avoid
4189 * NSS lookups for root we hardcode its data. */
4191 if (streq(*groupname, "root") || streq(*groupname, "0")) {
4192 *groupname = "root";
4200 if (parse_gid(*groupname, &id) >= 0) {
4205 *groupname = g->gr_name;
4208 g = getgrnam(*groupname);
4212 return errno > 0 ? -errno : -ESRCH;
4220 int in_gid(gid_t gid) {
4222 int ngroups_max, r, i;
4224 if (getgid() == gid)
4227 if (getegid() == gid)
4230 ngroups_max = sysconf(_SC_NGROUPS_MAX);
4231 assert(ngroups_max > 0);
4233 gids = alloca(sizeof(gid_t) * ngroups_max);
4235 r = getgroups(ngroups_max, gids);
4239 for (i = 0; i < r; i++)
4246 int in_group(const char *name) {
4250 r = get_group_creds(&name, &gid);
4257 int glob_exists(const char *path) {
4258 _cleanup_globfree_ glob_t g = {};
4264 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4266 if (k == GLOB_NOMATCH)
4268 else if (k == GLOB_NOSPACE)
4271 return !strv_isempty(g.gl_pathv);
4273 return errno ? -errno : -EIO;
4276 int glob_extend(char ***strv, const char *path) {
4277 _cleanup_globfree_ glob_t g = {};
4282 k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4284 if (k == GLOB_NOMATCH)
4286 else if (k == GLOB_NOSPACE)
4288 else if (k != 0 || strv_isempty(g.gl_pathv))
4289 return errno ? -errno : -EIO;
4291 STRV_FOREACH(p, g.gl_pathv) {
4292 k = strv_extend(strv, *p);
4300 int dirent_ensure_type(DIR *d, struct dirent *de) {
4306 if (de->d_type != DT_UNKNOWN)
4309 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4313 S_ISREG(st.st_mode) ? DT_REG :
4314 S_ISDIR(st.st_mode) ? DT_DIR :
4315 S_ISLNK(st.st_mode) ? DT_LNK :
4316 S_ISFIFO(st.st_mode) ? DT_FIFO :
4317 S_ISSOCK(st.st_mode) ? DT_SOCK :
4318 S_ISCHR(st.st_mode) ? DT_CHR :
4319 S_ISBLK(st.st_mode) ? DT_BLK :
4325 int get_files_in_directory(const char *path, char ***list) {
4326 _cleanup_closedir_ DIR *d = NULL;
4327 size_t bufsize = 0, n = 0;
4328 _cleanup_strv_free_ char **l = NULL;
4332 /* Returns all files in a directory in *list, and the number
4333 * of files as return value. If list is NULL returns only the
4345 if (!de && errno != 0)
4350 dirent_ensure_type(d, de);
4352 if (!dirent_is_file(de))
4356 /* one extra slot is needed for the terminating NULL */
4357 if (!GREEDY_REALLOC(l, bufsize, n + 2))
4360 l[n] = strdup(de->d_name);
4371 l = NULL; /* avoid freeing */
4377 char *strjoin(const char *x, ...) {
4391 t = va_arg(ap, const char *);
4396 if (n > ((size_t) -1) - l) {
4420 t = va_arg(ap, const char *);
4434 bool is_main_thread(void) {
4435 static thread_local int cached = 0;
4437 if (_unlikely_(cached == 0))
4438 cached = getpid() == gettid() ? 1 : -1;
4443 int block_get_whole_disk(dev_t d, dev_t *ret) {
4450 /* If it has a queue this is good enough for us */
4451 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4454 r = access(p, F_OK);
4462 /* If it is a partition find the originating device */
4463 if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4466 r = access(p, F_OK);
4472 /* Get parent dev_t */
4473 if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4476 r = read_one_line_file(p, &s);
4482 r = sscanf(s, "%u:%u", &m, &n);
4488 /* Only return this if it is really good enough for us. */
4489 if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4492 r = access(p, F_OK);
4496 *ret = makedev(m, n);
4503 static const char *const ioprio_class_table[] = {
4504 [IOPRIO_CLASS_NONE] = "none",
4505 [IOPRIO_CLASS_RT] = "realtime",
4506 [IOPRIO_CLASS_BE] = "best-effort",
4507 [IOPRIO_CLASS_IDLE] = "idle"
4510 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4512 static const char *const sigchld_code_table[] = {
4513 [CLD_EXITED] = "exited",
4514 [CLD_KILLED] = "killed",
4515 [CLD_DUMPED] = "dumped",
4516 [CLD_TRAPPED] = "trapped",
4517 [CLD_STOPPED] = "stopped",
4518 [CLD_CONTINUED] = "continued",
4521 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4523 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4524 [LOG_FAC(LOG_KERN)] = "kern",
4525 [LOG_FAC(LOG_USER)] = "user",
4526 [LOG_FAC(LOG_MAIL)] = "mail",
4527 [LOG_FAC(LOG_DAEMON)] = "daemon",
4528 [LOG_FAC(LOG_AUTH)] = "auth",
4529 [LOG_FAC(LOG_SYSLOG)] = "syslog",
4530 [LOG_FAC(LOG_LPR)] = "lpr",
4531 [LOG_FAC(LOG_NEWS)] = "news",
4532 [LOG_FAC(LOG_UUCP)] = "uucp",
4533 [LOG_FAC(LOG_CRON)] = "cron",
4534 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4535 [LOG_FAC(LOG_FTP)] = "ftp",
4536 [LOG_FAC(LOG_LOCAL0)] = "local0",
4537 [LOG_FAC(LOG_LOCAL1)] = "local1",
4538 [LOG_FAC(LOG_LOCAL2)] = "local2",
4539 [LOG_FAC(LOG_LOCAL3)] = "local3",
4540 [LOG_FAC(LOG_LOCAL4)] = "local4",
4541 [LOG_FAC(LOG_LOCAL5)] = "local5",
4542 [LOG_FAC(LOG_LOCAL6)] = "local6",
4543 [LOG_FAC(LOG_LOCAL7)] = "local7"
4546 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4548 static const char *const log_level_table[] = {
4549 [LOG_EMERG] = "emerg",
4550 [LOG_ALERT] = "alert",
4551 [LOG_CRIT] = "crit",
4553 [LOG_WARNING] = "warning",
4554 [LOG_NOTICE] = "notice",
4555 [LOG_INFO] = "info",
4556 [LOG_DEBUG] = "debug"
4559 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4561 static const char* const sched_policy_table[] = {
4562 [SCHED_OTHER] = "other",
4563 [SCHED_BATCH] = "batch",
4564 [SCHED_IDLE] = "idle",
4565 [SCHED_FIFO] = "fifo",
4569 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4571 static const char* const rlimit_table[_RLIMIT_MAX] = {
4572 [RLIMIT_CPU] = "LimitCPU",
4573 [RLIMIT_FSIZE] = "LimitFSIZE",
4574 [RLIMIT_DATA] = "LimitDATA",
4575 [RLIMIT_STACK] = "LimitSTACK",
4576 [RLIMIT_CORE] = "LimitCORE",
4577 [RLIMIT_RSS] = "LimitRSS",
4578 [RLIMIT_NOFILE] = "LimitNOFILE",
4579 [RLIMIT_AS] = "LimitAS",
4580 [RLIMIT_NPROC] = "LimitNPROC",
4581 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4582 [RLIMIT_LOCKS] = "LimitLOCKS",
4583 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4584 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4585 [RLIMIT_NICE] = "LimitNICE",
4586 [RLIMIT_RTPRIO] = "LimitRTPRIO",
4587 [RLIMIT_RTTIME] = "LimitRTTIME"
4590 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4592 static const char* const ip_tos_table[] = {
4593 [IPTOS_LOWDELAY] = "low-delay",
4594 [IPTOS_THROUGHPUT] = "throughput",
4595 [IPTOS_RELIABILITY] = "reliability",
4596 [IPTOS_LOWCOST] = "low-cost",
4599 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4601 static const char *const __signal_table[] = {
4618 [SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
4629 [SIGVTALRM] = "VTALRM",
4631 [SIGWINCH] = "WINCH",
4637 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4639 const char *signal_to_string(int signo) {
4640 static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4643 name = __signal_to_string(signo);
4647 if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4648 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4650 snprintf(buf, sizeof(buf), "%d", signo);
4655 int signal_from_string(const char *s) {
4660 signo = __signal_from_string(s);
4664 if (startswith(s, "RTMIN+")) {
4668 if (safe_atou(s, &u) >= 0) {
4669 signo = (int) u + offset;
4670 if (signo > 0 && signo < _NSIG)
4676 bool kexec_loaded(void) {
4677 bool loaded = false;
4680 if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4688 int prot_from_flags(int flags) {
4690 switch (flags & O_ACCMODE) {
4699 return PROT_READ|PROT_WRITE;
4706 char *format_bytes(char *buf, size_t l, off_t t) {
4709 static const struct {
4713 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4714 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4715 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4716 { "G", 1024ULL*1024ULL*1024ULL },
4717 { "M", 1024ULL*1024ULL },
4721 if (t == (off_t) -1)
4724 for (i = 0; i < ELEMENTSOF(table); i++) {
4726 if (t >= table[i].factor) {
4729 (unsigned long long) (t / table[i].factor),
4730 (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4737 snprintf(buf, l, "%lluB", (unsigned long long) t);
4745 void* memdup(const void *p, size_t l) {
4758 int fd_inc_sndbuf(int fd, size_t n) {
4760 socklen_t l = sizeof(value);
4762 r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4763 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4766 /* If we have the privileges we will ignore the kernel limit. */
4769 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
4770 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
4776 int fd_inc_rcvbuf(int fd, size_t n) {
4778 socklen_t l = sizeof(value);
4780 r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4781 if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4784 /* If we have the privileges we will ignore the kernel limit. */
4787 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
4788 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
4793 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4794 bool stdout_is_tty, stderr_is_tty;
4795 pid_t parent_pid, agent_pid;
4796 sigset_t ss, saved_ss;
4804 /* Spawns a temporary TTY agent, making sure it goes away when
4807 parent_pid = getpid();
4809 /* First we temporarily block all signals, so that the new
4810 * child has them blocked initially. This way, we can be sure
4811 * that SIGTERMs are not lost we might send to the agent. */
4812 assert_se(sigfillset(&ss) >= 0);
4813 assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
4816 if (agent_pid < 0) {
4817 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
4821 if (agent_pid != 0) {
4822 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
4829 * Make sure the agent goes away when the parent dies */
4830 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4831 _exit(EXIT_FAILURE);
4833 /* Make sure we actually can kill the agent, if we need to, in
4834 * case somebody invoked us from a shell script that trapped
4835 * SIGTERM or so... */
4836 reset_all_signal_handlers();
4837 reset_signal_mask();
4839 /* Check whether our parent died before we were able
4840 * to set the death signal and unblock the signals */
4841 if (getppid() != parent_pid)
4842 _exit(EXIT_SUCCESS);
4844 /* Don't leak fds to the agent */
4845 close_all_fds(except, n_except);
4847 stdout_is_tty = isatty(STDOUT_FILENO);
4848 stderr_is_tty = isatty(STDERR_FILENO);
4850 if (!stdout_is_tty || !stderr_is_tty) {
4853 /* Detach from stdout/stderr. and reopen
4854 * /dev/tty for them. This is important to
4855 * ensure that when systemctl is started via
4856 * popen() or a similar call that expects to
4857 * read EOF we actually do generate EOF and
4858 * not delay this indefinitely by because we
4859 * keep an unused copy of stdin around. */
4860 fd = open("/dev/tty", O_WRONLY);
4862 log_error_errno(errno, "Failed to open /dev/tty: %m");
4863 _exit(EXIT_FAILURE);
4867 dup2(fd, STDOUT_FILENO);
4870 dup2(fd, STDERR_FILENO);
4876 /* Count arguments */
4878 for (n = 0; va_arg(ap, char*); n++)
4883 l = alloca(sizeof(char *) * (n + 1));
4885 /* Fill in arguments */
4887 for (i = 0; i <= n; i++)
4888 l[i] = va_arg(ap, char*);
4892 _exit(EXIT_FAILURE);
4895 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4896 struct rlimit highest, fixed;
4900 if (setrlimit(resource, rlim) >= 0)
4906 /* So we failed to set the desired setrlimit, then let's try
4907 * to get as close as we can */
4908 assert_se(getrlimit(resource, &highest) == 0);
4910 fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4911 fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4913 if (setrlimit(resource, &fixed) < 0)
4919 bool http_etag_is_valid(const char *etag) {
4923 if (!endswith(etag, "\""))
4926 if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
4932 bool http_url_is_valid(const char *url) {
4938 p = startswith(url, "http://");
4940 p = startswith(url, "https://");
4947 return ascii_is_valid(p);
4950 bool documentation_url_is_valid(const char *url) {
4956 if (http_url_is_valid(url))
4959 p = startswith(url, "file:/");
4961 p = startswith(url, "info:");
4963 p = startswith(url, "man:");
4968 return ascii_is_valid(p);
4971 bool in_initrd(void) {
4972 static int saved = -1;
4978 /* We make two checks here:
4980 * 1. the flag file /etc/initrd-release must exist
4981 * 2. the root file system must be a memory file system
4983 * The second check is extra paranoia, since misdetecting an
4984 * initrd can have bad bad consequences due the initrd
4985 * emptying when transititioning to the main systemd.
4988 saved = access("/etc/initrd-release", F_OK) >= 0 &&
4989 statfs("/", &s) >= 0 &&
4990 is_temporary_fs(&s);
4995 void warn_melody(void) {
4996 _cleanup_close_ int fd = -1;
4998 fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5002 /* Yeah, this is synchronous. Kinda sucks. But well... */
5004 ioctl(fd, KIOCSOUND, (int)(1193180/440));
5005 usleep(125*USEC_PER_MSEC);
5007 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5008 usleep(125*USEC_PER_MSEC);
5010 ioctl(fd, KIOCSOUND, (int)(1193180/220));
5011 usleep(125*USEC_PER_MSEC);
5013 ioctl(fd, KIOCSOUND, 0);
5016 int make_console_stdio(void) {
5019 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5021 fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
5023 return log_error_errno(fd, "Failed to acquire terminal: %m");
5027 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
5032 int get_home_dir(char **_h) {
5040 /* Take the user specified one */
5041 e = secure_getenv("HOME");
5042 if (e && path_is_absolute(e)) {
5051 /* Hardcode home directory for root to avoid NSS */
5054 h = strdup("/root");
5062 /* Check the database... */
5066 return errno > 0 ? -errno : -ESRCH;
5068 if (!path_is_absolute(p->pw_dir))
5071 h = strdup(p->pw_dir);
5079 int get_shell(char **_s) {
5087 /* Take the user specified one */
5088 e = getenv("SHELL");
5098 /* Hardcode home directory for root to avoid NSS */
5101 s = strdup("/bin/sh");
5109 /* Check the database... */
5113 return errno > 0 ? -errno : -ESRCH;
5115 if (!path_is_absolute(p->pw_shell))
5118 s = strdup(p->pw_shell);
5126 bool filename_is_valid(const char *p) {
5140 if (strlen(p) > FILENAME_MAX)
5146 bool string_is_safe(const char *p) {
5152 for (t = p; *t; t++) {
5153 if (*t > 0 && *t < ' ')
5156 if (strchr("\\\"\'\0x7f", *t))
5164 * Check if a string contains control characters. If 'ok' is non-NULL
5165 * it may be a string containing additional CCs to be considered OK.
5167 bool string_has_cc(const char *p, const char *ok) {
5172 for (t = p; *t; t++) {
5173 if (ok && strchr(ok, *t))
5176 if (*t > 0 && *t < ' ')
5186 bool path_is_safe(const char *p) {
5191 if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5194 if (strlen(p) > PATH_MAX)
5197 /* The following two checks are not really dangerous, but hey, they still are confusing */
5198 if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5201 if (strstr(p, "//"))
5207 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5208 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5209 int (*compar) (const void *, const void *, void *), void *arg) {
5218 p = (void *)(((const char *) base) + (idx * size));
5219 comparison = compar(key, p, arg);
5222 else if (comparison > 0)
5230 void init_gettext(void) {
5231 setlocale(LC_ALL, "");
5232 textdomain(GETTEXT_PACKAGE);
5235 bool is_locale_utf8(void) {
5237 static int cached_answer = -1;
5239 if (cached_answer >= 0)
5242 if (!setlocale(LC_ALL, "")) {
5243 cached_answer = true;
5247 set = nl_langinfo(CODESET);
5249 cached_answer = true;
5253 if (streq(set, "UTF-8")) {
5254 cached_answer = true;
5258 /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5259 * unset and everything can do to UTF-8 nowadays. */
5260 set = setlocale(LC_CTYPE, NULL);
5262 cached_answer = true;
5266 /* Check result, but ignore the result if C was set
5270 !getenv("LC_ALL") &&
5271 !getenv("LC_CTYPE") &&
5275 return (bool) cached_answer;
5278 const char *draw_special_char(DrawSpecialChar ch) {
5279 static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5282 [DRAW_TREE_VERTICAL] = "\342\224\202 ", /* │ */
5283 [DRAW_TREE_BRANCH] = "\342\224\234\342\224\200", /* ├─ */
5284 [DRAW_TREE_RIGHT] = "\342\224\224\342\224\200", /* └─ */
5285 [DRAW_TREE_SPACE] = " ", /* */
5286 [DRAW_TRIANGULAR_BULLET] = "\342\200\243", /* ‣ */
5287 [DRAW_BLACK_CIRCLE] = "\342\227\217", /* ● */
5288 [DRAW_ARROW] = "\342\206\222", /* → */
5289 [DRAW_DASH] = "\342\200\223", /* – */
5292 /* ASCII fallback */ {
5293 [DRAW_TREE_VERTICAL] = "| ",
5294 [DRAW_TREE_BRANCH] = "|-",
5295 [DRAW_TREE_RIGHT] = "`-",
5296 [DRAW_TREE_SPACE] = " ",
5297 [DRAW_TRIANGULAR_BULLET] = ">",
5298 [DRAW_BLACK_CIRCLE] = "*",
5299 [DRAW_ARROW] = "->",
5304 return draw_table[!is_locale_utf8()][ch];
5307 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5310 size_t l, old_len, new_len;
5316 old_len = strlen(old_string);
5317 new_len = strlen(new_string);
5330 if (!startswith(f, old_string)) {
5336 nl = l - old_len + new_len;
5337 a = realloc(r, nl + 1);
5345 t = stpcpy(t, new_string);
5357 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5358 const char *i, *begin = NULL;
5363 } state = STATE_OTHER;
5365 size_t osz = 0, isz;
5371 /* Strips ANSI color and replaces TABs by 8 spaces */
5373 isz = _isz ? *_isz : strlen(*ibuf);
5375 f = open_memstream(&obuf, &osz);
5379 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5384 if (i >= *ibuf + isz) /* EOT */
5386 else if (*i == '\x1B')
5387 state = STATE_ESCAPE;
5388 else if (*i == '\t')
5395 if (i >= *ibuf + isz) { /* EOT */
5398 } else if (*i == '[') {
5399 state = STATE_BRACKET;
5404 state = STATE_OTHER;
5411 if (i >= *ibuf + isz || /* EOT */
5412 (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5415 state = STATE_OTHER;
5417 } else if (*i == 'm')
5418 state = STATE_OTHER;
5440 int on_ac_power(void) {
5441 bool found_offline = false, found_online = false;
5442 _cleanup_closedir_ DIR *d = NULL;
5444 d = opendir("/sys/class/power_supply");
5446 return errno == ENOENT ? true : -errno;
5450 _cleanup_close_ int fd = -1, device = -1;
5456 if (!de && errno != 0)
5462 if (hidden_file(de->d_name))
5465 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5467 if (errno == ENOENT || errno == ENOTDIR)
5473 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5475 if (errno == ENOENT)
5481 n = read(fd, contents, sizeof(contents));
5485 if (n != 6 || memcmp(contents, "Mains\n", 6))
5489 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5491 if (errno == ENOENT)
5497 n = read(fd, contents, sizeof(contents));
5501 if (n != 2 || contents[1] != '\n')
5504 if (contents[0] == '1') {
5505 found_online = true;
5507 } else if (contents[0] == '0')
5508 found_offline = true;
5513 return found_online || !found_offline;
5516 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
5523 if (!path_strv_resolve_uniq(search, root))
5526 STRV_FOREACH(i, search) {
5527 _cleanup_free_ char *p = NULL;
5531 p = strjoin(root, *i, "/", path, NULL);
5533 p = strjoin(*i, "/", path, NULL);
5543 if (errno != ENOENT)
5550 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
5551 _cleanup_strv_free_ char **copy = NULL;
5557 if (path_is_absolute(path)) {
5560 f = fopen(path, mode);
5569 copy = strv_copy((char**) search);
5573 return search_and_fopen_internal(path, mode, root, copy, _f);
5576 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
5577 _cleanup_strv_free_ char **s = NULL;
5579 if (path_is_absolute(path)) {
5582 f = fopen(path, mode);
5591 s = strv_split_nulstr(search);
5595 return search_and_fopen_internal(path, mode, root, s, _f);
5598 char *strextend(char **x, ...) {
5605 l = f = *x ? strlen(*x) : 0;
5612 t = va_arg(ap, const char *);
5617 if (n > ((size_t) -1) - l) {
5626 r = realloc(*x, l+1);
5636 t = va_arg(ap, const char *);
5650 char *strrep(const char *s, unsigned n) {
5658 p = r = malloc(l * n + 1);
5662 for (i = 0; i < n; i++)
5669 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
5676 if (*allocated >= need)
5679 newalloc = MAX(need * 2, 64u / size);
5680 a = newalloc * size;
5682 /* check for overflows */
5683 if (a < size * need)
5691 *allocated = newalloc;
5695 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
5704 q = greedy_realloc(p, allocated, need, size);
5708 if (*allocated > prev)
5709 memzero(q + prev * size, (*allocated - prev) * size);
5714 bool id128_is_valid(const char *s) {
5720 /* Simple formatted 128bit hex string */
5722 for (i = 0; i < l; i++) {
5725 if (!(c >= '0' && c <= '9') &&
5726 !(c >= 'a' && c <= 'z') &&
5727 !(c >= 'A' && c <= 'Z'))
5731 } else if (l == 36) {
5733 /* Formatted UUID */
5735 for (i = 0; i < l; i++) {
5738 if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5742 if (!(c >= '0' && c <= '9') &&
5743 !(c >= 'a' && c <= 'z') &&
5744 !(c >= 'A' && c <= 'Z'))
5755 int split_pair(const char *s, const char *sep, char **l, char **r) {
5770 a = strndup(s, x - s);
5774 b = strdup(x + strlen(sep));
5786 int shall_restore_state(void) {
5787 _cleanup_free_ char *value = NULL;
5790 r = get_proc_cmdline_key("systemd.restore_state=", &value);
5796 return parse_boolean(value) != 0;
5799 int proc_cmdline(char **ret) {
5802 if (detect_container(NULL) > 0)
5803 return get_process_cmdline(1, 0, false, ret);
5805 return read_one_line_file("/proc/cmdline", ret);
5808 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
5809 _cleanup_free_ char *line = NULL;
5815 r = proc_cmdline(&line);
5821 _cleanup_free_ char *word = NULL;
5824 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
5830 /* Filter out arguments that are intended only for the
5832 if (!in_initrd() && startswith(word, "rd."))
5835 value = strchr(word, '=');
5839 r = parse_item(word, value);
5847 int get_proc_cmdline_key(const char *key, char **value) {
5848 _cleanup_free_ char *line = NULL, *ret = NULL;
5855 r = proc_cmdline(&line);
5861 _cleanup_free_ char *word = NULL;
5864 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
5870 /* Filter out arguments that are intended only for the
5872 if (!in_initrd() && startswith(word, "rd."))
5876 e = startswith(word, key);
5880 r = free_and_strdup(&ret, e);
5886 if (streq(word, key))
5900 int container_get_leader(const char *machine, pid_t *pid) {
5901 _cleanup_free_ char *s = NULL, *class = NULL;
5909 p = strjoina("/run/systemd/machines/", machine);
5910 r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
5918 if (!streq_ptr(class, "container"))
5921 r = parse_pid(s, &leader);
5931 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
5932 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
5940 mntns = procfs_file_alloca(pid, "ns/mnt");
5941 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5949 pidns = procfs_file_alloca(pid, "ns/pid");
5950 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5958 netns = procfs_file_alloca(pid, "ns/net");
5959 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5967 root = procfs_file_alloca(pid, "root");
5968 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
5974 *pidns_fd = pidnsfd;
5977 *mntns_fd = mntnsfd;
5980 *netns_fd = netnsfd;
5985 pidnsfd = mntnsfd = netnsfd = -1;
5990 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
5993 if (setns(pidns_fd, CLONE_NEWPID) < 0)
5997 if (setns(mntns_fd, CLONE_NEWNS) < 0)
6001 if (setns(netns_fd, CLONE_NEWNET) < 0)
6005 if (fchdir(root_fd) < 0)
6008 if (chroot(".") < 0)
6012 if (setresgid(0, 0, 0) < 0)
6015 if (setgroups(0, NULL) < 0)
6018 if (setresuid(0, 0, 0) < 0)
6024 int getpeercred(int fd, struct ucred *ucred) {
6025 socklen_t n = sizeof(struct ucred);
6032 r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6036 if (n != sizeof(struct ucred))
6039 /* Check if the data is actually useful and not suppressed due
6040 * to namespacing issues */
6043 if (u.uid == UID_INVALID)
6045 if (u.gid == GID_INVALID)
6052 int getpeersec(int fd, char **ret) {
6064 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6068 if (errno != ERANGE)
6075 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6091 /* This is much like like mkostemp() but is subject to umask(). */
6092 int mkostemp_safe(char *pattern, int flags) {
6093 _cleanup_umask_ mode_t u;
6100 fd = mkostemp(pattern, flags);
6107 int open_tmpfile(const char *path, int flags) {
6114 /* Try O_TMPFILE first, if it is supported */
6115 fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6120 /* Fall back to unguessable name + unlinking */
6121 p = strjoina(path, "/systemd-tmp-XXXXXX");
6123 fd = mkostemp_safe(p, flags);
6131 int fd_warn_permissions(const char *path, int fd) {
6134 if (fstat(fd, &st) < 0)
6137 if (st.st_mode & 0111)
6138 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6140 if (st.st_mode & 0002)
6141 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6143 if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6144 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
6149 unsigned long personality_from_string(const char *p) {
6151 /* Parse a personality specifier. We introduce our own
6152 * identifiers that indicate specific ABIs, rather than just
6153 * hints regarding the register size, since we want to keep
6154 * things open for multiple locally supported ABIs for the
6155 * same register size. We try to reuse the ABI identifiers
6156 * used by libseccomp. */
6158 #if defined(__x86_64__)
6160 if (streq(p, "x86"))
6163 if (streq(p, "x86-64"))
6166 #elif defined(__i386__)
6168 if (streq(p, "x86"))
6172 /* personality(7) documents that 0xffffffffUL is used for
6173 * querying the current personality, hence let's use that here
6174 * as error indicator. */
6175 return 0xffffffffUL;
6178 const char* personality_to_string(unsigned long p) {
6180 #if defined(__x86_64__)
6182 if (p == PER_LINUX32)
6188 #elif defined(__i386__)
6197 uint64_t physical_memory(void) {
6200 /* We return this as uint64_t in case we are running as 32bit
6201 * process on a 64bit kernel with huge amounts of memory */
6203 mem = sysconf(_SC_PHYS_PAGES);
6206 return (uint64_t) mem * (uint64_t) page_size();
6209 void hexdump(FILE *f, const void *p, size_t s) {
6210 const uint8_t *b = p;
6213 assert(s == 0 || b);
6218 fprintf(f, "%04x ", n);
6220 for (i = 0; i < 16; i++) {
6225 fprintf(f, "%02x ", b[i]);
6233 for (i = 0; i < 16; i++) {
6238 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6252 int update_reboot_param_file(const char *param) {
6257 r = write_string_file(REBOOT_PARAM_FILE, param);
6259 log_error("Failed to write reboot param to "
6260 REBOOT_PARAM_FILE": %s", strerror(-r));
6262 unlink(REBOOT_PARAM_FILE);
6267 int umount_recursive(const char *prefix, int flags) {
6271 /* Try to umount everything recursively below a
6272 * directory. Also, take care of stacked mounts, and keep
6273 * unmounting them until they are gone. */
6276 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6281 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6282 if (!proc_self_mountinfo)
6286 _cleanup_free_ char *path = NULL, *p = NULL;
6289 k = fscanf(proc_self_mountinfo,
6290 "%*s " /* (1) mount id */
6291 "%*s " /* (2) parent id */
6292 "%*s " /* (3) major:minor */
6293 "%*s " /* (4) root */
6294 "%ms " /* (5) mount point */
6295 "%*s" /* (6) mount options */
6296 "%*[^-]" /* (7) optional fields */
6297 "- " /* (8) separator */
6298 "%*s " /* (9) file system type */
6299 "%*s" /* (10) mount source */
6300 "%*s" /* (11) mount options 2 */
6301 "%*[^\n]", /* some rubbish at the end */
6310 r = cunescape(path, UNESCAPE_RELAX, &p);
6314 if (!path_startswith(p, prefix))
6317 if (umount2(p, flags) < 0) {
6333 static int get_mount_flags(const char *path, unsigned long *flags) {
6336 if (statvfs(path, &buf) < 0)
6338 *flags = buf.f_flag;
6342 int bind_remount_recursive(const char *prefix, bool ro) {
6343 _cleanup_set_free_free_ Set *done = NULL;
6344 _cleanup_free_ char *cleaned = NULL;
6347 /* Recursively remount a directory (and all its submounts)
6348 * read-only or read-write. If the directory is already
6349 * mounted, we reuse the mount and simply mark it
6350 * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6351 * operation). If it isn't we first make it one. Afterwards we
6352 * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6353 * submounts we can access, too. When mounts are stacked on
6354 * the same mount point we only care for each individual
6355 * "top-level" mount on each point, as we cannot
6356 * influence/access the underlying mounts anyway. We do not
6357 * have any effect on future submounts that might get
6358 * propagated, they migt be writable. This includes future
6359 * submounts that have been triggered via autofs. */
6361 cleaned = strdup(prefix);
6365 path_kill_slashes(cleaned);
6367 done = set_new(&string_hash_ops);
6372 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6373 _cleanup_set_free_free_ Set *todo = NULL;
6374 bool top_autofs = false;
6376 unsigned long orig_flags;
6378 todo = set_new(&string_hash_ops);
6382 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6383 if (!proc_self_mountinfo)
6387 _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6390 k = fscanf(proc_self_mountinfo,
6391 "%*s " /* (1) mount id */
6392 "%*s " /* (2) parent id */
6393 "%*s " /* (3) major:minor */
6394 "%*s " /* (4) root */
6395 "%ms " /* (5) mount point */
6396 "%*s" /* (6) mount options (superblock) */
6397 "%*[^-]" /* (7) optional fields */
6398 "- " /* (8) separator */
6399 "%ms " /* (9) file system type */
6400 "%*s" /* (10) mount source */
6401 "%*s" /* (11) mount options (bind mount) */
6402 "%*[^\n]", /* some rubbish at the end */
6412 r = cunescape(path, UNESCAPE_RELAX, &p);
6416 /* Let's ignore autofs mounts. If they aren't
6417 * triggered yet, we want to avoid triggering
6418 * them, as we don't make any guarantees for
6419 * future submounts anyway. If they are
6420 * already triggered, then we will find
6421 * another entry for this. */
6422 if (streq(type, "autofs")) {
6423 top_autofs = top_autofs || path_equal(cleaned, p);
6427 if (path_startswith(p, cleaned) &&
6428 !set_contains(done, p)) {
6430 r = set_consume(todo, p);
6440 /* If we have no submounts to process anymore and if
6441 * the root is either already done, or an autofs, we
6443 if (set_isempty(todo) &&
6444 (top_autofs || set_contains(done, cleaned)))
6447 if (!set_contains(done, cleaned) &&
6448 !set_contains(todo, cleaned)) {
6449 /* The prefix directory itself is not yet a
6450 * mount, make it one. */
6451 if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6455 (void) get_mount_flags(cleaned, &orig_flags);
6456 orig_flags &= ~MS_RDONLY;
6458 if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6461 x = strdup(cleaned);
6465 r = set_consume(done, x);
6470 while ((x = set_steal_first(todo))) {
6472 r = set_consume(done, x);
6478 /* Try to reuse the original flag set, but
6479 * don't care for errors, in case of
6480 * obstructed mounts */
6482 (void) get_mount_flags(x, &orig_flags);
6483 orig_flags &= ~MS_RDONLY;
6485 if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
6487 /* Deal with mount points that are
6488 * obstructed by a later mount */
6490 if (errno != ENOENT)
6498 int fflush_and_check(FILE *f) {
6505 return errno ? -errno : -EIO;
6510 int tempfn_xxxxxx(const char *p, char **ret) {
6522 * /foo/bar/.#waldoXXXXXX
6526 if (!filename_is_valid(fn))
6529 t = new(char, strlen(p) + 2 + 6 + 1);
6533 strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
6535 *ret = path_kill_slashes(t);
6539 int tempfn_random(const char *p, char **ret) {
6553 * /foo/bar/.#waldobaa2a261115984a9
6557 if (!filename_is_valid(fn))
6560 t = new(char, strlen(p) + 2 + 16 + 1);
6564 x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
6567 for (i = 0; i < 16; i++) {
6568 *(x++) = hexchar(u & 0xF);
6574 *ret = path_kill_slashes(t);
6578 int tempfn_random_child(const char *p, char **ret) {
6589 * /foo/bar/waldo/.#3c2b6219aa75d7d0
6592 t = new(char, strlen(p) + 3 + 16 + 1);
6596 x = stpcpy(stpcpy(t, p), "/.#");
6599 for (i = 0; i < 16; i++) {
6600 *(x++) = hexchar(u & 0xF);
6606 *ret = path_kill_slashes(t);
6610 /* make sure the hostname is not "localhost" */
6611 bool is_localhost(const char *hostname) {
6614 /* This tries to identify local host and domain names
6615 * described in RFC6761 plus the redhatism of .localdomain */
6617 return streq(hostname, "localhost") ||
6618 streq(hostname, "localhost.") ||
6619 streq(hostname, "localdomain.") ||
6620 streq(hostname, "localdomain") ||
6621 endswith(hostname, ".localhost") ||
6622 endswith(hostname, ".localhost.") ||
6623 endswith(hostname, ".localdomain") ||
6624 endswith(hostname, ".localdomain.");
6627 int take_password_lock(const char *root) {
6629 struct flock flock = {
6631 .l_whence = SEEK_SET,
6639 /* This is roughly the same as lckpwdf(), but not as awful. We
6640 * don't want to use alarm() and signals, hence we implement
6641 * our own trivial version of this.
6643 * Note that shadow-utils also takes per-database locks in
6644 * addition to lckpwdf(). However, we don't given that they
6645 * are redundant as they they invoke lckpwdf() first and keep
6646 * it during everything they do. The per-database locks are
6647 * awfully racy, and thus we just won't do them. */
6650 path = strjoina(root, "/etc/.pwd.lock");
6652 path = "/etc/.pwd.lock";
6654 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
6658 r = fcntl(fd, F_SETLKW, &flock);
6667 int is_symlink(const char *path) {
6670 if (lstat(path, &info) < 0)
6673 return !!S_ISLNK(info.st_mode);
6676 int is_dir(const char* path, bool follow) {
6681 r = stat(path, &st);
6683 r = lstat(path, &st);
6687 return !!S_ISDIR(st.st_mode);
6690 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
6691 _cleanup_free_ char *s = NULL;
6692 size_t allocated = 0, sz = 0;
6700 SINGLE_QUOTE_ESCAPE,
6702 DOUBLE_QUOTE_ESCAPE,
6710 /* Parses the first word of a string, and returns it in
6711 * *ret. Removes all quotes in the process. When parsing fails
6712 * (because of an uneven number of quotes or similar), leaves
6713 * the pointer *p at the first invalid character. */
6723 else if (strchr(WHITESPACE, c))
6733 state = SINGLE_QUOTE;
6735 state = VALUE_ESCAPE;
6737 state = DOUBLE_QUOTE;
6738 else if (strchr(WHITESPACE, c))
6741 if (!GREEDY_REALLOC(s, allocated, sz+2))
6751 if (flags & UNQUOTE_RELAX)
6756 if (!GREEDY_REALLOC(s, allocated, sz+7))
6759 if (flags & UNQUOTE_CUNESCAPE) {
6762 r = cunescape_one(*p, (size_t) -1, &c, &u);
6769 s[sz++] = c; /* normal explicit char */
6771 sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
6780 if (flags & UNQUOTE_RELAX)
6783 } else if (c == '\'')
6786 state = SINGLE_QUOTE_ESCAPE;
6788 if (!GREEDY_REALLOC(s, allocated, sz+2))
6796 case SINGLE_QUOTE_ESCAPE:
6798 if (flags & UNQUOTE_RELAX)
6803 if (!GREEDY_REALLOC(s, allocated, sz+7))
6806 if (flags & UNQUOTE_CUNESCAPE) {
6809 r = cunescape_one(*p, (size_t) -1, &c, &u);
6818 sz += utf8_encode_unichar(s + sz, u);
6822 state = SINGLE_QUOTE;
6831 state = DOUBLE_QUOTE_ESCAPE;
6833 if (!GREEDY_REALLOC(s, allocated, sz+2))
6841 case DOUBLE_QUOTE_ESCAPE:
6843 if (flags & UNQUOTE_RELAX)
6848 if (!GREEDY_REALLOC(s, allocated, sz+7))
6851 if (flags & UNQUOTE_CUNESCAPE) {
6854 r = cunescape_one(*p, (size_t) -1, &c, &u);
6863 sz += utf8_encode_unichar(s + sz, u);
6867 state = DOUBLE_QUOTE;
6873 if (!strchr(WHITESPACE, c))
6895 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
6900 /* Parses a number of words from a string, stripping any
6901 * quotes if necessary. */
6905 /* Count how many words are expected */
6906 va_start(ap, flags);
6908 if (!va_arg(ap, char **))
6917 /* Read all words into a temporary array */
6918 l = newa0(char*, n);
6919 for (c = 0; c < n; c++) {
6921 r = unquote_first_word(p, &l[c], flags);
6925 for (j = 0; j < c; j++)
6935 /* If we managed to parse all words, return them in the passed
6937 va_start(ap, flags);
6938 for (i = 0; i < n; i++) {
6941 v = va_arg(ap, char **);
6951 int free_and_strdup(char **p, const char *s) {
6956 /* Replaces a string pointer with an strdup()ed new string,
6957 * possibly freeing the old one. */
6972 int sethostname_idempotent(const char *s) {
6974 char buf[HOST_NAME_MAX + 1] = {};
6978 r = gethostname(buf, sizeof(buf));
6985 r = sethostname(s, strlen(s));
6992 int ptsname_malloc(int fd, char **ret) {
7005 if (ptsname_r(fd, c, l) == 0) {
7009 if (errno != ERANGE) {
7019 int openpt_in_namespace(pid_t pid, int flags) {
7020 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
7021 _cleanup_close_pair_ int pair[2] = { -1, -1 };
7023 struct cmsghdr cmsghdr;
7024 uint8_t buf[CMSG_SPACE(sizeof(int))];
7026 struct msghdr mh = {
7027 .msg_control = &control,
7028 .msg_controllen = sizeof(control),
7030 struct cmsghdr *cmsg;
7037 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
7041 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
7051 pair[0] = safe_close(pair[0]);
7053 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
7055 _exit(EXIT_FAILURE);
7057 master = posix_openpt(flags);
7059 _exit(EXIT_FAILURE);
7061 cmsg = CMSG_FIRSTHDR(&mh);
7062 cmsg->cmsg_level = SOL_SOCKET;
7063 cmsg->cmsg_type = SCM_RIGHTS;
7064 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
7065 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
7067 mh.msg_controllen = cmsg->cmsg_len;
7069 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
7070 _exit(EXIT_FAILURE);
7072 _exit(EXIT_SUCCESS);
7075 pair[1] = safe_close(pair[1]);
7077 r = wait_for_terminate(child, &si);
7080 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
7083 if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
7086 for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
7087 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
7091 fds = (int*) CMSG_DATA(cmsg);
7092 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
7095 close_many(fds, n_fds);
7105 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
7106 _cleanup_close_ int fd = -1;
7109 /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
7111 fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
7115 l = fgetxattr(fd, attribute, value, size);
7122 static int parse_crtime(le64_t le, usec_t *usec) {
7128 if (u == 0 || u == (uint64_t) -1)
7135 int fd_getcrtime(int fd, usec_t *usec) {
7142 /* Until Linux gets a real concept of birthtime/creation time,
7143 * let's fake one with xattrs */
7145 n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
7148 if (n != sizeof(le))
7151 return parse_crtime(le, usec);
7154 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
7158 n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
7161 if (n != sizeof(le))
7164 return parse_crtime(le, usec);
7167 int path_getcrtime(const char *p, usec_t *usec) {
7174 n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
7177 if (n != sizeof(le))
7180 return parse_crtime(le, usec);
7183 int fd_setcrtime(int fd, usec_t usec) {
7189 usec = now(CLOCK_REALTIME);
7191 le = htole64((uint64_t) usec);
7192 if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
7198 int chattr_fd(int fd, unsigned value, unsigned mask) {
7199 unsigned old_attr, new_attr;
7206 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
7209 new_attr = (old_attr & ~mask) | (value & mask);
7210 if (new_attr == old_attr)
7213 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
7219 int chattr_path(const char *p, unsigned value, unsigned mask) {
7220 _cleanup_close_ int fd = -1;
7227 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7231 return chattr_fd(fd, value, mask);
7234 int read_attr_fd(int fd, unsigned *ret) {
7237 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
7243 int read_attr_path(const char *p, unsigned *ret) {
7244 _cleanup_close_ int fd = -1;
7249 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7253 return read_attr_fd(fd, ret);
7256 int make_lock_file(const char *p, int operation, LockFile *ret) {
7257 _cleanup_close_ int fd = -1;
7258 _cleanup_free_ char *t = NULL;
7262 * We use UNPOSIX locks if they are available. They have nice
7263 * semantics, and are mostly compatible with NFS. However,
7264 * they are only available on new kernels. When we detect we
7265 * are running on an older kernel, then we fall back to good
7266 * old BSD locks. They also have nice semantics, but are
7267 * slightly problematic on NFS, where they are upgraded to
7268 * POSIX locks, even though locally they are orthogonal to
7278 .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
7279 .l_whence = SEEK_SET,
7283 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
7287 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
7290 /* If the kernel is too old, use good old BSD locks */
7291 if (errno == EINVAL)
7292 r = flock(fd, operation);
7295 return errno == EAGAIN ? -EBUSY : -errno;
7298 /* If we acquired the lock, let's check if the file
7299 * still exists in the file system. If not, then the
7300 * previous exclusive owner removed it and then closed
7301 * it. In such a case our acquired lock is worthless,
7302 * hence try again. */
7307 if (st.st_nlink > 0)
7310 fd = safe_close(fd);
7315 ret->operation = operation;
7323 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
7331 if (!filename_is_valid(fn))
7334 t = newa(char, strlen(p) + 2 + 4 + 1);
7335 stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
7337 return make_lock_file(t, operation, ret);
7340 void release_lock_file(LockFile *f) {
7348 /* If we are the exclusive owner we can safely delete
7349 * the lock file itself. If we are not the exclusive
7350 * owner, we can try becoming it. */
7353 (f->operation & ~LOCK_NB) == LOCK_SH) {
7354 static const struct flock fl = {
7356 .l_whence = SEEK_SET,
7359 r = fcntl(f->fd, F_OFD_SETLK, &fl);
7360 if (r < 0 && errno == EINVAL)
7361 r = flock(f->fd, LOCK_EX|LOCK_NB);
7364 f->operation = LOCK_EX|LOCK_NB;
7367 if ((f->operation & ~LOCK_NB) == LOCK_EX)
7368 unlink_noerrno(f->path);
7374 f->fd = safe_close(f->fd);
7378 static size_t nul_length(const uint8_t *p, size_t sz) {
7393 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
7394 const uint8_t *q, *w, *e;
7402 n = nul_length(q, e - q);
7404 /* If there are more than the specified run length of
7405 * NUL bytes, or if this is the beginning or the end
7406 * of the buffer, then seek instead of write */
7407 if ((n > run_length) ||
7408 (n > 0 && q == p) ||
7409 (n > 0 && q + n >= e)) {
7411 l = write(fd, w, q - w);
7418 if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
7430 l = write(fd, w, q - w);
7437 return q - (const uint8_t*) p;
7440 void sigkill_wait(pid_t *pid) {
7446 if (kill(*pid, SIGKILL) > 0)
7447 (void) wait_for_terminate(*pid, NULL);
7450 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
7451 int a = 0, b = 0, c = 0;
7461 if (!strchr(*p, '>'))
7464 if ((*p)[2] == '>') {
7465 c = undecchar((*p)[1]);
7467 } else if ((*p)[3] == '>') {
7468 b = undecchar((*p)[1]);
7469 c = undecchar((*p)[2]);
7471 } else if ((*p)[4] == '>') {
7472 a = undecchar((*p)[1]);
7473 b = undecchar((*p)[2]);
7474 c = undecchar((*p)[3]);
7479 if (a < 0 || b < 0 || c < 0 ||
7480 (!with_facility && (a || b || c > 7)))
7484 *priority = a*100 + b*10 + c;
7486 *priority = (*priority & LOG_FACMASK) | c;
7492 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
7498 for (i = 0; i < len; ++i)
7499 if (streq_ptr(table[i], key))
7505 void cmsg_close_all(struct msghdr *mh) {
7506 struct cmsghdr *cmsg;
7510 for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
7511 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
7512 close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
7515 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
7519 ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
7523 /* Even though renameat2() exists since Linux 3.15, btrfs added
7524 * support for it later. If it is not implemented, fallback to another
7526 if (errno != EINVAL)
7529 /* The link()/unlink() fallback does not work on directories. But
7530 * renameat() without RENAME_NOREPLACE gives the same semantics on
7531 * directories, except when newpath is an *empty* directory. This is
7533 ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
7534 if (ret >= 0 && S_ISDIR(buf.st_mode)) {
7535 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
7536 return ret >= 0 ? 0 : -errno;
7539 /* If it is not a directory, use the link()/unlink() fallback. */
7540 ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
7544 ret = unlinkat(olddirfd, oldpath, 0);
7546 /* backup errno before the following unlinkat() alters it */
7548 (void) unlinkat(newdirfd, newpath, 0);
7556 char *shell_maybe_quote(const char *s) {
7562 /* Encloses a string in double quotes if necessary to make it
7563 * OK as shell string. */
7565 for (p = s; *p; p++)
7568 strchr(SHELL_NEED_QUOTES, *p))
7574 r = new(char, 1+strlen(s)*2+1+1);
7580 t = mempcpy(t, s, p - s);
7584 if (strchr(SHELL_NEED_ESCAPE, *p))
7596 int parse_mode(const char *s, mode_t *ret) {
7604 l = strtol(s, &x, 8);
7608 if (!x || x == s || *x)
7610 if (l < 0 || l > 07777)