]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/string-util.c
Merge pull request #10094 from keszybz/wants-loading
[thirdparty/systemd.git] / src / basic / string-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <stdarg.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <stdio_ext.h>
8 #include <stdlib.h>
9 #include <string.h>
10
11 #include "alloc-util.h"
12 #include "escape.h"
13 #include "gunicode.h"
14 #include "locale-util.h"
15 #include "macro.h"
16 #include "string-util.h"
17 #include "terminal-util.h"
18 #include "utf8.h"
19 #include "util.h"
20 #include "fileio.h"
21
22 int strcmp_ptr(const char *a, const char *b) {
23
24 /* Like strcmp(), but tries to make sense of NULL pointers */
25 if (a && b)
26 return strcmp(a, b);
27
28 if (!a && b)
29 return -1;
30
31 if (a && !b)
32 return 1;
33
34 return 0;
35 }
36
37 char* endswith(const char *s, const char *postfix) {
38 size_t sl, pl;
39
40 assert(s);
41 assert(postfix);
42
43 sl = strlen(s);
44 pl = strlen(postfix);
45
46 if (pl == 0)
47 return (char*) s + sl;
48
49 if (sl < pl)
50 return NULL;
51
52 if (memcmp(s + sl - pl, postfix, pl) != 0)
53 return NULL;
54
55 return (char*) s + sl - pl;
56 }
57
58 char* endswith_no_case(const char *s, const char *postfix) {
59 size_t sl, pl;
60
61 assert(s);
62 assert(postfix);
63
64 sl = strlen(s);
65 pl = strlen(postfix);
66
67 if (pl == 0)
68 return (char*) s + sl;
69
70 if (sl < pl)
71 return NULL;
72
73 if (strcasecmp(s + sl - pl, postfix) != 0)
74 return NULL;
75
76 return (char*) s + sl - pl;
77 }
78
79 char* first_word(const char *s, const char *word) {
80 size_t sl, wl;
81 const char *p;
82
83 assert(s);
84 assert(word);
85
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. */
89
90 sl = strlen(s);
91 wl = strlen(word);
92
93 if (sl < wl)
94 return NULL;
95
96 if (wl == 0)
97 return (char*) s;
98
99 if (memcmp(s, word, wl) != 0)
100 return NULL;
101
102 p = s + wl;
103 if (*p == 0)
104 return (char*) p;
105
106 if (!strchr(WHITESPACE, *p))
107 return NULL;
108
109 p += strspn(p, WHITESPACE);
110 return (char*) p;
111 }
112
113 static size_t strcspn_escaped(const char *s, const char *reject) {
114 bool escaped = false;
115 int n;
116
117 for (n=0; s[n]; n++) {
118 if (escaped)
119 escaped = false;
120 else if (s[n] == '\\')
121 escaped = true;
122 else if (strchr(reject, s[n]))
123 break;
124 }
125
126 /* if s ends in \, return index of previous char */
127 return n - escaped;
128 }
129
130 /* Split a string into words. */
131 const char* split(const char **state, size_t *l, const char *separator, SplitFlags flags) {
132 const char *current;
133
134 current = *state;
135
136 if (!*current) {
137 assert(**state == '\0');
138 return NULL;
139 }
140
141 current += strspn(current, separator);
142 if (!*current) {
143 *state = current;
144 return NULL;
145 }
146
147 if (flags & SPLIT_QUOTES && strchr("\'\"", *current)) {
148 char quotechars[2] = {*current, '\0'};
149
150 *l = strcspn_escaped(current + 1, quotechars);
151 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
152 (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
153 /* right quote missing or garbage at the end */
154 if (flags & SPLIT_RELAX) {
155 *state = current + *l + 1 + (current[*l + 1] != '\0');
156 return current + 1;
157 }
158 *state = current;
159 return NULL;
160 }
161 *state = current++ + *l + 2;
162 } else if (flags & SPLIT_QUOTES) {
163 *l = strcspn_escaped(current, separator);
164 if (current[*l] && !strchr(separator, current[*l]) && !(flags & SPLIT_RELAX)) {
165 /* unfinished escape */
166 *state = current;
167 return NULL;
168 }
169 *state = current + *l;
170 } else {
171 *l = strcspn(current, separator);
172 *state = current + *l;
173 }
174
175 return current;
176 }
177
178 char *strnappend(const char *s, const char *suffix, size_t b) {
179 size_t a;
180 char *r;
181
182 if (!s && !suffix)
183 return strdup("");
184
185 if (!s)
186 return strndup(suffix, b);
187
188 if (!suffix)
189 return strdup(s);
190
191 assert(s);
192 assert(suffix);
193
194 a = strlen(s);
195 if (b > ((size_t) -1) - a)
196 return NULL;
197
198 r = new(char, a+b+1);
199 if (!r)
200 return NULL;
201
202 memcpy(r, s, a);
203 memcpy(r+a, suffix, b);
204 r[a+b] = 0;
205
206 return r;
207 }
208
209 char *strappend(const char *s, const char *suffix) {
210 return strnappend(s, suffix, strlen_ptr(suffix));
211 }
212
213 char *strjoin_real(const char *x, ...) {
214 va_list ap;
215 size_t l;
216 char *r, *p;
217
218 va_start(ap, x);
219
220 if (x) {
221 l = strlen(x);
222
223 for (;;) {
224 const char *t;
225 size_t n;
226
227 t = va_arg(ap, const char *);
228 if (!t)
229 break;
230
231 n = strlen(t);
232 if (n > ((size_t) -1) - l) {
233 va_end(ap);
234 return NULL;
235 }
236
237 l += n;
238 }
239 } else
240 l = 0;
241
242 va_end(ap);
243
244 r = new(char, l+1);
245 if (!r)
246 return NULL;
247
248 if (x) {
249 p = stpcpy(r, x);
250
251 va_start(ap, x);
252
253 for (;;) {
254 const char *t;
255
256 t = va_arg(ap, const char *);
257 if (!t)
258 break;
259
260 p = stpcpy(p, t);
261 }
262
263 va_end(ap);
264 } else
265 r[0] = 0;
266
267 return r;
268 }
269
270 char *strstrip(char *s) {
271 if (!s)
272 return NULL;
273
274 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
275
276 return delete_trailing_chars(skip_leading_chars(s, WHITESPACE), WHITESPACE);
277 }
278
279 char *delete_chars(char *s, const char *bad) {
280 char *f, *t;
281
282 /* Drops all specified bad characters, regardless where in the string */
283
284 if (!s)
285 return NULL;
286
287 if (!bad)
288 bad = WHITESPACE;
289
290 for (f = s, t = s; *f; f++) {
291 if (strchr(bad, *f))
292 continue;
293
294 *(t++) = *f;
295 }
296
297 *t = 0;
298
299 return s;
300 }
301
302 char *delete_trailing_chars(char *s, const char *bad) {
303 char *p, *c = s;
304
305 /* Drops all specified bad characters, at the end of the string */
306
307 if (!s)
308 return NULL;
309
310 if (!bad)
311 bad = WHITESPACE;
312
313 for (p = s; *p; p++)
314 if (!strchr(bad, *p))
315 c = p + 1;
316
317 *c = 0;
318
319 return s;
320 }
321
322 char *truncate_nl(char *s) {
323 assert(s);
324
325 s[strcspn(s, NEWLINE)] = 0;
326 return s;
327 }
328
329 char ascii_tolower(char x) {
330
331 if (x >= 'A' && x <= 'Z')
332 return x - 'A' + 'a';
333
334 return x;
335 }
336
337 char ascii_toupper(char x) {
338
339 if (x >= 'a' && x <= 'z')
340 return x - 'a' + 'A';
341
342 return x;
343 }
344
345 char *ascii_strlower(char *t) {
346 char *p;
347
348 assert(t);
349
350 for (p = t; *p; p++)
351 *p = ascii_tolower(*p);
352
353 return t;
354 }
355
356 char *ascii_strupper(char *t) {
357 char *p;
358
359 assert(t);
360
361 for (p = t; *p; p++)
362 *p = ascii_toupper(*p);
363
364 return t;
365 }
366
367 char *ascii_strlower_n(char *t, size_t n) {
368 size_t i;
369
370 if (n <= 0)
371 return t;
372
373 for (i = 0; i < n; i++)
374 t[i] = ascii_tolower(t[i]);
375
376 return t;
377 }
378
379 int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
380
381 for (; n > 0; a++, b++, n--) {
382 int x, y;
383
384 x = (int) (uint8_t) ascii_tolower(*a);
385 y = (int) (uint8_t) ascii_tolower(*b);
386
387 if (x != y)
388 return x - y;
389 }
390
391 return 0;
392 }
393
394 int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
395 int r;
396
397 r = ascii_strcasecmp_n(a, b, MIN(n, m));
398 if (r != 0)
399 return r;
400
401 if (n < m)
402 return -1;
403 else if (n > m)
404 return 1;
405 else
406 return 0;
407 }
408
409 bool chars_intersect(const char *a, const char *b) {
410 const char *p;
411
412 /* Returns true if any of the chars in a are in b. */
413 for (p = a; *p; p++)
414 if (strchr(b, *p))
415 return true;
416
417 return false;
418 }
419
420 bool string_has_cc(const char *p, const char *ok) {
421 const char *t;
422
423 assert(p);
424
425 /*
426 * Check if a string contains control characters. If 'ok' is
427 * non-NULL it may be a string containing additional CCs to be
428 * considered OK.
429 */
430
431 for (t = p; *t; t++) {
432 if (ok && strchr(ok, *t))
433 continue;
434
435 if (*t > 0 && *t < ' ')
436 return true;
437
438 if (*t == 127)
439 return true;
440 }
441
442 return false;
443 }
444
445 static int write_ellipsis(char *buf, bool unicode) {
446 if (unicode || is_locale_utf8()) {
447 buf[0] = 0xe2; /* tri-dot ellipsis: … */
448 buf[1] = 0x80;
449 buf[2] = 0xa6;
450 } else {
451 buf[0] = '.';
452 buf[1] = '.';
453 buf[2] = '.';
454 }
455
456 return 3;
457 }
458
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, suffix_len;
461 char *t;
462
463 assert(s);
464 assert(percent <= 100);
465 assert(new_length != (size_t) -1);
466
467 if (old_length <= new_length)
468 return strndup(s, old_length);
469
470 /* Special case short ellipsations */
471 switch (new_length) {
472
473 case 0:
474 return strdup("");
475
476 case 1:
477 if (is_locale_utf8())
478 return strdup("…");
479 else
480 return strdup(".");
481
482 case 2:
483 if (!is_locale_utf8())
484 return strdup("..");
485
486 break;
487
488 default:
489 break;
490 }
491
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;
496
497 t = new(char, new_length+3);
498 if (!t)
499 return NULL;
500
501 assert(new_length >= need_space);
502
503 x = ((new_length - need_space) * percent + 50) / 100;
504 assert(x <= new_length - need_space);
505
506 memcpy(t, s, x);
507 write_ellipsis(t + x, false);
508 suffix_len = new_length - x - need_space;
509 memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
510 *(t + x + 3 + suffix_len) = '\0';
511
512 return t;
513 }
514
515 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
516 size_t x, k, len, len2;
517 const char *i, *j;
518 char *e;
519 int r;
520
521 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
522 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
523 * strings.
524 *
525 * Ellipsation is done in a locale-dependent way:
526 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
527 * 2. Otherwise, a unicode ellipsis is used ("…")
528 *
529 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
530 * the current locale is UTF-8.
531 */
532
533 assert(s);
534 assert(percent <= 100);
535
536 if (new_length == (size_t) -1)
537 return strndup(s, old_length);
538
539 if (new_length == 0)
540 return strdup("");
541
542 /* If no multibyte characters use ascii_ellipsize_mem for speed */
543 if (ascii_is_valid_n(s, old_length))
544 return ascii_ellipsize_mem(s, old_length, new_length, percent);
545
546 x = ((new_length - 1) * percent) / 100;
547 assert(x <= new_length - 1);
548
549 k = 0;
550 for (i = s; i < s + old_length; i = utf8_next_char(i)) {
551 char32_t c;
552 int w;
553
554 r = utf8_encoded_to_unichar(i, &c);
555 if (r < 0)
556 return NULL;
557
558 w = unichar_iswide(c) ? 2 : 1;
559 if (k + w <= x)
560 k += w;
561 else
562 break;
563 }
564
565 for (j = s + old_length; j > i; ) {
566 char32_t c;
567 int w;
568 const char *jj;
569
570 jj = utf8_prev_char(j);
571 r = utf8_encoded_to_unichar(jj, &c);
572 if (r < 0)
573 return NULL;
574
575 w = unichar_iswide(c) ? 2 : 1;
576 if (k + w <= new_length) {
577 k += w;
578 j = jj;
579 } else
580 break;
581 }
582 assert(i <= j);
583
584 /* we don't actually need to ellipsize */
585 if (i == j)
586 return memdup_suffix0(s, old_length);
587
588 /* make space for ellipsis, if possible */
589 if (j < s + old_length)
590 j = utf8_next_char(j);
591 else if (i > s)
592 i = utf8_prev_char(i);
593
594 len = i - s;
595 len2 = s + old_length - j;
596 e = new(char, len + 3 + len2 + 1);
597 if (!e)
598 return NULL;
599
600 /*
601 printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
602 old_length, new_length, x, len, len2, k);
603 */
604
605 memcpy(e, s, len);
606 write_ellipsis(e + len, true);
607 memcpy(e + len + 3, j, len2);
608 *(e + len + 3 + len2) = '\0';
609
610 return e;
611 }
612
613 char *cellescape(char *buf, size_t len, const char *s) {
614 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
615 * characters are copied as they are, everything else is escaped. The result
616 * is different then if escaping and ellipsization was performed in two
617 * separate steps, because each sequence is either stored in full or skipped.
618 *
619 * This function should be used for logging about strings which expected to
620 * be plain ASCII in a safe way.
621 *
622 * An ellipsis will be used if s is too long. It was always placed at the
623 * very end.
624 */
625
626 size_t i = 0, last_char_width[4] = {}, k = 0, j;
627
628 assert(len > 0); /* at least a terminating NUL */
629
630 for (;;) {
631 char four[4];
632 int w;
633
634 if (*s == 0) /* terminating NUL detected? then we are done! */
635 goto done;
636
637 w = cescape_char(*s, four);
638 if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
639 * ellipsize at the previous location */
640 break;
641
642 /* OK, there was space, let's add this escaped character to the buffer */
643 memcpy(buf + i, four, w);
644 i += w;
645
646 /* And remember its width in the ring buffer */
647 last_char_width[k] = w;
648 k = (k + 1) % 4;
649
650 s++;
651 }
652
653 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
654 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
655 for (j = 0; j < ELEMENTSOF(last_char_width); j++) {
656
657 if (i + 4 <= len) /* nice, we reached our space goal */
658 break;
659
660 k = k == 0 ? 3 : k - 1;
661 if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
662 break;
663
664 assert(i >= last_char_width[k]);
665 i -= last_char_width[k];
666 }
667
668 if (i + 4 <= len) /* yay, enough space */
669 i += write_ellipsis(buf + i, false);
670 else if (i + 3 <= len) { /* only space for ".." */
671 buf[i++] = '.';
672 buf[i++] = '.';
673 } else if (i + 2 <= len) /* only space for a single "." */
674 buf[i++] = '.';
675 else
676 assert(i + 1 <= len);
677
678 done:
679 buf[i] = '\0';
680 return buf;
681 }
682
683 bool nulstr_contains(const char *nulstr, const char *needle) {
684 const char *i;
685
686 if (!nulstr)
687 return false;
688
689 NULSTR_FOREACH(i, nulstr)
690 if (streq(i, needle))
691 return true;
692
693 return false;
694 }
695
696 char* strshorten(char *s, size_t l) {
697 assert(s);
698
699 if (strnlen(s, l+1) > l)
700 s[l] = 0;
701
702 return s;
703 }
704
705 char *strreplace(const char *text, const char *old_string, const char *new_string) {
706 size_t l, old_len, new_len, allocated = 0;
707 char *t, *ret = NULL;
708 const char *f;
709
710 assert(old_string);
711 assert(new_string);
712
713 if (!text)
714 return NULL;
715
716 old_len = strlen(old_string);
717 new_len = strlen(new_string);
718
719 l = strlen(text);
720 if (!GREEDY_REALLOC(ret, allocated, l+1))
721 return NULL;
722
723 f = text;
724 t = ret;
725 while (*f) {
726 size_t d, nl;
727
728 if (!startswith(f, old_string)) {
729 *(t++) = *(f++);
730 continue;
731 }
732
733 d = t - ret;
734 nl = l - old_len + new_len;
735
736 if (!GREEDY_REALLOC(ret, allocated, nl + 1))
737 return mfree(ret);
738
739 l = nl;
740 t = ret + d;
741
742 t = stpcpy(t, new_string);
743 f += old_len;
744 }
745
746 *t = 0;
747 return ret;
748 }
749
750 static void advance_offsets(ssize_t diff, size_t offsets[2], size_t shift[2], size_t size) {
751 if (!offsets)
752 return;
753
754 if ((size_t) diff < offsets[0])
755 shift[0] += size;
756 if ((size_t) diff < offsets[1])
757 shift[1] += size;
758 }
759
760 char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
761 const char *i, *begin = NULL;
762 enum {
763 STATE_OTHER,
764 STATE_ESCAPE,
765 STATE_CSI,
766 STATE_CSO,
767 } state = STATE_OTHER;
768 char *obuf = NULL;
769 size_t osz = 0, isz, shift[2] = {};
770 FILE *f;
771
772 assert(ibuf);
773 assert(*ibuf);
774
775 /* This does three things:
776 *
777 * 1. Replaces TABs by 8 spaces
778 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
779 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
780 *
781 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as are any
782 * other special characters. Truncated ANSI sequences are left-as is too. This call is supposed to suppress the
783 * most basic formatting noise, but nothing else.
784 *
785 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
786
787 isz = _isz ? *_isz : strlen(*ibuf);
788
789 f = open_memstream(&obuf, &osz);
790 if (!f)
791 return NULL;
792
793 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we created f here
794 * and it doesn't leave our scope. */
795
796 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
797
798 for (i = *ibuf; i < *ibuf + isz + 1; i++) {
799
800 switch (state) {
801
802 case STATE_OTHER:
803 if (i >= *ibuf + isz) /* EOT */
804 break;
805 else if (*i == '\x1B')
806 state = STATE_ESCAPE;
807 else if (*i == '\t') {
808 fputs(" ", f);
809 advance_offsets(i - *ibuf, highlight, shift, 7);
810 } else
811 fputc(*i, f);
812
813 break;
814
815 case STATE_ESCAPE:
816 if (i >= *ibuf + isz) { /* EOT */
817 fputc('\x1B', f);
818 advance_offsets(i - *ibuf, highlight, shift, 1);
819 break;
820 } else if (*i == '[') { /* ANSI CSI */
821 state = STATE_CSI;
822 begin = i + 1;
823 } else if (*i == ']') { /* ANSI CSO */
824 state = STATE_CSO;
825 begin = i + 1;
826 } else {
827 fputc('\x1B', f);
828 fputc(*i, f);
829 advance_offsets(i - *ibuf, highlight, shift, 1);
830 state = STATE_OTHER;
831 }
832
833 break;
834
835 case STATE_CSI:
836
837 if (i >= *ibuf + isz || /* EOT … */
838 !strchr("01234567890;m", *i)) { /* … or invalid chars in sequence */
839 fputc('\x1B', f);
840 fputc('[', f);
841 advance_offsets(i - *ibuf, highlight, shift, 2);
842 state = STATE_OTHER;
843 i = begin-1;
844 } else if (*i == 'm')
845 state = STATE_OTHER;
846
847 break;
848
849 case STATE_CSO:
850
851 if (i >= *ibuf + isz || /* EOT … */
852 (*i != '\a' && (uint8_t) *i < 32U) || (uint8_t) *i > 126U) { /* … or invalid chars in sequence */
853 fputc('\x1B', f);
854 fputc(']', f);
855 advance_offsets(i - *ibuf, highlight, shift, 2);
856 state = STATE_OTHER;
857 i = begin-1;
858 } else if (*i == '\a')
859 state = STATE_OTHER;
860
861 break;
862 }
863 }
864
865 if (fflush_and_check(f) < 0) {
866 fclose(f);
867 return mfree(obuf);
868 }
869
870 fclose(f);
871
872 free(*ibuf);
873 *ibuf = obuf;
874
875 if (_isz)
876 *_isz = osz;
877
878 if (highlight) {
879 highlight[0] += shift[0];
880 highlight[1] += shift[1];
881 }
882
883 return obuf;
884 }
885
886 char *strextend_with_separator(char **x, const char *separator, ...) {
887 bool need_separator;
888 size_t f, l, l_separator;
889 char *r, *p;
890 va_list ap;
891
892 assert(x);
893
894 l = f = strlen_ptr(*x);
895
896 need_separator = !isempty(*x);
897 l_separator = strlen_ptr(separator);
898
899 va_start(ap, separator);
900 for (;;) {
901 const char *t;
902 size_t n;
903
904 t = va_arg(ap, const char *);
905 if (!t)
906 break;
907
908 n = strlen(t);
909
910 if (need_separator)
911 n += l_separator;
912
913 if (n > ((size_t) -1) - l) {
914 va_end(ap);
915 return NULL;
916 }
917
918 l += n;
919 need_separator = true;
920 }
921 va_end(ap);
922
923 need_separator = !isempty(*x);
924
925 r = realloc(*x, l+1);
926 if (!r)
927 return NULL;
928
929 p = r + f;
930
931 va_start(ap, separator);
932 for (;;) {
933 const char *t;
934
935 t = va_arg(ap, const char *);
936 if (!t)
937 break;
938
939 if (need_separator && separator)
940 p = stpcpy(p, separator);
941
942 p = stpcpy(p, t);
943
944 need_separator = true;
945 }
946 va_end(ap);
947
948 assert(p == r + l);
949
950 *p = 0;
951 *x = r;
952
953 return r + l;
954 }
955
956 char *strrep(const char *s, unsigned n) {
957 size_t l;
958 char *r, *p;
959 unsigned i;
960
961 assert(s);
962
963 l = strlen(s);
964 p = r = malloc(l * n + 1);
965 if (!r)
966 return NULL;
967
968 for (i = 0; i < n; i++)
969 p = stpcpy(p, s);
970
971 *p = 0;
972 return r;
973 }
974
975 int split_pair(const char *s, const char *sep, char **l, char **r) {
976 char *x, *a, *b;
977
978 assert(s);
979 assert(sep);
980 assert(l);
981 assert(r);
982
983 if (isempty(sep))
984 return -EINVAL;
985
986 x = strstr(s, sep);
987 if (!x)
988 return -EINVAL;
989
990 a = strndup(s, x - s);
991 if (!a)
992 return -ENOMEM;
993
994 b = strdup(x + strlen(sep));
995 if (!b) {
996 free(a);
997 return -ENOMEM;
998 }
999
1000 *l = a;
1001 *r = b;
1002
1003 return 0;
1004 }
1005
1006 int free_and_strdup(char **p, const char *s) {
1007 char *t;
1008
1009 assert(p);
1010
1011 /* Replaces a string pointer with a strdup()ed new string,
1012 * possibly freeing the old one. */
1013
1014 if (streq_ptr(*p, s))
1015 return 0;
1016
1017 if (s) {
1018 t = strdup(s);
1019 if (!t)
1020 return -ENOMEM;
1021 } else
1022 t = NULL;
1023
1024 free(*p);
1025 *p = t;
1026
1027 return 1;
1028 }
1029
1030 int free_and_strndup(char **p, const char *s, size_t l) {
1031 char *t;
1032
1033 assert(p);
1034 assert(s || l == 0);
1035
1036 /* Replaces a string pointer with a strndup()ed new string,
1037 * freeing the old one. */
1038
1039 if (!*p && !s)
1040 return 0;
1041
1042 if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
1043 return 0;
1044
1045 if (s) {
1046 t = strndup(s, l);
1047 if (!t)
1048 return -ENOMEM;
1049 } else
1050 t = NULL;
1051
1052 free_and_replace(*p, t);
1053 return 1;
1054 }
1055
1056 #if !HAVE_EXPLICIT_BZERO
1057 /*
1058 * Pointer to memset is volatile so that compiler must de-reference
1059 * the pointer and can't assume that it points to any function in
1060 * particular (such as memset, which it then might further "optimize")
1061 * This approach is inspired by openssl's crypto/mem_clr.c.
1062 */
1063 typedef void *(*memset_t)(void *,int,size_t);
1064
1065 static volatile memset_t memset_func = memset;
1066
1067 void explicit_bzero(void *p, size_t l) {
1068 memset_func(p, '\0', l);
1069 }
1070 #endif
1071
1072 char* string_erase(char *x) {
1073 if (!x)
1074 return NULL;
1075
1076 /* A delicious drop of snake-oil! To be called on memory where
1077 * we stored passphrases or so, after we used them. */
1078 explicit_bzero(x, strlen(x));
1079 return x;
1080 }
1081
1082 char *string_free_erase(char *s) {
1083 return mfree(string_erase(s));
1084 }
1085
1086 bool string_is_safe(const char *p) {
1087 const char *t;
1088
1089 if (!p)
1090 return false;
1091
1092 for (t = p; *t; t++) {
1093 if (*t > 0 && *t < ' ') /* no control characters */
1094 return false;
1095
1096 if (strchr(QUOTES "\\\x7f", *t))
1097 return false;
1098 }
1099
1100 return true;
1101 }