1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
12 #include <stdio_ext.h>
16 #include "alloc-util.h"
19 #include "string-util.h"
20 //#include "terminal-util.h"
24 int strcmp_ptr(const char *a, const char *b) {
26 /* Like strcmp(), but tries to make sense of NULL pointers */
39 char* endswith(const char *s, const char *postfix) {
49 return (char*) s + sl;
54 if (memcmp(s + sl - pl, postfix, pl) != 0)
57 return (char*) s + sl - pl;
60 char* endswith_no_case(const char *s, const char *postfix) {
70 return (char*) s + sl;
75 if (strcasecmp(s + sl - pl, postfix) != 0)
78 return (char*) s + sl - pl;
81 char* first_word(const char *s, const char *word) {
88 /* Checks if the string starts with the specified word, either
89 * followed by NUL or by whitespace. Returns a pointer to the
90 * NUL or the first character after the whitespace. */
101 if (memcmp(s, word, wl) != 0)
108 if (!strchr(WHITESPACE, *p))
111 p += strspn(p, WHITESPACE);
115 static size_t strcspn_escaped(const char *s, const char *reject) {
116 bool escaped = false;
119 for (n=0; s[n]; n++) {
122 else if (s[n] == '\\')
124 else if (strchr(reject, s[n]))
128 /* if s ends in \, return index of previous char */
132 /* Split a string into words. */
133 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
139 assert(**state == '\0');
143 current += strspn(current, separator);
149 if (quoted && strchr("\'\"", *current)) {
150 char quotechars[2] = {*current, '\0'};
152 *l = strcspn_escaped(current + 1, quotechars);
153 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
154 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
155 /* right quote missing or garbage at the end */
159 *state = current++ + *l + 2;
161 *l = strcspn_escaped(current, separator);
162 if (current[*l] && !strchr(separator, current[*l])) {
163 /* unfinished escape */
167 *state = current + *l;
169 *l = strcspn(current, separator);
170 *state = current + *l;
176 char *strnappend(const char *s, const char *suffix, size_t b) {
184 return strndup(suffix, b);
193 if (b > ((size_t) -1) - a)
196 r = new(char, a+b+1);
201 memcpy(r+a, suffix, b);
207 char *strappend(const char *s, const char *suffix) {
208 return strnappend(s, suffix, strlen_ptr(suffix));
211 char *strjoin_real(const char *x, ...) {
225 t = va_arg(ap, const char *);
230 if (n > ((size_t) -1) - l) {
254 t = va_arg(ap, const char *);
268 char *strstrip(char *s) {
274 /* Drops trailing whitespace. Modifies the string in
275 * place. Returns pointer to first non-space character */
277 s += strspn(s, WHITESPACE);
279 for (e = strchr(s, 0); e > s; e --)
280 if (!strchr(WHITESPACE, e[-1]))
288 #if 0 /// UNNEEDED by elogind
289 char *delete_chars(char *s, const char *bad) {
292 /* Drops all specified bad characters, regardless where in the string */
300 for (f = s, t = s; *f; f++) {
313 char *delete_trailing_chars(char *s, const char *bad) {
316 /* Drops all specified bad characters, at the end of the string */
325 if (!strchr(bad, *p))
333 char *truncate_nl(char *s) {
336 s[strcspn(s, NEWLINE)] = 0;
340 #if 0 /// UNNEEDED by elogind
341 char ascii_tolower(char x) {
343 if (x >= 'A' && x <= 'Z')
344 return x - 'A' + 'a';
349 char ascii_toupper(char x) {
351 if (x >= 'a' && x <= 'z')
352 return x - 'a' + 'A';
357 char *ascii_strlower(char *t) {
363 *p = ascii_tolower(*p);
368 char *ascii_strupper(char *t) {
374 *p = ascii_toupper(*p);
379 char *ascii_strlower_n(char *t, size_t n) {
385 for (i = 0; i < n; i++)
386 t[i] = ascii_tolower(t[i]);
391 int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
393 for (; n > 0; a++, b++, n--) {
396 x = (int) (uint8_t) ascii_tolower(*a);
397 y = (int) (uint8_t) ascii_tolower(*b);
406 int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
409 r = ascii_strcasecmp_n(a, b, MIN(n, m));
421 bool chars_intersect(const char *a, const char *b) {
424 /* Returns true if any of the chars in a are in b. */
433 bool string_has_cc(const char *p, const char *ok) {
439 * Check if a string contains control characters. If 'ok' is
440 * non-NULL it may be a string containing additional CCs to be
444 for (t = p; *t; t++) {
445 if (ok && strchr(ok, *t))
448 if (*t > 0 && *t < ' ')
458 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
463 assert(percent <= 100);
464 assert(new_length >= 3);
466 if (old_length <= 3 || old_length <= new_length)
467 return strndup(s, old_length);
469 r = new0(char, new_length+3);
473 x = (new_length * percent) / 100;
475 if (x > new_length - 3)
479 r[x] = 0xe2; /* tri-dot ellipsis: … */
483 s + old_length - (new_length - x - 1),
489 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
493 unsigned k, len, len2;
497 assert(percent <= 100);
499 if (new_length == (size_t) -1)
500 return strndup(s, old_length);
502 assert(new_length >= 3);
504 /* if no multibyte characters use ascii_ellipsize_mem for speed */
505 if (ascii_is_valid(s))
506 return ascii_ellipsize_mem(s, old_length, new_length, percent);
508 if (old_length <= 3 || old_length <= new_length)
509 return strndup(s, old_length);
511 x = (new_length * percent) / 100;
513 if (x > new_length - 3)
517 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
520 r = utf8_encoded_to_unichar(i, &c);
523 k += unichar_iswide(c) ? 2 : 1;
526 if (k > x) /* last character was wide and went over quota */
529 for (j = s + old_length; k < new_length && j > i; ) {
532 j = utf8_prev_char(j);
533 r = utf8_encoded_to_unichar(j, &c);
536 k += unichar_iswide(c) ? 2 : 1;
540 /* we don't actually need to ellipsize */
542 return memdup(s, old_length + 1);
544 /* make space for ellipsis */
545 j = utf8_next_char(j);
548 len2 = s + old_length - j;
549 e = new(char, len + 3 + len2 + 1);
554 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
555 old_length, new_length, x, len, len2, k);
559 e[len] = 0xe2; /* tri-dot ellipsis: … */
563 memcpy(e + len + 3, j, len2 + 1);
568 char *ellipsize(const char *s, size_t length, unsigned percent) {
570 if (length == (size_t) -1)
573 return ellipsize_mem(s, strlen(s), length, percent);
576 bool nulstr_contains(const char *nulstr, const char *needle) {
582 NULSTR_FOREACH(i, nulstr)
583 if (streq(i, needle))
589 char* strshorten(char *s, size_t l) {
592 if (strnlen(s, l+1) > l)
598 char *strreplace(const char *text, const char *old_string, const char *new_string) {
599 size_t l, old_len, new_len, allocated = 0;
600 char *t, *ret = NULL;
609 old_len = strlen(old_string);
610 new_len = strlen(new_string);
613 if (!GREEDY_REALLOC(ret, allocated, l+1))
621 if (!startswith(f, old_string)) {
627 nl = l - old_len + new_len;
629 if (!GREEDY_REALLOC(ret, allocated, nl + 1))
635 t = stpcpy(t, new_string);
643 static void advance_offsets(ssize_t diff, size_t offsets[2], size_t shift[2], size_t size) {
647 if ((size_t) diff < offsets[0])
649 if ((size_t) diff < offsets[1])
653 char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
654 const char *i, *begin = NULL;
659 } state = STATE_OTHER;
661 size_t osz = 0, isz, shift[2] = {};
667 /* Strips ANSI color and replaces TABs by 8 spaces */
669 isz = _isz ? *_isz : strlen(*ibuf);
671 f = open_memstream(&obuf, &osz);
675 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
676 * and it doesn't leave our scope. */
678 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
680 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
685 if (i >= *ibuf + isz) /* EOT */
687 else if (*i == '\x1B')
688 state = STATE_ESCAPE;
689 else if (*i == '\t') {
691 advance_offsets(i - *ibuf, highlight, shift, 7);
698 if (i >= *ibuf + isz) { /* EOT */
700 advance_offsets(i - *ibuf, highlight, shift, 1);
702 } else if (*i == '[') {
703 state = STATE_BRACKET;
708 advance_offsets(i - *ibuf, highlight, shift, 1);
716 if (i >= *ibuf + isz || /* EOT */
717 (!(*i >= '0' && *i <= '9') && !IN_SET(*i, ';', 'm'))) {
720 advance_offsets(i - *ibuf, highlight, shift, 2);
723 } else if (*i == 'm')
743 highlight[0] += shift[0];
744 highlight[1] += shift[1];
750 char *strextend_with_separator(char **x, const char *separator, ...) {
752 size_t f, l, l_separator;
758 l = f = strlen_ptr(*x);
760 need_separator = !isempty(*x);
761 l_separator = strlen_ptr(separator);
763 va_start(ap, separator);
768 t = va_arg(ap, const char *);
777 if (n > ((size_t) -1) - l) {
783 need_separator = true;
787 need_separator = !isempty(*x);
789 r = realloc(*x, l+1);
795 va_start(ap, separator);
799 t = va_arg(ap, const char *);
803 if (need_separator && separator)
804 p = stpcpy(p, separator);
808 need_separator = true;
820 char *strrep(const char *s, unsigned n) {
828 p = r = malloc(l * n + 1);
832 for (i = 0; i < n; i++)
839 int split_pair(const char *s, const char *sep, char **l, char **r) {
854 a = strndup(s, x - s);
858 b = strdup(x + strlen(sep));
870 int free_and_strdup(char **p, const char *s) {
875 /* Replaces a string pointer with an strdup()ed new string,
876 * possibly freeing the old one. */
878 if (streq_ptr(*p, s))
894 #if !HAVE_EXPLICIT_BZERO
896 * Pointer to memset is volatile so that compiler must de-reference
897 * the pointer and can't assume that it points to any function in
898 * particular (such as memset, which it then might further "optimize")
899 * This approach is inspired by openssl's crypto/mem_clr.c.
901 typedef void *(*memset_t)(void *,int,size_t);
903 static volatile memset_t memset_func = memset;
905 void explicit_bzero(void *p, size_t l) {
906 memset_func(p, '\0', l);
910 char* string_erase(char *x) {
914 /* A delicious drop of snake-oil! To be called on memory where
915 * we stored passphrases or so, after we used them. */
916 explicit_bzero(x, strlen(x));
920 char *string_free_erase(char *s) {
921 return mfree(string_erase(s));
924 bool string_is_safe(const char *p) {
930 for (t = p; *t; t++) {
931 if (*t > 0 && *t < ' ') /* no control characters */
934 if (strchr(QUOTES "\\\x7f", *t))