]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/string-util.c
basic/string-util: use strdup_to() in string_extract_line()
[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) {
be492020 538 dst = mempcpy(dst, p, slen);
cb558ab2
ZJS
539 p += slen;
540 } else
541 p = utf8_next_char(p);
542 }
543
544 memcpy_safe(dst, j, len2);
545 dst[len2] = '\0';
07630cea
LP
546
547 return e;
548}
549
8409f688
ZJS
550char *cellescape(char *buf, size_t len, const char *s) {
551 /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
552 * characters are copied as they are, everything else is escaped. The result
553 * is different then if escaping and ellipsization was performed in two
554 * separate steps, because each sequence is either stored in full or skipped.
555 *
556 * This function should be used for logging about strings which expected to
557 * be plain ASCII in a safe way.
558 *
559 * An ellipsis will be used if s is too long. It was always placed at the
560 * very end.
561 */
562
a01080ce 563 size_t i = 0, last_char_width[4] = {}, k = 0;
61f6e276
LP
564
565 assert(len > 0); /* at least a terminating NUL */
8409f688 566
61f6e276
LP
567 for (;;) {
568 char four[4];
569 int w;
8409f688 570
61f6e276 571 if (*s == 0) /* terminating NUL detected? then we are done! */
8409f688 572 goto done;
61f6e276
LP
573
574 w = cescape_char(*s, four);
575 if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
576 * ellipsize at the previous location */
577 break;
578
579 /* OK, there was space, let's add this escaped character to the buffer */
580 memcpy(buf + i, four, w);
581 i += w;
582
583 /* And remember its width in the ring buffer */
584 last_char_width[k] = w;
585 k = (k + 1) % 4;
586
587 s++;
8409f688
ZJS
588 }
589
61f6e276
LP
590 /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
591 * characters ideally, but the buffer is shorter than that in the first place take what we can get */
a01080ce 592 for (size_t j = 0; j < ELEMENTSOF(last_char_width); j++) {
61f6e276
LP
593
594 if (i + 4 <= len) /* nice, we reached our space goal */
595 break;
596
597 k = k == 0 ? 3 : k - 1;
598 if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
599 break;
600
601 assert(i >= last_char_width[k]);
602 i -= last_char_width[k];
8409f688
ZJS
603 }
604
61f6e276
LP
605 if (i + 4 <= len) /* yay, enough space */
606 i += write_ellipsis(buf + i, false);
607 else if (i + 3 <= len) { /* only space for ".." */
608 buf[i++] = '.';
609 buf[i++] = '.';
610 } else if (i + 2 <= len) /* only space for a single "." */
611 buf[i++] = '.';
612 else
613 assert(i + 1 <= len);
614
8409f688
ZJS
615 done:
616 buf[i] = '\0';
617 return buf;
618}
619
07630cea
LP
620char* strshorten(char *s, size_t l) {
621 assert(s);
622
d49dc7bb
LP
623 if (l >= SIZE_MAX-1) /* Would not change anything */
624 return s;
625
47b33c7d 626 if (strnlen(s, l+1) > l)
07630cea
LP
627 s[l] = 0;
628
629 return s;
630}
631
2812017c 632int strgrowpad0(char **s, size_t l) {
8e479584
LP
633 size_t sz;
634
2812017c
DDM
635 assert(s);
636
8e479584
LP
637 if (*s) {
638 sz = strlen(*s) + 1;
639 if (sz >= l) /* never shrink */
640 return 0;
641 } else
642 sz = 0;
643
2812017c
DDM
644 char *q = realloc(*s, l);
645 if (!q)
646 return -ENOMEM;
8e479584 647
2812017c
DDM
648 *s = q;
649
2812017c
DDM
650 memzero(*s + sz, l - sz);
651 return 0;
652}
653
07630cea 654char *strreplace(const char *text, const char *old_string, const char *new_string) {
319a4f4b 655 size_t l, old_len, new_len;
9d73565a 656 char *t, *ret = NULL;
07630cea 657 const char *f;
07630cea 658
07630cea
LP
659 assert(old_string);
660 assert(new_string);
661
9d73565a
LP
662 if (!text)
663 return NULL;
664
07630cea
LP
665 old_len = strlen(old_string);
666 new_len = strlen(new_string);
667
668 l = strlen(text);
319a4f4b 669 if (!GREEDY_REALLOC(ret, l+1))
07630cea
LP
670 return NULL;
671
672 f = text;
9d73565a 673 t = ret;
07630cea 674 while (*f) {
07630cea
LP
675 size_t d, nl;
676
677 if (!startswith(f, old_string)) {
678 *(t++) = *(f++);
679 continue;
680 }
681
9d73565a 682 d = t - ret;
07630cea 683 nl = l - old_len + new_len;
9d73565a 684
319a4f4b 685 if (!GREEDY_REALLOC(ret, nl + 1))
9d73565a 686 return mfree(ret);
07630cea
LP
687
688 l = nl;
9d73565a 689 t = ret + d;
07630cea
LP
690
691 t = stpcpy(t, new_string);
692 f += old_len;
693 }
694
695 *t = 0;
9d73565a 696 return ret;
07630cea
LP
697}
698
6fb05690
LP
699static void advance_offsets(
700 ssize_t diff,
701 size_t offsets[2], /* note: we can't use [static 2] here, since this may be NULL */
702 size_t shift[static 2],
703 size_t size) {
704
b4766d5f
ZJS
705 if (!offsets)
706 return;
707
6fb05690
LP
708 assert(shift);
709
b4766d5f
ZJS
710 if ((size_t) diff < offsets[0])
711 shift[0] += size;
712 if ((size_t) diff < offsets[1])
713 shift[1] += size;
714}
715
716char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
62a3fc6d 717 const char *begin = NULL;
07630cea
LP
718 enum {
719 STATE_OTHER,
720 STATE_ESCAPE,
695a944c
LP
721 STATE_CSI,
722 STATE_CSO,
07630cea 723 } state = STATE_OTHER;
2485b7e2
YW
724 _cleanup_(memstream_done) MemStream m = {};
725 size_t isz, shift[2] = {}, n_carriage_returns = 0;
726 FILE *f;
07630cea
LP
727
728 assert(ibuf);
729 assert(*ibuf);
730
695a944c
LP
731 /* This does three things:
732 *
733 * 1. Replaces TABs by 8 spaces
734 * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
735 * 3. Strips ANSI operating system sequences (CSO), i.e. ESC ']' … BEL sequences
62a3fc6d
ZJS
736 * 4. Strip trailing \r characters (since they would "move the cursor", but have no
737 * other effect).
695a944c 738 *
2fe21124
ZJS
739 * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
740 * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
741 * supposed to suppress the most basic formatting noise, but nothing else.
695a944c
LP
742 *
743 * Why care for CSO sequences? Well, to undo what terminal_urlify() and friends generate. */
07630cea
LP
744
745 isz = _isz ? *_isz : strlen(*ibuf);
746
2fe21124
ZJS
747 /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
748 * created f here and it doesn't leave our scope. */
2485b7e2 749 f = memstream_init(&m);
07630cea
LP
750 if (!f)
751 return NULL;
752
62a3fc6d 753 for (const char *i = *ibuf; i < *ibuf + isz + 1; i++) {
07630cea
LP
754
755 switch (state) {
756
757 case STATE_OTHER:
758 if (i >= *ibuf + isz) /* EOT */
759 break;
62a3fc6d
ZJS
760
761 if (*i == '\r') {
762 n_carriage_returns++;
763 break;
764 } else if (*i == '\n')
765 /* Ignore carriage returns before new line */
766 n_carriage_returns = 0;
767 for (; n_carriage_returns > 0; n_carriage_returns--)
768 fputc('\r', f);
769
770 if (*i == '\x1B')
07630cea 771 state = STATE_ESCAPE;
b4766d5f 772 else if (*i == '\t') {
0d536673 773 fputs(" ", f);
b4766d5f
ZJS
774 advance_offsets(i - *ibuf, highlight, shift, 7);
775 } else
0d536673 776 fputc(*i, f);
b4766d5f 777
07630cea
LP
778 break;
779
780 case STATE_ESCAPE:
62a3fc6d
ZJS
781 assert(n_carriage_returns == 0);
782
07630cea 783 if (i >= *ibuf + isz) { /* EOT */
0d536673 784 fputc('\x1B', f);
b4766d5f 785 advance_offsets(i - *ibuf, highlight, shift, 1);
07630cea 786 break;
695a944c
LP
787 } else if (*i == '[') { /* ANSI CSI */
788 state = STATE_CSI;
789 begin = i + 1;
790 } else if (*i == ']') { /* ANSI CSO */
791 state = STATE_CSO;
07630cea
LP
792 begin = i + 1;
793 } else {
0d536673
LP
794 fputc('\x1B', f);
795 fputc(*i, f);
b4766d5f 796 advance_offsets(i - *ibuf, highlight, shift, 1);
07630cea
LP
797 state = STATE_OTHER;
798 }
799
800 break;
801
695a944c 802 case STATE_CSI:
62a3fc6d 803 assert(n_carriage_returns == 0);
07630cea 804
695a944c
LP
805 if (i >= *ibuf + isz || /* EOT … */
806 !strchr("01234567890;m", *i)) { /* … or invalid chars in sequence */
0d536673
LP
807 fputc('\x1B', f);
808 fputc('[', f);
b4766d5f 809 advance_offsets(i - *ibuf, highlight, shift, 2);
07630cea
LP
810 state = STATE_OTHER;
811 i = begin-1;
812 } else if (*i == 'm')
813 state = STATE_OTHER;
695a944c
LP
814
815 break;
816
817 case STATE_CSO:
62a3fc6d 818 assert(n_carriage_returns == 0);
695a944c
LP
819
820 if (i >= *ibuf + isz || /* EOT … */
821 (*i != '\a' && (uint8_t) *i < 32U) || (uint8_t) *i > 126U) { /* … or invalid chars in sequence */
822 fputc('\x1B', f);
823 fputc(']', f);
824 advance_offsets(i - *ibuf, highlight, shift, 2);
825 state = STATE_OTHER;
826 i = begin-1;
827 } else if (*i == '\a')
828 state = STATE_OTHER;
829
07630cea
LP
830 break;
831 }
832 }
833
2485b7e2
YW
834 char *obuf;
835 if (memstream_finalize(&m, &obuf, _isz) < 0)
f392dfb5 836 return NULL;
07630cea 837
6fb05690 838 free_and_replace(*ibuf, obuf);
07630cea 839
b4766d5f
ZJS
840 if (highlight) {
841 highlight[0] += shift[0];
842 highlight[1] += shift[1];
843 }
844
6fb05690 845 return *ibuf;
07630cea
LP
846}
847
c2bc710b 848char *strextend_with_separator_internal(char **x, const char *separator, ...) {
bb8ad9ea 849 size_t f, l, l_separator;
c2bc710b
LP
850 bool need_separator;
851 char *nr, *p;
bb8ad9ea 852 va_list ap;
07630cea
LP
853
854 assert(x);
855
7bf7ce28 856 l = f = strlen_ptr(*x);
07630cea 857
bb8ad9ea
LP
858 need_separator = !isempty(*x);
859 l_separator = strlen_ptr(separator);
860
861 va_start(ap, separator);
07630cea
LP
862 for (;;) {
863 const char *t;
864 size_t n;
865
866 t = va_arg(ap, const char *);
867 if (!t)
868 break;
869
870 n = strlen(t);
bb8ad9ea
LP
871
872 if (need_separator)
873 n += l_separator;
874
c2bc710b 875 if (n >= SIZE_MAX - l) {
07630cea
LP
876 va_end(ap);
877 return NULL;
878 }
879
880 l += n;
bb8ad9ea 881 need_separator = true;
07630cea
LP
882 }
883 va_end(ap);
884
bb8ad9ea
LP
885 need_separator = !isempty(*x);
886
2a4e1fd0 887 nr = realloc(*x, GREEDY_ALLOC_ROUND_UP(l+1));
c2bc710b 888 if (!nr)
07630cea
LP
889 return NULL;
890
c2bc710b
LP
891 *x = nr;
892 p = nr + f;
07630cea 893
bb8ad9ea 894 va_start(ap, separator);
07630cea
LP
895 for (;;) {
896 const char *t;
897
898 t = va_arg(ap, const char *);
899 if (!t)
900 break;
901
bb8ad9ea
LP
902 if (need_separator && separator)
903 p = stpcpy(p, separator);
904
07630cea 905 p = stpcpy(p, t);
bb8ad9ea
LP
906
907 need_separator = true;
07630cea
LP
908 }
909 va_end(ap);
910
c2bc710b 911 assert(p == nr + l);
bb8ad9ea 912
07630cea 913 *p = 0;
07630cea 914
c2bc710b 915 return p;
07630cea
LP
916}
917
6b13ca8a
YW
918int strextendf_with_separator(char **x, const char *separator, const char *format, ...) {
919 size_t m, a, l_separator;
e9b88a6d
LP
920 va_list ap;
921 int l;
922
923 /* Appends a formatted string to the specified string. Don't use this in inner loops, since then
924 * we'll spend a tonload of time in determining the length of the string passed in, over and over
925 * again. */
926
927 assert(x);
928 assert(format);
929
6b13ca8a
YW
930 l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
931
e9b88a6d
LP
932 /* Let's try to use the allocated buffer, if there's room at the end still. Otherwise let's extend by 64 chars. */
933 if (*x) {
934 m = strlen(*x);
6df28e1f 935 a = MALLOC_SIZEOF_SAFE(*x);
e9b88a6d
LP
936 assert(a >= m + 1);
937 } else
938 m = a = 0;
939
6b13ca8a 940 if (a - m < 17 + l_separator) { /* if there's less than 16 chars space, then enlarge the buffer first */
e9b88a6d
LP
941 char *n;
942
6b13ca8a
YW
943 if (_unlikely_(l_separator > SIZE_MAX - 64)) /* overflow check #1 */
944 return -ENOMEM;
945 if (_unlikely_(m > SIZE_MAX - 64 - l_separator)) /* overflow check #2 */
e9b88a6d
LP
946 return -ENOMEM;
947
6b13ca8a 948 n = realloc(*x, m + 64 + l_separator);
e9b88a6d
LP
949 if (!n)
950 return -ENOMEM;
951
952 *x = n;
6df28e1f 953 a = MALLOC_SIZEOF_SAFE(*x);
e9b88a6d
LP
954 }
955
956 /* Now, let's try to format the string into it */
6b13ca8a 957 memcpy_safe(*x + m, separator, l_separator);
e9b88a6d 958 va_start(ap, format);
6b13ca8a 959 l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
e9b88a6d
LP
960 va_end(ap);
961
962 assert(l >= 0);
963
6b13ca8a 964 if ((size_t) l < a - m - l_separator) {
e9b88a6d
LP
965 char *n;
966
967 /* Nice! This worked. We are done. But first, let's return the extra space we don't
968 * need. This should be a cheap operation, since we only lower the allocation size here,
969 * never increase. */
6b13ca8a 970 n = realloc(*x, m + (size_t) l + l_separator + 1);
e9b88a6d
LP
971 if (n)
972 *x = n;
973 } else {
974 char *n;
975
976 /* Wasn't enough. Then let's allocate exactly what we need. */
977
6b13ca8a 978 if (_unlikely_((size_t) l > SIZE_MAX - (l_separator + 1))) /* overflow check #1 */
e9b88a6d 979 goto oom;
6b13ca8a 980 if (_unlikely_(m > SIZE_MAX - ((size_t) l + l_separator + 1))) /* overflow check #2 */
e9b88a6d
LP
981 goto oom;
982
6b13ca8a 983 a = m + (size_t) l + l_separator + 1;
e9b88a6d
LP
984 n = realloc(*x, a);
985 if (!n)
986 goto oom;
987 *x = n;
988
989 va_start(ap, format);
6b13ca8a 990 l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
e9b88a6d
LP
991 va_end(ap);
992
6b13ca8a 993 assert((size_t) l < a - m - l_separator);
e9b88a6d
LP
994 }
995
996 return 0;
997
998oom:
999 /* truncate the bytes added after the first vsnprintf() attempt again */
1000 (*x)[m] = 0;
1001 return -ENOMEM;
1002}
1003
6b9f6007
LP
1004char *strextendn(char **x, const char *s, size_t l) {
1005 assert(x);
1006 assert(s || l == 0);
1007
1008 if (l == SIZE_MAX)
1009 l = strlen_ptr(s);
1010 else if (l > 0)
1011 l = strnlen(s, l); /* ignore trailing noise */
1012
1013 if (l > 0 || !*x) {
1014 size_t q;
1015 char *m;
1016
1017 q = strlen_ptr(*x);
1018 m = realloc(*x, q + l + 1);
1019 if (!m)
1020 return NULL;
1021
1022 memcpy_safe(m + q, s, l);
1023 m[q + l] = 0;
1024
1025 *x = m;
1026 }
1027
1028 return *x;
1029}
1030
07630cea 1031char *strrep(const char *s, unsigned n) {
07630cea 1032 char *r, *p;
fe96c0f8 1033 size_t l;
07630cea
LP
1034
1035 assert(s);
1036
1037 l = strlen(s);
1038 p = r = malloc(l * n + 1);
1039 if (!r)
1040 return NULL;
1041
fe96c0f8 1042 for (unsigned i = 0; i < n; i++)
07630cea
LP
1043 p = stpcpy(p, s);
1044
1045 *p = 0;
1046 return r;
1047}
1048
1049int split_pair(const char *s, const char *sep, char **l, char **r) {
1050 char *x, *a, *b;
1051
1052 assert(s);
1053 assert(sep);
1054 assert(l);
1055 assert(r);
1056
1057 if (isempty(sep))
1058 return -EINVAL;
1059
1060 x = strstr(s, sep);
1061 if (!x)
1062 return -EINVAL;
1063
1064 a = strndup(s, x - s);
1065 if (!a)
1066 return -ENOMEM;
1067
1068 b = strdup(x + strlen(sep));
1069 if (!b) {
1070 free(a);
1071 return -ENOMEM;
1072 }
1073
1074 *l = a;
1075 *r = b;
1076
1077 return 0;
1078}
1079
1080int free_and_strdup(char **p, const char *s) {
1081 char *t;
1082
1083 assert(p);
1084
7f546026 1085 /* Replaces a string pointer with a strdup()ed new string,
07630cea
LP
1086 * possibly freeing the old one. */
1087
1088 if (streq_ptr(*p, s))
1089 return 0;
1090
1091 if (s) {
1092 t = strdup(s);
1093 if (!t)
1094 return -ENOMEM;
1095 } else
1096 t = NULL;
1097
d6f2cd67 1098 free_and_replace(*p, t);
07630cea
LP
1099
1100 return 1;
1101}
1102
7f546026
ZJS
1103int free_and_strndup(char **p, const char *s, size_t l) {
1104 char *t;
1105
1106 assert(p);
1107 assert(s || l == 0);
1108
1109 /* Replaces a string pointer with a strndup()ed new string,
1110 * freeing the old one. */
1111
1112 if (!*p && !s)
1113 return 0;
1114
1115 if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
1116 return 0;
1117
1118 if (s) {
1119 t = strndup(s, l);
1120 if (!t)
1121 return -ENOMEM;
1122 } else
1123 t = NULL;
1124
1125 free_and_replace(*p, t);
1126 return 1;
1127}
1128
892c5902
ZJS
1129int strdup_to_full(char **ret, const char *src) {
1130 if (!src) {
1131 if (ret)
1132 *ret = NULL;
1133
1134 return 0;
1135 } else {
1136 if (ret) {
1137 char *t = strdup(src);
1138 if (!t)
1139 return -ENOMEM;
1140 *ret = t;
1141 }
1142
1143 return 1;
1144 }
1145};
1146
f3e2e81d 1147bool string_is_safe(const char *p) {
f3e2e81d
LP
1148 if (!p)
1149 return false;
1150
839d1b20
LP
1151 /* Checks if the specified string contains no quotes or control characters */
1152
a01080ce 1153 for (const char *t = p; *t; t++) {
f3e2e81d
LP
1154 if (*t > 0 && *t < ' ') /* no control characters */
1155 return false;
1156
1157 if (strchr(QUOTES "\\\x7f", *t))
1158 return false;
1159 }
1160
1161 return true;
1162}
53caaffd
LP
1163
1164char* string_erase(char *x) {
1165 if (!x)
1166 return NULL;
1167
1168 /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1169 * used them. */
1170 explicit_bzero_safe(x, strlen(x));
1171 return x;
1172}
8dd6491e
LP
1173
1174int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
1175 const char *p = s, *e = s;
1176 bool truncation_applied = false;
1177 char *copy;
1178 size_t n = 0;
1179
1180 assert(s);
1181
1182 /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1183 * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1184 * generated either. */
1185
1186 for (;;) {
1187 size_t k;
1188
1189 k = strcspn(p, "\n");
1190
1191 if (p[k] == 0) {
1192 if (k == 0) /* final empty line */
1193 break;
1194
1195 if (n >= n_lines) /* above threshold */
1196 break;
1197
1198 e = p + k; /* last line to include */
1199 break;
1200 }
1201
1202 assert(p[k] == '\n');
1203
1204 if (n >= n_lines)
1205 break;
1206
1207 if (k > 0)
1208 e = p + k;
1209
1210 p += k + 1;
1211 n++;
1212 }
1213
1214 /* e points after the last character we want to keep */
1215 if (isempty(e))
1216 copy = strdup(s);
1217 else {
1218 if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
1219 * isn't a new-line or a series of them */
1220 truncation_applied = true;
1221
1222 copy = strndup(s, e - s);
1223 }
1224 if (!copy)
1225 return -ENOMEM;
1226
1227 *ret = copy;
1228 return truncation_applied;
1229}
f6857fa6
LP
1230
1231int string_extract_line(const char *s, size_t i, char **ret) {
1232 const char *p = s;
1233 size_t c = 0;
1234
1235 /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1236 * and == 0 if we are looking at the last line or already beyond the last line. As special
1237 * optimization, if the first line is requested and the string only consists of one line we return
1238 * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1239 * common case. */
1240
1241 for (;;) {
1242 const char *q;
1243
1244 q = strchr(p, '\n');
1245 if (i == c) {
1246 /* The line we are looking for! */
1247
1248 if (q) {
1249 char *m;
1250
1251 m = strndup(p, q - p);
1252 if (!m)
1253 return -ENOMEM;
1254
1255 *ret = m;
f174b294
ZJS
1256 return !isempty(q + 1); /* More coming? */
1257 } else
1258 /* Tell the caller to use the input string if equal */
1259 return strdup_to(ret, p != s ? p : NULL);
f6857fa6
LP
1260 }
1261
f174b294 1262 if (!q)
f6857fa6 1263 /* No more lines, return empty line */
f174b294 1264 return strdup_to(ret, "");
f6857fa6
LP
1265
1266 p = q + 1;
1267 c++;
1268 }
1269}
53cd7f33 1270
46bf625a 1271int string_contains_word_strv(const char *string, const char *separators, char **words, const char **ret_word) {
53cd7f33
ZJS
1272 /* In the default mode with no separators specified, we split on whitespace and
1273 * don't coalesce separators. */
1274 const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
1275
46bf625a
ZJS
1276 const char *found = NULL;
1277
53cd7f33
ZJS
1278 for (const char *p = string;;) {
1279 _cleanup_free_ char *w = NULL;
1280 int r;
1281
1282 r = extract_first_word(&p, &w, separators, flags);
1283 if (r < 0)
1284 return r;
1285 if (r == 0)
46bf625a
ZJS
1286 break;
1287
1288 found = strv_find(words, w);
1289 if (found)
1290 break;
53cd7f33 1291 }
46bf625a
ZJS
1292
1293 if (ret_word)
1294 *ret_word = found;
1295 return !!found;
53cd7f33 1296}
8034b42c
ADT
1297
1298bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
1299 if (!s1 && !s2)
1300 return true;
1301 if (!s1 || !s2)
1302 return false;
1303
1304 if (!ok)
1305 ok = WHITESPACE;
1306
1307 for (; *s1 && *s2; s1++, s2++)
1308 if (*s1 != *s2)
1309 break;
1310
1311 return in_charset(s1, ok) && in_charset(s2, ok);
1312}
072f5f9b
YW
1313
1314char *string_replace_char(char *str, char old_char, char new_char) {
1315 assert(str);
1316 assert(old_char != '\0');
1317 assert(new_char != '\0');
1318 assert(old_char != new_char);
1319
1320 for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
1321 *p = new_char;
1322
1323 return str;
1324}
146f4482 1325
7153213e
LP
1326int make_cstring(const char *s, size_t n, MakeCStringMode mode, char **ret) {
1327 char *b;
1328
1329 assert(s || n == 0);
1330 assert(mode >= 0);
1331 assert(mode < _MAKE_CSTRING_MODE_MAX);
1332
1333 /* Converts a sized character buffer into a NUL-terminated NUL string, refusing if there are embedded
1334 * NUL bytes. Whether to expect a trailing NUL byte can be specified via 'mode' */
1335
1336 if (n == 0) {
1337 if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
1338 return -EINVAL;
1339
1340 if (!ret)
1341 return 0;
1342
1343 b = new0(char, 1);
1344 } else {
1345 const char *nul;
1346
1347 nul = memchr(s, 0, n);
1348 if (nul) {
1349 if (nul < s + n - 1 || /* embedded NUL? */
1350 mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1351 return -EINVAL;
1352
1353 n--;
1354 } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
1355 return -EINVAL;
1356
1357 if (!ret)
1358 return 0;
1359
1360 b = memdup_suffix0(s, n);
1361 }
1362 if (!b)
1363 return -ENOMEM;
1364
1365 *ret = b;
1366 return 0;
1367}
1368
146f4482
YW
1369size_t strspn_from_end(const char *str, const char *accept) {
1370 size_t n = 0;
1371
1372 if (isempty(str))
1373 return 0;
1374
1375 if (isempty(accept))
1376 return 0;
1377
1378 for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1379 n++;
1380
1381 return n;
1382}
e8bec624
LP
1383
1384char *strdupspn(const char *a, const char *accept) {
1385 if (isempty(a) || isempty(accept))
1386 return strdup("");
1387
1388 return strndup(a, strspn(a, accept));
1389}
1390
1391char *strdupcspn(const char *a, const char *reject) {
1392 if (isempty(a))
1393 return strdup("");
1394 if (isempty(reject))
1395 return strdup(a);
1396
1397 return strndup(a, strcspn(a, reject));
1398}
7b82d95f
LP
1399
1400char *find_line_startswith(const char *haystack, const char *needle) {
1401 char *p;
1402
1403 assert(haystack);
1404 assert(needle);
1405
1406 /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1407 * first character after it */
1408
1409 p = strstr(haystack, needle);
1410 if (!p)
1411 return NULL;
1412
1413 if (p > haystack)
1414 while (p[-1] != '\n') {
1415 p = strstr(p + 1, needle);
1416 if (!p)
1417 return NULL;
1418 }
1419
1420 return p + strlen(needle);
1421}
70cc7ed9 1422
f5c6b4f4
LP
1423bool version_is_valid(const char *s) {
1424 if (isempty(s))
1425 return false;
1426
1427 if (!filename_part_is_valid(s))
1428 return false;
1429
1430 /* This is a superset of the characters used by semver. We additionally allow "," and "_". */
1431 if (!in_charset(s, ALPHANUMERICAL ".,_-+"))
1432 return false;
1433
1434 return true;
1435}
c46f5680
JB
1436
1437bool version_is_valid_versionspec(const char *s) {
1438 if (!filename_part_is_valid(s))
1439 return false;
1440
1441 if (!in_charset(s, ALPHANUMERICAL "-.~^"))
1442 return false;
1443
1444 return true;
1445}
7ef5b0a4
LP
1446
1447ssize_t strlevenshtein(const char *x, const char *y) {
1448 _cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
1449 size_t xl, yl;
1450
1451 /* This is inspired from the Linux kernel's Levenshtein implementation */
1452
1453 if (streq_ptr(x, y))
1454 return 0;
1455
1456 xl = strlen_ptr(x);
1457 if (xl > SSIZE_MAX)
1458 return -E2BIG;
1459
1460 yl = strlen_ptr(y);
1461 if (yl > SSIZE_MAX)
1462 return -E2BIG;
1463
1464 if (isempty(x))
1465 return yl;
1466 if (isempty(y))
1467 return xl;
1468
1469 t0 = new0(size_t, yl + 1);
1470 if (!t0)
1471 return -ENOMEM;
1472 t1 = new0(size_t, yl + 1);
1473 if (!t1)
1474 return -ENOMEM;
1475 t2 = new0(size_t, yl + 1);
1476 if (!t2)
1477 return -ENOMEM;
1478
1479 for (size_t i = 0; i <= yl; i++)
1480 t1[i] = i;
1481
1482 for (size_t i = 0; i < xl; i++) {
1483 t2[0] = i + 1;
1484
1485 for (size_t j = 0; j < yl; j++) {
1486 /* Substitution */
1487 t2[j+1] = t1[j] + (x[i] != y[j]);
1488
1489 /* Swap */
1490 if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
1491 t2[j+1] = t0[j-1] + 1;
1492
1493 /* Deletion */
1494 if (t2[j+1] > t1[j+1] + 1)
1495 t2[j+1] = t1[j+1] + 1;
1496
1497 /* Insertion */
1498 if (t2[j+1] > t2[j] + 1)
1499 t2[j+1] = t2[j] + 1;
1500 }
1501
1502 size_t *dummy = t0;
1503 t0 = t1;
1504 t1 = t2;
1505 t2 = dummy;
1506 }
1507
1508 return t1[yl];
1509}
63566c6b
LP
1510
1511char *strrstr(const char *haystack, const char *needle) {
9e44842a 1512 /* Like strstr() but returns the last rather than the first occurrence of "needle" in "haystack". */
63566c6b
LP
1513
1514 if (!haystack || !needle)
1515 return NULL;
1516
9e44842a 1517 /* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
63566c6b 1518 * last char, not before. */
aa9ff6c2 1519 if (*needle == 0)
63566c6b
LP
1520 return strchr(haystack, 0);
1521
aa9ff6c2
R
1522 for (const char *p = strstr(haystack, needle), *q; p; p = q) {
1523 q = strstr(p + 1, needle);
1524 if (!q)
1525 return (char *) p;
1526 }
1527 return NULL;
63566c6b 1528}