]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/string-util.c
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 char *delete_chars(char *s
, const char *bad
) {
281 /* Drops all specified bad characters, regardless where in the string */
289 for (f
= s
, t
= s
; *f
; f
++) {
301 char *delete_trailing_chars(char *s
, const char *bad
) {
304 /* Drops all specified bad characters, at the end of the string */
313 if (!strchr(bad
, *p
))
321 char *truncate_nl(char *s
) {
324 s
[strcspn(s
, NEWLINE
)] = 0;
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. */
419 bool string_has_cc(const char *p
, const char *ok
) {
425 * Check if a string contains control characters. If 'ok' is
426 * non-NULL it may be a string containing additional CCs to be
430 for (t
= p
; *t
; t
++) {
431 if (ok
&& strchr(ok
, *t
))
434 if (*t
> 0 && *t
< ' ')
444 static int write_ellipsis(char *buf
, bool unicode
) {
445 if (unicode
|| is_locale_utf8()) {
446 buf
[0] = 0xe2; /* tri-dot ellipsis: … */
458 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
459 size_t x
, need_space
, suffix_len
;
463 assert(percent
<= 100);
464 assert(new_length
!= (size_t) -1);
466 if (old_length
<= new_length
)
467 return strndup(s
, old_length
);
469 /* Special case short ellipsations */
470 switch (new_length
) {
476 if (is_locale_utf8())
477 return strdup("…");
482 if (!is_locale_utf8())
491 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
492 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
493 * either for the UTF-8 encoded character or for three ASCII characters. */
494 need_space
= is_locale_utf8() ? 1 : 3;
496 t
= new(char, new_length
+3);
500 assert(new_length
>= need_space
);
502 x
= ((new_length
- need_space
) * percent
+ 50) / 100;
503 assert(x
<= new_length
- need_space
);
506 write_ellipsis(t
+ x
, false);
507 suffix_len
= new_length
- x
- need_space
;
508 memcpy(t
+ x
+ 3, s
+ old_length
- suffix_len
, suffix_len
);
509 *(t
+ x
+ 3 + suffix_len
) = '\0';
514 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
515 size_t x
, k
, len
, len2
;
520 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
521 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
524 * Ellipsation is done in a locale-dependent way:
525 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
526 * 2. Otherwise, a unicode ellipsis is used ("…")
528 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
529 * the current locale is UTF-8.
533 assert(percent
<= 100);
535 if (new_length
== (size_t) -1)
536 return strndup(s
, old_length
);
541 /* If no multibyte characters use ascii_ellipsize_mem for speed */
542 if (ascii_is_valid_n(s
, old_length
))
543 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
545 x
= ((new_length
- 1) * percent
) / 100;
546 assert(x
<= new_length
- 1);
549 for (i
= s
; i
< s
+ old_length
; i
= utf8_next_char(i
)) {
553 r
= utf8_encoded_to_unichar(i
, &c
);
557 w
= unichar_iswide(c
) ? 2 : 1;
564 for (j
= s
+ old_length
; j
> i
; ) {
569 jj
= utf8_prev_char(j
);
570 r
= utf8_encoded_to_unichar(jj
, &c
);
574 w
= unichar_iswide(c
) ? 2 : 1;
575 if (k
+ w
<= new_length
) {
583 /* we don't actually need to ellipsize */
585 return memdup_suffix0(s
, old_length
);
587 /* make space for ellipsis, if possible */
588 if (j
< s
+ old_length
)
589 j
= utf8_next_char(j
);
591 i
= utf8_prev_char(i
);
594 len2
= s
+ old_length
- j
;
595 e
= new(char, len
+ 3 + len2
+ 1);
600 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
601 old_length, new_length, x, len, len2, k);
605 write_ellipsis(e
+ len
, true);
606 memcpy(e
+ len
+ 3, j
, len2
);
607 *(e
+ len
+ 3 + len2
) = '\0';
612 char *cellescape(char *buf
, size_t len
, const char *s
) {
613 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
614 * characters are copied as they are, everything else is escaped. The result
615 * is different then if escaping and ellipsization was performed in two
616 * separate steps, because each sequence is either stored in full or skipped.
618 * This function should be used for logging about strings which expected to
619 * be plain ASCII in a safe way.
621 * An ellipsis will be used if s is too long. It was always placed at the
625 size_t i
= 0, last_char_width
[4] = {}, k
= 0, j
;
627 assert(len
> 0); /* at least a terminating NUL */
633 if (*s
== 0) /* terminating NUL detected? then we are done! */
636 w
= cescape_char(*s
, four
);
637 if (i
+ w
+ 1 > len
) /* This character doesn't fit into the buffer anymore? In that case let's
638 * ellipsize at the previous location */
641 /* OK, there was space, let's add this escaped character to the buffer */
642 memcpy(buf
+ i
, four
, w
);
645 /* And remember its width in the ring buffer */
646 last_char_width
[k
] = w
;
652 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
653 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
654 for (j
= 0; j
< ELEMENTSOF(last_char_width
); j
++) {
656 if (i
+ 4 <= len
) /* nice, we reached our space goal */
659 k
= k
== 0 ? 3 : k
- 1;
660 if (last_char_width
[k
] == 0) /* bummer, we reached the beginning of the strings */
663 assert(i
>= last_char_width
[k
]);
664 i
-= last_char_width
[k
];
667 if (i
+ 4 <= len
) /* yay, enough space */
668 i
+= write_ellipsis(buf
+ i
, false);
669 else if (i
+ 3 <= len
) { /* only space for ".." */
672 } else if (i
+ 2 <= len
) /* only space for a single "." */
675 assert(i
+ 1 <= len
);
682 bool nulstr_contains(const char *nulstr
, const char *needle
) {
688 NULSTR_FOREACH(i
, nulstr
)
689 if (streq(i
, needle
))
695 char* strshorten(char *s
, size_t l
) {
698 if (strnlen(s
, l
+1) > l
)
704 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
705 size_t l
, old_len
, new_len
, allocated
= 0;
706 char *t
, *ret
= NULL
;
715 old_len
= strlen(old_string
);
716 new_len
= strlen(new_string
);
719 if (!GREEDY_REALLOC(ret
, allocated
, l
+1))
727 if (!startswith(f
, old_string
)) {
733 nl
= l
- old_len
+ new_len
;
735 if (!GREEDY_REALLOC(ret
, allocated
, nl
+ 1))
741 t
= stpcpy(t
, new_string
);
749 static void advance_offsets(ssize_t diff
, size_t offsets
[2], size_t shift
[2], size_t size
) {
753 if ((size_t) diff
< offsets
[0])
755 if ((size_t) diff
< offsets
[1])
759 char *strip_tab_ansi(char **ibuf
, size_t *_isz
, size_t highlight
[2]) {
760 const char *i
, *begin
= NULL
;
766 } state
= STATE_OTHER
;
768 size_t osz
= 0, isz
, shift
[2] = {};
774 /* This does three things:
776 * 1. Replaces TABs by 8 spaces
777 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
778 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
780 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as are any
781 * other special characters. Truncated ANSI sequences are left-as is too. This call is supposed to suppress the
782 * most basic formatting noise, but nothing else.
784 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
786 isz
= _isz
? *_isz
: strlen(*ibuf
);
788 f
= open_memstream(&obuf
, &osz
);
792 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
793 * and it doesn't leave our scope. */
795 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
797 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
802 if (i
>= *ibuf
+ isz
) /* EOT */
804 else if (*i
== '\x1B')
805 state
= STATE_ESCAPE
;
806 else if (*i
== '\t') {
808 advance_offsets(i
- *ibuf
, highlight
, shift
, 7);
815 if (i
>= *ibuf
+ isz
) { /* EOT */
817 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
819 } else if (*i
== '[') { /* ANSI CSI */
822 } else if (*i
== ']') { /* ANSI CSO */
828 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
836 if (i
>= *ibuf
+ isz
|| /* EOT … */
837 !strchr("01234567890;m", *i
)) { /* … or invalid chars in sequence */
840 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
843 } else if (*i
== 'm')
850 if (i
>= *ibuf
+ isz
|| /* EOT … */
851 (*i
!= '\a' && (uint8_t) *i
< 32U) || (uint8_t) *i
> 126U) { /* … or invalid chars in sequence */
854 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
857 } else if (*i
== '\a')
864 if (fflush_and_check(f
) < 0) {
878 highlight
[0] += shift
[0];
879 highlight
[1] += shift
[1];
885 char *strextend_with_separator(char **x
, const char *separator
, ...) {
887 size_t f
, l
, l_separator
;
893 l
= f
= strlen_ptr(*x
);
895 need_separator
= !isempty(*x
);
896 l_separator
= strlen_ptr(separator
);
898 va_start(ap
, separator
);
903 t
= va_arg(ap
, const char *);
912 if (n
> ((size_t) -1) - l
) {
918 need_separator
= true;
922 need_separator
= !isempty(*x
);
924 r
= realloc(*x
, l
+1);
930 va_start(ap
, separator
);
934 t
= va_arg(ap
, const char *);
938 if (need_separator
&& separator
)
939 p
= stpcpy(p
, separator
);
943 need_separator
= true;
955 char *strrep(const char *s
, unsigned n
) {
963 p
= r
= malloc(l
* n
+ 1);
967 for (i
= 0; i
< n
; i
++)
974 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
989 a
= strndup(s
, x
- s
);
993 b
= strdup(x
+ strlen(sep
));
1005 int free_and_strdup(char **p
, const char *s
) {
1010 /* Replaces a string pointer with an strdup()ed new string,
1011 * possibly freeing the old one. */
1013 if (streq_ptr(*p
, s
))
1029 #if !HAVE_EXPLICIT_BZERO
1031 * Pointer to memset is volatile so that compiler must de-reference
1032 * the pointer and can't assume that it points to any function in
1033 * particular (such as memset, which it then might further "optimize")
1034 * This approach is inspired by openssl's crypto/mem_clr.c.
1036 typedef void *(*memset_t
)(void *,int,size_t);
1038 static volatile memset_t memset_func
= memset
;
1040 void explicit_bzero(void *p
, size_t l
) {
1041 memset_func(p
, '\0', l
);
1045 char* string_erase(char *x
) {
1049 /* A delicious drop of snake-oil! To be called on memory where
1050 * we stored passphrases or so, after we used them. */
1051 explicit_bzero(x
, strlen(x
));
1055 char *string_free_erase(char *s
) {
1056 return mfree(string_erase(s
));
1059 bool string_is_safe(const char *p
) {
1065 for (t
= p
; *t
; t
++) {
1066 if (*t
> 0 && *t
< ' ') /* no control characters */
1069 if (strchr(QUOTES
"\\\x7f", *t
))