]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/string-util.c
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 char *delete_chars(char *s
, const char *bad
) {
283 /* Drops all specified bad characters, regardless where in the string */
291 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 char ascii_tolower(char x
) {
332 if (x
>= 'A' && x
<= 'Z')
333 return x
- 'A' + 'a';
338 char ascii_toupper(char x
) {
340 if (x
>= 'a' && x
<= 'z')
341 return x
- 'a' + 'A';
346 char *ascii_strlower(char *t
) {
352 *p
= ascii_tolower(*p
);
357 char *ascii_strupper(char *t
) {
363 *p
= ascii_toupper(*p
);
368 char *ascii_strlower_n(char *t
, size_t n
) {
374 for (i
= 0; i
< n
; i
++)
375 t
[i
] = ascii_tolower(t
[i
]);
380 int ascii_strcasecmp_n(const char *a
, const char *b
, size_t n
) {
382 for (; n
> 0; a
++, b
++, n
--) {
385 x
= (int) (uint8_t) ascii_tolower(*a
);
386 y
= (int) (uint8_t) ascii_tolower(*b
);
395 int ascii_strcasecmp_nn(const char *a
, size_t n
, const char *b
, size_t m
) {
398 r
= ascii_strcasecmp_n(a
, b
, MIN(n
, m
));
410 bool chars_intersect(const char *a
, const char *b
) {
413 /* Returns true if any of the chars in a are in b. */
421 bool string_has_cc(const char *p
, const char *ok
) {
427 * Check if a string contains control characters. If 'ok' is
428 * non-NULL it may be a string containing additional CCs to be
432 for (t
= p
; *t
; t
++) {
433 if (ok
&& strchr(ok
, *t
))
436 if (*t
> 0 && *t
< ' ')
446 static int write_ellipsis(char *buf
, bool unicode
) {
447 if (unicode
|| is_locale_utf8()) {
448 buf
[0] = 0xe2; /* tri-dot ellipsis: … */
460 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
461 size_t x
, need_space
, suffix_len
;
465 assert(percent
<= 100);
466 assert(new_length
!= (size_t) -1);
468 if (old_length
<= new_length
)
469 return strndup(s
, old_length
);
471 /* Special case short ellipsations */
472 switch (new_length
) {
478 if (is_locale_utf8())
484 if (!is_locale_utf8())
493 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
494 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
495 * either for the UTF-8 encoded character or for three ASCII characters. */
496 need_space
= is_locale_utf8() ? 1 : 3;
498 t
= new(char, new_length
+3);
502 assert(new_length
>= need_space
);
504 x
= ((new_length
- need_space
) * percent
+ 50) / 100;
505 assert(x
<= new_length
- need_space
);
508 write_ellipsis(t
+ x
, false);
509 suffix_len
= new_length
- x
- need_space
;
510 memcpy(t
+ x
+ 3, s
+ old_length
- suffix_len
, suffix_len
);
511 *(t
+ x
+ 3 + suffix_len
) = '\0';
516 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
517 size_t x
, k
, len
, len2
;
522 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
523 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
526 * Ellipsation is done in a locale-dependent way:
527 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
528 * 2. Otherwise, a unicode ellipsis is used ("…")
530 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
531 * the current locale is UTF-8.
535 assert(percent
<= 100);
537 if (new_length
== (size_t) -1)
538 return strndup(s
, old_length
);
543 /* If no multibyte characters use ascii_ellipsize_mem for speed */
544 if (ascii_is_valid(s
))
545 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
547 x
= ((new_length
- 1) * percent
) / 100;
548 assert(x
<= new_length
- 1);
551 for (i
= s
; i
< s
+ old_length
; i
= utf8_next_char(i
)) {
555 r
= utf8_encoded_to_unichar(i
, &c
);
559 w
= unichar_iswide(c
) ? 2 : 1;
566 for (j
= s
+ old_length
; j
> i
; ) {
571 jj
= utf8_prev_char(j
);
572 r
= utf8_encoded_to_unichar(jj
, &c
);
576 w
= unichar_iswide(c
) ? 2 : 1;
577 if (k
+ w
<= new_length
) {
585 /* we don't actually need to ellipsize */
587 return memdup_suffix0(s
, old_length
);
589 /* make space for ellipsis, if possible */
590 if (j
< s
+ old_length
)
591 j
= utf8_next_char(j
);
593 i
= utf8_prev_char(i
);
596 len2
= s
+ old_length
- j
;
597 e
= new(char, len
+ 3 + len2
+ 1);
602 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
603 old_length, new_length, x, len, len2, k);
607 write_ellipsis(e
+ len
, true);
608 memcpy(e
+ len
+ 3, j
, len2
);
609 *(e
+ len
+ 3 + len2
) = '\0';
614 char *cellescape(char *buf
, size_t len
, const char *s
) {
615 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
616 * characters are copied as they are, everything else is escaped. The result
617 * is different then if escaping and ellipsization was performed in two
618 * separate steps, because each sequence is either stored in full or skipped.
620 * This function should be used for logging about strings which expected to
621 * be plain ASCII in a safe way.
623 * An ellipsis will be used if s is too long. It was always placed at the
627 size_t i
= 0, last_char_width
[4] = {}, k
= 0, j
;
629 assert(len
> 0); /* at least a terminating NUL */
635 if (*s
== 0) /* terminating NUL detected? then we are done! */
638 w
= cescape_char(*s
, four
);
639 if (i
+ w
+ 1 > len
) /* This character doesn't fit into the buffer anymore? In that case let's
640 * ellipsize at the previous location */
643 /* OK, there was space, let's add this escaped character to the buffer */
644 memcpy(buf
+ i
, four
, w
);
647 /* And remember its width in the ring buffer */
648 last_char_width
[k
] = w
;
654 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
655 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
656 for (j
= 0; j
< ELEMENTSOF(last_char_width
); j
++) {
658 if (i
+ 4 <= len
) /* nice, we reached our space goal */
661 k
= k
== 0 ? 3 : k
- 1;
662 if (last_char_width
[k
] == 0) /* bummer, we reached the beginning of the strings */
665 assert(i
>= last_char_width
[k
]);
666 i
-= last_char_width
[k
];
669 if (i
+ 4 <= len
) /* yay, enough space */
670 i
+= write_ellipsis(buf
+ i
, false);
671 else if (i
+ 3 <= len
) { /* only space for ".." */
674 } else if (i
+ 2 <= len
) /* only space for a single "." */
677 assert(i
+ 1 <= len
);
684 bool nulstr_contains(const char *nulstr
, const char *needle
) {
690 NULSTR_FOREACH(i
, nulstr
)
691 if (streq(i
, needle
))
697 char* strshorten(char *s
, size_t l
) {
700 if (strnlen(s
, l
+1) > l
)
706 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
707 size_t l
, old_len
, new_len
, allocated
= 0;
708 char *t
, *ret
= NULL
;
717 old_len
= strlen(old_string
);
718 new_len
= strlen(new_string
);
721 if (!GREEDY_REALLOC(ret
, allocated
, l
+1))
729 if (!startswith(f
, old_string
)) {
735 nl
= l
- old_len
+ new_len
;
737 if (!GREEDY_REALLOC(ret
, allocated
, nl
+ 1))
743 t
= stpcpy(t
, new_string
);
751 static void advance_offsets(ssize_t diff
, size_t offsets
[2], size_t shift
[2], size_t size
) {
755 if ((size_t) diff
< offsets
[0])
757 if ((size_t) diff
< offsets
[1])
761 char *strip_tab_ansi(char **ibuf
, size_t *_isz
, size_t highlight
[2]) {
762 const char *i
, *begin
= NULL
;
768 } state
= STATE_OTHER
;
770 size_t osz
= 0, isz
, shift
[2] = {};
776 /* This does three things:
778 * 1. Replaces TABs by 8 spaces
779 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
780 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
782 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as are any
783 * other special characters. Truncated ANSI sequences are left-as is too. This call is supposed to suppress the
784 * most basic formatting noise, but nothing else.
786 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
788 isz
= _isz
? *_isz
: strlen(*ibuf
);
790 f
= open_memstream(&obuf
, &osz
);
794 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
795 * and it doesn't leave our scope. */
797 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
799 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
804 if (i
>= *ibuf
+ isz
) /* EOT */
806 else if (*i
== '\x1B')
807 state
= STATE_ESCAPE
;
808 else if (*i
== '\t') {
810 advance_offsets(i
- *ibuf
, highlight
, shift
, 7);
817 if (i
>= *ibuf
+ isz
) { /* EOT */
819 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
821 } else if (*i
== '[') { /* ANSI CSI */
824 } else if (*i
== ']') { /* ANSI CSO */
830 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
838 if (i
>= *ibuf
+ isz
|| /* EOT … */
839 !strchr("01234567890;m", *i
)) { /* … or invalid chars in sequence */
842 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
845 } else if (*i
== 'm')
852 if (i
>= *ibuf
+ isz
|| /* EOT … */
853 (*i
!= '\a' && (uint8_t) *i
< 32U) || (uint8_t) *i
> 126U) { /* … or invalid chars in sequence */
856 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
859 } else if (*i
== '\a')
866 if (fflush_and_check(f
) < 0) {
880 highlight
[0] += shift
[0];
881 highlight
[1] += shift
[1];
887 char *strextend_with_separator(char **x
, const char *separator
, ...) {
889 size_t f
, l
, l_separator
;
895 l
= f
= strlen_ptr(*x
);
897 need_separator
= !isempty(*x
);
898 l_separator
= strlen_ptr(separator
);
900 va_start(ap
, separator
);
905 t
= va_arg(ap
, const char *);
914 if (n
> ((size_t) -1) - l
) {
920 need_separator
= true;
924 need_separator
= !isempty(*x
);
926 r
= realloc(*x
, l
+1);
932 va_start(ap
, separator
);
936 t
= va_arg(ap
, const char *);
940 if (need_separator
&& separator
)
941 p
= stpcpy(p
, separator
);
945 need_separator
= true;
957 char *strrep(const char *s
, unsigned n
) {
965 p
= r
= malloc(l
* n
+ 1);
969 for (i
= 0; i
< n
; i
++)
976 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
991 a
= strndup(s
, x
- s
);
995 b
= strdup(x
+ strlen(sep
));
1007 int free_and_strdup(char **p
, const char *s
) {
1012 /* Replaces a string pointer with an strdup()ed new string,
1013 * possibly freeing the old one. */
1015 if (streq_ptr(*p
, s
))
1031 #if !HAVE_EXPLICIT_BZERO
1033 * Pointer to memset is volatile so that compiler must de-reference
1034 * the pointer and can't assume that it points to any function in
1035 * particular (such as memset, which it then might further "optimize")
1036 * This approach is inspired by openssl's crypto/mem_clr.c.
1038 typedef void *(*memset_t
)(void *,int,size_t);
1040 static volatile memset_t memset_func
= memset
;
1042 void explicit_bzero(void *p
, size_t l
) {
1043 memset_func(p
, '\0', l
);
1047 char* string_erase(char *x
) {
1051 /* A delicious drop of snake-oil! To be called on memory where
1052 * we stored passphrases or so, after we used them. */
1053 explicit_bzero(x
, strlen(x
));
1057 char *string_free_erase(char *s
) {
1058 return mfree(string_erase(s
));
1061 bool string_is_safe(const char *p
) {
1067 for (t
= p
; *t
; t
++) {
1068 if (*t
> 0 && *t
< ' ') /* no control characters */
1071 if (strchr(QUOTES
"\\\x7f", *t
))