1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #include "alloc-util.h"
14 //#include "locale-util.h"
16 #include "string-util.h"
17 //#include "terminal-util.h"
22 int strcmp_ptr(const char *a, const char *b) {
24 /* Like strcmp(), but tries to make sense of NULL pointers */
37 char* endswith(const char *s, const char *postfix) {
47 return (char*) s + sl;
52 if (memcmp(s + sl - pl, postfix, pl) != 0)
55 return (char*) s + sl - pl;
58 char* endswith_no_case(const char *s, const char *postfix) {
68 return (char*) s + sl;
73 if (strcasecmp(s + sl - pl, postfix) != 0)
76 return (char*) s + sl - pl;
79 char* first_word(const char *s, const char *word) {
86 /* Checks if the string starts with the specified word, either
87 * followed by NUL or by whitespace. Returns a pointer to the
88 * NUL or the first character after the whitespace. */
99 if (memcmp(s, word, wl) != 0)
106 if (!strchr(WHITESPACE, *p))
109 p += strspn(p, WHITESPACE);
113 static size_t strcspn_escaped(const char *s, const char *reject) {
114 bool escaped = false;
117 for (n=0; s[n]; n++) {
120 else if (s[n] == '\\')
122 else if (strchr(reject, s[n]))
126 /* if s ends in \, return index of previous char */
130 /* Split a string into words. */
131 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
137 assert(**state == '\0');
141 current += strspn(current, separator);
147 if (quoted && strchr("\'\"", *current)) {
148 char quotechars[2] = {*current, '\0'};
150 *l = strcspn_escaped(current + 1, quotechars);
151 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
152 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
153 /* right quote missing or garbage at the end */
157 *state = current++ + *l + 2;
159 *l = strcspn_escaped(current, separator);
160 if (current[*l] && !strchr(separator, current[*l])) {
161 /* unfinished escape */
165 *state = current + *l;
167 *l = strcspn(current, separator);
168 *state = current + *l;
174 char *strnappend(const char *s, const char *suffix, size_t b) {
182 return strndup(suffix, b);
191 if (b > ((size_t) -1) - a)
194 r = new(char, a+b+1);
199 memcpy(r+a, suffix, b);
205 char *strappend(const char *s, const char *suffix) {
206 return strnappend(s, suffix, strlen_ptr(suffix));
209 char *strjoin_real(const char *x, ...) {
223 t = va_arg(ap, const char *);
228 if (n > ((size_t) -1) - l) {
252 t = va_arg(ap, const char *);
266 char *strstrip(char *s) {
270 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
272 return delete_trailing_chars(skip_leading_chars(s, WHITESPACE), WHITESPACE);
275 #if 0 /// UNNEEDED by elogind
276 char *delete_chars(char *s, const char *bad) {
279 /* Drops all specified bad characters, regardless where in the string */
287 for (f = s, t = s; *f; f++) {
300 char *delete_trailing_chars(char *s, const char *bad) {
303 /* Drops all specified bad characters, at the end of the string */
312 if (!strchr(bad, *p))
320 char *truncate_nl(char *s) {
323 s[strcspn(s, NEWLINE)] = 0;
327 #if 0 /// UNNEEDED by elogind
328 char ascii_tolower(char x) {
330 if (x >= 'A' && x <= 'Z')
331 return x - 'A' + 'a';
336 char ascii_toupper(char x) {
338 if (x >= 'a' && x <= 'z')
339 return x - 'a' + 'A';
344 char *ascii_strlower(char *t) {
350 *p = ascii_tolower(*p);
355 char *ascii_strupper(char *t) {
361 *p = ascii_toupper(*p);
366 char *ascii_strlower_n(char *t, size_t n) {
372 for (i = 0; i < n; i++)
373 t[i] = ascii_tolower(t[i]);
378 int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
380 for (; n > 0; a++, b++, n--) {
383 x = (int) (uint8_t) ascii_tolower(*a);
384 y = (int) (uint8_t) ascii_tolower(*b);
393 int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
396 r = ascii_strcasecmp_n(a, b, MIN(n, m));
408 bool chars_intersect(const char *a, const char *b) {
411 /* Returns true if any of the chars in a are in b. */
420 bool string_has_cc(const char *p, const char *ok) {
426 * Check if a string contains control characters. If 'ok' is
427 * non-NULL it may be a string containing additional CCs to be
431 for (t = p; *t; t++) {
432 if (ok && strchr(ok, *t))
435 if (*t > 0 && *t < ' ')
445 static int write_ellipsis(char *buf, bool unicode) {
446 if (unicode || is_locale_utf8()) {
447 buf[0] = 0xe2; /* tri-dot ellipsis: … */
459 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
460 size_t x, need_space, suffix_len;
464 assert(percent <= 100);
465 assert(new_length != (size_t) -1);
467 if (old_length <= new_length)
468 return strndup(s, old_length);
470 /* Special case short ellipsations */
471 switch (new_length) {
477 if (is_locale_utf8())
478 return strdup("…");
483 if (!is_locale_utf8())
492 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
493 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
494 * either for the UTF-8 encoded character or for three ASCII characters. */
495 need_space = is_locale_utf8() ? 1 : 3;
497 t = new(char, new_length+3);
501 assert(new_length >= need_space);
503 x = ((new_length - need_space) * percent + 50) / 100;
504 assert(x <= new_length - need_space);
507 write_ellipsis(t + x, false);
508 suffix_len = new_length - x - need_space;
509 memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
510 *(t + x + 3 + suffix_len) = '\0';
515 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
516 size_t x, k, len, len2;
521 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
522 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
525 * Ellipsation is done in a locale-dependent way:
526 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
527 * 2. Otherwise, a unicode ellipsis is used ("…")
529 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
530 * the current locale is UTF-8.
534 assert(percent <= 100);
536 if (new_length == (size_t) -1)
537 return strndup(s, old_length);
542 /* If no multibyte characters use ascii_ellipsize_mem for speed */
543 if (ascii_is_valid_n(s, old_length))
544 return ascii_ellipsize_mem(s, old_length, new_length, percent);
546 x = ((new_length - 1) * percent) / 100;
547 assert(x <= new_length - 1);
550 for (i = s; i < s + old_length; i = utf8_next_char(i)) {
554 r = utf8_encoded_to_unichar(i, &c);
558 w = unichar_iswide(c) ? 2 : 1;
565 for (j = s + old_length; j > i; ) {
570 jj = utf8_prev_char(j);
571 r = utf8_encoded_to_unichar(jj, &c);
575 w = unichar_iswide(c) ? 2 : 1;
576 if (k + w <= new_length) {
584 /* we don't actually need to ellipsize */
586 return memdup_suffix0(s, old_length);
588 /* make space for ellipsis, if possible */
589 if (j < s + old_length)
590 j = utf8_next_char(j);
592 i = utf8_prev_char(i);
595 len2 = s + old_length - j;
596 e = new(char, len + 3 + len2 + 1);
601 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
602 old_length, new_length, x, len, len2, k);
606 write_ellipsis(e + len, true);
607 memcpy(e + len + 3, j, len2);
608 *(e + len + 3 + len2) = '\0';
613 char *cellescape(char *buf, size_t len, const char *s) {
614 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
615 * characters are copied as they are, everything else is escaped. The result
616 * is different then if escaping and ellipsization was performed in two
617 * separate steps, because each sequence is either stored in full or skipped.
619 * This function should be used for logging about strings which expected to
620 * be plain ASCII in a safe way.
622 * An ellipsis will be used if s is too long. It was always placed at the
626 size_t i = 0, last_char_width[4] = {}, k = 0, j;
628 assert(len > 0); /* at least a terminating NUL */
634 if (*s == 0) /* terminating NUL detected? then we are done! */
637 w = cescape_char(*s, four);
638 if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
639 * ellipsize at the previous location */
642 /* OK, there was space, let's add this escaped character to the buffer */
643 memcpy(buf + i, four, w);
646 /* And remember its width in the ring buffer */
647 last_char_width[k] = w;
653 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
654 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
655 for (j = 0; j < ELEMENTSOF(last_char_width); j++) {
657 if (i + 4 <= len) /* nice, we reached our space goal */
660 k = k == 0 ? 3 : k - 1;
661 if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
664 assert(i >= last_char_width[k]);
665 i -= last_char_width[k];
668 if (i + 4 <= len) /* yay, enough space */
669 i += write_ellipsis(buf + i, false);
670 else if (i + 3 <= len) { /* only space for ".." */
673 } else if (i + 2 <= len) /* only space for a single "." */
676 assert(i + 1 <= len);
683 bool nulstr_contains(const char *nulstr, const char *needle) {
689 NULSTR_FOREACH(i, nulstr)
690 if (streq(i, needle))
696 char* strshorten(char *s, size_t l) {
699 if (strnlen(s, l+1) > l)
705 char *strreplace(const char *text, const char *old_string, const char *new_string) {
706 size_t l, old_len, new_len, allocated = 0;
707 char *t, *ret = NULL;
716 old_len = strlen(old_string);
717 new_len = strlen(new_string);
720 if (!GREEDY_REALLOC(ret, allocated, l+1))
728 if (!startswith(f, old_string)) {
734 nl = l - old_len + new_len;
736 if (!GREEDY_REALLOC(ret, allocated, nl + 1))
742 t = stpcpy(t, new_string);
750 static void advance_offsets(ssize_t diff, size_t offsets[2], size_t shift[2], size_t size) {
754 if ((size_t) diff < offsets[0])
756 if ((size_t) diff < offsets[1])
760 char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
761 const char *i, *begin = NULL;
767 } state = STATE_OTHER;
769 size_t osz = 0, isz, shift[2] = {};
775 /* This does three things:
777 * 1. Replaces TABs by 8 spaces
778 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
779 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
781 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as are any
782 * other special characters. Truncated ANSI sequences are left-as is too. This call is supposed to suppress the
783 * most basic formatting noise, but nothing else.
785 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
787 isz = _isz ? *_isz : strlen(*ibuf);
789 f = open_memstream(&obuf, &osz);
793 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
794 * and it doesn't leave our scope. */
796 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
798 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
803 if (i >= *ibuf + isz) /* EOT */
805 else if (*i == '\x1B')
806 state = STATE_ESCAPE;
807 else if (*i == '\t') {
809 advance_offsets(i - *ibuf, highlight, shift, 7);
816 if (i >= *ibuf + isz) { /* EOT */
818 advance_offsets(i - *ibuf, highlight, shift, 1);
820 } else if (*i == '[') { /* ANSI CSI */
823 } else if (*i == ']') { /* ANSI CSO */
829 advance_offsets(i - *ibuf, highlight, shift, 1);
837 if (i >= *ibuf + isz || /* EOT … */
838 !strchr("01234567890;m", *i)) { /* … or invalid chars in sequence */
841 advance_offsets(i - *ibuf, highlight, shift, 2);
844 } else if (*i == 'm')
851 if (i >= *ibuf + isz || /* EOT … */
852 (*i != '\a' && (uint8_t) *i < 32U) || (uint8_t) *i > 126U) { /* … or invalid chars in sequence */
855 advance_offsets(i - *ibuf, highlight, shift, 2);
858 } else if (*i == '\a')
865 if (fflush_and_check(f) < 0) {
879 highlight[0] += shift[0];
880 highlight[1] += shift[1];
886 char *strextend_with_separator(char **x, const char *separator, ...) {
888 size_t f, l, l_separator;
894 l = f = strlen_ptr(*x);
896 need_separator = !isempty(*x);
897 l_separator = strlen_ptr(separator);
899 va_start(ap, separator);
904 t = va_arg(ap, const char *);
913 if (n > ((size_t) -1) - l) {
919 need_separator = true;
923 need_separator = !isempty(*x);
925 r = realloc(*x, l+1);
931 va_start(ap, separator);
935 t = va_arg(ap, const char *);
939 if (need_separator && separator)
940 p = stpcpy(p, separator);
944 need_separator = true;
956 char *strrep(const char *s, unsigned n) {
964 p = r = malloc(l * n + 1);
968 for (i = 0; i < n; i++)
975 int split_pair(const char *s, const char *sep, char **l, char **r) {
990 a = strndup(s, x - s);
994 b = strdup(x + strlen(sep));
1006 int free_and_strdup(char **p, const char *s) {
1011 /* Replaces a string pointer with an strdup()ed new string,
1012 * possibly freeing the old one. */
1014 if (streq_ptr(*p, s))
1030 #if !HAVE_EXPLICIT_BZERO
1032 * Pointer to memset is volatile so that compiler must de-reference
1033 * the pointer and can't assume that it points to any function in
1034 * particular (such as memset, which it then might further "optimize")
1035 * This approach is inspired by openssl's crypto/mem_clr.c.
1037 typedef void *(*memset_t)(void *,int,size_t);
1039 static volatile memset_t memset_func = memset;
1041 void explicit_bzero(void *p, size_t l) {
1042 memset_func(p, '\0', l);
1046 char* string_erase(char *x) {
1050 /* A delicious drop of snake-oil! To be called on memory where
1051 * we stored passphrases or so, after we used them. */
1052 explicit_bzero(x, strlen(x));
1056 char *string_free_erase(char *s) {
1057 return mfree(string_erase(s));
1060 bool string_is_safe(const char *p) {
1066 for (t = p; *t; t++) {
1067 if (*t > 0 && *t < ' ') /* no control characters */
1070 if (strchr(QUOTES "\\\x7f", *t))