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