HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/basic/string-util.c
Git blob: 26602ac771c93743fe1b835d5b80d053f3c6c101
Lines 1001–1681 of 1,681
char *n;
/* Wasn't enough. Then let's allocate exactly what we need. */
if (_unlikely_((size_t) l > SIZE_MAX - (l_separator + 1))) /* overflow check #1 */
goto oom;
if (_unlikely_(m > SIZE_MAX - ((size_t) l + l_separator + 1))) /* overflow check #2 */
goto oom;
a = m + (size_t) l + l_separator + 1;
n = realloc(*x, a);
if (!n)
goto oom;
*x = n;
va_start(ap, format);
l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
va_end(ap);
assert((size_t) l < a - m - l_separator);
}
return 0;
oom:
/* truncate the bytes added after memcpy_safe() again */
(*x)[m] = 0;
return -ENOMEM;
}
char* strrep(const char *s, size_t n) {
char *ret, *p;
size_t l;
assert(s);
l = strlen(s);
if (!MUL_ASSIGN_SAFE(&l, n))
return NULL;
if (!INC_SAFE(&l, 1))
return NULL;
p = ret = malloc(l);
if (!ret)
return NULL;
for (size_t i = 0; i < n; i++)
p = stpcpy(p, s);
*p = 0;
return ret;
}
int split_pair(const char *s, const char *sep, char **ret_first, char **ret_second) {
assert(s);
assert(!isempty(sep));
const char *x = strstr(s, sep);
if (!x)
return -EINVAL;
_cleanup_free_ char *a = NULL;
if (ret_first) {
a = strndup(s, x - s);
if (!a)
return -ENOMEM;
}
_cleanup_free_ char *b = NULL;
if (ret_second) {
b = strdup(x + strlen(sep));
if (!b)
return -ENOMEM;
}
if (ret_first)
*ret_first = TAKE_PTR(a);
if (ret_second)
*ret_second = TAKE_PTR(b);
return 0;
}
int free_and_strdup(char **p, const char *s) {
char *t;
assert(p);
/* Replaces a string pointer with a strdup()ed new string,
* possibly freeing the old one. */
if (streq_ptr(*p, s))
return 0;
if (s) {
t = strdup(s);
if (!t)
return -ENOMEM;
} else
t = NULL;
free_and_replace(*p, t);
return 1;
}
int free_and_strdup_warn(char **p, const char *s) {
int r;
r = free_and_strdup(p, s);
if (r < 0)
return log_oom();
return r;
}
int free_and_strndup(char **p, const char *s, size_t l) {
char *t;
assert(p);
assert(s || l == 0);
/* Replaces a string pointer with a strndup()ed new string,
* freeing the old one. */
if (!*p && !s)
return 0;
if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
return 0;
if (s) {
t = strndup(s, l);
if (!t)
return -ENOMEM;
} else
t = NULL;
free_and_replace(*p, t);
return 1;
}
int strdup_to_full(char **ret, const char *src) {
if (!src) {
if (ret)
*ret = NULL;
return 0;
} else {
if (ret) {
char *t = strdup(src);
if (!t)
return -ENOMEM;
*ret = t;
}
return 1;
}
};
bool string_is_safe(const char *p, StringSafeFlags flags) {
/* Baseline checks are:
* • No control characters (i.e. 0…31 + 127)
* • UTF-8 valid (well, technically we skip this test if STRING_ASCII is set, since that is a tighter test)
*/
if (FLAGS_SET(flags, STRING_ALLOW_EMPTY) ? !p : isempty(p))
return false;
if (!FLAGS_SET(flags, STRING_ASCII) && !utf8_is_valid(p))
return false;
for (const char *t = p; *t; t++) {
/* never allow control characters, except for new line */
if ((*t > 0 && *t < ' ' && *t != '\n') || *t == 0x7f)
return false;
if (!FLAGS_SET(flags, STRING_ALLOW_NEWLINES) && *t == '\n')
return false;
if (!FLAGS_SET(flags, STRING_ALLOW_BACKSLASHES) && *t == '\\')
return false;
if (!FLAGS_SET(flags, STRING_ALLOW_QUOTES) && strchr(QUOTES, *t))
return false;
if (!FLAGS_SET(flags, STRING_ALLOW_GLOBS) && strchr(GLOB_CHARS, *t))
return false;
if (FLAGS_SET(flags, STRING_DISALLOW_WHITESPACE) && strchr(WHITESPACE, *t))
return false;
if (FLAGS_SET(flags, STRING_ASCII) && (uint8_t) *t >= 0x80)
return false;
}
if (FLAGS_SET(flags, STRING_FILENAME) && !filename_is_valid(p))
return false;
if (FLAGS_SET(flags, STRING_FILENAME_PART) && !filename_part_is_valid(p))
return false;
return true;
}
char* str_realloc(char *p) {
/* Reallocate *p to actual size. Ignore failure, and return the original string on error. */
if (!p)
return NULL;
return realloc(p, strlen(p) + 1) ?: p;
}
char* string_erase(char *x) {
if (!x)
return NULL;
/* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
* used them. */
explicit_bzero_safe(x, strlen(x));
return x;
}
int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
const char *p = s, *e = s;
bool truncation_applied = false;
char *copy;
size_t n = 0;
assert(s);
assert(ret);
/* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
* there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
* generated either. */
for (;;) {
size_t k;
k = strcspn(p, "\n");
if (p[k] == 0) {
if (k == 0) /* final empty line */
break;
if (n >= n_lines) /* above threshold */
break;
e = p + k; /* last line to include */
break;
}
assert(p[k] == '\n');
if (n >= n_lines)
break;
if (k > 0)
e = p + k;
p += k + 1;
n++;
}
/* e points after the last character we want to keep */
if (isempty(e))
copy = strdup(s);
else {
if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
* isn't a new-line or a series of them */
truncation_applied = true;
copy = strndup(s, e - s);
}
if (!copy)
return -ENOMEM;
*ret = copy;
return truncation_applied;
}
int string_extract_line(const char *s, size_t i, char **ret) {
const char *p = s;
size_t c = 0;
assert(ret);
/* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
* and == 0 if we are looking at the last line or already beyond the last line. As special
* optimization, if the first line is requested and the string only consists of one line we return
* NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
* common case. */
for (;;) {
const char *q;
q = strchr(p, '\n');
if (i == c) {
/* The line we are looking for! */
if (q) {
char *m;
m = strndup(p, q - p);
if (!m)
return -ENOMEM;
*ret = m;
return !isempty(q + 1); /* More coming? */
} else
/* Tell the caller to use the input string if equal */
return strdup_to(ret, p != s ? p : NULL);
}
if (!q)
/* No more lines, return empty line */
return strdup_to(ret, "");
p = q + 1;
c++;
}
}
int string_contains_word_strv(const char *string, const char *separators, char * const *words, const char **ret_word) {
/* In the default mode with no separators specified, we split on whitespace and coalesce separators. */
const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
const char *found = NULL;
int r;
for (;;) {
_cleanup_free_ char *w = NULL;
r = extract_first_word(&string, &w, separators, flags);
if (r < 0)
return r;
if (r == 0)
break;
found = strv_find(words, w);
if (found)
break;
}
if (ret_word)
*ret_word = found;
return !!found;
}
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
if (!s1 && !s2)
return true;
if (!s1 || !s2)
return false;
if (!ok)
ok = WHITESPACE;
for (; *s1 && *s2; s1++, s2++)
if (*s1 != *s2)
break;
return in_charset(s1, ok) && in_charset(s2, ok);
}
char* string_replace_char(char *str, char old_char, char new_char) {
assert(str);
assert(old_char != '\0');
assert(new_char != '\0');
assert(old_char != new_char);
for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
*p = new_char;
return str;
}
int make_cstring(const void *s, size_t n, MakeCStringMode mode, char **ret) {
char *b;
assert(s || n == 0);
assert(mode >= 0);
assert(mode < _MAKE_CSTRING_MODE_MAX);
/* Converts a sized character buffer into a NUL-terminated NUL string, refusing if there are embedded
* NUL bytes. Whether to expect a trailing NUL byte can be specified via 'mode' */
if (n == 0) {
if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
return -EINVAL;
if (!ret)
return 0;
b = new0(char, 1);
} else {
const uint8_t *nul;
nul = memchr(s, 0, n);
if (nul) {
if (nul < (const uint8_t*) s + n - 1 || /* embedded NUL? */
mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
return -EINVAL;
n--;
} else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
return -EINVAL;
if (!ret)
return 0;
b = memdup_suffix0(s, n);
}
if (!b)
return -ENOMEM;
*ret = b;
return 0;
}
size_t strspn_from_end(const char *str, const char *accept) {
size_t n = 0;
if (isempty(str))
return 0;
if (isempty(accept))
return 0;
for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
n++;
return n;
}
size_t strnspn(const char *str, const char *accept, size_t n) {
size_t i;
/* Like strspn(), but reads at most 'n' bytes from 'str'. Returns the length of the initial
* run of 'str' (capped at 'n') that consists solely of bytes found in 'accept'. Stops at a
* NUL byte too. Unlike strspn() this is safe on a buffer that is not NUL terminated within
* 'n' bytes. */
assert(str || n == 0);
assert(accept);
for (i = 0; i < n && str[i] != '\0' && strchr(accept, str[i]); i++)
;
return i;
}
char* strdupspn(const char *a, const char *accept) {
if (isempty(a) || isempty(accept))
return strdup("");
return strndup(a, strspn(a, accept));
}
char* strdupcspn(const char *a, const char *reject) {
if (isempty(a))
return strdup("");
if (isempty(reject))
return strdup(a);
return strndup(a, strcspn(a, reject));
}
char* find_line_startswith_internal(const char *haystack, const char *needle) {
assert(haystack);
assert(needle);
/* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
* first character after it */
char *p = (char*) strstr(haystack, needle);
if (!p)
return NULL;
if (p > haystack)
while (p[-1] != '\n') {
p = strstr(p + 1, needle);
if (!p)
return NULL;
}
return p + strlen(needle);
}
char* find_line_internal(const char *haystack, const char *needle) {
assert(haystack);
assert(needle);
/* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
* beginning of the line */
char *p = (char*) find_line_startswith(haystack, needle);
if (!p)
return NULL;
if (*p == 0 || strchr(NEWLINE, *p))
return p - strlen(needle);
return NULL;
}
char* find_line_after_internal(const char *haystack, const char *needle) {
assert(haystack);
assert(needle);
/* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
* next line after it */
char *p = (char*) find_line_startswith(haystack, needle);
if (!p)
return NULL;
if (*p == 0)
return p;
if (strchr(NEWLINE, *p))
return p + 1;
return NULL;
}
bool version_is_valid(const char *s, VersionFlags flags) {
/* Validates a version string superficially. This does not process the version string in any
* semantical way, it mostly just validates that its charset is reasonable. */
if (FLAGS_SET(flags, VERSION_ALLOW_EMPTY) ? !s : isempty(s))
return false;
if (!filename_part_is_valid(s))
return false;
/* We always allow all characters specified by the UAPI.10 Version Specification, i.e. 0-9, a-z, A-Z,
* ".", "-", "~", "^".
*
* If the relevant flags are set we'll also allow "+" and "_" separators.
*
* Note that with SemVer allows 0-9, a-z, A-Z, "+", "-", ".", hence with VERSION_ALLOW_PLUS we
* implement a superset of it.
*
* If you wonder when to use which flags: when validating foreign versions (e.g. distribution
* versions in /etc/os-release or so) validate liberally, i.e. add
* VERSION_ALLOW_UNDERSCORE|VERSION_ALLOW_PLUS. When validating our own versioned objects (e.g. vpick
* or so) validate more strictly, and in particular refuse characters such as "_" and "+" that may be
* used for separating component names or boot attempt counters. Also: first – if appropriate – split
* the string into individual components. For example, if the string consists of a name and a
* version, separated by some character, only pass the version part to this function. The name part
* may pass verification, but it's cleaner to not rely on that.
*
* For details about UAPI.10 see:
*
* → https://uapi-group.org/specifications/specs/version_format_specification/ */
char charset[] = ALPHANUMERICAL ".-~^" /* plus room for the two chars below: */ "\0\0";
size_t l = strlen(charset);
if (FLAGS_SET(flags, VERSION_ALLOW_UNDERSCORE))
charset[l++] = '_';
if (FLAGS_SET(flags, VERSION_ALLOW_PLUS))
charset[l++] = '+';
return in_charset(s, charset);
}
ssize_t strlevenshtein(const char *x, const char *y) {
_cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
size_t xl, yl;
/* This is inspired from the Linux kernel's Levenshtein implementation */
if (streq_ptr(x, y))
return 0;
xl = strlen_ptr(x);
if (xl > SSIZE_MAX)
return -E2BIG;
yl = strlen_ptr(y);
if (yl > SSIZE_MAX)
return -E2BIG;
if (isempty(x))
return yl;
if (isempty(y))
return xl;
t0 = new0(size_t, yl + 1);
if (!t0)
return -ENOMEM;
t1 = new0(size_t, yl + 1);
if (!t1)
return -ENOMEM;
t2 = new0(size_t, yl + 1);
if (!t2)
return -ENOMEM;
for (size_t i = 0; i <= yl; i++)
t1[i] = i;
for (size_t i = 0; i < xl; i++) {
t2[0] = i + 1;
for (size_t j = 0; j < yl; j++) {
/* Substitution */
t2[j+1] = t1[j] + (x[i] != y[j]);
/* Swap */
if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
t2[j+1] = t0[j-1] + 1;
/* Deletion */
if (t2[j+1] > t1[j+1] + 1)
t2[j+1] = t1[j+1] + 1;
/* Insertion */
if (t2[j+1] > t2[j] + 1)
t2[j+1] = t2[j] + 1;
}
size_t *dummy = t0;
t0 = t1;
t1 = t2;
t2 = dummy;
}
return t1[yl];
}
char* strrstr_internal(const char *haystack, const char *needle) {
/* Like strstr() but returns the last rather than the first occurrence of "needle" in "haystack". */
if (!haystack || !needle)
return NULL;
/* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
* last char, not before. */
if (needle[0] == 0)
return (char*) strchr(haystack, 0);
/* Special case: for single character strings, just use optimized strrchr() */
if (needle[1] == 0)
return (char*) strrchr(haystack, needle[0]);
for (const char *p = strstr(haystack, needle), *q; p; p = q) {
q = strstr(p + 1, needle);
if (!q)
return (char*) p;
}
return NULL;
}
char* strrstr_no_case_internal(const char *haystack, const char *needle) {
if (!haystack || !needle)
return NULL;
for (const char *p = strchr(haystack, 0); p > haystack; p--)
if (startswith_no_case(p, needle))
return (char*) p;
return startswith_no_case(haystack, needle) ? (char*) haystack : NULL;
}
size_t str_common_prefix(const char *a, const char *b) {
assert(a);
assert(b);
/* Returns the length of the common prefix of the two specified strings, or SIZE_MAX in case the
* strings are fully identical. */
for (size_t n = 0;; n++) {
char c = a[n];
if (c != b[n])
return n;
if (c == 0)
return SIZE_MAX;
}
}