]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/string-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include "alloc-util.h"
14 #include "locale-util.h"
16 #include "memory-util.h"
17 #include "string-util.h"
18 #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
, SplitFlags flags
) {
137 assert(**state
== '\0');
141 current
+= strspn(current
, separator
);
147 if (flags
& SPLIT_QUOTES
&& 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 */
154 if (flags
& SPLIT_RELAX
) {
155 *state
= current
+ *l
+ 1 + (current
[*l
+ 1] != '\0');
161 *state
= current
++ + *l
+ 2;
162 } else if (flags
& SPLIT_QUOTES
) {
163 *l
= strcspn_escaped(current
, separator
);
164 if (current
[*l
] && !strchr(separator
, current
[*l
]) && !(flags
& SPLIT_RELAX
)) {
165 /* unfinished escape */
169 *state
= current
+ *l
;
171 *l
= strcspn(current
, separator
);
172 *state
= current
+ *l
;
178 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
186 return strndup(suffix
, b
);
195 if (b
> ((size_t) -1) - a
)
198 r
= new(char, a
+b
+1);
203 memcpy(r
+a
, suffix
, b
);
209 char *strappend(const char *s
, const char *suffix
) {
210 return strnappend(s
, suffix
, strlen_ptr(suffix
));
213 char *strjoin_real(const char *x
, ...) {
227 t
= va_arg(ap
, const char *);
232 if (n
> ((size_t) -1) - l
) {
256 t
= va_arg(ap
, const char *);
270 char *strstrip(char *s
) {
274 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
276 return delete_trailing_chars(skip_leading_chars(s
, WHITESPACE
), WHITESPACE
);
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
++) {
302 char *delete_trailing_chars(char *s
, const char *bad
) {
305 /* Drops all specified bad characters, at the end of the string */
314 if (!strchr(bad
, *p
))
322 char *truncate_nl(char *s
) {
325 s
[strcspn(s
, NEWLINE
)] = 0;
329 char ascii_tolower(char x
) {
331 if (x
>= 'A' && x
<= 'Z')
332 return x
- 'A' + 'a';
337 char ascii_toupper(char x
) {
339 if (x
>= 'a' && x
<= 'z')
340 return x
- 'a' + 'A';
345 char *ascii_strlower(char *t
) {
351 *p
= ascii_tolower(*p
);
356 char *ascii_strupper(char *t
) {
362 *p
= ascii_toupper(*p
);
367 char *ascii_strlower_n(char *t
, size_t n
) {
373 for (i
= 0; i
< n
; i
++)
374 t
[i
] = ascii_tolower(t
[i
]);
379 int ascii_strcasecmp_n(const char *a
, const char *b
, size_t n
) {
381 for (; n
> 0; a
++, b
++, n
--) {
384 x
= (int) (uint8_t) ascii_tolower(*a
);
385 y
= (int) (uint8_t) ascii_tolower(*b
);
394 int ascii_strcasecmp_nn(const char *a
, size_t n
, const char *b
, size_t m
) {
397 r
= ascii_strcasecmp_n(a
, b
, MIN(n
, m
));
404 bool chars_intersect(const char *a
, const char *b
) {
407 /* Returns true if any of the chars in a are in b. */
415 bool string_has_cc(const char *p
, const char *ok
) {
421 * Check if a string contains control characters. If 'ok' is
422 * non-NULL it may be a string containing additional CCs to be
426 for (t
= p
; *t
; t
++) {
427 if (ok
&& strchr(ok
, *t
))
430 if (*t
> 0 && *t
< ' ')
440 static int write_ellipsis(char *buf
, bool unicode
) {
441 if (unicode
|| is_locale_utf8()) {
442 buf
[0] = 0xe2; /* tri-dot ellipsis: … */
454 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
455 size_t x
, need_space
, suffix_len
;
459 assert(percent
<= 100);
460 assert(new_length
!= (size_t) -1);
462 if (old_length
<= new_length
)
463 return strndup(s
, old_length
);
465 /* Special case short ellipsations */
466 switch (new_length
) {
472 if (is_locale_utf8())
473 return strdup("…");
478 if (!is_locale_utf8())
487 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
488 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
489 * either for the UTF-8 encoded character or for three ASCII characters. */
490 need_space
= is_locale_utf8() ? 1 : 3;
492 t
= new(char, new_length
+3);
496 assert(new_length
>= need_space
);
498 x
= ((new_length
- need_space
) * percent
+ 50) / 100;
499 assert(x
<= new_length
- need_space
);
502 write_ellipsis(t
+ x
, false);
503 suffix_len
= new_length
- x
- need_space
;
504 memcpy(t
+ x
+ 3, s
+ old_length
- suffix_len
, suffix_len
);
505 *(t
+ x
+ 3 + suffix_len
) = '\0';
510 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
511 size_t x
, k
, len
, len2
;
516 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
517 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
520 * Ellipsation is done in a locale-dependent way:
521 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
522 * 2. Otherwise, a unicode ellipsis is used ("…")
524 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
525 * the current locale is UTF-8.
529 assert(percent
<= 100);
531 if (new_length
== (size_t) -1)
532 return strndup(s
, old_length
);
537 /* If no multibyte characters use ascii_ellipsize_mem for speed */
538 if (ascii_is_valid_n(s
, old_length
))
539 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
541 x
= ((new_length
- 1) * percent
) / 100;
542 assert(x
<= new_length
- 1);
545 for (i
= s
; i
< s
+ old_length
; i
= utf8_next_char(i
)) {
549 r
= utf8_encoded_to_unichar(i
, &c
);
553 w
= unichar_iswide(c
) ? 2 : 1;
560 for (j
= s
+ old_length
; j
> i
; ) {
565 jj
= utf8_prev_char(j
);
566 r
= utf8_encoded_to_unichar(jj
, &c
);
570 w
= unichar_iswide(c
) ? 2 : 1;
571 if (k
+ w
<= new_length
) {
579 /* we don't actually need to ellipsize */
581 return memdup_suffix0(s
, old_length
);
583 /* make space for ellipsis, if possible */
584 if (j
< s
+ old_length
)
585 j
= utf8_next_char(j
);
587 i
= utf8_prev_char(i
);
590 len2
= s
+ old_length
- j
;
591 e
= new(char, len
+ 3 + len2
+ 1);
596 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
597 old_length, new_length, x, len, len2, k);
601 write_ellipsis(e
+ len
, true);
602 memcpy(e
+ len
+ 3, j
, len2
);
603 *(e
+ len
+ 3 + len2
) = '\0';
608 char *cellescape(char *buf
, size_t len
, const char *s
) {
609 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
610 * characters are copied as they are, everything else is escaped. The result
611 * is different then if escaping and ellipsization was performed in two
612 * separate steps, because each sequence is either stored in full or skipped.
614 * This function should be used for logging about strings which expected to
615 * be plain ASCII in a safe way.
617 * An ellipsis will be used if s is too long. It was always placed at the
621 size_t i
= 0, last_char_width
[4] = {}, k
= 0, j
;
623 assert(len
> 0); /* at least a terminating NUL */
629 if (*s
== 0) /* terminating NUL detected? then we are done! */
632 w
= cescape_char(*s
, four
);
633 if (i
+ w
+ 1 > len
) /* This character doesn't fit into the buffer anymore? In that case let's
634 * ellipsize at the previous location */
637 /* OK, there was space, let's add this escaped character to the buffer */
638 memcpy(buf
+ i
, four
, w
);
641 /* And remember its width in the ring buffer */
642 last_char_width
[k
] = w
;
648 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
649 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
650 for (j
= 0; j
< ELEMENTSOF(last_char_width
); j
++) {
652 if (i
+ 4 <= len
) /* nice, we reached our space goal */
655 k
= k
== 0 ? 3 : k
- 1;
656 if (last_char_width
[k
] == 0) /* bummer, we reached the beginning of the strings */
659 assert(i
>= last_char_width
[k
]);
660 i
-= last_char_width
[k
];
663 if (i
+ 4 <= len
) /* yay, enough space */
664 i
+= write_ellipsis(buf
+ i
, false);
665 else if (i
+ 3 <= len
) { /* only space for ".." */
668 } else if (i
+ 2 <= len
) /* only space for a single "." */
671 assert(i
+ 1 <= len
);
678 char* strshorten(char *s
, size_t l
) {
681 if (strnlen(s
, l
+1) > l
)
687 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
688 size_t l
, old_len
, new_len
, allocated
= 0;
689 char *t
, *ret
= NULL
;
698 old_len
= strlen(old_string
);
699 new_len
= strlen(new_string
);
702 if (!GREEDY_REALLOC(ret
, allocated
, l
+1))
710 if (!startswith(f
, old_string
)) {
716 nl
= l
- old_len
+ new_len
;
718 if (!GREEDY_REALLOC(ret
, allocated
, nl
+ 1))
724 t
= stpcpy(t
, new_string
);
732 static void advance_offsets(ssize_t diff
, size_t offsets
[static 2], size_t shift
[static 2], size_t size
) {
736 if ((size_t) diff
< offsets
[0])
738 if ((size_t) diff
< offsets
[1])
742 char *strip_tab_ansi(char **ibuf
, size_t *_isz
, size_t highlight
[2]) {
743 const char *i
, *begin
= NULL
;
749 } state
= STATE_OTHER
;
751 size_t osz
= 0, isz
, shift
[2] = {};
757 /* This does three things:
759 * 1. Replaces TABs by 8 spaces
760 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
761 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
763 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
764 * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
765 * supposed to suppress the most basic formatting noise, but nothing else.
767 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
769 isz
= _isz
? *_isz
: strlen(*ibuf
);
771 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
772 * created f here and it doesn't leave our scope. */
773 f
= open_memstream_unlocked(&obuf
, &osz
);
777 for (i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
782 if (i
>= *ibuf
+ isz
) /* EOT */
784 else if (*i
== '\x1B')
785 state
= STATE_ESCAPE
;
786 else if (*i
== '\t') {
788 advance_offsets(i
- *ibuf
, highlight
, shift
, 7);
795 if (i
>= *ibuf
+ isz
) { /* EOT */
797 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
799 } else if (*i
== '[') { /* ANSI CSI */
802 } else if (*i
== ']') { /* ANSI CSO */
808 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
816 if (i
>= *ibuf
+ isz
|| /* EOT … */
817 !strchr("01234567890;m", *i
)) { /* … or invalid chars in sequence */
820 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
823 } else if (*i
== 'm')
830 if (i
>= *ibuf
+ isz
|| /* EOT … */
831 (*i
!= '\a' && (uint8_t) *i
< 32U) || (uint8_t) *i
> 126U) { /* … or invalid chars in sequence */
834 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
837 } else if (*i
== '\a')
844 if (fflush_and_check(f
) < 0) {
858 highlight
[0] += shift
[0];
859 highlight
[1] += shift
[1];
865 char *strextend_with_separator(char **x
, const char *separator
, ...) {
867 size_t f
, l
, l_separator
;
873 l
= f
= strlen_ptr(*x
);
875 need_separator
= !isempty(*x
);
876 l_separator
= strlen_ptr(separator
);
878 va_start(ap
, separator
);
883 t
= va_arg(ap
, const char *);
892 if (n
> ((size_t) -1) - l
) {
898 need_separator
= true;
902 need_separator
= !isempty(*x
);
904 r
= realloc(*x
, l
+1);
910 va_start(ap
, separator
);
914 t
= va_arg(ap
, const char *);
918 if (need_separator
&& separator
)
919 p
= stpcpy(p
, separator
);
923 need_separator
= true;
935 char *strrep(const char *s
, unsigned n
) {
943 p
= r
= malloc(l
* n
+ 1);
947 for (i
= 0; i
< n
; i
++)
954 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
969 a
= strndup(s
, x
- s
);
973 b
= strdup(x
+ strlen(sep
));
985 int free_and_strdup(char **p
, const char *s
) {
990 /* Replaces a string pointer with a strdup()ed new string,
991 * possibly freeing the old one. */
993 if (streq_ptr(*p
, s
))
1009 int free_and_strndup(char **p
, const char *s
, size_t l
) {
1013 assert(s
|| l
== 0);
1015 /* Replaces a string pointer with a strndup()ed new string,
1016 * freeing the old one. */
1021 if (*p
&& s
&& strneq(*p
, s
, l
) && (l
> strlen(*p
) || (*p
)[l
] == '\0'))
1031 free_and_replace(*p
, t
);
1035 char* string_erase(char *x
) {
1039 /* A delicious drop of snake-oil! To be called on memory where
1040 * we stored passphrases or so, after we used them. */
1041 explicit_bzero_safe(x
, strlen(x
));
1045 char *string_free_erase(char *s
) {
1046 return mfree(string_erase(s
));
1049 bool string_is_safe(const char *p
) {
1055 for (t
= p
; *t
; t
++) {
1056 if (*t
> 0 && *t
< ' ') /* no control characters */
1059 if (strchr(QUOTES
"\\\x7f", *t
))