1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
12 #include <stdio_ext.h>
16 #include "alloc-util.h"
19 //#include "locale-util.h"
21 #include "string-util.h"
22 //#include "terminal-util.h"
27 int strcmp_ptr(const char *a, const char *b) {
29 /* Like strcmp(), but tries to make sense of NULL pointers */
42 char* endswith(const char *s, const char *postfix) {
52 return (char*) s + sl;
57 if (memcmp(s + sl - pl, postfix, pl) != 0)
60 return (char*) s + sl - pl;
63 char* endswith_no_case(const char *s, const char *postfix) {
73 return (char*) s + sl;
78 if (strcasecmp(s + sl - pl, postfix) != 0)
81 return (char*) s + sl - pl;
84 char* first_word(const char *s, const char *word) {
91 /* Checks if the string starts with the specified word, either
92 * followed by NUL or by whitespace. Returns a pointer to the
93 * NUL or the first character after the whitespace. */
104 if (memcmp(s, word, wl) != 0)
111 if (!strchr(WHITESPACE, *p))
114 p += strspn(p, WHITESPACE);
118 static size_t strcspn_escaped(const char *s, const char *reject) {
119 bool escaped = false;
122 for (n=0; s[n]; n++) {
125 else if (s[n] == '\\')
127 else if (strchr(reject, s[n]))
131 /* if s ends in \, return index of previous char */
135 /* Split a string into words. */
136 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
142 assert(**state == '\0');
146 current += strspn(current, separator);
152 if (quoted && strchr("\'\"", *current)) {
153 char quotechars[2] = {*current, '\0'};
155 *l = strcspn_escaped(current + 1, quotechars);
156 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
157 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
158 /* right quote missing or garbage at the end */
162 *state = current++ + *l + 2;
164 *l = strcspn_escaped(current, separator);
165 if (current[*l] && !strchr(separator, current[*l])) {
166 /* unfinished escape */
170 *state = current + *l;
172 *l = strcspn(current, separator);
173 *state = current + *l;
179 char *strnappend(const char *s, const char *suffix, size_t b) {
187 return strndup(suffix, b);
196 if (b > ((size_t) -1) - a)
199 r = new(char, a+b+1);
204 memcpy(r+a, suffix, b);
210 char *strappend(const char *s, const char *suffix) {
211 return strnappend(s, suffix, strlen_ptr(suffix));
214 char *strjoin_real(const char *x, ...) {
228 t = va_arg(ap, const char *);
233 if (n > ((size_t) -1) - l) {
257 t = va_arg(ap, const char *);
271 char *strstrip(char *s) {
277 /* Drops trailing whitespace. Modifies the string in
278 * place. Returns pointer to first non-space character */
280 s += strspn(s, WHITESPACE);
282 for (e = strchr(s, 0); e > s; e --)
283 if (!strchr(WHITESPACE, e[-1]))
291 #if 0 /// UNNEEDED by elogind
292 char *delete_chars(char *s, const char *bad) {
295 /* Drops all specified bad characters, regardless where in the string */
303 for (f = s, t = s; *f; f++) {
316 char *delete_trailing_chars(char *s, const char *bad) {
319 /* Drops all specified bad characters, at the end of the string */
328 if (!strchr(bad, *p))
336 char *truncate_nl(char *s) {
339 s[strcspn(s, NEWLINE)] = 0;
343 #if 0 /// UNNEEDED by elogind
344 char ascii_tolower(char x) {
346 if (x >= 'A' && x <= 'Z')
347 return x - 'A' + 'a';
352 char ascii_toupper(char x) {
354 if (x >= 'a' && x <= 'z')
355 return x - 'a' + 'A';
360 char *ascii_strlower(char *t) {
366 *p = ascii_tolower(*p);
371 char *ascii_strupper(char *t) {
377 *p = ascii_toupper(*p);
382 char *ascii_strlower_n(char *t, size_t n) {
388 for (i = 0; i < n; i++)
389 t[i] = ascii_tolower(t[i]);
394 int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
396 for (; n > 0; a++, b++, n--) {
399 x = (int) (uint8_t) ascii_tolower(*a);
400 y = (int) (uint8_t) ascii_tolower(*b);
409 int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
412 r = ascii_strcasecmp_n(a, b, MIN(n, m));
424 bool chars_intersect(const char *a, const char *b) {
427 /* Returns true if any of the chars in a are in b. */
436 bool string_has_cc(const char *p, const char *ok) {
442 * Check if a string contains control characters. If 'ok' is
443 * non-NULL it may be a string containing additional CCs to be
447 for (t = p; *t; t++) {
448 if (ok && strchr(ok, *t))
451 if (*t > 0 && *t < ' ')
461 static int write_ellipsis(char *buf, bool unicode) {
462 if (unicode || is_locale_utf8()) {
463 buf[0] = 0xe2; /* tri-dot ellipsis: … */
475 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
476 size_t x, need_space;
480 assert(percent <= 100);
481 assert(new_length != (size_t) -1);
483 if (old_length <= new_length)
484 return strndup(s, old_length);
486 /* Special case short ellipsations */
487 switch (new_length) {
493 if (is_locale_utf8())
499 if (!is_locale_utf8())
508 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
509 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
510 * either for the UTF-8 encoded character or for three ASCII characters. */
511 need_space = is_locale_utf8() ? 1 : 3;
513 r = new(char, new_length+3);
517 assert(new_length >= need_space);
519 x = ((new_length - need_space) * percent + 50) / 100;
520 assert(x <= new_length - need_space);
523 write_ellipsis(r + x, false);
525 s + old_length - (new_length - x - need_space),
526 new_length - x - need_space + 1);
531 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
532 size_t x, k, len, len2;
537 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
538 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
541 * Ellipsation is done in a locale-dependent way:
542 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
543 * 2. Otherwise, a unicode ellipsis is used ("…")
545 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
546 * the current locale is UTF-8.
550 assert(percent <= 100);
552 if (new_length == (size_t) -1)
553 return strndup(s, old_length);
558 /* If no multibyte characters use ascii_ellipsize_mem for speed */
559 if (ascii_is_valid(s))
560 return ascii_ellipsize_mem(s, old_length, new_length, percent);
562 x = ((new_length - 1) * percent) / 100;
563 assert(x <= new_length - 1);
566 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
569 r = utf8_encoded_to_unichar(i, &c);
572 k += unichar_iswide(c) ? 2 : 1;
575 if (k > x) /* last character was wide and went over quota */
578 for (j = s + old_length; k < new_length && j > i; ) {
581 j = utf8_prev_char(j);
582 r = utf8_encoded_to_unichar(j, &c);
585 k += unichar_iswide(c) ? 2 : 1;
589 /* we don't actually need to ellipsize */
591 return memdup(s, old_length + 1);
593 /* make space for ellipsis */
594 j = utf8_next_char(j);
597 len2 = s + old_length - j;
598 e = new(char, len + 3 + len2 + 1);
603 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
604 old_length, new_length, x, len, len2, k);
608 write_ellipsis(e + len, true);
609 memcpy(e + len + 3, j, len2 + 1);
614 char *cellescape(char *buf, size_t len, const char *s) {
615 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
616 * characters are copied as they are, everything else is escaped. The result
617 * is different then if escaping and ellipsization was performed in two
618 * separate steps, because each sequence is either stored in full or skipped.
620 * This function should be used for logging about strings which expected to
621 * be plain ASCII in a safe way.
623 * An ellipsis will be used if s is too long. It was always placed at the
627 size_t i = 0, last_char_width[4] = {}, k = 0, j;
629 assert(len > 0); /* at least a terminating NUL */
635 if (*s == 0) /* terminating NUL detected? then we are done! */
638 w = cescape_char(*s, four);
639 if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
640 * ellipsize at the previous location */
643 /* OK, there was space, let's add this escaped character to the buffer */
644 memcpy(buf + i, four, w);
647 /* And remember its width in the ring buffer */
648 last_char_width[k] = w;
654 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
655 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
656 for (j = 0; j < ELEMENTSOF(last_char_width); j++) {
658 if (i + 4 <= len) /* nice, we reached our space goal */
661 k = k == 0 ? 3 : k - 1;
662 if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
665 assert(i >= last_char_width[k]);
666 i -= last_char_width[k];
669 if (i + 4 <= len) /* yay, enough space */
670 i += write_ellipsis(buf + i, false);
671 else if (i + 3 <= len) { /* only space for ".." */
674 } else if (i + 2 <= len) /* only space for a single "." */
677 assert(i + 1 <= len);
684 bool nulstr_contains(const char *nulstr, const char *needle) {
690 NULSTR_FOREACH(i, nulstr)
691 if (streq(i, needle))
697 char* strshorten(char *s, size_t l) {
700 if (strnlen(s, l+1) > l)
706 char *strreplace(const char *text, const char *old_string, const char *new_string) {
707 size_t l, old_len, new_len, allocated = 0;
708 char *t, *ret = NULL;
717 old_len = strlen(old_string);
718 new_len = strlen(new_string);
721 if (!GREEDY_REALLOC(ret, allocated, l+1))
729 if (!startswith(f, old_string)) {
735 nl = l - old_len + new_len;
737 if (!GREEDY_REALLOC(ret, allocated, nl + 1))
743 t = stpcpy(t, new_string);
751 static void advance_offsets(ssize_t diff, size_t offsets[2], size_t shift[2], size_t size) {
755 if ((size_t) diff < offsets[0])
757 if ((size_t) diff < offsets[1])
761 char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
762 const char *i, *begin = NULL;
768 } state = STATE_OTHER;
770 size_t osz = 0, isz, shift[2] = {};
776 /* This does three things:
778 * 1. Replaces TABs by 8 spaces
779 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
780 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
782 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as are any
783 * other special characters. Truncated ANSI sequences are left-as is too. This call is supposed to suppress the
784 * most basic formatting noise, but nothing else.
786 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
788 isz = _isz ? *_isz : strlen(*ibuf);
790 f = open_memstream(&obuf, &osz);
794 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
795 * and it doesn't leave our scope. */
797 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
799 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
804 if (i >= *ibuf + isz) /* EOT */
806 else if (*i == '\x1B')
807 state = STATE_ESCAPE;
808 else if (*i == '\t') {
810 advance_offsets(i - *ibuf, highlight, shift, 7);
817 if (i >= *ibuf + isz) { /* EOT */
819 advance_offsets(i - *ibuf, highlight, shift, 1);
821 } else if (*i == '[') { /* ANSI CSI */
824 } else if (*i == ']') { /* ANSI CSO */
830 advance_offsets(i - *ibuf, highlight, shift, 1);
838 if (i >= *ibuf + isz || /* EOT … */
839 !strchr("01234567890;m", *i)) { /* … or invalid chars in sequence */
842 advance_offsets(i - *ibuf, highlight, shift, 2);
845 } else if (*i == 'm')
852 if (i >= *ibuf + isz || /* EOT … */
853 (*i != '\a' && (uint8_t) *i < 32U) || (uint8_t) *i > 126U) { /* … or invalid chars in sequence */
856 advance_offsets(i - *ibuf, highlight, shift, 2);
859 } else if (*i == '\a')
866 if (fflush_and_check(f) < 0) {
880 highlight[0] += shift[0];
881 highlight[1] += shift[1];
887 char *strextend_with_separator(char **x, const char *separator, ...) {
889 size_t f, l, l_separator;
895 l = f = strlen_ptr(*x);
897 need_separator = !isempty(*x);
898 l_separator = strlen_ptr(separator);
900 va_start(ap, separator);
905 t = va_arg(ap, const char *);
914 if (n > ((size_t) -1) - l) {
920 need_separator = true;
924 need_separator = !isempty(*x);
926 r = realloc(*x, l+1);
932 va_start(ap, separator);
936 t = va_arg(ap, const char *);
940 if (need_separator && separator)
941 p = stpcpy(p, separator);
945 need_separator = true;
957 char *strrep(const char *s, unsigned n) {
965 p = r = malloc(l * n + 1);
969 for (i = 0; i < n; i++)
976 int split_pair(const char *s, const char *sep, char **l, char **r) {
991 a = strndup(s, x - s);
995 b = strdup(x + strlen(sep));
1007 int free_and_strdup(char **p, const char *s) {
1012 /* Replaces a string pointer with an strdup()ed new string,
1013 * possibly freeing the old one. */
1015 if (streq_ptr(*p, s))
1031 #if !HAVE_EXPLICIT_BZERO
1033 * Pointer to memset is volatile so that compiler must de-reference
1034 * the pointer and can't assume that it points to any function in
1035 * particular (such as memset, which it then might further "optimize")
1036 * This approach is inspired by openssl's crypto/mem_clr.c.
1038 typedef void *(*memset_t)(void *,int,size_t);
1040 static volatile memset_t memset_func = memset;
1042 void explicit_bzero(void *p, size_t l) {
1043 memset_func(p, '\0', l);
1047 char* string_erase(char *x) {
1051 /* A delicious drop of snake-oil! To be called on memory where
1052 * we stored passphrases or so, after we used them. */
1053 explicit_bzero(x, strlen(x));
1057 char *string_free_erase(char *s) {
1058 return mfree(string_erase(s));
1061 bool string_is_safe(const char *p) {
1067 for (t = p; *t; t++) {
1068 if (*t > 0 && *t < ' ') /* no control characters */
1071 if (strchr(QUOTES "\\\x7f", *t))