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 "locale-util.h"
21 #include "string-util.h"
22 //#include "terminal-util.h"
27 int strcmp_ptr(const char *a, const char *b) {
29 /* Like strcmp(), but tries to make sense of NULL pointers */
42 char* endswith(const char *s, const char *postfix) {
52 return (char*) s + sl;
57 if (memcmp(s + sl - pl, postfix, pl) != 0)
60 return (char*) s + sl - pl;
63 char* endswith_no_case(const char *s, const char *postfix) {
73 return (char*) s + sl;
78 if (strcasecmp(s + sl - pl, postfix) != 0)
81 return (char*) s + sl - pl;
84 char* first_word(const char *s, const char *word) {
91 /* Checks if the string starts with the specified word, either
92 * followed by NUL or by whitespace. Returns a pointer to the
93 * NUL or the first character after the whitespace. */
104 if (memcmp(s, word, wl) != 0)
111 if (!strchr(WHITESPACE, *p))
114 p += strspn(p, WHITESPACE);
118 static size_t strcspn_escaped(const char *s, const char *reject) {
119 bool escaped = false;
122 for (n=0; s[n]; n++) {
125 else if (s[n] == '\\')
127 else if (strchr(reject, s[n]))
131 /* if s ends in \, return index of previous char */
135 /* Split a string into words. */
136 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
142 assert(**state == '\0');
146 current += strspn(current, separator);
152 if (quoted && strchr("\'\"", *current)) {
153 char quotechars[2] = {*current, '\0'};
155 *l = strcspn_escaped(current + 1, quotechars);
156 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
157 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
158 /* right quote missing or garbage at the end */
162 *state = current++ + *l + 2;
164 *l = strcspn_escaped(current, separator);
165 if (current[*l] && !strchr(separator, current[*l])) {
166 /* unfinished escape */
170 *state = current + *l;
172 *l = strcspn(current, separator);
173 *state = current + *l;
179 char *strnappend(const char *s, const char *suffix, size_t b) {
187 return strndup(suffix, b);
196 if (b > ((size_t) -1) - a)
199 r = new(char, a+b+1);
204 memcpy(r+a, suffix, b);
210 char *strappend(const char *s, const char *suffix) {
211 return strnappend(s, suffix, strlen_ptr(suffix));
214 char *strjoin_real(const char *x, ...) {
228 t = va_arg(ap, const char *);
233 if (n > ((size_t) -1) - l) {
257 t = va_arg(ap, const char *);
271 char *strstrip(char *s) {
275 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
277 return delete_trailing_chars(skip_leading_chars(s, WHITESPACE), WHITESPACE);
280 #if 0 /// UNNEEDED by elogind
281 char *delete_chars(char *s, const char *bad) {
284 /* Drops all specified bad characters, regardless where in the string */
292 for (f = s, t = s; *f; f++) {
305 char *delete_trailing_chars(char *s, const char *bad) {
308 /* Drops all specified bad characters, at the end of the string */
317 if (!strchr(bad, *p))
325 char *truncate_nl(char *s) {
328 s[strcspn(s, NEWLINE)] = 0;
332 #if 0 /// UNNEEDED by elogind
333 char ascii_tolower(char x) {
335 if (x >= 'A' && x <= 'Z')
336 return x - 'A' + 'a';
341 char ascii_toupper(char x) {
343 if (x >= 'a' && x <= 'z')
344 return x - 'a' + 'A';
349 char *ascii_strlower(char *t) {
355 *p = ascii_tolower(*p);
360 char *ascii_strupper(char *t) {
366 *p = ascii_toupper(*p);
371 char *ascii_strlower_n(char *t, size_t n) {
377 for (i = 0; i < n; i++)
378 t[i] = ascii_tolower(t[i]);
383 int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
385 for (; n > 0; a++, b++, n--) {
388 x = (int) (uint8_t) ascii_tolower(*a);
389 y = (int) (uint8_t) ascii_tolower(*b);
398 int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
401 r = ascii_strcasecmp_n(a, b, MIN(n, m));
413 bool chars_intersect(const char *a, const char *b) {
416 /* Returns true if any of the chars in a are in b. */
425 bool string_has_cc(const char *p, const char *ok) {
431 * Check if a string contains control characters. If 'ok' is
432 * non-NULL it may be a string containing additional CCs to be
436 for (t = p; *t; t++) {
437 if (ok && strchr(ok, *t))
440 if (*t > 0 && *t < ' ')
450 static int write_ellipsis(char *buf, bool unicode) {
451 if (unicode || is_locale_utf8()) {
452 buf[0] = 0xe2; /* tri-dot ellipsis: … */
464 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
465 size_t x, need_space, suffix_len;
469 assert(percent <= 100);
470 assert(new_length != (size_t) -1);
472 if (old_length <= new_length)
473 return strndup(s, old_length);
475 /* Special case short ellipsations */
476 switch (new_length) {
482 if (is_locale_utf8())
488 if (!is_locale_utf8())
497 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
498 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
499 * either for the UTF-8 encoded character or for three ASCII characters. */
500 need_space = is_locale_utf8() ? 1 : 3;
502 t = new(char, new_length+3);
506 assert(new_length >= need_space);
508 x = ((new_length - need_space) * percent + 50) / 100;
509 assert(x <= new_length - need_space);
512 write_ellipsis(t + x, false);
513 suffix_len = new_length - x - need_space;
514 memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
515 *(t + x + 3 + suffix_len) = '\0';
520 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
521 size_t x, k, len, len2;
526 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
527 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
530 * Ellipsation is done in a locale-dependent way:
531 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
532 * 2. Otherwise, a unicode ellipsis is used ("…")
534 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
535 * the current locale is UTF-8.
539 assert(percent <= 100);
541 if (new_length == (size_t) -1)
542 return strndup(s, old_length);
547 /* If no multibyte characters use ascii_ellipsize_mem for speed */
548 if (ascii_is_valid_n(s, old_length))
549 return ascii_ellipsize_mem(s, old_length, new_length, percent);
551 x = ((new_length - 1) * percent) / 100;
552 assert(x <= new_length - 1);
555 for (i = s; i < s + old_length; i = utf8_next_char(i)) {
559 r = utf8_encoded_to_unichar(i, &c);
563 w = unichar_iswide(c) ? 2 : 1;
570 for (j = s + old_length; j > i; ) {
575 jj = utf8_prev_char(j);
576 r = utf8_encoded_to_unichar(jj, &c);
580 w = unichar_iswide(c) ? 2 : 1;
581 if (k + w <= new_length) {
589 /* we don't actually need to ellipsize */
591 return memdup_suffix0(s, old_length);
593 /* make space for ellipsis, if possible */
594 if (j < s + old_length)
595 j = utf8_next_char(j);
597 i = utf8_prev_char(i);
600 len2 = s + old_length - j;
601 e = new(char, len + 3 + len2 + 1);
606 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
607 old_length, new_length, x, len, len2, k);
611 write_ellipsis(e + len, true);
612 memcpy(e + len + 3, j, len2);
613 *(e + len + 3 + len2) = '\0';
618 char *cellescape(char *buf, size_t len, const char *s) {
619 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
620 * characters are copied as they are, everything else is escaped. The result
621 * is different then if escaping and ellipsization was performed in two
622 * separate steps, because each sequence is either stored in full or skipped.
624 * This function should be used for logging about strings which expected to
625 * be plain ASCII in a safe way.
627 * An ellipsis will be used if s is too long. It was always placed at the
631 size_t i = 0, last_char_width[4] = {}, k = 0, j;
633 assert(len > 0); /* at least a terminating NUL */
639 if (*s == 0) /* terminating NUL detected? then we are done! */
642 w = cescape_char(*s, four);
643 if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
644 * ellipsize at the previous location */
647 /* OK, there was space, let's add this escaped character to the buffer */
648 memcpy(buf + i, four, w);
651 /* And remember its width in the ring buffer */
652 last_char_width[k] = w;
658 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
659 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
660 for (j = 0; j < ELEMENTSOF(last_char_width); j++) {
662 if (i + 4 <= len) /* nice, we reached our space goal */
665 k = k == 0 ? 3 : k - 1;
666 if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
669 assert(i >= last_char_width[k]);
670 i -= last_char_width[k];
673 if (i + 4 <= len) /* yay, enough space */
674 i += write_ellipsis(buf + i, false);
675 else if (i + 3 <= len) { /* only space for ".." */
678 } else if (i + 2 <= len) /* only space for a single "." */
681 assert(i + 1 <= len);
688 bool nulstr_contains(const char *nulstr, const char *needle) {
694 NULSTR_FOREACH(i, nulstr)
695 if (streq(i, needle))
701 char* strshorten(char *s, size_t l) {
704 if (strnlen(s, l+1) > l)
710 char *strreplace(const char *text, const char *old_string, const char *new_string) {
711 size_t l, old_len, new_len, allocated = 0;
712 char *t, *ret = NULL;
721 old_len = strlen(old_string);
722 new_len = strlen(new_string);
725 if (!GREEDY_REALLOC(ret, allocated, l+1))
733 if (!startswith(f, old_string)) {
739 nl = l - old_len + new_len;
741 if (!GREEDY_REALLOC(ret, allocated, nl + 1))
747 t = stpcpy(t, new_string);
755 static void advance_offsets(ssize_t diff, size_t offsets[2], size_t shift[2], size_t size) {
759 if ((size_t) diff < offsets[0])
761 if ((size_t) diff < offsets[1])
765 char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
766 const char *i, *begin = NULL;
772 } state = STATE_OTHER;
774 size_t osz = 0, isz, shift[2] = {};
780 /* This does three things:
782 * 1. Replaces TABs by 8 spaces
783 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
784 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
786 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as are any
787 * other special characters. Truncated ANSI sequences are left-as is too. This call is supposed to suppress the
788 * most basic formatting noise, but nothing else.
790 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
792 isz = _isz ? *_isz : strlen(*ibuf);
794 f = open_memstream(&obuf, &osz);
798 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
799 * and it doesn't leave our scope. */
801 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
803 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
808 if (i >= *ibuf + isz) /* EOT */
810 else if (*i == '\x1B')
811 state = STATE_ESCAPE;
812 else if (*i == '\t') {
814 advance_offsets(i - *ibuf, highlight, shift, 7);
821 if (i >= *ibuf + isz) { /* EOT */
823 advance_offsets(i - *ibuf, highlight, shift, 1);
825 } else if (*i == '[') { /* ANSI CSI */
828 } else if (*i == ']') { /* ANSI CSO */
834 advance_offsets(i - *ibuf, highlight, shift, 1);
842 if (i >= *ibuf + isz || /* EOT … */
843 !strchr("01234567890;m", *i)) { /* … or invalid chars in sequence */
846 advance_offsets(i - *ibuf, highlight, shift, 2);
849 } else if (*i == 'm')
856 if (i >= *ibuf + isz || /* EOT … */
857 (*i != '\a' && (uint8_t) *i < 32U) || (uint8_t) *i > 126U) { /* … or invalid chars in sequence */
860 advance_offsets(i - *ibuf, highlight, shift, 2);
863 } else if (*i == '\a')
870 if (fflush_and_check(f) < 0) {
884 highlight[0] += shift[0];
885 highlight[1] += shift[1];
891 char *strextend_with_separator(char **x, const char *separator, ...) {
893 size_t f, l, l_separator;
899 l = f = strlen_ptr(*x);
901 need_separator = !isempty(*x);
902 l_separator = strlen_ptr(separator);
904 va_start(ap, separator);
909 t = va_arg(ap, const char *);
918 if (n > ((size_t) -1) - l) {
924 need_separator = true;
928 need_separator = !isempty(*x);
930 r = realloc(*x, l+1);
936 va_start(ap, separator);
940 t = va_arg(ap, const char *);
944 if (need_separator && separator)
945 p = stpcpy(p, separator);
949 need_separator = true;
961 char *strrep(const char *s, unsigned n) {
969 p = r = malloc(l * n + 1);
973 for (i = 0; i < n; i++)
980 int split_pair(const char *s, const char *sep, char **l, char **r) {
995 a = strndup(s, x - s);
999 b = strdup(x + strlen(sep));
1011 int free_and_strdup(char **p, const char *s) {
1016 /* Replaces a string pointer with an strdup()ed new string,
1017 * possibly freeing the old one. */
1019 if (streq_ptr(*p, s))
1035 #if !HAVE_EXPLICIT_BZERO
1037 * Pointer to memset is volatile so that compiler must de-reference
1038 * the pointer and can't assume that it points to any function in
1039 * particular (such as memset, which it then might further "optimize")
1040 * This approach is inspired by openssl's crypto/mem_clr.c.
1042 typedef void *(*memset_t)(void *,int,size_t);
1044 static volatile memset_t memset_func = memset;
1046 void explicit_bzero(void *p, size_t l) {
1047 memset_func(p, '\0', l);
1051 char* string_erase(char *x) {
1055 /* A delicious drop of snake-oil! To be called on memory where
1056 * we stored passphrases or so, after we used them. */
1057 explicit_bzero(x, strlen(x));
1061 char *string_free_erase(char *s) {
1062 return mfree(string_erase(s));
1065 bool string_is_safe(const char *p) {
1071 for (t = p; *t; t++) {
1072 if (*t > 0 && *t < ' ') /* no control characters */
1075 if (strchr(QUOTES "\\\x7f", *t))