1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
10 #include <stdio_ext.h>
14 #include "alloc-util.h"
17 //#include "locale-util.h"
19 #include "string-util.h"
20 //#include "terminal-util.h"
25 int strcmp_ptr(const char *a, const char *b) {
27 /* Like strcmp(), but tries to make sense of NULL pointers */
40 char* endswith(const char *s, const char *postfix) {
50 return (char*) s + sl;
55 if (memcmp(s + sl - pl, postfix, pl) != 0)
58 return (char*) s + sl - pl;
61 char* endswith_no_case(const char *s, const char *postfix) {
71 return (char*) s + sl;
76 if (strcasecmp(s + sl - pl, postfix) != 0)
79 return (char*) s + sl - pl;
82 char* first_word(const char *s, const char *word) {
89 /* Checks if the string starts with the specified word, either
90 * followed by NUL or by whitespace. Returns a pointer to the
91 * NUL or the first character after the whitespace. */
102 if (memcmp(s, word, wl) != 0)
109 if (!strchr(WHITESPACE, *p))
112 p += strspn(p, WHITESPACE);
116 static size_t strcspn_escaped(const char *s, const char *reject) {
117 bool escaped = false;
120 for (n=0; s[n]; n++) {
123 else if (s[n] == '\\')
125 else if (strchr(reject, s[n]))
129 /* if s ends in \, return index of previous char */
133 /* Split a string into words. */
134 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
140 assert(**state == '\0');
144 current += strspn(current, separator);
150 if (quoted && strchr("\'\"", *current)) {
151 char quotechars[2] = {*current, '\0'};
153 *l = strcspn_escaped(current + 1, quotechars);
154 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
155 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
156 /* right quote missing or garbage at the end */
160 *state = current++ + *l + 2;
162 *l = strcspn_escaped(current, separator);
163 if (current[*l] && !strchr(separator, current[*l])) {
164 /* unfinished escape */
168 *state = current + *l;
170 *l = strcspn(current, separator);
171 *state = current + *l;
177 char *strnappend(const char *s, const char *suffix, size_t b) {
185 return strndup(suffix, b);
194 if (b > ((size_t) -1) - a)
197 r = new(char, a+b+1);
202 memcpy(r+a, suffix, b);
208 char *strappend(const char *s, const char *suffix) {
209 return strnappend(s, suffix, strlen_ptr(suffix));
212 char *strjoin_real(const char *x, ...) {
226 t = va_arg(ap, const char *);
231 if (n > ((size_t) -1) - l) {
255 t = va_arg(ap, const char *);
269 char *strstrip(char *s) {
273 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
275 return delete_trailing_chars(skip_leading_chars(s, WHITESPACE), WHITESPACE);
278 #if 0 /// UNNEEDED by elogind
279 char *delete_chars(char *s, const char *bad) {
282 /* Drops all specified bad characters, regardless where in the string */
290 for (f = s, t = s; *f; f++) {
303 char *delete_trailing_chars(char *s, const char *bad) {
306 /* Drops all specified bad characters, at the end of the string */
315 if (!strchr(bad, *p))
323 char *truncate_nl(char *s) {
326 s[strcspn(s, NEWLINE)] = 0;
330 #if 0 /// UNNEEDED by elogind
331 char ascii_tolower(char x) {
333 if (x >= 'A' && x <= 'Z')
334 return x - 'A' + 'a';
339 char ascii_toupper(char x) {
341 if (x >= 'a' && x <= 'z')
342 return x - 'a' + 'A';
347 char *ascii_strlower(char *t) {
353 *p = ascii_tolower(*p);
358 char *ascii_strupper(char *t) {
364 *p = ascii_toupper(*p);
369 char *ascii_strlower_n(char *t, size_t n) {
375 for (i = 0; i < n; i++)
376 t[i] = ascii_tolower(t[i]);
381 int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
383 for (; n > 0; a++, b++, n--) {
386 x = (int) (uint8_t) ascii_tolower(*a);
387 y = (int) (uint8_t) ascii_tolower(*b);
396 int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
399 r = ascii_strcasecmp_n(a, b, MIN(n, m));
411 bool chars_intersect(const char *a, const char *b) {
414 /* Returns true if any of the chars in a are in b. */
423 bool string_has_cc(const char *p, const char *ok) {
429 * Check if a string contains control characters. If 'ok' is
430 * non-NULL it may be a string containing additional CCs to be
434 for (t = p; *t; t++) {
435 if (ok && strchr(ok, *t))
438 if (*t > 0 && *t < ' ')
448 static int write_ellipsis(char *buf, bool unicode) {
449 if (unicode || is_locale_utf8()) {
450 buf[0] = 0xe2; /* tri-dot ellipsis: … */
462 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
463 size_t x, need_space, suffix_len;
467 assert(percent <= 100);
468 assert(new_length != (size_t) -1);
470 if (old_length <= new_length)
471 return strndup(s, old_length);
473 /* Special case short ellipsations */
474 switch (new_length) {
480 if (is_locale_utf8())
486 if (!is_locale_utf8())
495 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
496 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
497 * either for the UTF-8 encoded character or for three ASCII characters. */
498 need_space = is_locale_utf8() ? 1 : 3;
500 t = new(char, new_length+3);
504 assert(new_length >= need_space);
506 x = ((new_length - need_space) * percent + 50) / 100;
507 assert(x <= new_length - need_space);
510 write_ellipsis(t + x, false);
511 suffix_len = new_length - x - need_space;
512 memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
513 *(t + x + 3 + suffix_len) = '\0';
518 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
519 size_t x, k, len, len2;
524 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
525 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
528 * Ellipsation is done in a locale-dependent way:
529 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
530 * 2. Otherwise, a unicode ellipsis is used ("…")
532 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
533 * the current locale is UTF-8.
537 assert(percent <= 100);
539 if (new_length == (size_t) -1)
540 return strndup(s, old_length);
545 /* If no multibyte characters use ascii_ellipsize_mem for speed */
546 if (ascii_is_valid_n(s, old_length))
547 return ascii_ellipsize_mem(s, old_length, new_length, percent);
549 x = ((new_length - 1) * percent) / 100;
550 assert(x <= new_length - 1);
553 for (i = s; i < s + old_length; i = utf8_next_char(i)) {
557 r = utf8_encoded_to_unichar(i, &c);
561 w = unichar_iswide(c) ? 2 : 1;
568 for (j = s + old_length; j > i; ) {
573 jj = utf8_prev_char(j);
574 r = utf8_encoded_to_unichar(jj, &c);
578 w = unichar_iswide(c) ? 2 : 1;
579 if (k + w <= new_length) {
587 /* we don't actually need to ellipsize */
589 return memdup_suffix0(s, old_length);
591 /* make space for ellipsis, if possible */
592 if (j < s + old_length)
593 j = utf8_next_char(j);
595 i = utf8_prev_char(i);
598 len2 = s + old_length - j;
599 e = new(char, len + 3 + len2 + 1);
604 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
605 old_length, new_length, x, len, len2, k);
609 write_ellipsis(e + len, true);
610 memcpy(e + len + 3, j, len2);
611 *(e + len + 3 + len2) = '\0';
616 char *cellescape(char *buf, size_t len, const char *s) {
617 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
618 * characters are copied as they are, everything else is escaped. The result
619 * is different then if escaping and ellipsization was performed in two
620 * separate steps, because each sequence is either stored in full or skipped.
622 * This function should be used for logging about strings which expected to
623 * be plain ASCII in a safe way.
625 * An ellipsis will be used if s is too long. It was always placed at the
629 size_t i = 0, last_char_width[4] = {}, k = 0, j;
631 assert(len > 0); /* at least a terminating NUL */
637 if (*s == 0) /* terminating NUL detected? then we are done! */
640 w = cescape_char(*s, four);
641 if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
642 * ellipsize at the previous location */
645 /* OK, there was space, let's add this escaped character to the buffer */
646 memcpy(buf + i, four, w);
649 /* And remember its width in the ring buffer */
650 last_char_width[k] = w;
656 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
657 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
658 for (j = 0; j < ELEMENTSOF(last_char_width); j++) {
660 if (i + 4 <= len) /* nice, we reached our space goal */
663 k = k == 0 ? 3 : k - 1;
664 if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
667 assert(i >= last_char_width[k]);
668 i -= last_char_width[k];
671 if (i + 4 <= len) /* yay, enough space */
672 i += write_ellipsis(buf + i, false);
673 else if (i + 3 <= len) { /* only space for ".." */
676 } else if (i + 2 <= len) /* only space for a single "." */
679 assert(i + 1 <= len);
686 bool nulstr_contains(const char *nulstr, const char *needle) {
692 NULSTR_FOREACH(i, nulstr)
693 if (streq(i, needle))
699 char* strshorten(char *s, size_t l) {
702 if (strnlen(s, l+1) > l)
708 char *strreplace(const char *text, const char *old_string, const char *new_string) {
709 size_t l, old_len, new_len, allocated = 0;
710 char *t, *ret = NULL;
719 old_len = strlen(old_string);
720 new_len = strlen(new_string);
723 if (!GREEDY_REALLOC(ret, allocated, l+1))
731 if (!startswith(f, old_string)) {
737 nl = l - old_len + new_len;
739 if (!GREEDY_REALLOC(ret, allocated, nl + 1))
745 t = stpcpy(t, new_string);
753 static void advance_offsets(ssize_t diff, size_t offsets[2], size_t shift[2], size_t size) {
757 if ((size_t) diff < offsets[0])
759 if ((size_t) diff < offsets[1])
763 char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
764 const char *i, *begin = NULL;
770 } state = STATE_OTHER;
772 size_t osz = 0, isz, shift[2] = {};
778 /* This does three things:
780 * 1. Replaces TABs by 8 spaces
781 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
782 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
784 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as are any
785 * other special characters. Truncated ANSI sequences are left-as is too. This call is supposed to suppress the
786 * most basic formatting noise, but nothing else.
788 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
790 isz = _isz ? *_isz : strlen(*ibuf);
792 f = open_memstream(&obuf, &osz);
796 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
797 * and it doesn't leave our scope. */
799 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
801 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
806 if (i >= *ibuf + isz) /* EOT */
808 else if (*i == '\x1B')
809 state = STATE_ESCAPE;
810 else if (*i == '\t') {
812 advance_offsets(i - *ibuf, highlight, shift, 7);
819 if (i >= *ibuf + isz) { /* EOT */
821 advance_offsets(i - *ibuf, highlight, shift, 1);
823 } else if (*i == '[') { /* ANSI CSI */
826 } else if (*i == ']') { /* ANSI CSO */
832 advance_offsets(i - *ibuf, highlight, shift, 1);
840 if (i >= *ibuf + isz || /* EOT … */
841 !strchr("01234567890;m", *i)) { /* … or invalid chars in sequence */
844 advance_offsets(i - *ibuf, highlight, shift, 2);
847 } else if (*i == 'm')
854 if (i >= *ibuf + isz || /* EOT … */
855 (*i != '\a' && (uint8_t) *i < 32U) || (uint8_t) *i > 126U) { /* … or invalid chars in sequence */
858 advance_offsets(i - *ibuf, highlight, shift, 2);
861 } else if (*i == '\a')
868 if (fflush_and_check(f) < 0) {
882 highlight[0] += shift[0];
883 highlight[1] += shift[1];
889 char *strextend_with_separator(char **x, const char *separator, ...) {
891 size_t f, l, l_separator;
897 l = f = strlen_ptr(*x);
899 need_separator = !isempty(*x);
900 l_separator = strlen_ptr(separator);
902 va_start(ap, separator);
907 t = va_arg(ap, const char *);
916 if (n > ((size_t) -1) - l) {
922 need_separator = true;
926 need_separator = !isempty(*x);
928 r = realloc(*x, l+1);
934 va_start(ap, separator);
938 t = va_arg(ap, const char *);
942 if (need_separator && separator)
943 p = stpcpy(p, separator);
947 need_separator = true;
959 char *strrep(const char *s, unsigned n) {
967 p = r = malloc(l * n + 1);
971 for (i = 0; i < n; i++)
978 int split_pair(const char *s, const char *sep, char **l, char **r) {
993 a = strndup(s, x - s);
997 b = strdup(x + strlen(sep));
1009 int free_and_strdup(char **p, const char *s) {
1014 /* Replaces a string pointer with an strdup()ed new string,
1015 * possibly freeing the old one. */
1017 if (streq_ptr(*p, s))
1033 #if !HAVE_EXPLICIT_BZERO
1035 * Pointer to memset is volatile so that compiler must de-reference
1036 * the pointer and can't assume that it points to any function in
1037 * particular (such as memset, which it then might further "optimize")
1038 * This approach is inspired by openssl's crypto/mem_clr.c.
1040 typedef void *(*memset_t)(void *,int,size_t);
1042 static volatile memset_t memset_func = memset;
1044 void explicit_bzero(void *p, size_t l) {
1045 memset_func(p, '\0', l);
1049 char* string_erase(char *x) {
1053 /* A delicious drop of snake-oil! To be called on memory where
1054 * we stored passphrases or so, after we used them. */
1055 explicit_bzero(x, strlen(x));
1059 char *string_free_erase(char *s) {
1060 return mfree(string_erase(s));
1063 bool string_is_safe(const char *p) {
1069 for (t = p; *t; t++) {
1070 if (*t > 0 && *t < ' ') /* no control characters */
1073 if (strchr(QUOTES "\\\x7f", *t))