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
, ...) {
152 for (const char *t
= x
; t
; t
= va_arg(ap
, const char *)) {
156 if (n
> SIZE_MAX
- l
) {
164 p
= r
= new(char, l
);
169 for (const char *t
= x
; t
; t
= va_arg(ap
, const char *))
178 char *strstrip(char *s
) {
182 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
184 return delete_trailing_chars(skip_leading_chars(s
, WHITESPACE
), WHITESPACE
);
187 char *delete_chars(char *s
, const char *bad
) {
190 /* Drops all specified bad characters, regardless where in the string */
198 for (f
= s
, t
= s
; *f
; f
++) {
210 char *delete_trailing_chars(char *s
, const char *bad
) {
213 /* Drops all specified bad characters, at the end of the string */
222 if (!strchr(bad
, *p
))
230 char *truncate_nl(char *s
) {
233 s
[strcspn(s
, NEWLINE
)] = 0;
237 char ascii_tolower(char x
) {
239 if (x
>= 'A' && x
<= 'Z')
240 return x
- 'A' + 'a';
245 char ascii_toupper(char x
) {
247 if (x
>= 'a' && x
<= 'z')
248 return x
- 'a' + 'A';
253 char *ascii_strlower(char *t
) {
259 *p
= ascii_tolower(*p
);
264 char *ascii_strupper(char *t
) {
270 *p
= ascii_toupper(*p
);
275 char *ascii_strlower_n(char *t
, size_t n
) {
281 for (i
= 0; i
< n
; i
++)
282 t
[i
] = ascii_tolower(t
[i
]);
287 int ascii_strcasecmp_n(const char *a
, const char *b
, size_t n
) {
289 for (; n
> 0; a
++, b
++, n
--) {
292 x
= (int) (uint8_t) ascii_tolower(*a
);
293 y
= (int) (uint8_t) ascii_tolower(*b
);
302 int ascii_strcasecmp_nn(const char *a
, size_t n
, const char *b
, size_t m
) {
305 r
= ascii_strcasecmp_n(a
, b
, MIN(n
, m
));
312 bool chars_intersect(const char *a
, const char *b
) {
315 /* Returns true if any of the chars in a are in b. */
323 bool string_has_cc(const char *p
, const char *ok
) {
329 * Check if a string contains control characters. If 'ok' is
330 * non-NULL it may be a string containing additional CCs to be
334 for (t
= p
; *t
; t
++) {
335 if (ok
&& strchr(ok
, *t
))
338 if (*t
> 0 && *t
< ' ')
348 static int write_ellipsis(char *buf
, bool unicode
) {
349 if (unicode
|| is_locale_utf8()) {
350 buf
[0] = 0xe2; /* tri-dot ellipsis: … */
362 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
363 size_t x
, need_space
, suffix_len
;
367 assert(percent
<= 100);
368 assert(new_length
!= (size_t) -1);
370 if (old_length
<= new_length
)
371 return strndup(s
, old_length
);
373 /* Special case short ellipsations */
374 switch (new_length
) {
380 if (is_locale_utf8())
381 return strdup("…");
386 if (!is_locale_utf8())
395 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
396 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
397 * either for the UTF-8 encoded character or for three ASCII characters. */
398 need_space
= is_locale_utf8() ? 1 : 3;
400 t
= new(char, new_length
+3);
404 assert(new_length
>= need_space
);
406 x
= ((new_length
- need_space
) * percent
+ 50) / 100;
407 assert(x
<= new_length
- need_space
);
410 write_ellipsis(t
+ x
, false);
411 suffix_len
= new_length
- x
- need_space
;
412 memcpy(t
+ x
+ 3, s
+ old_length
- suffix_len
, suffix_len
);
413 *(t
+ x
+ 3 + suffix_len
) = '\0';
418 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
419 size_t x
, k
, len
, len2
;
424 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
425 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
428 * Ellipsation is done in a locale-dependent way:
429 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
430 * 2. Otherwise, a unicode ellipsis is used ("…")
432 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
433 * the current locale is UTF-8.
437 assert(percent
<= 100);
439 if (new_length
== (size_t) -1)
440 return strndup(s
, old_length
);
445 /* If no multibyte characters use ascii_ellipsize_mem for speed */
446 if (ascii_is_valid_n(s
, old_length
))
447 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
449 x
= ((new_length
- 1) * percent
) / 100;
450 assert(x
<= new_length
- 1);
453 for (i
= s
; i
< s
+ old_length
; i
= utf8_next_char(i
)) {
457 r
= utf8_encoded_to_unichar(i
, &c
);
461 w
= unichar_iswide(c
) ? 2 : 1;
468 for (j
= s
+ old_length
; j
> i
; ) {
473 jj
= utf8_prev_char(j
);
474 r
= utf8_encoded_to_unichar(jj
, &c
);
478 w
= unichar_iswide(c
) ? 2 : 1;
479 if (k
+ w
<= new_length
) {
487 /* we don't actually need to ellipsize */
489 return memdup_suffix0(s
, old_length
);
491 /* make space for ellipsis, if possible */
492 if (j
< s
+ old_length
)
493 j
= utf8_next_char(j
);
495 i
= utf8_prev_char(i
);
498 len2
= s
+ old_length
- j
;
499 e
= new(char, len
+ 3 + len2
+ 1);
504 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
505 old_length, new_length, x, len, len2, k);
509 write_ellipsis(e
+ len
, true);
510 memcpy(e
+ len
+ 3, j
, len2
);
511 *(e
+ len
+ 3 + len2
) = '\0';
516 char *cellescape(char *buf
, size_t len
, const char *s
) {
517 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
518 * characters are copied as they are, everything else is escaped. The result
519 * is different then if escaping and ellipsization was performed in two
520 * separate steps, because each sequence is either stored in full or skipped.
522 * This function should be used for logging about strings which expected to
523 * be plain ASCII in a safe way.
525 * An ellipsis will be used if s is too long. It was always placed at the
529 size_t i
= 0, last_char_width
[4] = {}, k
= 0, j
;
531 assert(len
> 0); /* at least a terminating NUL */
537 if (*s
== 0) /* terminating NUL detected? then we are done! */
540 w
= cescape_char(*s
, four
);
541 if (i
+ w
+ 1 > len
) /* This character doesn't fit into the buffer anymore? In that case let's
542 * ellipsize at the previous location */
545 /* OK, there was space, let's add this escaped character to the buffer */
546 memcpy(buf
+ i
, four
, w
);
549 /* And remember its width in the ring buffer */
550 last_char_width
[k
] = w
;
556 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
557 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
558 for (j
= 0; j
< ELEMENTSOF(last_char_width
); j
++) {
560 if (i
+ 4 <= len
) /* nice, we reached our space goal */
563 k
= k
== 0 ? 3 : k
- 1;
564 if (last_char_width
[k
] == 0) /* bummer, we reached the beginning of the strings */
567 assert(i
>= last_char_width
[k
]);
568 i
-= last_char_width
[k
];
571 if (i
+ 4 <= len
) /* yay, enough space */
572 i
+= write_ellipsis(buf
+ i
, false);
573 else if (i
+ 3 <= len
) { /* only space for ".." */
576 } else if (i
+ 2 <= len
) /* only space for a single "." */
579 assert(i
+ 1 <= len
);
586 char* strshorten(char *s
, size_t l
) {
589 if (strnlen(s
, l
+1) > l
)
595 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
596 size_t l
, old_len
, new_len
, allocated
= 0;
597 char *t
, *ret
= NULL
;
606 old_len
= strlen(old_string
);
607 new_len
= strlen(new_string
);
610 if (!GREEDY_REALLOC(ret
, allocated
, l
+1))
618 if (!startswith(f
, old_string
)) {
624 nl
= l
- old_len
+ new_len
;
626 if (!GREEDY_REALLOC(ret
, allocated
, nl
+ 1))
632 t
= stpcpy(t
, new_string
);
640 static void advance_offsets(
642 size_t offsets
[2], /* note: we can't use [static 2] here, since this may be NULL */
643 size_t shift
[static 2],
651 if ((size_t) diff
< offsets
[0])
653 if ((size_t) diff
< offsets
[1])
657 char *strip_tab_ansi(char **ibuf
, size_t *_isz
, size_t highlight
[2]) {
658 const char *begin
= NULL
;
664 } state
= STATE_OTHER
;
666 size_t osz
= 0, isz
, shift
[2] = {}, n_carriage_returns
= 0;
672 /* This does three things:
674 * 1. Replaces TABs by 8 spaces
675 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
676 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
677 * 4. Strip trailing \r characters (since they would "move the cursor", but have no
680 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
681 * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
682 * supposed to suppress the most basic formatting noise, but nothing else.
684 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
686 isz
= _isz
? *_isz
: strlen(*ibuf
);
688 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
689 * created f here and it doesn't leave our scope. */
690 f
= open_memstream_unlocked(&obuf
, &osz
);
694 for (const char *i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
699 if (i
>= *ibuf
+ isz
) /* EOT */
703 n_carriage_returns
++;
705 } else if (*i
== '\n')
706 /* Ignore carriage returns before new line */
707 n_carriage_returns
= 0;
708 for (; n_carriage_returns
> 0; n_carriage_returns
--)
712 state
= STATE_ESCAPE
;
713 else if (*i
== '\t') {
715 advance_offsets(i
- *ibuf
, highlight
, shift
, 7);
722 assert(n_carriage_returns
== 0);
724 if (i
>= *ibuf
+ isz
) { /* EOT */
726 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
728 } else if (*i
== '[') { /* ANSI CSI */
731 } else if (*i
== ']') { /* ANSI CSO */
737 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
744 assert(n_carriage_returns
== 0);
746 if (i
>= *ibuf
+ isz
|| /* EOT … */
747 !strchr("01234567890;m", *i
)) { /* … or invalid chars in sequence */
750 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
753 } else if (*i
== 'm')
759 assert(n_carriage_returns
== 0);
761 if (i
>= *ibuf
+ isz
|| /* EOT … */
762 (*i
!= '\a' && (uint8_t) *i
< 32U) || (uint8_t) *i
> 126U) { /* … or invalid chars in sequence */
765 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
768 } else if (*i
== '\a')
775 if (fflush_and_check(f
) < 0) {
781 free_and_replace(*ibuf
, obuf
);
787 highlight
[0] += shift
[0];
788 highlight
[1] += shift
[1];
794 char *strextend_with_separator(char **x
, const char *separator
, ...) {
796 size_t f
, l
, l_separator
;
802 l
= f
= strlen_ptr(*x
);
804 need_separator
= !isempty(*x
);
805 l_separator
= strlen_ptr(separator
);
807 va_start(ap
, separator
);
812 t
= va_arg(ap
, const char *);
821 if (n
> ((size_t) -1) - l
) {
827 need_separator
= true;
831 need_separator
= !isempty(*x
);
833 r
= realloc(*x
, l
+1);
839 va_start(ap
, separator
);
843 t
= va_arg(ap
, const char *);
847 if (need_separator
&& separator
)
848 p
= stpcpy(p
, separator
);
852 need_separator
= true;
864 char *strrep(const char *s
, unsigned n
) {
872 p
= r
= malloc(l
* n
+ 1);
876 for (i
= 0; i
< n
; i
++)
883 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
898 a
= strndup(s
, x
- s
);
902 b
= strdup(x
+ strlen(sep
));
914 int free_and_strdup(char **p
, const char *s
) {
919 /* Replaces a string pointer with a strdup()ed new string,
920 * possibly freeing the old one. */
922 if (streq_ptr(*p
, s
))
938 int free_and_strndup(char **p
, const char *s
, size_t l
) {
944 /* Replaces a string pointer with a strndup()ed new string,
945 * freeing the old one. */
950 if (*p
&& s
&& strneq(*p
, s
, l
) && (l
> strlen(*p
) || (*p
)[l
] == '\0'))
960 free_and_replace(*p
, t
);
964 bool string_is_safe(const char *p
) {
970 /* Checks if the specified string contains no quotes or control characters */
972 for (t
= p
; *t
; t
++) {
973 if (*t
> 0 && *t
< ' ') /* no control characters */
976 if (strchr(QUOTES
"\\\x7f", *t
))
983 char* string_erase(char *x
) {
987 /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
989 explicit_bzero_safe(x
, strlen(x
));
993 int string_truncate_lines(const char *s
, size_t n_lines
, char **ret
) {
994 const char *p
= s
, *e
= s
;
995 bool truncation_applied
= false;
1001 /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1002 * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1003 * generated either. */
1008 k
= strcspn(p
, "\n");
1011 if (k
== 0) /* final empty line */
1014 if (n
>= n_lines
) /* above threshold */
1017 e
= p
+ k
; /* last line to include */
1021 assert(p
[k
] == '\n');
1033 /* e points after the last character we want to keep */
1037 if (!in_charset(e
, "\n")) /* We only consider things truncated if we remove something that
1038 * isn't a new-line or a series of them */
1039 truncation_applied
= true;
1041 copy
= strndup(s
, e
- s
);
1047 return truncation_applied
;
1050 int string_extract_line(const char *s
, size_t i
, char **ret
) {
1054 /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1055 * and == 0 if we are looking at the last line or already beyond the last line. As special
1056 * optimization, if the first line is requested and the string only consists of one line we return
1057 * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1063 q
= strchr(p
, '\n');
1065 /* The line we are looking for! */
1070 m
= strndup(p
, q
- p
);
1075 return !isempty(q
+ 1); /* more coming? */
1078 *ret
= NULL
; /* Just use the input string */
1089 return 0; /* The end */
1096 /* No more lines, return empty line */
1103 return 0; /* The end */
1111 int string_contains_word_strv(const char *string
, const char *separators
, char **words
, const char **ret_word
) {
1112 /* In the default mode with no separators specified, we split on whitespace and
1113 * don't coalesce separators. */
1114 const ExtractFlags flags
= separators
? EXTRACT_DONT_COALESCE_SEPARATORS
: 0;
1116 const char *found
= NULL
;
1118 for (const char *p
= string
;;) {
1119 _cleanup_free_
char *w
= NULL
;
1122 r
= extract_first_word(&p
, &w
, separators
, flags
);
1128 found
= strv_find(words
, w
);