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"
18 //#include "locale-util.h"
20 #include "string-util.h"
21 //#include "terminal-util.h"
25 int strcmp_ptr(const char *a, const char *b) {
27 /* Like strcmp(), but tries to make sense of NULL pointers */
40 char* endswith(const char *s, const char *postfix) {
50 return (char*) s + sl;
55 if (memcmp(s + sl - pl, postfix, pl) != 0)
58 return (char*) s + sl - pl;
61 char* endswith_no_case(const char *s, const char *postfix) {
71 return (char*) s + sl;
76 if (strcasecmp(s + sl - pl, postfix) != 0)
79 return (char*) s + sl - pl;
82 char* first_word(const char *s, const char *word) {
89 /* Checks if the string starts with the specified word, either
90 * followed by NUL or by whitespace. Returns a pointer to the
91 * NUL or the first character after the whitespace. */
102 if (memcmp(s, word, wl) != 0)
109 if (!strchr(WHITESPACE, *p))
112 p += strspn(p, WHITESPACE);
116 static size_t strcspn_escaped(const char *s, const char *reject) {
117 bool escaped = false;
120 for (n=0; s[n]; n++) {
123 else if (s[n] == '\\')
125 else if (strchr(reject, s[n]))
129 /* if s ends in \, return index of previous char */
133 /* Split a string into words. */
134 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
140 assert(**state == '\0');
144 current += strspn(current, separator);
150 if (quoted && strchr("\'\"", *current)) {
151 char quotechars[2] = {*current, '\0'};
153 *l = strcspn_escaped(current + 1, quotechars);
154 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
155 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
156 /* right quote missing or garbage at the end */
160 *state = current++ + *l + 2;
162 *l = strcspn_escaped(current, separator);
163 if (current[*l] && !strchr(separator, current[*l])) {
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 *strappend(const char *s, const char *suffix) {
209 return strnappend(s, suffix, strlen_ptr(suffix));
212 char *strjoin_real(const char *x, ...) {
226 t = va_arg(ap, const char *);
231 if (n > ((size_t) -1) - l) {
255 t = va_arg(ap, const char *);
269 char *strstrip(char *s) {
275 /* Drops trailing whitespace. Modifies the string in
276 * place. Returns pointer to first non-space character */
278 s += strspn(s, WHITESPACE);
280 for (e = strchr(s, 0); e > s; e --)
281 if (!strchr(WHITESPACE, e[-1]))
289 #if 0 /// UNNEEDED by elogind
290 char *delete_chars(char *s, const char *bad) {
293 /* Drops all specified bad characters, regardless where in the string */
301 for (f = s, t = s; *f; f++) {
314 char *delete_trailing_chars(char *s, const char *bad) {
317 /* Drops all specified bad characters, at the end of the string */
326 if (!strchr(bad, *p))
334 char *truncate_nl(char *s) {
337 s[strcspn(s, NEWLINE)] = 0;
341 #if 0 /// UNNEEDED by elogind
342 char ascii_tolower(char x) {
344 if (x >= 'A' && x <= 'Z')
345 return x - 'A' + 'a';
350 char ascii_toupper(char x) {
352 if (x >= 'a' && x <= 'z')
353 return x - 'a' + 'A';
358 char *ascii_strlower(char *t) {
364 *p = ascii_tolower(*p);
369 char *ascii_strupper(char *t) {
375 *p = ascii_toupper(*p);
380 char *ascii_strlower_n(char *t, size_t n) {
386 for (i = 0; i < n; i++)
387 t[i] = ascii_tolower(t[i]);
392 int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
394 for (; n > 0; a++, b++, n--) {
397 x = (int) (uint8_t) ascii_tolower(*a);
398 y = (int) (uint8_t) ascii_tolower(*b);
407 int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
410 r = ascii_strcasecmp_n(a, b, MIN(n, m));
422 bool chars_intersect(const char *a, const char *b) {
425 /* Returns true if any of the chars in a are in b. */
434 bool string_has_cc(const char *p, const char *ok) {
440 * Check if a string contains control characters. If 'ok' is
441 * non-NULL it may be a string containing additional CCs to be
445 for (t = p; *t; t++) {
446 if (ok && strchr(ok, *t))
449 if (*t > 0 && *t < ' ')
459 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
460 size_t x, need_space;
464 assert(percent <= 100);
465 assert(new_length != (size_t) -1);
467 if (old_length <= new_length)
468 return strndup(s, old_length);
470 /* Special case short ellipsations */
471 switch (new_length) {
477 if (is_locale_utf8())
483 if (!is_locale_utf8())
492 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
493 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
494 * either for the UTF-8 encoded character or for three ASCII characters. */
495 need_space = is_locale_utf8() ? 1 : 3;
497 r = new(char, new_length+3);
501 assert(new_length >= need_space);
503 x = ((new_length - need_space) * percent + 50) / 100;
504 assert(x <= new_length - need_space);
508 if (is_locale_utf8()) {
509 r[x+0] = 0xe2; /* tri-dot ellipsis: … */
519 s + old_length - (new_length - x - need_space),
520 new_length - x - need_space + 1);
525 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
526 size_t x, k, len, len2;
531 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
532 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
535 * Ellipsation is done in a locale-dependent way:
536 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
537 * 2. Otherwise, a unicode ellipsis is used ("…")
539 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
540 * the current locale is UTF-8.
544 assert(percent <= 100);
546 if (new_length == (size_t) -1)
547 return strndup(s, old_length);
552 /* If no multibyte characters use ascii_ellipsize_mem for speed */
553 if (ascii_is_valid(s))
554 return ascii_ellipsize_mem(s, old_length, new_length, percent);
556 x = ((new_length - 1) * percent) / 100;
557 assert(x <= new_length - 1);
560 for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
563 r = utf8_encoded_to_unichar(i, &c);
566 k += unichar_iswide(c) ? 2 : 1;
569 if (k > x) /* last character was wide and went over quota */
572 for (j = s + old_length; k < new_length && j > i; ) {
575 j = utf8_prev_char(j);
576 r = utf8_encoded_to_unichar(j, &c);
579 k += unichar_iswide(c) ? 2 : 1;
583 /* we don't actually need to ellipsize */
585 return memdup(s, old_length + 1);
587 /* make space for ellipsis */
588 j = utf8_next_char(j);
591 len2 = s + old_length - j;
592 e = new(char, len + 3 + len2 + 1);
597 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
598 old_length, new_length, x, len, len2, k);
602 e[len + 0] = 0xe2; /* tri-dot ellipsis: … */
606 memcpy(e + len + 3, j, len2 + 1);
611 char *ellipsize(const char *s, size_t length, unsigned percent) {
613 if (length == (size_t) -1)
616 return ellipsize_mem(s, strlen(s), length, percent);
619 bool nulstr_contains(const char *nulstr, const char *needle) {
625 NULSTR_FOREACH(i, nulstr)
626 if (streq(i, needle))
632 char* strshorten(char *s, size_t l) {
635 if (strnlen(s, l+1) > l)
641 char *strreplace(const char *text, const char *old_string, const char *new_string) {
642 size_t l, old_len, new_len, allocated = 0;
643 char *t, *ret = NULL;
652 old_len = strlen(old_string);
653 new_len = strlen(new_string);
656 if (!GREEDY_REALLOC(ret, allocated, l+1))
664 if (!startswith(f, old_string)) {
670 nl = l - old_len + new_len;
672 if (!GREEDY_REALLOC(ret, allocated, nl + 1))
678 t = stpcpy(t, new_string);
686 static void advance_offsets(ssize_t diff, size_t offsets[2], size_t shift[2], size_t size) {
690 if ((size_t) diff < offsets[0])
692 if ((size_t) diff < offsets[1])
696 char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
697 const char *i, *begin = NULL;
703 } state = STATE_OTHER;
705 size_t osz = 0, isz, shift[2] = {};
711 /* This does three things:
713 * 1. Replaces TABs by 8 spaces
714 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
715 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
717 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as are any
718 * other special characters. Truncated ANSI sequences are left-as is too. This call is supposed to suppress the
719 * most basic formatting noise, but nothing else.
721 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
723 isz = _isz ? *_isz : strlen(*ibuf);
725 f = open_memstream(&obuf, &osz);
729 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
730 * and it doesn't leave our scope. */
732 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
734 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
739 if (i >= *ibuf + isz) /* EOT */
741 else if (*i == '\x1B')
742 state = STATE_ESCAPE;
743 else if (*i == '\t') {
745 advance_offsets(i - *ibuf, highlight, shift, 7);
752 if (i >= *ibuf + isz) { /* EOT */
754 advance_offsets(i - *ibuf, highlight, shift, 1);
756 } else if (*i == '[') { /* ANSI CSI */
759 } else if (*i == ']') { /* ANSI CSO */
765 advance_offsets(i - *ibuf, highlight, shift, 1);
773 if (i >= *ibuf + isz || /* EOT … */
774 !strchr("01234567890;m", *i)) { /* … or invalid chars in sequence */
777 advance_offsets(i - *ibuf, highlight, shift, 2);
780 } else if (*i == 'm')
787 if (i >= *ibuf + isz || /* EOT … */
788 (*i != '\a' && (uint8_t) *i < 32U) || (uint8_t) *i > 126U) { /* … or invalid chars in sequence */
791 advance_offsets(i - *ibuf, highlight, shift, 2);
794 } else if (*i == '\a')
815 highlight[0] += shift[0];
816 highlight[1] += shift[1];
822 char *strextend_with_separator(char **x, const char *separator, ...) {
824 size_t f, l, l_separator;
830 l = f = strlen_ptr(*x);
832 need_separator = !isempty(*x);
833 l_separator = strlen_ptr(separator);
835 va_start(ap, separator);
840 t = va_arg(ap, const char *);
849 if (n > ((size_t) -1) - l) {
855 need_separator = true;
859 need_separator = !isempty(*x);
861 r = realloc(*x, l+1);
867 va_start(ap, separator);
871 t = va_arg(ap, const char *);
875 if (need_separator && separator)
876 p = stpcpy(p, separator);
880 need_separator = true;
892 char *strrep(const char *s, unsigned n) {
900 p = r = malloc(l * n + 1);
904 for (i = 0; i < n; i++)
911 int split_pair(const char *s, const char *sep, char **l, char **r) {
926 a = strndup(s, x - s);
930 b = strdup(x + strlen(sep));
942 int free_and_strdup(char **p, const char *s) {
947 /* Replaces a string pointer with an strdup()ed new string,
948 * possibly freeing the old one. */
950 if (streq_ptr(*p, s))
966 #if !HAVE_EXPLICIT_BZERO
968 * Pointer to memset is volatile so that compiler must de-reference
969 * the pointer and can't assume that it points to any function in
970 * particular (such as memset, which it then might further "optimize")
971 * This approach is inspired by openssl's crypto/mem_clr.c.
973 typedef void *(*memset_t)(void *,int,size_t);
975 static volatile memset_t memset_func = memset;
977 void explicit_bzero(void *p, size_t l) {
978 memset_func(p, '\0', l);
982 char* string_erase(char *x) {
986 /* A delicious drop of snake-oil! To be called on memory where
987 * we stored passphrases or so, after we used them. */
988 explicit_bzero(x, strlen(x));
992 char *string_free_erase(char *s) {
993 return mfree(string_erase(s));
996 bool string_is_safe(const char *p) {
1002 for (t = p; *t; t++) {
1003 if (*t > 0 && *t < ' ') /* no control characters */
1006 if (strchr(QUOTES "\\\x7f", *t))