]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/string-util.c
755a37f6675aaf4abe6cc0f1e3356437ea3125d8
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
) {
22 /* Like strcmp(), but tries to make sense of NULL pointers */
26 return CMP(a
, b
); /* Direct comparison of pointers, one of which is NULL */
29 int strcasecmp_ptr(const char *a
, const char *b
) {
30 /* Like strcasecmp(), but tries to make sense of NULL pointers */
33 return strcasecmp(a
, b
);
34 return CMP(a
, b
); /* Direct comparison of pointers, one of which is NULL */
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
] != '\0'; n
++) {
120 else if (s
[n
] == '\\')
122 else if (strchr(reject
, s
[n
]))
129 /* Split a string into words. */
133 const char *separator
,
142 separator
= WHITESPACE
;
146 if (*current
== '\0') /* already at the end? */
149 current
+= strspn(current
, separator
); /* skip leading separators */
150 if (*current
== '\0') { /* at the end now? */
155 if (FLAGS_SET(flags
, SPLIT_QUOTES
)) {
157 if (strchr(QUOTES
, *current
)) {
158 /* We are looking at a quote */
159 *l
= strcspn_escaped(current
+ 1, CHAR_TO_STR(*current
));
160 if (current
[*l
+ 1] != *current
||
161 (current
[*l
+ 2] != 0 && !strchr(separator
, current
[*l
+ 2]))) {
162 /* right quote missing or garbage at the end */
163 if (FLAGS_SET(flags
, SPLIT_RELAX
)) {
164 *state
= current
+ *l
+ 1 + (current
[*l
+ 1] != '\0');
170 *state
= current
++ + *l
+ 2;
173 /* We are looking at a something that is not a quote */
174 *l
= strcspn_escaped(current
, separator
);
175 if (current
[*l
] && !strchr(separator
, current
[*l
]) && !FLAGS_SET(flags
, SPLIT_RELAX
)) {
176 /* unfinished escape */
180 *state
= current
+ *l
;
183 *l
= strcspn(current
, separator
);
184 *state
= current
+ *l
;
190 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
198 return strndup(suffix
, b
);
207 if (b
> ((size_t) -1) - a
)
210 r
= new(char, a
+b
+1);
215 memcpy(r
+a
, suffix
, b
);
221 char *strjoin_real(const char *x
, ...) {
235 t
= va_arg(ap
, const char *);
240 if (n
> ((size_t) -1) - l
) {
264 t
= va_arg(ap
, const char *);
278 char *strstrip(char *s
) {
282 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
284 return delete_trailing_chars(skip_leading_chars(s
, WHITESPACE
), WHITESPACE
);
287 char *delete_chars(char *s
, const char *bad
) {
290 /* Drops all specified bad characters, regardless where in the string */
298 for (f
= s
, t
= s
; *f
; f
++) {
310 char *delete_trailing_chars(char *s
, const char *bad
) {
313 /* Drops all specified bad characters, at the end of the string */
322 if (!strchr(bad
, *p
))
330 char *truncate_nl(char *s
) {
333 s
[strcspn(s
, NEWLINE
)] = 0;
337 char ascii_tolower(char x
) {
339 if (x
>= 'A' && x
<= 'Z')
340 return x
- 'A' + 'a';
345 char ascii_toupper(char x
) {
347 if (x
>= 'a' && x
<= 'z')
348 return x
- 'a' + 'A';
353 char *ascii_strlower(char *t
) {
359 *p
= ascii_tolower(*p
);
364 char *ascii_strupper(char *t
) {
370 *p
= ascii_toupper(*p
);
375 char *ascii_strlower_n(char *t
, size_t n
) {
381 for (i
= 0; i
< n
; i
++)
382 t
[i
] = ascii_tolower(t
[i
]);
387 int ascii_strcasecmp_n(const char *a
, const char *b
, size_t n
) {
389 for (; n
> 0; a
++, b
++, n
--) {
392 x
= (int) (uint8_t) ascii_tolower(*a
);
393 y
= (int) (uint8_t) ascii_tolower(*b
);
402 int ascii_strcasecmp_nn(const char *a
, size_t n
, const char *b
, size_t m
) {
405 r
= ascii_strcasecmp_n(a
, b
, MIN(n
, m
));
412 bool chars_intersect(const char *a
, const char *b
) {
415 /* Returns true if any of the chars in a are in b. */
423 bool string_has_cc(const char *p
, const char *ok
) {
429 * Check if a string contains control characters. If 'ok' is
430 * non-NULL it may be a string containing additional CCs to be
434 for (t
= p
; *t
; t
++) {
435 if (ok
&& strchr(ok
, *t
))
438 if (*t
> 0 && *t
< ' ')
448 static int write_ellipsis(char *buf
, bool unicode
) {
449 if (unicode
|| is_locale_utf8()) {
450 buf
[0] = 0xe2; /* tri-dot ellipsis: … */
462 static char *ascii_ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
463 size_t x
, need_space
, suffix_len
;
467 assert(percent
<= 100);
468 assert(new_length
!= (size_t) -1);
470 if (old_length
<= new_length
)
471 return strndup(s
, old_length
);
473 /* Special case short ellipsations */
474 switch (new_length
) {
480 if (is_locale_utf8())
481 return strdup("…");
486 if (!is_locale_utf8())
495 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
496 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
497 * either for the UTF-8 encoded character or for three ASCII characters. */
498 need_space
= is_locale_utf8() ? 1 : 3;
500 t
= new(char, new_length
+3);
504 assert(new_length
>= need_space
);
506 x
= ((new_length
- need_space
) * percent
+ 50) / 100;
507 assert(x
<= new_length
- need_space
);
510 write_ellipsis(t
+ x
, false);
511 suffix_len
= new_length
- x
- need_space
;
512 memcpy(t
+ x
+ 3, s
+ old_length
- suffix_len
, suffix_len
);
513 *(t
+ x
+ 3 + suffix_len
) = '\0';
518 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
519 size_t x
, k
, len
, len2
;
524 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
525 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
528 * Ellipsation is done in a locale-dependent way:
529 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
530 * 2. Otherwise, a unicode ellipsis is used ("…")
532 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
533 * the current locale is UTF-8.
537 assert(percent
<= 100);
539 if (new_length
== (size_t) -1)
540 return strndup(s
, old_length
);
545 /* If no multibyte characters use ascii_ellipsize_mem for speed */
546 if (ascii_is_valid_n(s
, old_length
))
547 return ascii_ellipsize_mem(s
, old_length
, new_length
, percent
);
549 x
= ((new_length
- 1) * percent
) / 100;
550 assert(x
<= new_length
- 1);
553 for (i
= s
; i
< s
+ old_length
; i
= utf8_next_char(i
)) {
557 r
= utf8_encoded_to_unichar(i
, &c
);
561 w
= unichar_iswide(c
) ? 2 : 1;
568 for (j
= s
+ old_length
; j
> i
; ) {
573 jj
= utf8_prev_char(j
);
574 r
= utf8_encoded_to_unichar(jj
, &c
);
578 w
= unichar_iswide(c
) ? 2 : 1;
579 if (k
+ w
<= new_length
) {
587 /* we don't actually need to ellipsize */
589 return memdup_suffix0(s
, old_length
);
591 /* make space for ellipsis, if possible */
592 if (j
< s
+ old_length
)
593 j
= utf8_next_char(j
);
595 i
= utf8_prev_char(i
);
598 len2
= s
+ old_length
- j
;
599 e
= new(char, len
+ 3 + len2
+ 1);
604 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
605 old_length, new_length, x, len, len2, k);
609 write_ellipsis(e
+ len
, true);
610 memcpy(e
+ len
+ 3, j
, len2
);
611 *(e
+ len
+ 3 + len2
) = '\0';
616 char *cellescape(char *buf
, size_t len
, const char *s
) {
617 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
618 * characters are copied as they are, everything else is escaped. The result
619 * is different then if escaping and ellipsization was performed in two
620 * separate steps, because each sequence is either stored in full or skipped.
622 * This function should be used for logging about strings which expected to
623 * be plain ASCII in a safe way.
625 * An ellipsis will be used if s is too long. It was always placed at the
629 size_t i
= 0, last_char_width
[4] = {}, k
= 0, j
;
631 assert(len
> 0); /* at least a terminating NUL */
637 if (*s
== 0) /* terminating NUL detected? then we are done! */
640 w
= cescape_char(*s
, four
);
641 if (i
+ w
+ 1 > len
) /* This character doesn't fit into the buffer anymore? In that case let's
642 * ellipsize at the previous location */
645 /* OK, there was space, let's add this escaped character to the buffer */
646 memcpy(buf
+ i
, four
, w
);
649 /* And remember its width in the ring buffer */
650 last_char_width
[k
] = w
;
656 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
657 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
658 for (j
= 0; j
< ELEMENTSOF(last_char_width
); j
++) {
660 if (i
+ 4 <= len
) /* nice, we reached our space goal */
663 k
= k
== 0 ? 3 : k
- 1;
664 if (last_char_width
[k
] == 0) /* bummer, we reached the beginning of the strings */
667 assert(i
>= last_char_width
[k
]);
668 i
-= last_char_width
[k
];
671 if (i
+ 4 <= len
) /* yay, enough space */
672 i
+= write_ellipsis(buf
+ i
, false);
673 else if (i
+ 3 <= len
) { /* only space for ".." */
676 } else if (i
+ 2 <= len
) /* only space for a single "." */
679 assert(i
+ 1 <= len
);
686 char* strshorten(char *s
, size_t l
) {
689 if (strnlen(s
, l
+1) > l
)
695 char *strreplace(const char *text
, const char *old_string
, const char *new_string
) {
696 size_t l
, old_len
, new_len
, allocated
= 0;
697 char *t
, *ret
= NULL
;
706 old_len
= strlen(old_string
);
707 new_len
= strlen(new_string
);
710 if (!GREEDY_REALLOC(ret
, allocated
, l
+1))
718 if (!startswith(f
, old_string
)) {
724 nl
= l
- old_len
+ new_len
;
726 if (!GREEDY_REALLOC(ret
, allocated
, nl
+ 1))
732 t
= stpcpy(t
, new_string
);
740 static void advance_offsets(
742 size_t offsets
[2], /* note: we can't use [static 2] here, since this may be NULL */
743 size_t shift
[static 2],
751 if ((size_t) diff
< offsets
[0])
753 if ((size_t) diff
< offsets
[1])
757 char *strip_tab_ansi(char **ibuf
, size_t *_isz
, size_t highlight
[2]) {
758 const char *begin
= NULL
;
764 } state
= STATE_OTHER
;
766 size_t osz
= 0, isz
, shift
[2] = {}, n_carriage_returns
= 0;
772 /* This does three things:
774 * 1. Replaces TABs by 8 spaces
775 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
776 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
777 * 4. Strip trailing \r characters (since they would "move the cursor", but have no
780 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
781 * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
782 * supposed to suppress the most basic formatting noise, but nothing else.
784 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
786 isz
= _isz
? *_isz
: strlen(*ibuf
);
788 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
789 * created f here and it doesn't leave our scope. */
790 f
= open_memstream_unlocked(&obuf
, &osz
);
794 for (const char *i
= *ibuf
; i
< *ibuf
+ isz
+ 1; i
++) {
799 if (i
>= *ibuf
+ isz
) /* EOT */
803 n_carriage_returns
++;
805 } else if (*i
== '\n')
806 /* Ignore carriage returns before new line */
807 n_carriage_returns
= 0;
808 for (; n_carriage_returns
> 0; n_carriage_returns
--)
812 state
= STATE_ESCAPE
;
813 else if (*i
== '\t') {
815 advance_offsets(i
- *ibuf
, highlight
, shift
, 7);
822 assert(n_carriage_returns
== 0);
824 if (i
>= *ibuf
+ isz
) { /* EOT */
826 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
828 } else if (*i
== '[') { /* ANSI CSI */
831 } else if (*i
== ']') { /* ANSI CSO */
837 advance_offsets(i
- *ibuf
, highlight
, shift
, 1);
844 assert(n_carriage_returns
== 0);
846 if (i
>= *ibuf
+ isz
|| /* EOT … */
847 !strchr("01234567890;m", *i
)) { /* … or invalid chars in sequence */
850 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
853 } else if (*i
== 'm')
859 assert(n_carriage_returns
== 0);
861 if (i
>= *ibuf
+ isz
|| /* EOT … */
862 (*i
!= '\a' && (uint8_t) *i
< 32U) || (uint8_t) *i
> 126U) { /* … or invalid chars in sequence */
865 advance_offsets(i
- *ibuf
, highlight
, shift
, 2);
868 } else if (*i
== '\a')
875 if (fflush_and_check(f
) < 0) {
881 free_and_replace(*ibuf
, obuf
);
887 highlight
[0] += shift
[0];
888 highlight
[1] += shift
[1];
894 char *strextend_with_separator(char **x
, const char *separator
, ...) {
896 size_t f
, l
, l_separator
;
902 l
= f
= strlen_ptr(*x
);
904 need_separator
= !isempty(*x
);
905 l_separator
= strlen_ptr(separator
);
907 va_start(ap
, separator
);
912 t
= va_arg(ap
, const char *);
921 if (n
> ((size_t) -1) - l
) {
927 need_separator
= true;
931 need_separator
= !isempty(*x
);
933 r
= realloc(*x
, l
+1);
939 va_start(ap
, separator
);
943 t
= va_arg(ap
, const char *);
947 if (need_separator
&& separator
)
948 p
= stpcpy(p
, separator
);
952 need_separator
= true;
964 char *strrep(const char *s
, unsigned n
) {
972 p
= r
= malloc(l
* n
+ 1);
976 for (i
= 0; i
< n
; i
++)
983 int split_pair(const char *s
, const char *sep
, char **l
, char **r
) {
998 a
= strndup(s
, x
- s
);
1002 b
= strdup(x
+ strlen(sep
));
1014 int free_and_strdup(char **p
, const char *s
) {
1019 /* Replaces a string pointer with a strdup()ed new string,
1020 * possibly freeing the old one. */
1022 if (streq_ptr(*p
, s
))
1038 int free_and_strndup(char **p
, const char *s
, size_t l
) {
1042 assert(s
|| l
== 0);
1044 /* Replaces a string pointer with a strndup()ed new string,
1045 * freeing the old one. */
1050 if (*p
&& s
&& strneq(*p
, s
, l
) && (l
> strlen(*p
) || (*p
)[l
] == '\0'))
1060 free_and_replace(*p
, t
);
1064 bool string_is_safe(const char *p
) {
1070 /* Checks if the specified string contains no quotes or control characters */
1072 for (t
= p
; *t
; t
++) {
1073 if (*t
> 0 && *t
< ' ') /* no control characters */
1076 if (strchr(QUOTES
"\\\x7f", *t
))
1083 char* string_erase(char *x
) {
1087 /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1089 explicit_bzero_safe(x
, strlen(x
));
1093 int string_truncate_lines(const char *s
, size_t n_lines
, char **ret
) {
1094 const char *p
= s
, *e
= s
;
1095 bool truncation_applied
= false;
1101 /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1102 * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1103 * generated either. */
1108 k
= strcspn(p
, "\n");
1111 if (k
== 0) /* final empty line */
1114 if (n
>= n_lines
) /* above threshold */
1117 e
= p
+ k
; /* last line to include */
1121 assert(p
[k
] == '\n');
1133 /* e points after the last character we want to keep */
1137 if (!in_charset(e
, "\n")) /* We only consider things truncated if we remove something that
1138 * isn't a new-line or a series of them */
1139 truncation_applied
= true;
1141 copy
= strndup(s
, e
- s
);
1147 return truncation_applied
;
1150 int string_extract_line(const char *s
, size_t i
, char **ret
) {
1154 /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1155 * and == 0 if we are looking at the last line or already beyond the last line. As special
1156 * optimization, if the first line is requested and the string only consists of one line we return
1157 * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1163 q
= strchr(p
, '\n');
1165 /* The line we are looking for! */
1170 m
= strndup(p
, q
- p
);
1175 return !isempty(q
+ 1); /* more coming? */
1178 *ret
= NULL
; /* Just use the input string */
1189 return 0; /* The end */
1196 /* No more lines, return empty line */
1203 return 0; /* The end */