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