]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/string-util.c
Merge pull request #28370 from ldv-alt/cname
[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"
f392dfb5 12#include "fd-util.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"
2485b7e2 18#include "memstream-util.h"
f5c6b4f4 19#include "path-util.h"
b11d6a7b 20#include "string-util.h"
46bf625a 21#include "strv.h"
b4766d5f 22#include "terminal-util.h"
07630cea 23#include "utf8.h"
07630cea 24
07630cea
LP
25char* first_word(const char *s, const char *word) {
26 size_t sl, wl;
27 const char *p;
28
29 assert(s);
30 assert(word);
31
32 /* Checks if the string starts with the specified word, either
33 * followed by NUL or by whitespace. Returns a pointer to the
34 * NUL or the first character after the whitespace. */
35
36 sl = strlen(s);
37 wl = strlen(word);
38
39 if (sl < wl)
40 return NULL;
41
42 if (wl == 0)
43 return (char*) s;
44
45 if (memcmp(s, word, wl) != 0)
46 return NULL;
47
48 p = s + wl;
49 if (*p == 0)
50 return (char*) p;
51
52 if (!strchr(WHITESPACE, *p))
53 return NULL;
54
55 p += strspn(p, WHITESPACE);
56 return (char*) p;
57}
58
07630cea
LP
59char *strnappend(const char *s, const char *suffix, size_t b) {
60 size_t a;
61 char *r;
62
63 if (!s && !suffix)
64 return strdup("");
65
66 if (!s)
67 return strndup(suffix, b);
68
69 if (!suffix)
70 return strdup(s);
71
72 assert(s);
73 assert(suffix);
74
75 a = strlen(s);
fd4e991d 76 if (b > SIZE_MAX - a)
07630cea
LP
77 return NULL;
78
79 r = new(char, a+b+1);
80 if (!r)
81 return NULL;
82
83 memcpy(r, s, a);
84 memcpy(r+a, suffix, b);
85 r[a+b] = 0;
86
87 return r;
88}
89
605405c6 90char *strjoin_real(const char *x, ...) {
07630cea 91 va_list ap;
6ced0770 92 size_t l = 1;
07630cea
LP
93 char *r, *p;
94
95 va_start(ap, x);
020003f2
RV
96 for (const char *t = x; t; t = va_arg(ap, const char *)) {
97 size_t n;
07630cea 98
020003f2
RV
99 n = strlen(t);
100 if (n > SIZE_MAX - l) {
101 va_end(ap);
102 return NULL;
07630cea 103 }
020003f2
RV
104 l += n;
105 }
07630cea
LP
106 va_end(ap);
107
6ced0770 108 p = r = new(char, l);
07630cea
LP
109 if (!r)
110 return NULL;
111
020003f2
RV
112 va_start(ap, x);
113 for (const char *t = x; t; t = va_arg(ap, const char *))
114 p = stpcpy(p, t);
115 va_end(ap);
07630cea 116
020003f2 117 *p = 0;
07630cea
LP
118
119 return r;
120}
121
122char *strstrip(char *s) {
7546145e
LP
123 if (!s)
124 return NULL;
125
0a6ffc5c 126 /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
07630cea 127
0a6ffc5c 128 return delete_trailing_chars(skip_leading_chars(s, WHITESPACE), WHITESPACE);
07630cea
LP
129}
130
131char *delete_chars(char *s, const char *bad) {
132 char *f, *t;
133
7546145e
LP
134 /* Drops all specified bad characters, regardless where in the string */
135
136 if (!s)
137 return NULL;
138
139 if (!bad)
140 bad = WHITESPACE;
07630cea
LP
141
142 for (f = s, t = s; *f; f++) {
143 if (strchr(bad, *f))
144 continue;
145
146 *(t++) = *f;
147 }
148
149 *t = 0;
150
151 return s;
152}
153
7546145e 154char *delete_trailing_chars(char *s, const char *bad) {
a01080ce 155 char *c = s;
7546145e
LP
156
157 /* Drops all specified bad characters, at the end of the string */
158
159 if (!s)
160 return NULL;
161
162 if (!bad)
163 bad = WHITESPACE;
164
a01080ce 165 for (char *p = s; *p; p++)
7546145e
LP
166 if (!strchr(bad, *p))
167 c = p + 1;
168
169 *c = 0;
170
171 return s;
172}
173
61cecfa0 174char *truncate_nl_full(char *s, size_t *ret_len) {
175 size_t n;
176
07630cea
LP
177 assert(s);
178
61cecfa0 179 n = strcspn(s, NEWLINE);
180 s[n] = '\0';
181 if (ret_len)
182 *ret_len = n;
07630cea
LP
183 return s;
184}
185
b577e3d5
LP
186char ascii_tolower(char x) {
187
188 if (x >= 'A' && x <= 'Z')
189 return x - 'A' + 'a';
190
191 return x;
192}
193
846b8fc3
LP
194char ascii_toupper(char x) {
195
196 if (x >= 'a' && x <= 'z')
197 return x - 'a' + 'A';
198
199 return x;
200}
201
07630cea 202char *ascii_strlower(char *t) {
07630cea
LP
203 assert(t);
204
a01080ce 205 for (char *p = t; *p; p++)
b577e3d5
LP
206 *p = ascii_tolower(*p);
207
208 return t;
209}
210
846b8fc3 211char *ascii_strupper(char *t) {
846b8fc3
LP
212 assert(t);
213
a01080ce 214 for (char *p = t; *p; p++)
846b8fc3
LP
215 *p = ascii_toupper(*p);
216
217 return t;
218}
219
b577e3d5 220char *ascii_strlower_n(char *t, size_t n) {
b577e3d5
LP
221 if (n <= 0)
222 return t;
223
a01080ce 224 for (size_t i = 0; i < n; i++)
b577e3d5 225 t[i] = ascii_tolower(t[i]);
07630cea
LP
226
227 return t;
228}
522d85ae
LP
229
230int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
231
232 for (; n > 0; a++, b++, n--) {
233 int x, y;
234
235 x = (int) (uint8_t) ascii_tolower(*a);
236 y = (int) (uint8_t) ascii_tolower(*b);
237
238 if (x != y)
239 return x - y;
240 }
241
242 return 0;
243}
c1749834
LP
244
245int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
246 int r;
247
248 r = ascii_strcasecmp_n(a, b, MIN(n, m));
249 if (r != 0)
250 return r;
251
6dd91b36 252 return CMP(n, m);
c1749834 253}
07630cea
LP
254
255bool chars_intersect(const char *a, const char *b) {
07630cea 256 /* Returns true if any of the chars in a are in b. */
a01080ce 257 for (const char *p = a; *p; p++)
07630cea
LP
258 if (strchr(b, *p))
259 return true;
260
261 return false;
262}
263
264bool string_has_cc(const char *p, const char *ok) {
07630cea
LP
265 assert(p);
266
267 /*
268 * Check if a string contains control characters. If 'ok' is
269 * non-NULL it may be a string containing additional CCs to be
270 * considered OK.
271 */
272
a01080ce 273 for (const char *t = p; *t; t++) {
07630cea
LP
274 if (ok && strchr(ok, *t))
275 continue;
276
6302d386 277 if (char_is_cc(*t))
07630cea
LP
278 return true;
279 }
280
281 return false;
282}
283
8409f688
ZJS
284static int write_ellipsis(char *buf, bool unicode) {
285 if (unicode || is_locale_utf8()) {
286 buf[0] = 0xe2; /* tri-dot ellipsis: … */
287 buf[1] = 0x80;
288 buf[2] = 0xa6;
289 } else {
290 buf[0] = '.';
291 buf[1] = '.';
292 buf[2] = '.';
293 }
294
295 return 3;
296}
297
cb558ab2
ZJS
298static size_t ansi_sequence_length(const char *s, size_t len) {
299 assert(s);
300
301 if (len < 2)
302 return 0;
303
304 if (s[0] != 0x1B) /* ASCII 27, aka ESC, aka Ctrl-[ */
305 return 0; /* Not the start of a sequence */
306
307 if (s[1] == 0x5B) { /* [, start of CSI sequence */
308 size_t i = 2;
309
310 if (i == len)
311 return 0;
312
313 while (s[i] >= 0x30 && s[i] <= 0x3F) /* Parameter bytes */
314 if (++i == len)
315 return 0;
316 while (s[i] >= 0x20 && s[i] <= 0x2F) /* Intermediate bytes */
317 if (++i == len)
318 return 0;
319 if (s[i] >= 0x40 && s[i] <= 0x7E) /* Final byte */
320 return i + 1;
321 return 0; /* Bad sequence */
322
323 } else if (s[1] >= 0x40 && s[1] <= 0x5F) /* other non-CSI Fe sequence */
324 return 2;
325
326 return 0; /* Bad escape? */
327}
328
329static bool string_has_ansi_sequence(const char *s, size_t len) {
330 const char *t = s;
331
332 while ((t = memchr(s, 0x1B, len - (t - s))))
333 if (ansi_sequence_length(t, len - (t - s)) > 0)
334 return true;
335 return false;
336}
337
338static size_t previous_ansi_sequence(const char *s, size_t length, const char **ret_where) {
339 /* Locate the previous ANSI sequence and save its start in *ret_where and return length. */
340
341 for (size_t i = length - 2; i > 0; i--) { /* -2 because at least two bytes are needed */
342 size_t slen = ansi_sequence_length(s + (i - 1), length - (i - 1));
343 if (slen == 0)
344 continue;
345
346 *ret_where = s + (i - 1);
347 return slen;
348 }
349
350 *ret_where = NULL;
351 return 0;
352}
353
07630cea 354static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
9924aef6
ZJS
355 size_t x, need_space, suffix_len;
356 char *t;
07630cea
LP
357
358 assert(s);
359 assert(percent <= 100);
f5fbe71d 360 assert(new_length != SIZE_MAX);
07630cea 361
c30a49b2 362 if (old_length <= new_length)
07630cea
LP
363 return strndup(s, old_length);
364
c30a49b2
LP
365 /* Special case short ellipsations */
366 switch (new_length) {
367
368 case 0:
369 return strdup("");
370
371 case 1:
372 if (is_locale_utf8())
373 return strdup("…");
374 else
375 return strdup(".");
376
377 case 2:
378 if (!is_locale_utf8())
379 return strdup("..");
380
381 break;
382
383 default:
384 break;
385 }
386
387 /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
388 * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
389 * either for the UTF-8 encoded character or for three ASCII characters. */
390 need_space = is_locale_utf8() ? 1 : 3;
391
9924aef6
ZJS
392 t = new(char, new_length+3);
393 if (!t)
07630cea
LP
394 return NULL;
395
c30a49b2 396 assert(new_length >= need_space);
07630cea 397
c30a49b2
LP
398 x = ((new_length - need_space) * percent + 50) / 100;
399 assert(x <= new_length - need_space);
07630cea 400
9924aef6
ZJS
401 memcpy(t, s, x);
402 write_ellipsis(t + x, false);
403 suffix_len = new_length - x - need_space;
404 memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
405 *(t + x + 3 + suffix_len) = '\0';
07630cea 406
9924aef6 407 return t;
07630cea
LP
408}
409
410char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
c30a49b2 411 size_t x, k, len, len2;
07630cea 412 const char *i, *j;
c932fb71 413 int r;
07630cea 414
c30a49b2
LP
415 /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
416 * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
417 * strings.
418 *
419 * Ellipsation is done in a locale-dependent way:
420 * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
421 * 2. Otherwise, a unicode ellipsis is used ("…")
422 *
423 * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
424 * the current locale is UTF-8.
425 */
426
07630cea
LP
427 assert(s);
428 assert(percent <= 100);
ddbc9319 429
f5fbe71d 430 if (new_length == SIZE_MAX)
ddbc9319
LP
431 return strndup(s, old_length);
432
c30a49b2
LP
433 if (new_length == 0)
434 return strdup("");
07630cea 435
cb558ab2
ZJS
436 bool has_ansi_seq = string_has_ansi_sequence(s, old_length);
437
438 /* If no multibyte characters or ANSI sequences, use ascii_ellipsize_mem for speed */
439 if (!has_ansi_seq && ascii_is_valid_n(s, old_length))
07630cea
LP
440 return ascii_ellipsize_mem(s, old_length, new_length, percent);
441
cb558ab2 442 x = (new_length - 1) * percent / 100;
c30a49b2 443 assert(x <= new_length - 1);
07630cea
LP
444
445 k = 0;
cb558ab2
ZJS
446 for (i = s; i < s + old_length; ) {
447 size_t slen = has_ansi_seq ? ansi_sequence_length(i, old_length - (i - s)) : 0;
448 if (slen > 0) {
449 i += slen;
450 continue; /* ANSI sequences don't take up any space in output */
451 }
07630cea 452
cb558ab2 453 char32_t c;
c932fb71
SL
454 r = utf8_encoded_to_unichar(i, &c);
455 if (r < 0)
07630cea 456 return NULL;
07630cea 457
cb558ab2
ZJS
458 int w = unichar_iswide(c) ? 2 : 1;
459 if (k + w > x)
9924aef6 460 break;
cb558ab2
ZJS
461
462 k += w;
463 i += r;
9924aef6 464 }
07630cea 465
cb558ab2
ZJS
466 const char *ansi_start = s + old_length;
467 size_t ansi_len = 0;
468
469 for (const char *t = j = s + old_length; t > i && k < new_length; ) {
c932fb71 470 char32_t c;
9924aef6 471 int w;
cb558ab2
ZJS
472 const char *tt;
473
474 if (has_ansi_seq && ansi_start >= t)
475 /* Figure out the previous ANSI sequence, if any */
476 ansi_len = previous_ansi_sequence(s, t - s, &ansi_start);
07630cea 477
cb558ab2
ZJS
478 /* If the sequence extends all the way to the current position, skip it. */
479 if (has_ansi_seq && ansi_len > 0 && ansi_start + ansi_len == t) {
480 t = ansi_start;
481 continue;
482 }
483
484 tt = utf8_prev_char(t);
485 r = utf8_encoded_to_unichar(tt, &c);
c932fb71 486 if (r < 0)
07630cea 487 return NULL;
9924aef6
ZJS
488
489 w = unichar_iswide(c) ? 2 : 1;
cb558ab2 490 if (k + w > new_length)
9924aef6 491 break;
cb558ab2
ZJS
492
493 k += w;
494 j = t = tt; /* j should always point to the first "real" character */
07630cea 495 }
07630cea 496
cb558ab2
ZJS
497 /* We don't actually need to ellipsize */
498 if (i >= j)
9924aef6 499 return memdup_suffix0(s, old_length);
07630cea 500
cb558ab2
ZJS
501 if (k >= new_length) {
502 /* Make space for ellipsis, if required and possible. We know that the edge character is not
503 * part of an ANSI sequence (because then we'd skip it). If the last character we looked at
504 * was wide, we don't need to make space. */
505 if (j < s + old_length)
506 j = utf8_next_char(j);
507 else if (i > s)
508 i = utf8_prev_char(i);
509 }
07630cea
LP
510
511 len = i - s;
512 len2 = s + old_length - j;
cb558ab2
ZJS
513
514 /* If we have ANSI, allow the same length as the source string + ellipsis. It'd be too involved to
515 * figure out what exact space is needed. Strings with ANSI sequences are most likely to be fairly
516 * short anyway. */
517 size_t alloc_len = has_ansi_seq ? old_length + 3 + 1 : len + 3 + len2 + 1;
518
519 char *e = new(char, alloc_len);
07630cea
LP
520 if (!e)
521 return NULL;
522
523 /*
cb558ab2 524 printf("old_length=%zu new_length=%zu x=%zu len=%zu len2=%zu k=%zu\n",
07630cea
LP
525 old_length, new_length, x, len, len2, k);
526 */
527
cb558ab2 528 memcpy_safe(e, s, len);
8409f688 529 write_ellipsis(e + len, true);
cb558ab2
ZJS
530
531 char *dst = e + len + 3;
532
533 if (has_ansi_seq)
534 /* Copy over any ANSI sequences in full */
535 for (const char *p = s + len; p < j; ) {
536 size_t slen = ansi_sequence_length(p, j - p);
537 if (slen > 0) {
538 memcpy(dst, p, slen);
539 dst += slen;
540 p += slen;
541 } else
542 p = utf8_next_char(p);
543 }
544
545 memcpy_safe(dst, j, len2);
546 dst[len2] = '\0';
07630cea
LP
547
548 return e;
549}
550
8409f688
ZJS
551char *cellescape(char *buf, size_t len, const char *s) {
552 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
553 * characters are copied as they are, everything else is escaped. The result
554 * is different then if escaping and ellipsization was performed in two
555 * separate steps, because each sequence is either stored in full or skipped.
556 *
557 * This function should be used for logging about strings which expected to
558 * be plain ASCII in a safe way.
559 *
560 * An ellipsis will be used if s is too long. It was always placed at the
561 * very end.
562 */
563
a01080ce 564 size_t i = 0, last_char_width[4] = {}, k = 0;
61f6e276
LP
565
566 assert(len > 0); /* at least a terminating NUL */
8409f688 567
61f6e276
LP
568 for (;;) {
569 char four[4];
570 int w;
8409f688 571
61f6e276 572 if (*s == 0) /* terminating NUL detected? then we are done! */
8409f688 573 goto done;
61f6e276
LP
574
575 w = cescape_char(*s, four);
576 if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
577 * ellipsize at the previous location */
578 break;
579
580 /* OK, there was space, let's add this escaped character to the buffer */
581 memcpy(buf + i, four, w);
582 i += w;
583
584 /* And remember its width in the ring buffer */
585 last_char_width[k] = w;
586 k = (k + 1) % 4;
587
588 s++;
8409f688
ZJS
589 }
590
61f6e276
LP
591 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
592 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
a01080ce 593 for (size_t j = 0; j < ELEMENTSOF(last_char_width); j++) {
61f6e276
LP
594
595 if (i + 4 <= len) /* nice, we reached our space goal */
596 break;
597
598 k = k == 0 ? 3 : k - 1;
599 if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
600 break;
601
602 assert(i >= last_char_width[k]);
603 i -= last_char_width[k];
8409f688
ZJS
604 }
605
61f6e276
LP
606 if (i + 4 <= len) /* yay, enough space */
607 i += write_ellipsis(buf + i, false);
608 else if (i + 3 <= len) { /* only space for ".." */
609 buf[i++] = '.';
610 buf[i++] = '.';
611 } else if (i + 2 <= len) /* only space for a single "." */
612 buf[i++] = '.';
613 else
614 assert(i + 1 <= len);
615
8409f688
ZJS
616 done:
617 buf[i] = '\0';
618 return buf;
619}
620
07630cea
LP
621char* strshorten(char *s, size_t l) {
622 assert(s);
623
47b33c7d 624 if (strnlen(s, l+1) > l)
07630cea
LP
625 s[l] = 0;
626
627 return s;
628}
629
2812017c
DDM
630int strgrowpad0(char **s, size_t l) {
631 assert(s);
632
633 char *q = realloc(*s, l);
634 if (!q)
635 return -ENOMEM;
636 *s = q;
637
638 size_t sz = strlen(*s);
639 memzero(*s + sz, l - sz);
640 return 0;
641}
642
07630cea 643char *strreplace(const char *text, const char *old_string, const char *new_string) {
319a4f4b 644 size_t l, old_len, new_len;
9d73565a 645 char *t, *ret = NULL;
07630cea 646 const char *f;
07630cea 647
07630cea
LP
648 assert(old_string);
649 assert(new_string);
650
9d73565a
LP
651 if (!text)
652 return NULL;
653
07630cea
LP
654 old_len = strlen(old_string);
655 new_len = strlen(new_string);
656
657 l = strlen(text);
319a4f4b 658 if (!GREEDY_REALLOC(ret, l+1))
07630cea
LP
659 return NULL;
660
661 f = text;
9d73565a 662 t = ret;
07630cea 663 while (*f) {
07630cea
LP
664 size_t d, nl;
665
666 if (!startswith(f, old_string)) {
667 *(t++) = *(f++);
668 continue;
669 }
670
9d73565a 671 d = t - ret;
07630cea 672 nl = l - old_len + new_len;
9d73565a 673
319a4f4b 674 if (!GREEDY_REALLOC(ret, nl + 1))
9d73565a 675 return mfree(ret);
07630cea
LP
676
677 l = nl;
9d73565a 678 t = ret + d;
07630cea
LP
679
680 t = stpcpy(t, new_string);
681 f += old_len;
682 }
683
684 *t = 0;
9d73565a 685 return ret;
07630cea
LP
686}
687
6fb05690
LP
688static void advance_offsets(
689 ssize_t diff,
690 size_t offsets[2], /* note: we can't use [static 2] here, since this may be NULL */
691 size_t shift[static 2],
692 size_t size) {
693
b4766d5f
ZJS
694 if (!offsets)
695 return;
696
6fb05690
LP
697 assert(shift);
698
b4766d5f
ZJS
699 if ((size_t) diff < offsets[0])
700 shift[0] += size;
701 if ((size_t) diff < offsets[1])
702 shift[1] += size;
703}
704
705char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
62a3fc6d 706 const char *begin = NULL;
07630cea
LP
707 enum {
708 STATE_OTHER,
709 STATE_ESCAPE,
695a944c
LP
710 STATE_CSI,
711 STATE_CSO,
07630cea 712 } state = STATE_OTHER;
2485b7e2
YW
713 _cleanup_(memstream_done) MemStream m = {};
714 size_t isz, shift[2] = {}, n_carriage_returns = 0;
715 FILE *f;
07630cea
LP
716
717 assert(ibuf);
718 assert(*ibuf);
719
695a944c
LP
720 /* This does three things:
721 *
722 * 1. Replaces TABs by 8 spaces
723 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
724 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
62a3fc6d
ZJS
725 * 4. Strip trailing \r characters (since they would "move the cursor", but have no
726 * other effect).
695a944c 727 *
2fe21124
ZJS
728 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
729 * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
730 * supposed to suppress the most basic formatting noise, but nothing else.
695a944c
LP
731 *
732 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
07630cea
LP
733
734 isz = _isz ? *_isz : strlen(*ibuf);
735
2fe21124
ZJS
736 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
737 * created f here and it doesn't leave our scope. */
2485b7e2 738 f = memstream_init(&m);
07630cea
LP
739 if (!f)
740 return NULL;
741
62a3fc6d 742 for (const char *i = *ibuf; i < *ibuf + isz + 1; i++) {
07630cea
LP
743
744 switch (state) {
745
746 case STATE_OTHER:
747 if (i >= *ibuf + isz) /* EOT */
748 break;
62a3fc6d
ZJS
749
750 if (*i == '\r') {
751 n_carriage_returns++;
752 break;
753 } else if (*i == '\n')
754 /* Ignore carriage returns before new line */
755 n_carriage_returns = 0;
756 for (; n_carriage_returns > 0; n_carriage_returns--)
757 fputc('\r', f);
758
759 if (*i == '\x1B')
07630cea 760 state = STATE_ESCAPE;
b4766d5f 761 else if (*i == '\t') {
0d536673 762 fputs(" ", f);
b4766d5f
ZJS
763 advance_offsets(i - *ibuf, highlight, shift, 7);
764 } else
0d536673 765 fputc(*i, f);
b4766d5f 766
07630cea
LP
767 break;
768
769 case STATE_ESCAPE:
62a3fc6d
ZJS
770 assert(n_carriage_returns == 0);
771
07630cea 772 if (i >= *ibuf + isz) { /* EOT */
0d536673 773 fputc('\x1B', f);
b4766d5f 774 advance_offsets(i - *ibuf, highlight, shift, 1);
07630cea 775 break;
695a944c
LP
776 } else if (*i == '[') { /* ANSI CSI */
777 state = STATE_CSI;
778 begin = i + 1;
779 } else if (*i == ']') { /* ANSI CSO */
780 state = STATE_CSO;
07630cea
LP
781 begin = i + 1;
782 } else {
0d536673
LP
783 fputc('\x1B', f);
784 fputc(*i, f);
b4766d5f 785 advance_offsets(i - *ibuf, highlight, shift, 1);
07630cea
LP
786 state = STATE_OTHER;
787 }
788
789 break;
790
695a944c 791 case STATE_CSI:
62a3fc6d 792 assert(n_carriage_returns == 0);
07630cea 793
695a944c
LP
794 if (i >= *ibuf + isz || /* EOT … */
795 !strchr("01234567890;m", *i)) { /* … or invalid chars in sequence */
0d536673
LP
796 fputc('\x1B', f);
797 fputc('[', f);
b4766d5f 798 advance_offsets(i - *ibuf, highlight, shift, 2);
07630cea
LP
799 state = STATE_OTHER;
800 i = begin-1;
801 } else if (*i == 'm')
802 state = STATE_OTHER;
695a944c
LP
803
804 break;
805
806 case STATE_CSO:
62a3fc6d 807 assert(n_carriage_returns == 0);
695a944c
LP
808
809 if (i >= *ibuf + isz || /* EOT … */
810 (*i != '\a' && (uint8_t) *i < 32U) || (uint8_t) *i > 126U) { /* … or invalid chars in sequence */
811 fputc('\x1B', f);
812 fputc(']', f);
813 advance_offsets(i - *ibuf, highlight, shift, 2);
814 state = STATE_OTHER;
815 i = begin-1;
816 } else if (*i == '\a')
817 state = STATE_OTHER;
818
07630cea
LP
819 break;
820 }
821 }
822
2485b7e2
YW
823 char *obuf;
824 if (memstream_finalize(&m, &obuf, _isz) < 0)
f392dfb5 825 return NULL;
07630cea 826
6fb05690 827 free_and_replace(*ibuf, obuf);
07630cea 828
b4766d5f
ZJS
829 if (highlight) {
830 highlight[0] += shift[0];
831 highlight[1] += shift[1];
832 }
833
6fb05690 834 return *ibuf;
07630cea
LP
835}
836
c2bc710b 837char *strextend_with_separator_internal(char **x, const char *separator, ...) {
bb8ad9ea 838 size_t f, l, l_separator;
c2bc710b
LP
839 bool need_separator;
840 char *nr, *p;
bb8ad9ea 841 va_list ap;
07630cea
LP
842
843 assert(x);
844
7bf7ce28 845 l = f = strlen_ptr(*x);
07630cea 846
bb8ad9ea
LP
847 need_separator = !isempty(*x);
848 l_separator = strlen_ptr(separator);
849
850 va_start(ap, separator);
07630cea
LP
851 for (;;) {
852 const char *t;
853 size_t n;
854
855 t = va_arg(ap, const char *);
856 if (!t)
857 break;
858
859 n = strlen(t);
bb8ad9ea
LP
860
861 if (need_separator)
862 n += l_separator;
863
c2bc710b 864 if (n >= SIZE_MAX - l) {
07630cea
LP
865 va_end(ap);
866 return NULL;
867 }
868
869 l += n;
bb8ad9ea 870 need_separator = true;
07630cea
LP
871 }
872 va_end(ap);
873
bb8ad9ea
LP
874 need_separator = !isempty(*x);
875
2a4e1fd0 876 nr = realloc(*x, GREEDY_ALLOC_ROUND_UP(l+1));
c2bc710b 877 if (!nr)
07630cea
LP
878 return NULL;
879
c2bc710b
LP
880 *x = nr;
881 p = nr + f;
07630cea 882
bb8ad9ea 883 va_start(ap, separator);
07630cea
LP
884 for (;;) {
885 const char *t;
886
887 t = va_arg(ap, const char *);
888 if (!t)
889 break;
890
bb8ad9ea
LP
891 if (need_separator && separator)
892 p = stpcpy(p, separator);
893
07630cea 894 p = stpcpy(p, t);
bb8ad9ea
LP
895
896 need_separator = true;
07630cea
LP
897 }
898 va_end(ap);
899
c2bc710b 900 assert(p == nr + l);
bb8ad9ea 901
07630cea 902 *p = 0;
07630cea 903
c2bc710b 904 return p;
07630cea
LP
905}
906
6b13ca8a
YW
907int strextendf_with_separator(char **x, const char *separator, const char *format, ...) {
908 size_t m, a, l_separator;
e9b88a6d
LP
909 va_list ap;
910 int l;
911
912 /* Appends a formatted string to the specified string. Don't use this in inner loops, since then
913 * we'll spend a tonload of time in determining the length of the string passed in, over and over
914 * again. */
915
916 assert(x);
917 assert(format);
918
6b13ca8a
YW
919 l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
920
e9b88a6d
LP
921 /* Let's try to use the allocated buffer, if there's room at the end still. Otherwise let's extend by 64 chars. */
922 if (*x) {
923 m = strlen(*x);
6df28e1f 924 a = MALLOC_SIZEOF_SAFE(*x);
e9b88a6d
LP
925 assert(a >= m + 1);
926 } else
927 m = a = 0;
928
6b13ca8a 929 if (a - m < 17 + l_separator) { /* if there's less than 16 chars space, then enlarge the buffer first */
e9b88a6d
LP
930 char *n;
931
6b13ca8a
YW
932 if (_unlikely_(l_separator > SIZE_MAX - 64)) /* overflow check #1 */
933 return -ENOMEM;
934 if (_unlikely_(m > SIZE_MAX - 64 - l_separator)) /* overflow check #2 */
e9b88a6d
LP
935 return -ENOMEM;
936
6b13ca8a 937 n = realloc(*x, m + 64 + l_separator);
e9b88a6d
LP
938 if (!n)
939 return -ENOMEM;
940
941 *x = n;
6df28e1f 942 a = MALLOC_SIZEOF_SAFE(*x);
e9b88a6d
LP
943 }
944
945 /* Now, let's try to format the string into it */
6b13ca8a 946 memcpy_safe(*x + m, separator, l_separator);
e9b88a6d 947 va_start(ap, format);
6b13ca8a 948 l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
e9b88a6d
LP
949 va_end(ap);
950
951 assert(l >= 0);
952
6b13ca8a 953 if ((size_t) l < a - m - l_separator) {
e9b88a6d
LP
954 char *n;
955
956 /* Nice! This worked. We are done. But first, let's return the extra space we don't
957 * need. This should be a cheap operation, since we only lower the allocation size here,
958 * never increase. */
6b13ca8a 959 n = realloc(*x, m + (size_t) l + l_separator + 1);
e9b88a6d
LP
960 if (n)
961 *x = n;
962 } else {
963 char *n;
964
965 /* Wasn't enough. Then let's allocate exactly what we need. */
966
6b13ca8a 967 if (_unlikely_((size_t) l > SIZE_MAX - (l_separator + 1))) /* overflow check #1 */
e9b88a6d 968 goto oom;
6b13ca8a 969 if (_unlikely_(m > SIZE_MAX - ((size_t) l + l_separator + 1))) /* overflow check #2 */
e9b88a6d
LP
970 goto oom;
971
6b13ca8a 972 a = m + (size_t) l + l_separator + 1;
e9b88a6d
LP
973 n = realloc(*x, a);
974 if (!n)
975 goto oom;
976 *x = n;
977
978 va_start(ap, format);
6b13ca8a 979 l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
e9b88a6d
LP
980 va_end(ap);
981
6b13ca8a 982 assert((size_t) l < a - m - l_separator);
e9b88a6d
LP
983 }
984
985 return 0;
986
987oom:
988 /* truncate the bytes added after the first vsnprintf() attempt again */
989 (*x)[m] = 0;
990 return -ENOMEM;
991}
992
6b9f6007
LP
993char *strextendn(char **x, const char *s, size_t l) {
994 assert(x);
995 assert(s || l == 0);
996
997 if (l == SIZE_MAX)
998 l = strlen_ptr(s);
999 else if (l > 0)
1000 l = strnlen(s, l); /* ignore trailing noise */
1001
1002 if (l > 0 || !*x) {
1003 size_t q;
1004 char *m;
1005
1006 q = strlen_ptr(*x);
1007 m = realloc(*x, q + l + 1);
1008 if (!m)
1009 return NULL;
1010
1011 memcpy_safe(m + q, s, l);
1012 m[q + l] = 0;
1013
1014 *x = m;
1015 }
1016
1017 return *x;
1018}
1019
07630cea 1020char *strrep(const char *s, unsigned n) {
07630cea 1021 char *r, *p;
fe96c0f8 1022 size_t l;
07630cea
LP
1023
1024 assert(s);
1025
1026 l = strlen(s);
1027 p = r = malloc(l * n + 1);
1028 if (!r)
1029 return NULL;
1030
fe96c0f8 1031 for (unsigned i = 0; i < n; i++)
07630cea
LP
1032 p = stpcpy(p, s);
1033
1034 *p = 0;
1035 return r;
1036}
1037
1038int split_pair(const char *s, const char *sep, char **l, char **r) {
1039 char *x, *a, *b;
1040
1041 assert(s);
1042 assert(sep);
1043 assert(l);
1044 assert(r);
1045
1046 if (isempty(sep))
1047 return -EINVAL;
1048
1049 x = strstr(s, sep);
1050 if (!x)
1051 return -EINVAL;
1052
1053 a = strndup(s, x - s);
1054 if (!a)
1055 return -ENOMEM;
1056
1057 b = strdup(x + strlen(sep));
1058 if (!b) {
1059 free(a);
1060 return -ENOMEM;
1061 }
1062
1063 *l = a;
1064 *r = b;
1065
1066 return 0;
1067}
1068
1069int free_and_strdup(char **p, const char *s) {
1070 char *t;
1071
1072 assert(p);
1073
7f546026 1074 /* Replaces a string pointer with a strdup()ed new string,
07630cea
LP
1075 * possibly freeing the old one. */
1076
1077 if (streq_ptr(*p, s))
1078 return 0;
1079
1080 if (s) {
1081 t = strdup(s);
1082 if (!t)
1083 return -ENOMEM;
1084 } else
1085 t = NULL;
1086
d6f2cd67 1087 free_and_replace(*p, t);
07630cea
LP
1088
1089 return 1;
1090}
1091
7f546026
ZJS
1092int free_and_strndup(char **p, const char *s, size_t l) {
1093 char *t;
1094
1095 assert(p);
1096 assert(s || l == 0);
1097
1098 /* Replaces a string pointer with a strndup()ed new string,
1099 * freeing the old one. */
1100
1101 if (!*p && !s)
1102 return 0;
1103
1104 if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
1105 return 0;
1106
1107 if (s) {
1108 t = strndup(s, l);
1109 if (!t)
1110 return -ENOMEM;
1111 } else
1112 t = NULL;
1113
1114 free_and_replace(*p, t);
1115 return 1;
1116}
1117
f3e2e81d 1118bool string_is_safe(const char *p) {
f3e2e81d
LP
1119 if (!p)
1120 return false;
1121
839d1b20
LP
1122 /* Checks if the specified string contains no quotes or control characters */
1123
a01080ce 1124 for (const char *t = p; *t; t++) {
f3e2e81d
LP
1125 if (*t > 0 && *t < ' ') /* no control characters */
1126 return false;
1127
1128 if (strchr(QUOTES "\\\x7f", *t))
1129 return false;
1130 }
1131
1132 return true;
1133}
53caaffd
LP
1134
1135char* string_erase(char *x) {
1136 if (!x)
1137 return NULL;
1138
1139 /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1140 * used them. */
1141 explicit_bzero_safe(x, strlen(x));
1142 return x;
1143}
8dd6491e
LP
1144
1145int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
1146 const char *p = s, *e = s;
1147 bool truncation_applied = false;
1148 char *copy;
1149 size_t n = 0;
1150
1151 assert(s);
1152
1153 /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1154 * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1155 * generated either. */
1156
1157 for (;;) {
1158 size_t k;
1159
1160 k = strcspn(p, "\n");
1161
1162 if (p[k] == 0) {
1163 if (k == 0) /* final empty line */
1164 break;
1165
1166 if (n >= n_lines) /* above threshold */
1167 break;
1168
1169 e = p + k; /* last line to include */
1170 break;
1171 }
1172
1173 assert(p[k] == '\n');
1174
1175 if (n >= n_lines)
1176 break;
1177
1178 if (k > 0)
1179 e = p + k;
1180
1181 p += k + 1;
1182 n++;
1183 }
1184
1185 /* e points after the last character we want to keep */
1186 if (isempty(e))
1187 copy = strdup(s);
1188 else {
1189 if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
1190 * isn't a new-line or a series of them */
1191 truncation_applied = true;
1192
1193 copy = strndup(s, e - s);
1194 }
1195 if (!copy)
1196 return -ENOMEM;
1197
1198 *ret = copy;
1199 return truncation_applied;
1200}
f6857fa6
LP
1201
1202int string_extract_line(const char *s, size_t i, char **ret) {
1203 const char *p = s;
1204 size_t c = 0;
1205
1206 /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1207 * and == 0 if we are looking at the last line or already beyond the last line. As special
1208 * optimization, if the first line is requested and the string only consists of one line we return
1209 * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1210 * common case. */
1211
1212 for (;;) {
1213 const char *q;
1214
1215 q = strchr(p, '\n');
1216 if (i == c) {
1217 /* The line we are looking for! */
1218
1219 if (q) {
1220 char *m;
1221
1222 m = strndup(p, q - p);
1223 if (!m)
1224 return -ENOMEM;
1225
1226 *ret = m;
1227 return !isempty(q + 1); /* more coming? */
1228 } else {
1229 if (p == s)
1230 *ret = NULL; /* Just use the input string */
1231 else {
1232 char *m;
1233
1234 m = strdup(p);
1235 if (!m)
1236 return -ENOMEM;
1237
1238 *ret = m;
1239 }
1240
1241 return 0; /* The end */
1242 }
1243 }
1244
1245 if (!q) {
1246 char *m;
1247
1248 /* No more lines, return empty line */
1249
1250 m = strdup("");
1251 if (!m)
1252 return -ENOMEM;
1253
1254 *ret = m;
1255 return 0; /* The end */
1256 }
1257
1258 p = q + 1;
1259 c++;
1260 }
1261}
53cd7f33 1262
46bf625a 1263int string_contains_word_strv(const char *string, const char *separators, char **words, const char **ret_word) {
53cd7f33
ZJS
1264 /* In the default mode with no separators specified, we split on whitespace and
1265 * don't coalesce separators. */
1266 const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
1267
46bf625a
ZJS
1268 const char *found = NULL;
1269
53cd7f33
ZJS
1270 for (const char *p = string;;) {
1271 _cleanup_free_ char *w = NULL;
1272 int r;
1273
1274 r = extract_first_word(&p, &w, separators, flags);
1275 if (r < 0)
1276 return r;
1277 if (r == 0)
46bf625a
ZJS
1278 break;
1279
1280 found = strv_find(words, w);
1281 if (found)
1282 break;
53cd7f33 1283 }
46bf625a
ZJS
1284
1285 if (ret_word)
1286 *ret_word = found;
1287 return !!found;
53cd7f33 1288}
8034b42c
ADT
1289
1290bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
1291 if (!s1 && !s2)
1292 return true;
1293 if (!s1 || !s2)
1294 return false;
1295
1296 if (!ok)
1297 ok = WHITESPACE;
1298
1299 for (; *s1 && *s2; s1++, s2++)
1300 if (*s1 != *s2)
1301 break;
1302
1303 return in_charset(s1, ok) && in_charset(s2, ok);
1304}
072f5f9b
YW
1305
1306char *string_replace_char(char *str, char old_char, char new_char) {
1307 assert(str);
1308 assert(old_char != '\0');
1309 assert(new_char != '\0');
1310 assert(old_char != new_char);
1311
1312 for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
1313 *p = new_char;
1314
1315 return str;
1316}
146f4482 1317
7153213e
LP
1318int make_cstring(const char *s, size_t n, MakeCStringMode mode, char **ret) {
1319 char *b;
1320
1321 assert(s || n == 0);
1322 assert(mode >= 0);
1323 assert(mode < _MAKE_CSTRING_MODE_MAX);
1324
1325 /* Converts a sized character buffer into a NUL-terminated NUL string, refusing if there are embedded
1326 * NUL bytes. Whether to expect a trailing NUL byte can be specified via 'mode' */
1327
1328 if (n == 0) {
1329 if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
1330 return -EINVAL;
1331
1332 if (!ret)
1333 return 0;
1334
1335 b = new0(char, 1);
1336 } else {
1337 const char *nul;
1338
1339 nul = memchr(s, 0, n);
1340 if (nul) {
1341 if (nul < s + n - 1 || /* embedded NUL? */
1342 mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1343 return -EINVAL;
1344
1345 n--;
1346 } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
1347 return -EINVAL;
1348
1349 if (!ret)
1350 return 0;
1351
1352 b = memdup_suffix0(s, n);
1353 }
1354 if (!b)
1355 return -ENOMEM;
1356
1357 *ret = b;
1358 return 0;
1359}
1360
146f4482
YW
1361size_t strspn_from_end(const char *str, const char *accept) {
1362 size_t n = 0;
1363
1364 if (isempty(str))
1365 return 0;
1366
1367 if (isempty(accept))
1368 return 0;
1369
1370 for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1371 n++;
1372
1373 return n;
1374}
e8bec624
LP
1375
1376char *strdupspn(const char *a, const char *accept) {
1377 if (isempty(a) || isempty(accept))
1378 return strdup("");
1379
1380 return strndup(a, strspn(a, accept));
1381}
1382
1383char *strdupcspn(const char *a, const char *reject) {
1384 if (isempty(a))
1385 return strdup("");
1386 if (isempty(reject))
1387 return strdup(a);
1388
1389 return strndup(a, strcspn(a, reject));
1390}
7b82d95f
LP
1391
1392char *find_line_startswith(const char *haystack, const char *needle) {
1393 char *p;
1394
1395 assert(haystack);
1396 assert(needle);
1397
1398 /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1399 * first character after it */
1400
1401 p = strstr(haystack, needle);
1402 if (!p)
1403 return NULL;
1404
1405 if (p > haystack)
1406 while (p[-1] != '\n') {
1407 p = strstr(p + 1, needle);
1408 if (!p)
1409 return NULL;
1410 }
1411
1412 return p + strlen(needle);
1413}
70cc7ed9
DDM
1414
1415char *startswith_strv(const char *string, char **strv) {
1416 char *found = NULL;
1417
1418 STRV_FOREACH(i, strv) {
1419 found = startswith(string, *i);
1420 if (found)
1421 break;
1422 }
1423
1424 return found;
1425}
f5c6b4f4
LP
1426
1427bool version_is_valid(const char *s) {
1428 if (isempty(s))
1429 return false;
1430
1431 if (!filename_part_is_valid(s))
1432 return false;
1433
1434 /* This is a superset of the characters used by semver. We additionally allow "," and "_". */
1435 if (!in_charset(s, ALPHANUMERICAL ".,_-+"))
1436 return false;
1437
1438 return true;
1439}