1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include "alloc-util.h"
11 #include "extract-word.h"
14 #include "locale-util.h"
16 #include "memory-util.h"
17 #include "string-util.h"
19 #include "terminal-util.h"
23 int strcmp_ptr(const char *a
, const char *b
) {
24 /* Like strcmp(), but tries to make sense of NULL pointers */
28 return CMP(a
, b
); /* Direct comparison of pointers, one of which is NULL */
31 int strcasecmp_ptr(const char *a
, const char *b
) {
32 /* Like strcasecmp(), but tries to make sense of NULL pointers */
35 return strcasecmp(a
, b
);
36 return CMP(a
, b
); /* Direct comparison of pointers, one of which is NULL */
39 char* endswith(const char *s
, const char *postfix
) {
49 return (char*) s
+ sl
;
54 if (memcmp(s
+ sl
- pl
, postfix
, pl
) != 0)
57 return (char*) s
+ sl
- pl
;
60 char* endswith_no_case(const char *s
, const char *postfix
) {
70 return (char*) s
+ sl
;
75 if (strcasecmp(s
+ sl
- pl
, postfix
) != 0)
78 return (char*) s
+ sl
- pl
;
81 char* first_word(const char *s
, const char *word
) {
88 /* Checks if the string starts with the specified word, either
89 * followed by NUL or by whitespace. Returns a pointer to the
90 * NUL or the first character after the whitespace. */
101 if (memcmp(s
, word
, wl
) != 0)
108 if (!strchr(WHITESPACE
, *p
))
111 p
+= strspn(p
, WHITESPACE
);
115 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
123 return strndup(suffix
, b
);
132 if (b
> ((size_t) -1) - a
)
135 r
= new(char, a
+b
+1);
140 memcpy(r
+a
, suffix
, b
);
146 char *strjoin_real(const char *x
, ...) {
160 t
= va_arg(ap
, const char *);
165 if (n
> ((size_t) -1) - l
) {
189 t
= va_arg(ap
, const char *);
203 char *strstrip(char *s
) {
207 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
209 return delete_trailing_chars(skip_leading_chars(s
, WHITESPACE
), WHITESPACE
);
212 char *delete_chars(char *s
, const char *bad
) {
215 /* Drops all specified bad characters, regardless where in the string */
223 for (f
= s
, t
= s
; *f
; f
++) {
235 char *delete_trailing_chars(char *s
, const char *bad
) {
238 /* Drops all specified bad characters, at the end of the string */
247 if (!strchr(bad
, *p
))
255 char *truncate_nl(char *s
) {
258 s
[strcspn(s
, NEWLINE
)] = 0;
262 char ascii_tolower(char x
) {
264 if (x
>= 'A' && x
<= 'Z')
265 return x
- 'A' + 'a';
270 char ascii_toupper(char x
) {
272 if (x
>= 'a' && x
<= 'z')
273 return x
- 'a' + 'A';
278 char *ascii_strlower(char *t
) {
284 *p
= ascii_tolower(*p
);
289 char *ascii_strupper(char *t
) {
295 *p
= ascii_toupper(*p
);
300 char *ascii_strlower_n(char *t
, size_t n
) {
306 for (i
= 0; i
< n
; i
++)
307 t
[i
] = ascii_tolower(t
[i
]);
312 int ascii_strcasecmp_n(const char *a
, const char *b
, size_t n
) {
314 for (; n
> 0; a
++, b
++, n
--) {
317 x
= (int) (uint8_t) ascii_tolower(*a
);
318 y
= (int) (uint8_t) ascii_tolower(*b
);
327 int ascii_strcasecmp_nn(const char *a
, size_t n
, const char *b
, size_t m
) {
330 r
= ascii_strcasecmp_n(a
, b
, MIN(n
, m
));
337 bool chars_intersect(const char *a
, const char *b
) {
340 /* Returns true if any of the chars in a are in b. */
348 bool string_has_cc(const char *p
, const char *ok
) {
354 * Check if a string contains control characters. If 'ok' is
355 * non-NULL it may be a string containing additional CCs to be
359 for (t
= p
; *t
; t
++) {
360 if (ok
&& strchr(ok
, *t
))
363 if (*t
> 0 && *t
< ' ')
373 static int write_ellipsis(char *buf
, bool unicode
) {
374 if (unicode
|| is_locale_utf8()) {
375 buf
[0] = 0xe2; /* tri-dot ellipsis: … */
387 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
388 size_t x
, need_space
, suffix_len
;
392 assert(percent
<= 100);
393 assert(new_length
!= (size_t) -1);
395 if (old_length
<= new_length
)
396 return strndup(s
, old_length
);
398 /* Special case short ellipsations */
399 switch (new_length
) {
405 if (is_locale_utf8())
406 return strdup("…");
411 if (!is_locale_utf8())
420 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
421 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
422 * either for the UTF-8 encoded character or for three ASCII characters. */
423 need_space
= is_locale_utf8() ? 1 : 3;
425 t
= new(char, new_length
+3);
429 assert(new_length
>= need_space
);
431 x
= ((new_length
- need_space
) * percent
+ 50) / 100;
432 assert(x
<= new_length
- need_space
);
435 write_ellipsis(t
+ x
, false);
436 suffix_len
= new_length
- x
- need_space
;
437 memcpy(t
+ x
+ 3, s
+ old_length
- suffix_len
, suffix_len
);
438 *(t
+ x
+ 3 + suffix_len
) = '\0';
443 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
444 size_t x
, k
, len
, len2
;
449 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
450 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
453 * Ellipsation is done in a locale-dependent way:
454 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
455 * 2. Otherwise, a unicode ellipsis is used ("…")
457 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
458 * the current locale is UTF-8.
462 assert(percent
<= 100);
464 if (new_length
== (size_t) -1)
465 return strndup(s
, old_length
);
470 /* If no multibyte characters use ascii_ellipsize_mem for speed */
471 if (ascii_is_valid_n(s
, old_length
))
472 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
474 x
= ((new_length
- 1) * percent
) / 100;
475 assert(x
<= new_length
- 1);
478 for (i
= s
; i
< s
+ old_length
; i
= utf8_next_char(i
)) {
482 r
= utf8_encoded_to_unichar(i
, &c
);
486 w
= unichar_iswide(c
) ? 2 : 1;
493 for (j
= s
+ old_length
; j
> i
; ) {
498 jj
= utf8_prev_char(j
);
499 r
= utf8_encoded_to_unichar(jj
, &c
);
503 w
= unichar_iswide(c
) ? 2 : 1;
504 if (k
+ w
<= new_length
) {
512 /* we don't actually need to ellipsize */
514 return memdup_suffix0(s
, old_length
);
516 /* make space for ellipsis, if possible */
517 if (j
< s
+ old_length
)
518 j
= utf8_next_char(j
);
520 i
= utf8_prev_char(i
);
523 len2
= s
+ old_length
- j
;
524 e
= new(char, len
+ 3 + len2
+ 1);
529 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
530 old_length, new_length, x, len, len2, k);
534 write_ellipsis(e
+ len
, true);
535 memcpy(e
+ len
+ 3, j
, len2
);
536 *(e
+ len
+ 3 + len2
) = '\0';
541 char *cellescape(char *buf
, size_t len
, const char *s
) {
542 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
543 * characters are copied as they are, everything else is escaped. The result
544 * is different then if escaping and ellipsization was performed in two
545 * separate steps, because each sequence is either stored in full or skipped.
547 * This function should be used for logging about strings which expected to
548 * be plain ASCII in a safe way.
550 * An ellipsis will be used if s is too long. It was always placed at the
554 size_t i
= 0, last_char_width
[4] = {}, k
= 0, j
;
556 assert(len
> 0); /* at least a terminating NUL */
562 if (*s
== 0) /* terminating NUL detected? then we are done! */
565 w
= cescape_char(*s
, four
);
566 if (i
+ w
+ 1 > len
) /* This character doesn't fit into the buffer anymore? In that case let's
567 * ellipsize at the previous location */
570 /* OK, there was space, let's add this escaped character to the buffer */
571 memcpy(buf
+ i
, four
, w
);
574 /* And remember its width in the ring buffer */
575 last_char_width
[k
] = w
;
581 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
582 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
583 for (j
= 0; j
< ELEMENTSOF(last_char_width
); j
++) {
585 if (i
+ 4 <= len
) /* nice, we reached our space goal */
588 k
= k
== 0 ? 3 : k
- 1;
589 if (last_char_width
[k
] == 0) /* bummer, we reached the beginning of the strings */
592 assert(i
>= last_char_width
[k
]);
593 i
-= last_char_width
[k
];
596 if (i
+ 4 <= len
) /* yay, enough space */
597 i
+= write_ellipsis(buf
+ i
, false);
598 else if (i
+ 3 <= len
) { /* only space for ".." */
601 } else if (i
+ 2 <= len
) /* only space for a single "." */
604 assert(i
+ 1 <= len
);
611 char* strshorten(char *s
, size_t l
) {
614 if (strnlen(s
, l
+1) > l
)
620 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
621 size_t l
, old_len
, new_len
, allocated
= 0;
622 char *t
, *ret
= NULL
;
631 old_len
= strlen(old_string
);
632 new_len
= strlen(new_string
);
635 if (!GREEDY_REALLOC(ret
, allocated
, l
+1))
643 if (!startswith(f
, old_string
)) {
649 nl
= l
- old_len
+ new_len
;
651 if (!GREEDY_REALLOC(ret
, allocated
, nl
+ 1))
657 t
= stpcpy(t
, new_string
);
665 static void advance_offsets(
667 size_t offsets
[2], /* note: we can't use [static 2] here, since this may be NULL */
668 size_t shift
[static 2],
676 if ((size_t) diff
< offsets
[0])
678 if ((size_t) diff
< offsets
[1])
682 char *strip_tab_ansi(char **ibuf
, size_t *_isz
, size_t highlight
[2]) {
683 const char *begin
= NULL
;
689 } state
= STATE_OTHER
;
691 size_t osz
= 0, isz
, shift
[2] = {}, n_carriage_returns
= 0;
697 /* This does three things:
699 * 1. Replaces TABs by 8 spaces
700 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
701 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
702 * 4. Strip trailing \r characters (since they would "move the cursor", but have no
705 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
706 * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
707 * supposed to suppress the most basic formatting noise, but nothing else.
709 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
711 isz
= _isz
? *_isz
: strlen(*ibuf
);
713 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
714 * created f here and it doesn't leave our scope. */
715 f
= open_memstream_unlocked(&obuf
, &osz
);
719 for (const char *i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
724 if (i
>= *ibuf
+ isz
) /* EOT */
728 n_carriage_returns
++;
730 } else if (*i
== '\n')
731 /* Ignore carriage returns before new line */
732 n_carriage_returns
= 0;
733 for (; n_carriage_returns
> 0; n_carriage_returns
--)
737 state
= STATE_ESCAPE
;
738 else if (*i
== '\t') {
740 advance_offsets(i
- *ibuf
, highlight
, shift
, 7);
747 assert(n_carriage_returns
== 0);
749 if (i
>= *ibuf
+ isz
) { /* EOT */
751 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
753 } else if (*i
== '[') { /* ANSI CSI */
756 } else if (*i
== ']') { /* ANSI CSO */
762 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
769 assert(n_carriage_returns
== 0);
771 if (i
>= *ibuf
+ isz
|| /* EOT … */
772 !strchr("01234567890;m", *i
)) { /* … or invalid chars in sequence */
775 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
778 } else if (*i
== 'm')
784 assert(n_carriage_returns
== 0);
786 if (i
>= *ibuf
+ isz
|| /* EOT … */
787 (*i
!= '\a' && (uint8_t) *i
< 32U) || (uint8_t) *i
> 126U) { /* … or invalid chars in sequence */
790 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
793 } else if (*i
== '\a')
800 if (fflush_and_check(f
) < 0) {
806 free_and_replace(*ibuf
, obuf
);
812 highlight
[0] += shift
[0];
813 highlight
[1] += shift
[1];
819 char *strextend_with_separator(char **x
, const char *separator
, ...) {
821 size_t f
, l
, l_separator
;
827 l
= f
= strlen_ptr(*x
);
829 need_separator
= !isempty(*x
);
830 l_separator
= strlen_ptr(separator
);
832 va_start(ap
, separator
);
837 t
= va_arg(ap
, const char *);
846 if (n
> ((size_t) -1) - l
) {
852 need_separator
= true;
856 need_separator
= !isempty(*x
);
858 r
= realloc(*x
, l
+1);
864 va_start(ap
, separator
);
868 t
= va_arg(ap
, const char *);
872 if (need_separator
&& separator
)
873 p
= stpcpy(p
, separator
);
877 need_separator
= true;
889 char *strrep(const char *s
, unsigned n
) {
897 p
= r
= malloc(l
* n
+ 1);
901 for (i
= 0; i
< n
; i
++)
908 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
923 a
= strndup(s
, x
- s
);
927 b
= strdup(x
+ strlen(sep
));
939 int free_and_strdup(char **p
, const char *s
) {
944 /* Replaces a string pointer with a strdup()ed new string,
945 * possibly freeing the old one. */
947 if (streq_ptr(*p
, s
))
963 int free_and_strndup(char **p
, const char *s
, size_t l
) {
969 /* Replaces a string pointer with a strndup()ed new string,
970 * freeing the old one. */
975 if (*p
&& s
&& strneq(*p
, s
, l
) && (l
> strlen(*p
) || (*p
)[l
] == '\0'))
985 free_and_replace(*p
, t
);
989 bool string_is_safe(const char *p
) {
995 /* Checks if the specified string contains no quotes or control characters */
997 for (t
= p
; *t
; t
++) {
998 if (*t
> 0 && *t
< ' ') /* no control characters */
1001 if (strchr(QUOTES
"\\\x7f", *t
))
1008 char* string_erase(char *x
) {
1012 /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1014 explicit_bzero_safe(x
, strlen(x
));
1018 int string_truncate_lines(const char *s
, size_t n_lines
, char **ret
) {
1019 const char *p
= s
, *e
= s
;
1020 bool truncation_applied
= false;
1026 /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1027 * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1028 * generated either. */
1033 k
= strcspn(p
, "\n");
1036 if (k
== 0) /* final empty line */
1039 if (n
>= n_lines
) /* above threshold */
1042 e
= p
+ k
; /* last line to include */
1046 assert(p
[k
] == '\n');
1058 /* e points after the last character we want to keep */
1062 if (!in_charset(e
, "\n")) /* We only consider things truncated if we remove something that
1063 * isn't a new-line or a series of them */
1064 truncation_applied
= true;
1066 copy
= strndup(s
, e
- s
);
1072 return truncation_applied
;
1075 int string_extract_line(const char *s
, size_t i
, char **ret
) {
1079 /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1080 * and == 0 if we are looking at the last line or already beyond the last line. As special
1081 * optimization, if the first line is requested and the string only consists of one line we return
1082 * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1088 q
= strchr(p
, '\n');
1090 /* The line we are looking for! */
1095 m
= strndup(p
, q
- p
);
1100 return !isempty(q
+ 1); /* more coming? */
1103 *ret
= NULL
; /* Just use the input string */
1114 return 0; /* The end */
1121 /* No more lines, return empty line */
1128 return 0; /* The end */
1136 int string_contains_word_strv(const char *string
, const char *separators
, char **words
, const char **ret_word
) {
1137 /* In the default mode with no separators specified, we split on whitespace and
1138 * don't coalesce separators. */
1139 const ExtractFlags flags
= separators
? EXTRACT_DONT_COALESCE_SEPARATORS
: 0;
1141 const char *found
= NULL
;
1143 for (const char *p
= string
;;) {
1144 _cleanup_free_
char *w
= NULL
;
1147 r
= extract_first_word(&p
, &w
, separators
, flags
);
1153 found
= strv_find(words
, w
);