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