]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/string-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include "alloc-util.h"
13 #include "locale-util.h"
15 #include "memory-util.h"
16 #include "string-util.h"
17 #include "terminal-util.h"
21 int strcmp_ptr(const char *a
, const char *b
) {
23 /* Like strcmp(), but tries to make sense of NULL pointers */
36 char* endswith(const char *s
, const char *postfix
) {
46 return (char*) s
+ sl
;
51 if (memcmp(s
+ sl
- pl
, postfix
, pl
) != 0)
54 return (char*) s
+ sl
- pl
;
57 char* endswith_no_case(const char *s
, const char *postfix
) {
67 return (char*) s
+ sl
;
72 if (strcasecmp(s
+ sl
- pl
, postfix
) != 0)
75 return (char*) s
+ sl
- pl
;
78 char* first_word(const char *s
, const char *word
) {
85 /* Checks if the string starts with the specified word, either
86 * followed by NUL or by whitespace. Returns a pointer to the
87 * NUL or the first character after the whitespace. */
98 if (memcmp(s
, word
, wl
) != 0)
105 if (!strchr(WHITESPACE
, *p
))
108 p
+= strspn(p
, WHITESPACE
);
112 static size_t strcspn_escaped(const char *s
, const char *reject
) {
113 bool escaped
= false;
116 for (n
=0; s
[n
]; n
++) {
119 else if (s
[n
] == '\\')
121 else if (strchr(reject
, s
[n
]))
125 /* if s ends in \, return index of previous char */
129 /* Split a string into words. */
130 const char* split(const char **state
, size_t *l
, const char *separator
, SplitFlags flags
) {
136 assert(**state
== '\0');
140 current
+= strspn(current
, separator
);
146 if (flags
& SPLIT_QUOTES
&& strchr("\'\"", *current
)) {
147 char quotechars
[2] = {*current
, '\0'};
149 *l
= strcspn_escaped(current
+ 1, quotechars
);
150 if (current
[*l
+ 1] == '\0' || current
[*l
+ 1] != quotechars
[0] ||
151 (current
[*l
+ 2] && !strchr(separator
, current
[*l
+ 2]))) {
152 /* right quote missing or garbage at the end */
153 if (flags
& SPLIT_RELAX
) {
154 *state
= current
+ *l
+ 1 + (current
[*l
+ 1] != '\0');
160 *state
= current
++ + *l
+ 2;
161 } else if (flags
& SPLIT_QUOTES
) {
162 *l
= strcspn_escaped(current
, separator
);
163 if (current
[*l
] && !strchr(separator
, current
[*l
]) && !(flags
& SPLIT_RELAX
)) {
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 *strjoin_real(const char *x
, ...) {
222 t
= va_arg(ap
, const char *);
227 if (n
> ((size_t) -1) - l
) {
251 t
= va_arg(ap
, const char *);
265 char *strstrip(char *s
) {
269 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
271 return delete_trailing_chars(skip_leading_chars(s
, WHITESPACE
), WHITESPACE
);
274 char *delete_chars(char *s
, const char *bad
) {
277 /* Drops all specified bad characters, regardless where in the string */
285 for (f
= s
, t
= s
; *f
; f
++) {
297 char *delete_trailing_chars(char *s
, const char *bad
) {
300 /* Drops all specified bad characters, at the end of the string */
309 if (!strchr(bad
, *p
))
317 char *truncate_nl(char *s
) {
320 s
[strcspn(s
, NEWLINE
)] = 0;
324 char ascii_tolower(char x
) {
326 if (x
>= 'A' && x
<= 'Z')
327 return x
- 'A' + 'a';
332 char ascii_toupper(char x
) {
334 if (x
>= 'a' && x
<= 'z')
335 return x
- 'a' + 'A';
340 char *ascii_strlower(char *t
) {
346 *p
= ascii_tolower(*p
);
351 char *ascii_strupper(char *t
) {
357 *p
= ascii_toupper(*p
);
362 char *ascii_strlower_n(char *t
, size_t n
) {
368 for (i
= 0; i
< n
; i
++)
369 t
[i
] = ascii_tolower(t
[i
]);
374 int ascii_strcasecmp_n(const char *a
, const char *b
, size_t n
) {
376 for (; n
> 0; a
++, b
++, n
--) {
379 x
= (int) (uint8_t) ascii_tolower(*a
);
380 y
= (int) (uint8_t) ascii_tolower(*b
);
389 int ascii_strcasecmp_nn(const char *a
, size_t n
, const char *b
, size_t m
) {
392 r
= ascii_strcasecmp_n(a
, b
, MIN(n
, m
));
399 bool chars_intersect(const char *a
, const char *b
) {
402 /* Returns true if any of the chars in a are in b. */
410 bool string_has_cc(const char *p
, const char *ok
) {
416 * Check if a string contains control characters. If 'ok' is
417 * non-NULL it may be a string containing additional CCs to be
421 for (t
= p
; *t
; t
++) {
422 if (ok
&& strchr(ok
, *t
))
425 if (*t
> 0 && *t
< ' ')
435 static int write_ellipsis(char *buf
, bool unicode
) {
436 if (unicode
|| is_locale_utf8()) {
437 buf
[0] = 0xe2; /* tri-dot ellipsis: … */
449 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
450 size_t x
, need_space
, suffix_len
;
454 assert(percent
<= 100);
455 assert(new_length
!= (size_t) -1);
457 if (old_length
<= new_length
)
458 return strndup(s
, old_length
);
460 /* Special case short ellipsations */
461 switch (new_length
) {
467 if (is_locale_utf8())
468 return strdup("…");
473 if (!is_locale_utf8())
482 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
483 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
484 * either for the UTF-8 encoded character or for three ASCII characters. */
485 need_space
= is_locale_utf8() ? 1 : 3;
487 t
= new(char, new_length
+3);
491 assert(new_length
>= need_space
);
493 x
= ((new_length
- need_space
) * percent
+ 50) / 100;
494 assert(x
<= new_length
- need_space
);
497 write_ellipsis(t
+ x
, false);
498 suffix_len
= new_length
- x
- need_space
;
499 memcpy(t
+ x
+ 3, s
+ old_length
- suffix_len
, suffix_len
);
500 *(t
+ x
+ 3 + suffix_len
) = '\0';
505 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
506 size_t x
, k
, len
, len2
;
511 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
512 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
515 * Ellipsation is done in a locale-dependent way:
516 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
517 * 2. Otherwise, a unicode ellipsis is used ("…")
519 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
520 * the current locale is UTF-8.
524 assert(percent
<= 100);
526 if (new_length
== (size_t) -1)
527 return strndup(s
, old_length
);
532 /* If no multibyte characters use ascii_ellipsize_mem for speed */
533 if (ascii_is_valid_n(s
, old_length
))
534 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
536 x
= ((new_length
- 1) * percent
) / 100;
537 assert(x
<= new_length
- 1);
540 for (i
= s
; i
< s
+ old_length
; i
= utf8_next_char(i
)) {
544 r
= utf8_encoded_to_unichar(i
, &c
);
548 w
= unichar_iswide(c
) ? 2 : 1;
555 for (j
= s
+ old_length
; j
> i
; ) {
560 jj
= utf8_prev_char(j
);
561 r
= utf8_encoded_to_unichar(jj
, &c
);
565 w
= unichar_iswide(c
) ? 2 : 1;
566 if (k
+ w
<= new_length
) {
574 /* we don't actually need to ellipsize */
576 return memdup_suffix0(s
, old_length
);
578 /* make space for ellipsis, if possible */
579 if (j
< s
+ old_length
)
580 j
= utf8_next_char(j
);
582 i
= utf8_prev_char(i
);
585 len2
= s
+ old_length
- j
;
586 e
= new(char, len
+ 3 + len2
+ 1);
591 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
592 old_length, new_length, x, len, len2, k);
596 write_ellipsis(e
+ len
, true);
597 memcpy(e
+ len
+ 3, j
, len2
);
598 *(e
+ len
+ 3 + len2
) = '\0';
603 char *cellescape(char *buf
, size_t len
, const char *s
) {
604 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
605 * characters are copied as they are, everything else is escaped. The result
606 * is different then if escaping and ellipsization was performed in two
607 * separate steps, because each sequence is either stored in full or skipped.
609 * This function should be used for logging about strings which expected to
610 * be plain ASCII in a safe way.
612 * An ellipsis will be used if s is too long. It was always placed at the
616 size_t i
= 0, last_char_width
[4] = {}, k
= 0, j
;
618 assert(len
> 0); /* at least a terminating NUL */
624 if (*s
== 0) /* terminating NUL detected? then we are done! */
627 w
= cescape_char(*s
, four
);
628 if (i
+ w
+ 1 > len
) /* This character doesn't fit into the buffer anymore? In that case let's
629 * ellipsize at the previous location */
632 /* OK, there was space, let's add this escaped character to the buffer */
633 memcpy(buf
+ i
, four
, w
);
636 /* And remember its width in the ring buffer */
637 last_char_width
[k
] = w
;
643 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
644 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
645 for (j
= 0; j
< ELEMENTSOF(last_char_width
); j
++) {
647 if (i
+ 4 <= len
) /* nice, we reached our space goal */
650 k
= k
== 0 ? 3 : k
- 1;
651 if (last_char_width
[k
] == 0) /* bummer, we reached the beginning of the strings */
654 assert(i
>= last_char_width
[k
]);
655 i
-= last_char_width
[k
];
658 if (i
+ 4 <= len
) /* yay, enough space */
659 i
+= write_ellipsis(buf
+ i
, false);
660 else if (i
+ 3 <= len
) { /* only space for ".." */
663 } else if (i
+ 2 <= len
) /* only space for a single "." */
666 assert(i
+ 1 <= len
);
673 char* strshorten(char *s
, size_t l
) {
676 if (strnlen(s
, l
+1) > l
)
682 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
683 size_t l
, old_len
, new_len
, allocated
= 0;
684 char *t
, *ret
= NULL
;
693 old_len
= strlen(old_string
);
694 new_len
= strlen(new_string
);
697 if (!GREEDY_REALLOC(ret
, allocated
, l
+1))
705 if (!startswith(f
, old_string
)) {
711 nl
= l
- old_len
+ new_len
;
713 if (!GREEDY_REALLOC(ret
, allocated
, nl
+ 1))
719 t
= stpcpy(t
, new_string
);
727 static void advance_offsets(
729 size_t offsets
[2], /* note: we can't use [static 2] here, since this may be NULL */
730 size_t shift
[static 2],
738 if ((size_t) diff
< offsets
[0])
740 if ((size_t) diff
< offsets
[1])
744 char *strip_tab_ansi(char **ibuf
, size_t *_isz
, size_t highlight
[2]) {
745 const char *begin
= NULL
;
751 } state
= STATE_OTHER
;
753 size_t osz
= 0, isz
, shift
[2] = {}, n_carriage_returns
= 0;
759 /* This does three things:
761 * 1. Replaces TABs by 8 spaces
762 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
763 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
764 * 4. Strip trailing \r characters (since they would "move the cursor", but have no
767 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
768 * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
769 * supposed to suppress the most basic formatting noise, but nothing else.
771 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
773 isz
= _isz
? *_isz
: strlen(*ibuf
);
775 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
776 * created f here and it doesn't leave our scope. */
777 f
= open_memstream_unlocked(&obuf
, &osz
);
781 for (const char *i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
786 if (i
>= *ibuf
+ isz
) /* EOT */
790 n_carriage_returns
++;
792 } else if (*i
== '\n')
793 /* Ignore carriage returns before new line */
794 n_carriage_returns
= 0;
795 for (; n_carriage_returns
> 0; n_carriage_returns
--)
799 state
= STATE_ESCAPE
;
800 else if (*i
== '\t') {
802 advance_offsets(i
- *ibuf
, highlight
, shift
, 7);
809 assert(n_carriage_returns
== 0);
811 if (i
>= *ibuf
+ isz
) { /* EOT */
813 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
815 } else if (*i
== '[') { /* ANSI CSI */
818 } else if (*i
== ']') { /* ANSI CSO */
824 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
831 assert(n_carriage_returns
== 0);
833 if (i
>= *ibuf
+ isz
|| /* EOT … */
834 !strchr("01234567890;m", *i
)) { /* … or invalid chars in sequence */
837 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
840 } else if (*i
== 'm')
846 assert(n_carriage_returns
== 0);
848 if (i
>= *ibuf
+ isz
|| /* EOT … */
849 (*i
!= '\a' && (uint8_t) *i
< 32U) || (uint8_t) *i
> 126U) { /* … or invalid chars in sequence */
852 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
855 } else if (*i
== '\a')
862 if (fflush_and_check(f
) < 0) {
868 free_and_replace(*ibuf
, obuf
);
874 highlight
[0] += shift
[0];
875 highlight
[1] += shift
[1];
881 char *strextend_with_separator(char **x
, const char *separator
, ...) {
883 size_t f
, l
, l_separator
;
889 l
= f
= strlen_ptr(*x
);
891 need_separator
= !isempty(*x
);
892 l_separator
= strlen_ptr(separator
);
894 va_start(ap
, separator
);
899 t
= va_arg(ap
, const char *);
908 if (n
> ((size_t) -1) - l
) {
914 need_separator
= true;
918 need_separator
= !isempty(*x
);
920 r
= realloc(*x
, l
+1);
926 va_start(ap
, separator
);
930 t
= va_arg(ap
, const char *);
934 if (need_separator
&& separator
)
935 p
= stpcpy(p
, separator
);
939 need_separator
= true;
951 char *strrep(const char *s
, unsigned n
) {
959 p
= r
= malloc(l
* n
+ 1);
963 for (i
= 0; i
< n
; i
++)
970 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
985 a
= strndup(s
, x
- s
);
989 b
= strdup(x
+ strlen(sep
));
1001 int free_and_strdup(char **p
, const char *s
) {
1006 /* Replaces a string pointer with a strdup()ed new string,
1007 * possibly freeing the old one. */
1009 if (streq_ptr(*p
, s
))
1025 int free_and_strndup(char **p
, const char *s
, size_t l
) {
1029 assert(s
|| l
== 0);
1031 /* Replaces a string pointer with a strndup()ed new string,
1032 * freeing the old one. */
1037 if (*p
&& s
&& strneq(*p
, s
, l
) && (l
> strlen(*p
) || (*p
)[l
] == '\0'))
1047 free_and_replace(*p
, t
);
1051 bool string_is_safe(const char *p
) {
1057 for (t
= p
; *t
; t
++) {
1058 if (*t
> 0 && *t
< ' ') /* no control characters */
1061 if (strchr(QUOTES
"\\\x7f", *t
))
1068 char* string_erase(char *x
) {
1072 /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1074 explicit_bzero_safe(x
, strlen(x
));
1078 int string_truncate_lines(const char *s
, size_t n_lines
, char **ret
) {
1079 const char *p
= s
, *e
= s
;
1080 bool truncation_applied
= false;
1086 /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1087 * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1088 * generated either. */
1093 k
= strcspn(p
, "\n");
1096 if (k
== 0) /* final empty line */
1099 if (n
>= n_lines
) /* above threshold */
1102 e
= p
+ k
; /* last line to include */
1106 assert(p
[k
] == '\n');
1118 /* e points after the last character we want to keep */
1122 if (!in_charset(e
, "\n")) /* We only consider things truncated if we remove something that
1123 * isn't a new-line or a series of them */
1124 truncation_applied
= true;
1126 copy
= strndup(s
, e
- s
);
1132 return truncation_applied
;
1135 int string_extract_line(const char *s
, size_t i
, char **ret
) {
1139 /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1140 * and == 0 if we are looking at the last line or already beyond the last line. As special
1141 * optimization, if the first line is requested and the string only consists of one line we return
1142 * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1148 q
= strchr(p
, '\n');
1150 /* The line we are looking for! */
1155 m
= strndup(p
, q
- p
);
1160 return !isempty(q
+ 1); /* more coming? */
1163 *ret
= NULL
; /* Just use the input string */
1174 return 0; /* The end */
1181 /* No more lines, return empty line */
1188 return 0; /* The end */