• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 29378720657

14 Jul 2026 11:44PM UTC coverage: 72.936% (-0.004%) from 72.94%
29378720657

push

github

yuwata
sd-dhcp-relay: fix off-by-one when discarding BOOTREQUEST messages by hops count

According to RFC specifications
```
RFC 1542 section 4.1.1 states:
The relay agent MUST silently discard BOOTREQUEST messages whose 'hops'
   field exceeds the value 16."
```

"Exceeds the value 16" means hops > 16, i.e. a message that arrives with
hops == 16 is still valid and must be relayed (after which its hops field
becomes 17). The code used ">= 16", which silently dropped a valid message
that had legitimately traversed exactly 16 relay agents, one hop too early.

This matches the wording of the adjacent comment, which already says
"exceeds the value 16".

2 of 2 new or added lines in 2 files covered. (100.0%)

4253 existing lines in 80 files now uncovered.

345834 of 474164 relevant lines covered (72.94%)

1318659.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.36
/src/basic/string-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdio.h>
4

5
#include "alloc-util.h"
6
#include "escape.h"
7
#include "extract-word.h"
8
#include "glyph-util.h"
9
#include "gunicode.h"
10
#include "locale-util.h"
11
#include "log.h"
12
#include "memory-util.h"
13
#include "memstream-util.h"
14
#include "path-util.h"
15
#include "string-util.h"
16
#include "strv.h"
17
#include "terminal-util.h"
18
#include "utf8.h"
19

20
char* first_word(const char *s, const char *word) {
4,344,801✔
21
        assert(s);
4,344,801✔
22
        assert(word);
4,344,801✔
23

24
        /* Checks if the string starts with the specified word, either followed by NUL or by whitespace.
25
         * Returns a pointer to the NUL or the first character after the whitespace. */
26

27
        if (isempty(word))
4,344,801✔
28
                return (char*) s;
29

30
        const char *p = startswith(s, word);
4,344,800✔
31
        if (!p)
4,344,800✔
32
                return NULL;
33
        if (*p == '\0')
251,325✔
34
                return (char*) p;
35

36
        const char *nw = skip_leading_chars(p, WHITESPACE);
251,324✔
37
        if (p == nw)
251,324✔
38
                return NULL;
913✔
39

40
        return (char*) nw;
41
}
42

43
char* strextendn(char **x, const char *s, size_t l) {
33,490✔
44
        assert(x);
33,490✔
45
        assert(s || l == 0);
33,490✔
46

47
        if (l > 0)
33,490✔
48
                l = strnlen(s, l); /* ignore trailing noise */
33,156✔
49

50
        if (l > 0 || !*x) {
33,490✔
51
                size_t q;
33,330✔
52
                char *m;
33,330✔
53

54
                q = strlen_ptr(*x);
33,330✔
55
                m = realloc(*x, q + l + 1);
33,330✔
56
                if (!m)
33,330✔
57
                        return NULL;
58

59
                *mempcpy_typesafe(m + q, s, l) = 0;
33,330✔
60

61
                *x = m;
33,330✔
62
        }
63

64
        return *x;
33,490✔
65
}
66

67
char* strstrip(char *s) {
10,386,330✔
68
        if (!s)
10,386,330✔
69
                return NULL;
70

71
        /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
72

73
        return delete_trailing_chars(skip_leading_chars(s, WHITESPACE), WHITESPACE);
10,383,615✔
74
}
75

76
char* delete_chars(char *s, const char *bad) {
9✔
77
        char *f, *t;
9✔
78

79
        /* Drops all specified bad characters, regardless where in the string */
80

81
        if (!s)
9✔
82
                return NULL;
83

84
        if (!bad)
9✔
85
                bad = WHITESPACE;
×
86

87
        for (f = s, t = s; *f; f++) {
131✔
88
                if (strchr(bad, *f))
122✔
89
                        continue;
67✔
90

91
                *(t++) = *f;
55✔
92
        }
93

94
        *t = 0;
9✔
95

96
        return s;
9✔
97
}
98

99
char* delete_trailing_chars(char *s, const char *bad) {
12,033,820✔
100
        char *c = s;
12,033,820✔
101

102
        /* Drops all specified bad characters, at the end of the string */
103

104
        if (!s)
12,033,820✔
105
                return NULL;
106

107
        if (!bad)
12,033,820✔
108
                bad = WHITESPACE;
89,099✔
109

110
        for (char *p = s; *p; p++)
390,979,107✔
111
                if (!strchr(bad, *p))
378,945,287✔
112
                        c = p + 1;
364,059,906✔
113

114
        *c = 0;
12,033,820✔
115

116
        return s;
12,033,820✔
117
}
118

119
char* truncate_nl_full(char *s, size_t *ret_len) {
2,981,753✔
120
        size_t n;
2,981,753✔
121

122
        assert(s);
2,981,753✔
123

124
        n = strcspn(s, NEWLINE);
2,981,753✔
125
        s[n] = '\0';
2,981,753✔
126
        if (ret_len)
2,981,753✔
127
                *ret_len = n;
6✔
128
        return s;
2,981,753✔
129
}
130

131
char ascii_tolower(char x) {
54,741,692✔
132

133
        if (x >= 'A' && x <= 'Z')
54,741,692✔
134
                return x - 'A' + 'a';
3,785,785✔
135

136
        return x;
137
}
138

139
char ascii_toupper(char x) {
323,953✔
140

141
        if (x >= 'a' && x <= 'z')
323,953✔
142
                return x - 'a' + 'A';
197,995✔
143

144
        return x;
145
}
146

147
char* ascii_strlower(char *s) {
24,160✔
148
        assert(s);
24,160✔
149

150
        for (char *p = s; *p; p++)
156,931✔
151
                *p = ascii_tolower(*p);
132,771✔
152

153
        return s;
24,160✔
154
}
155

156
char* ascii_strupper(char *s) {
22,896✔
157
        assert(s);
22,896✔
158

159
        for (char *p = s; *p; p++)
346,719✔
160
                *p = ascii_toupper(*p);
323,823✔
161

162
        return s;
22,896✔
163
}
164

165
char* ascii_strlower_n(char *s, size_t n) {
1,842,218✔
166
        assert(n <= 0 || s);
1,842,218✔
167

168
        if (n <= 0)
1,842,218✔
169
                return s;
170

171
        for (size_t i = 0; i < n; i++)
15,522,311✔
172
                s[i] = ascii_tolower(s[i]);
13,680,440✔
173

174
        return s;
175
}
176

177
int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
2,676,747✔
178

179
        assert(a);
2,676,747✔
180
        assert(b);
2,676,747✔
181

182
        for (; n > 0; a++, b++, n--) {
22,507,505✔
183
                int x, y;
20,459,252✔
184

185
                x = (int) (uint8_t) ascii_tolower(*a);
20,459,252✔
186
                y = (int) (uint8_t) ascii_tolower(*b);
20,459,252✔
187

188
                if (x != y)
20,459,252✔
189
                        return x - y;
628,494✔
190
        }
191

192
        return 0;
193
}
194

195
int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
1,096,045✔
196
        int r;
1,096,045✔
197

198
        r = ascii_strcasecmp_n(a, b, MIN(n, m));
1,096,045✔
199
        if (r != 0)
1,096,045✔
200
                return r;
201

202
        return CMP(n, m);
965,815✔
203
}
204

205
bool chars_intersect(const char *a, const char *b) {
12,462✔
206
        /* Returns true if any of the chars in a are in b. */
207
        for (const char *p = a; *p; p++)
180,600✔
208
                if (strchr(b, *p))
168,160✔
209
                        return true;
210

211
        return false;
212
}
213

214
bool string_has_cc(const char *p, const char *ok) {
292,261✔
215
        assert(p);
292,261✔
216

217
        /*
218
         * Check if a string contains control characters. If 'ok' is
219
         * non-NULL it may be a string containing additional CCs to be
220
         * considered OK.
221
         */
222

223
        for (const char *t = p; *t; t++) {
2,849,495✔
224
                if (ok && strchr(ok, *t))
2,557,250✔
225
                        continue;
8✔
226

227
                if (char_is_cc(*t))
2,557,242✔
228
                        return true;
229
        }
230

231
        return false;
232
}
233

234
static int write_ellipsis(char *buf, bool unicode) {
4,173✔
235
        const char *s = glyph_full(GLYPH_ELLIPSIS, unicode);
4,173✔
236
        assert(strlen(s) == 3);
4,173✔
237
        memcpy(buf, s, 3);
4,173✔
238
        return 3;
4,173✔
239
}
240

241
static size_t ansi_sequence_length(const char *s, size_t len) {
6,342✔
242
        assert(s);
6,342✔
243

244
        if (len < 2)
6,342✔
245
                return 0;
246

247
        if (s[0] != 0x1B)  /* ASCII 27, aka ESC, aka Ctrl-[ */
6,250✔
248
                return 0;  /* Not the start of a sequence */
249

250
        if (s[1] == 0x5B) { /* [, start of CSI sequence */
909✔
251
                size_t i = 2;
908✔
252

253
                if (i == len)
908✔
254
                        return 0;
255

256
                while (s[i] >= 0x30 && s[i] <= 0x3F) /* Parameter bytes */
9,251✔
257
                        if (++i == len)
8,343✔
258
                                return 0;
259
                while (s[i] >= 0x20 && s[i] <= 0x2F) /* Intermediate bytes */
908✔
260
                        if (++i == len)
×
261
                                return 0;
262
                if (s[i] >= 0x40 && s[i] <= 0x7E) /* Final byte */
908✔
263
                        return i + 1;
908✔
264
                return 0;  /* Bad sequence */
265

266
        } else if (s[1] >= 0x40 && s[1] <= 0x5F) /* other non-CSI Fe sequence */
1✔
267
                return 2;
×
268

269
        return 0;  /* Bad escape? */
270
}
271

272
static bool string_has_ansi_sequence(const char *s, size_t len) {
7,781✔
273
        const char *t = s;
7,781✔
274

275
        while ((t = memchr(t, 0x1B, len - (t - s)))) {
7,782✔
276
                if (ansi_sequence_length(t, len - (t - s)) > 0)
157✔
277
                        return true;
278
                t++;
1✔
279
        }
280
        return false;
281
}
282

283
static size_t previous_ansi_sequence(const char *s, size_t length, const char **ret_where) {
269✔
284

285
        assert(s);
269✔
286
        assert(ret_where);
269✔
287

288
        /* Locate the previous ANSI sequence and save its start in *ret_where and return length. */
289

290
        if (length < 2) {
269✔
291
                /* Need at least two bytes for an ANSI sequence */
292
                *ret_where = NULL;
2✔
293
                return 0;
2✔
294
        }
295

296
        for (size_t i = length - 2; i > 0; i--) {  /* -2 because at least two bytes are needed */
3,444✔
297
                size_t slen = ansi_sequence_length(s + (i - 1), length - (i - 1));
3,442✔
298
                if (slen == 0)
3,442✔
299
                        continue;
3,177✔
300

301
                *ret_where = s + (i - 1);
265✔
302
                return slen;
265✔
303
        }
304

305
        *ret_where = NULL;
2✔
306
        return 0;
2✔
307
}
308

309
static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4,368✔
310
        size_t x, need_space, suffix_len;
4,368✔
311
        char *t;
4,368✔
312

313
        assert(s);
4,368✔
314
        assert(percent <= 100);
4,368✔
315
        assert(new_length != SIZE_MAX);
4,368✔
316

317
        if (old_length <= new_length)
4,368✔
318
                return strndup(s, old_length);
1,843✔
319

320
        /* Special case short ellipsations */
321
        switch (new_length) {
2,525✔
322

323
        case 0:
×
324
                return strdup("");
×
325

326
        case 1:
65✔
327
                if (is_locale_utf8())
65✔
328
                        return strdup("…");
65✔
329
                else
330
                        return strdup(".");
×
331

332
        case 2:
35✔
333
                if (!is_locale_utf8())
35✔
334
                        return strdup("..");
×
335
                break;
336
        }
337

338
        /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
339
         * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
340
         * either for the UTF-8 encoded character or for three ASCII characters. */
341
        need_space = is_locale_utf8() ? 1 : 3;
2,460✔
342

343
        t = new(char, new_length+3);
2,460✔
344
        if (!t)
2,460✔
345
                return NULL;
346

347
        assert(new_length >= need_space);
2,460✔
348

349
        x = ((new_length - need_space) * percent + 50) / 100;
2,460✔
350
        assert(x <= new_length - need_space);
2,460✔
351

352
        write_ellipsis(mempcpy(t, s, x), /* unicode= */ false);
2,460✔
353
        suffix_len = new_length - x - need_space;
2,460✔
354
        memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
2,460✔
355
        *(t + x + 3 + suffix_len) = '\0';
2,460✔
356

357
        return t;
2,460✔
358
}
359

360
/* Walk backwards from 'end' (exclusive) to the start of the last complete UTF-8 character, without
361
 * descending below 'start', validate it and return a pointer to its first byte, optionally decoding it
362
 * into *ret_c. Returns NULL on a truncated or otherwise malformed sequence. */
363
static const char* find_previous_unichar(const char *start, const char *end, char32_t *ret_c) {
8,945✔
364
        const char *p;
8,945✔
365
        int r;
8,945✔
366

367
        assert(start);
8,945✔
368
        assert(end);
8,945✔
369
        assert(end > start);
8,945✔
370

371
        for (p = end; p > start; ) {
13,330✔
372
                p--;
13,330✔
373
                if (((uint8_t) *p & 0xc0) != 0x80) /* Found a non-continuation byte, i.e. a character start. */
13,330✔
374
                        break;
375
        }
376

377
        r = utf8_encoded_valid_unichar(p, end - p);
8,945✔
378
        if (r < 0 || p + r != end)
8,945✔
379
                return NULL;
380

381
        if (ret_c)
8,944✔
382
                assert_se(utf8_encoded_to_unichar(p, ret_c) == r);
8,944✔
383

384
        return p;
385
}
386

387
char* ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
7,952✔
388
        size_t x, k, len, len2;
7,952✔
389
        const char *i, *j;
7,952✔
390
        int r;
7,952✔
391

392
        /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
393
         * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
394
         * strings.
395
         *
396
         * Ellipsation is done in a locale-dependent way:
397
         * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
398
         * 2. Otherwise, a unicode ellipsis is used ("…")
399
         *
400
         * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
401
         * the current locale is UTF-8.
402
         */
403

404
        assert(s);
7,952✔
405
        assert(percent <= 100);
7,952✔
406

407
        if (new_length == SIZE_MAX)
7,952✔
UNCOV
408
                return strndup(s, old_length);
×
409

410
        if (new_length == 0)
7,952✔
411
                return strdup("");
171✔
412

413
        bool has_ansi_seq = string_has_ansi_sequence(s, old_length);
7,781✔
414

415
        /* If no multibyte characters or ANSI sequences, use ascii_ellipsize_mem for speed */
416
        if (!has_ansi_seq && ascii_is_valid_n(s, old_length))
7,781✔
417
                return ascii_ellipsize_mem(s, old_length, new_length, percent);
4,368✔
418

419
        x = (new_length - 1) * percent / 100;
3,413✔
420
        assert(x <= new_length - 1);
3,413✔
421

422
        k = 0;
423
        for (i = s; i < s + old_length; ) {
45,132✔
424
                size_t slen = has_ansi_seq ? ansi_sequence_length(i, old_length - (i - s)) : 0;
43,940✔
425
                if (slen > 0) {
1,014✔
426
                        i += slen;
225✔
427
                        continue;  /* ANSI sequences don't take up any space in output */
225✔
428
                }
429

430
                r = utf8_encoded_valid_unichar(i, s + old_length - i);
43,715✔
431
                if (r < 0)
43,715✔
UNCOV
432
                        return NULL;
×
433

434
                char32_t c;
43,715✔
435
                assert_se(utf8_encoded_to_unichar(i, &c) == r);
43,715✔
436

437
                int w = unichar_iswide(c) ? 2 : 1;
43,715✔
438
                if (k + w > x)
43,715✔
439
                        break;
440

441
                k += w;
41,494✔
442
                i += r;
41,494✔
443
        }
444

445
        const char *ansi_start = s + old_length;
3,413✔
446
        size_t ansi_len = 0;
3,413✔
447

448
        for (const char *t = j = s + old_length; t > i && k < new_length; ) {
12,385✔
449
                char32_t c;
9,059✔
450
                int w;
9,059✔
451
                const char *tt;
9,059✔
452

453
                if (has_ansi_seq && ansi_start >= t)
9,059✔
454
                        /* Figure out the previous ANSI sequence, if any */
455
                        ansi_len = previous_ansi_sequence(s, t - s, &ansi_start);
269✔
456

457
                /* If the sequence extends all the way to the current position, skip it. */
458
                if (has_ansi_seq && ansi_len > 0 && ansi_start + ansi_len == t) {
9,059✔
459
                        t = ansi_start;
114✔
460
                        continue;
114✔
461
                }
462

463
                /* Find the previous complete UTF-8 character inside the retained suffix. */
464
                tt = find_previous_unichar(i, t, &c);
8,945✔
465
                if (!tt)
8,945✔
466
                        return NULL;
1✔
467

468
                w = unichar_iswide(c) ? 2 : 1;
8,944✔
469
                if (k + w > new_length)
8,944✔
470
                        break;
471

472
                k += w;
8,858✔
473
                j = t = tt;  /* j should always point to the first "real" character */
8,858✔
474
        }
475

476
        /* We don't actually need to ellipsize */
477
        if (i >= j)
3,412✔
478
                return memdup_suffix0(s, old_length);
1,723✔
479

480
        if (k >= new_length) {
1,689✔
481
                /* Make space for ellipsis, if required and possible. We know that the edge character is not
482
                 * part of an ANSI sequence (because then we'd skip it). If the last character we looked at
483
                 * was wide, we don't need to make space.
484
                 * Move the edge by one complete UTF-8 character within the input slice. */
485
                if (j < s + old_length) {
1,603✔
486
                        r = utf8_encoded_valid_unichar(j, s + old_length - j);
1,603✔
487
                        if (r < 0)
1,603✔
488
                                return NULL;
489

490
                        j += r;
1,603✔
UNCOV
491
                } else if (i > s) {
×
UNCOV
492
                        const char *tt = find_previous_unichar(s, i, NULL);
×
UNCOV
493
                        if (!tt)
×
494
                                return NULL;
495

496
                        i = tt;
497
                }
498
        }
499

500
        len = i - s;
1,689✔
501
        len2 = s + old_length - j;
1,689✔
502

503
        /* If we have ANSI, allow the same length as the source string + ellipsis. It'd be too involved to
504
         * figure out what exact space is needed. Strings with ANSI sequences are most likely to be fairly
505
         * short anyway. */
506
        size_t alloc_len = has_ansi_seq ? old_length + 3 + 1 : len + 3 + len2 + 1;
1,689✔
507

508
        char *e = new(char, alloc_len);
1,689✔
509
        if (!e)
1,689✔
510
                return NULL;
511

512
        memcpy_safe(e, s, len);
1,689✔
513
        write_ellipsis(e + len, /* unicode= */ true);
1,689✔
514

515
        char *dst = e + len + 3;
1,689✔
516

517
        if (has_ansi_seq)
1,689✔
518
                /* Copy over any ANSI sequences in full */
519
                for (const char *p = s + len; p < j; ) {
1,864✔
520
                        size_t slen = ansi_sequence_length(p, j - p);
1,729✔
521
                        if (slen > 0) {
1,729✔
522
                                dst = mempcpy(dst, p, slen);
262✔
523
                                p += slen;
262✔
524
                        } else
525
                                p = utf8_next_char(p);
1,467✔
526
                }
527

528
        memcpy_safe(dst, j, len2);
1,689✔
529
        dst[len2] = '\0';
1,689✔
530

531
        return e;
1,689✔
532
}
533

534
char* cellescape(char *buf, size_t len, const char *s) {
58,065✔
535
        /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
536
         * characters are copied as they are, everything else is escaped. The result
537
         * is different then if escaping and ellipsization was performed in two
538
         * separate steps, because each sequence is either stored in full or skipped.
539
         *
540
         * This function should be used for logging about strings which expected to
541
         * be plain ASCII in a safe way.
542
         *
543
         * An ellipsis will be used if s is too long. It was always placed at the
544
         * very end.
545
         */
546

547
        size_t i = 0, last_char_width[4] = {}, k = 0;
58,065✔
548

549
        assert(buf);
58,065✔
550
        assert(len > 0); /* at least a terminating NUL */
58,065✔
551
        assert(s);
58,065✔
552

553
        for (;;) {
1,255,525✔
554
                char four[4];
656,795✔
555
                int w;
656,795✔
556

557
                if (*s == 0) /* terminating NUL detected? then we are done! */
656,795✔
558
                        goto done;
58,029✔
559

560
                w = cescape_char(*s, four);
598,766✔
561
                if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
598,766✔
562
                                      * ellipsize at the previous location */
563
                        break;
564

565
                /* OK, there was space, let's add this escaped character to the buffer */
566
                memcpy(buf + i, four, w);
598,730✔
567
                i += w;
598,730✔
568

569
                /* And remember its width in the ring buffer */
570
                last_char_width[k] = w;
598,730✔
571
                k = (k + 1) % 4;
598,730✔
572

573
                s++;
598,730✔
574
        }
575

576
        /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
577
         * characters ideally, but the buffer is shorter than that in the first place take what we can get */
578
        for (size_t j = 0; j < ELEMENTSOF(last_char_width); j++) {
81✔
579

580
                if (i + 4 <= len) /* nice, we reached our space goal */
81✔
581
                        break;
582

583
                k = k == 0 ? 3 : k - 1;
57✔
584
                if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
57✔
585
                        break;
586

587
                assert(i >= last_char_width[k]);
45✔
588
                i -= last_char_width[k];
45✔
589
        }
590

591
        if (i + 4 <= len) /* yay, enough space */
36✔
592
                i += write_ellipsis(buf + i, /* unicode= */ false);
24✔
593
        else if (i + 3 <= len) { /* only space for ".." */
12✔
594
                buf[i++] = '.';
4✔
595
                buf[i++] = '.';
4✔
596
        } else if (i + 2 <= len) /* only space for a single "." */
8✔
597
                buf[i++] = '.';
4✔
598
        else
599
                assert(i + 1 <= len);
4✔
600

601
done:
4✔
602
        buf[i] = '\0';
58,065✔
603
        return buf;
58,065✔
604
}
605

606
char* strshorten(char *s, size_t l) {
318,213✔
607
        assert(s);
318,213✔
608

609
        if (l >= SIZE_MAX-1) /* Would not change anything */
318,213✔
610
                return s;
611

612
        if (strnlen(s, l+1) > l)
318,211✔
613
                s[l] = 0;
107✔
614

615
        return s;
616
}
617

618
int strgrowpad0(char **s, size_t l) {
24✔
619
        size_t sz;
24✔
620

621
        assert(s);
24✔
622

623
        if (*s) {
24✔
624
                sz = strlen(*s) + 1;
24✔
625
                if (sz >= l) /* never shrink */
24✔
626
                        return 0;
627
        } else
628
                sz = 0;
629

630
        char *q = realloc(*s, l);
24✔
631
        if (!q)
24✔
632
                return -ENOMEM;
633

634
        *s = q;
24✔
635

636
        memzero(*s + sz, l - sz);
24✔
637
        return 0;
638
}
639

640
char* strreplace(const char *text, const char *old_string, const char *new_string) {
7,579✔
641
        size_t l, old_len, new_len;
7,579✔
642
        char *t, *ret = NULL;
7,579✔
643
        const char *f;
7,579✔
644

645
        assert(old_string);
7,579✔
646
        assert(new_string);
7,579✔
647

648
        if (!text)
7,579✔
649
                return NULL;
7,579✔
650

651
        old_len = strlen(old_string);
7,578✔
652
        new_len = strlen(new_string);
7,578✔
653

654
        l = strlen(text);
7,578✔
655
        if (!GREEDY_REALLOC(ret, l+1))
7,578✔
656
                return NULL;
657

658
        f = text;
7,578✔
659
        t = ret;
7,578✔
660
        while (*f) {
245,650✔
661
                size_t d, nl;
238,072✔
662

663
                if (!startswith(f, old_string)) {
238,072✔
664
                        *(t++) = *(f++);
235,653✔
665
                        continue;
235,653✔
666
                }
667

668
                d = t - ret;
2,419✔
669
                nl = l - old_len + new_len;
2,419✔
670

671
                if (!GREEDY_REALLOC(ret, nl + 1))
2,419✔
UNCOV
672
                        return mfree(ret);
×
673

674
                l = nl;
2,419✔
675
                t = ret + d;
2,419✔
676

677
                t = stpcpy(t, new_string);
2,419✔
678
                f += old_len;
2,419✔
679
        }
680

681
        *t = 0;
7,578✔
682
        return ret;
7,578✔
683
}
684

685
static void advance_offsets(
559✔
686
                ssize_t diff,
687
                size_t offsets[2], /* note: we can't use [static 2] here, since this may be NULL */
688
                size_t shift[static 2],
689
                size_t size) {
690

691
        if (!offsets)
559✔
692
                return;
693

694
        assert(shift);
549✔
695

696
        if ((size_t) diff < offsets[0])
549✔
UNCOV
697
                shift[0] += size;
×
698
        if ((size_t) diff < offsets[1])
549✔
UNCOV
699
                shift[1] += size;
×
700
}
701

702
char* strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
281,504✔
703
        const char *begin = NULL;
281,504✔
704
        enum {
281,504✔
705
                STATE_OTHER,
706
                STATE_ESCAPE,
707
                STATE_CSI,
708
                STATE_OSC,
709
                STATE_OSC_CLOSING,
710
        } state = STATE_OTHER;
281,504✔
711
        _cleanup_(memstream_done) MemStream m = {};
281,504✔
712
        size_t isz, shift[2] = {}, n_carriage_returns = 0;
281,504✔
713
        FILE *f;
281,504✔
714

715
        assert(ibuf);
281,504✔
716
        assert(*ibuf);
281,504✔
717
        POINTER_MAY_BE_NULL(_isz);
281,504✔
718

719
        /* This does three things:
720
         *
721
         * 1. Replaces TABs by 8 spaces
722
         * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
723
         * 3. Strips ANSI operating system sequences (OSC), i.e. ESC ']' … ST sequences
724
         * 4. Strip trailing \r characters (since they would "move the cursor", but have no
725
         *    other effect).
726
         *
727
         * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
728
         * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
729
         * supposed to suppress the most basic formatting noise, but nothing else.
730
         *
731
         * Why care for OSC sequences? Well, to undo what terminal_urlify() and friends generate. */
732

733
        isz = _isz ? *_isz : strlen(*ibuf);
281,504✔
734

735
        /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
736
         * created f here and it doesn't leave our scope. */
737
        f = memstream_init(&m);
281,504✔
738
        if (!f)
281,504✔
739
                return NULL;
740

741
        for (const char *i = *ibuf; i < *ibuf + isz + 1; i++) {
34,258,430✔
742

743
                bool eot = i >= *ibuf + isz;
33,976,926✔
744

745
                switch (state) {
33,976,926✔
746

747
                case STATE_OTHER:
33,976,675✔
748
                        if (eot)
33,976,675✔
749
                                break;
750

751
                        if (*i == '\r') {
33,695,171✔
752
                                n_carriage_returns++;
7✔
753
                                break;
7✔
754
                        } else if (*i == '\n')
33,695,164✔
755
                                /* Ignore carriage returns before new line */
756
                                n_carriage_returns = 0;
35✔
757
                        for (; n_carriage_returns > 0; n_carriage_returns--)
33,695,166✔
758
                                fputc('\r', f);
2✔
759

760
                        if (*i == '\x1B')
33,695,164✔
761
                                state = STATE_ESCAPE;
762
                        else if (*i == '\t') {
33,695,130✔
763
                                fputs("        ", f);
554✔
764
                                advance_offsets(i - *ibuf, highlight, shift, 7);
554✔
765
                        } else
766
                                fputc(*i, f);
33,694,576✔
767

768
                        break;
769

770
                case STATE_ESCAPE:
34✔
771
                        assert(n_carriage_returns == 0);
34✔
772

773
                        if (eot) {
34✔
774
                                fputc('\x1B', f);
×
775
                                advance_offsets(i - *ibuf, highlight, shift, 1);
×
776
                                break;
777
                        } else if (*i == '[') { /* ANSI CSI */
34✔
778
                                state = STATE_CSI;
31✔
779
                                begin = i + 1;
31✔
780
                        } else if (*i == ']') { /* ANSI OSC */
3✔
781
                                state = STATE_OSC;
3✔
782
                                begin = i + 1;
3✔
783
                        } else {
UNCOV
784
                                fputc('\x1B', f);
×
UNCOV
785
                                fputc(*i, f);
×
UNCOV
786
                                advance_offsets(i - *ibuf, highlight, shift, 1);
×
UNCOV
787
                                state = STATE_OTHER;
×
788
                        }
789

790
                        break;
791

792
                case STATE_CSI:
191✔
793
                        assert(n_carriage_returns == 0);
191✔
794

795
                        if (eot || !strchr(DIGITS ";:m", *i)) { /* EOT or invalid chars in sequence */
191✔
796
                                fputc('\x1B', f);
5✔
797
                                fputc('[', f);
5✔
798
                                advance_offsets(i - *ibuf, highlight, shift, 2);
5✔
799
                                state = STATE_OTHER;
5✔
800
                                i = begin-1;
5✔
801
                        } else if (*i == 'm')
186✔
802
                                state = STATE_OTHER;
26✔
803

804
                        break;
805

806
                case STATE_OSC:
24✔
807
                        assert(n_carriage_returns == 0);
24✔
808

809
                        /* There are three kinds of OSC terminators: \x07, \x1b\x5c or \x9c. We only support
810
                         * the first two, because the last one is a valid UTF-8 codepoint and hence creates
811
                         * an ambiguity (many Terminal emulators refuse to support it as well). */
812
                        if (eot || (!IN_SET(*i, '\x07', '\x1b') && !osc_char_is_valid(*i))) { /* EOT or invalid chars in sequence */
24✔
UNCOV
813
                                fputc('\x1B', f);
×
UNCOV
814
                                fputc(']', f);
×
UNCOV
815
                                advance_offsets(i - *ibuf, highlight, shift, 2);
×
UNCOV
816
                                state = STATE_OTHER;
×
UNCOV
817
                                i = begin-1;
×
818
                        } else if (*i == '\x07') /* Single character ST */
24✔
819
                                state = STATE_OTHER;
820
                        else if (*i == '\x1B')
23✔
821
                                state = STATE_OSC_CLOSING;
2✔
822

823
                        break;
824

825
                case STATE_OSC_CLOSING:
2✔
826
                        if (eot || *i != '\x5c') { /* EOT or incomplete two-byte ST in sequence */
2✔
UNCOV
827
                                fputc('\x1B', f);
×
UNCOV
828
                                fputc(']', f);
×
UNCOV
829
                                advance_offsets(i - *ibuf, highlight, shift, 2);
×
UNCOV
830
                                state = STATE_OTHER;
×
UNCOV
831
                                i = begin-1;
×
832
                        } else if (*i == '\x5c')
833
                                state = STATE_OTHER;
834

835
                        break;
836
                }
837
        }
838

839
        char *obuf;
281,504✔
840
        if (memstream_finalize(&m, &obuf, _isz) < 0)
281,504✔
841
                return NULL;
842

843
        free_and_replace(*ibuf, obuf);
281,504✔
844

845
        if (highlight) {
281,504✔
846
                highlight[0] += shift[0];
281,477✔
847
                highlight[1] += shift[1];
281,477✔
848
        }
849

850
        return *ibuf;
281,504✔
851
}
852

853
char* strextendv_with_separator(char **x, const char *separator, va_list ap) {
32,978,973✔
854
        _cleanup_free_ char *buffer = NULL;
32,978,973✔
855
        size_t f, l, l_separator;
32,978,973✔
856
        bool need_separator;
32,978,973✔
857
        char *nr, *p;
32,978,973✔
858

859
        if (!x)
32,978,973✔
860
                x = &buffer;
30,783,573✔
861

862
        l = f = strlen_ptr(*x);
32,978,973✔
863

864
        need_separator = !isempty(*x);
32,978,973✔
865
        l_separator = strlen_ptr(separator);
32,978,973✔
866

867
        va_list aq;
32,978,973✔
868
        va_copy(aq, ap);
32,978,973✔
869
        for (const char *t;;) {
124,307,135✔
870
                size_t n;
124,307,135✔
871

872
                t = va_arg(aq, const char *);
124,307,135✔
873
                if (!t)
124,307,135✔
874
                        break;
875
                if (t == POINTER_MAX)
91,328,162✔
876
                        continue;
3✔
877

878
                n = strlen(t);
91,328,159✔
879

880
                if (need_separator)
91,328,159✔
881
                        n += l_separator;
59,591,070✔
882

883
                if (n >= SIZE_MAX - l) {
91,328,159✔
UNCOV
884
                        va_end(aq);
×
UNCOV
885
                        return NULL;
×
886
                }
887

888
                l += n;
91,328,159✔
889
                need_separator = true;
91,328,159✔
890
        }
891
        va_end(aq);
32,978,973✔
892

893
        need_separator = !isempty(*x);
32,978,973✔
894

895
        nr = realloc(*x, GREEDY_ALLOC_ROUND_UP(l+1));
32,978,973✔
896
        if (!nr)
32,978,973✔
897
                return NULL;
898

899
        *x = nr;
32,978,973✔
900
        p = nr + f;
32,978,973✔
901

902
        for (;;) {
124,307,135✔
903
                const char *t;
124,307,135✔
904

905
                t = va_arg(ap, const char *);
124,307,135✔
906
                if (!t)
124,307,135✔
907
                        break;
908
                if (t == POINTER_MAX)
91,328,162✔
909
                        continue;
3✔
910

911
                if (need_separator && separator)
91,328,159✔
912
                        p = stpcpy(p, separator);
167,541✔
913

914
                p = stpcpy(p, t);
91,328,159✔
915

916
                need_separator = true;
91,328,159✔
917
        }
918

919
        assert(p == nr + l);
32,978,973✔
920
        *p = 0;
32,978,973✔
921

922
        /* If no buffer to extend was passed in return the start of the buffer */
923
        if (buffer)
32,978,973✔
924
                return TAKE_PTR(buffer);
30,783,573✔
925

926
        /* Otherwise we extended the buffer: return the end */
927
        return p;
928
}
929

930
char* strextend_with_separator_internal(char **x, const char *separator, ...) {
32,916,581✔
931
        va_list ap;
32,916,581✔
932
        char *ret;
32,916,581✔
933

934
        va_start(ap, separator);
32,916,581✔
935
        ret = strextendv_with_separator(x, separator, ap);
32,916,581✔
936
        va_end(ap);
32,916,581✔
937

938
        return ret;
32,916,581✔
939
}
940

941
int strextendf_with_separator(char **x, const char *separator, const char *format, ...) {
25,371✔
942
        size_t m, a, l_separator;
25,371✔
943
        va_list ap;
25,371✔
944
        int l;
25,371✔
945

946
        /* Appends a formatted string to the specified string. Don't use this in inner loops, since then
947
         * we'll spend a tonload of time in determining the length of the string passed in, over and over
948
         * again. */
949

950
        assert(x);
25,371✔
951
        assert(format);
25,371✔
952

953
        l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
43,538✔
954

955
        /* Let's try to use the allocated buffer, if there's room at the end still. Otherwise let's extend by 64 chars. */
956
        if (*x) {
25,371✔
957
                m = strlen(*x);
18,167✔
958
                a = MALLOC_SIZEOF_SAFE(*x);
18,167✔
959
                assert(a >= m + 1);
18,167✔
960
        } else
961
                m = a = 0;
962

963
        if (a - m < 17 + l_separator) { /* if there's less than 16 chars space, then enlarge the buffer first */
25,371✔
964
                char *n;
14,044✔
965

966
                if (_unlikely_(l_separator > SIZE_MAX - 64)) /* overflow check #1 */
14,044✔
967
                        return -ENOMEM;
25,371✔
968
                if (_unlikely_(m > SIZE_MAX - 64 - l_separator)) /* overflow check #2 */
14,044✔
969
                        return -ENOMEM;
970

971
                n = realloc(*x, m + 64 + l_separator);
14,044✔
972
                if (!n)
14,044✔
973
                        return -ENOMEM;
974

975
                *x = n;
14,044✔
976
                a = MALLOC_SIZEOF_SAFE(*x);
14,044✔
977
        }
978

979
        /* Now, let's try to format the string into it */
980
        memcpy_safe(*x + m, separator, l_separator);
25,371✔
981
        va_start(ap, format);
25,371✔
982
        l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
25,371✔
983
        va_end(ap);
25,371✔
984

985
        assert(l >= 0);
25,371✔
986

987
        if ((size_t) l < a - m - l_separator) {
25,371✔
988
                char *n;
24,869✔
989

990
                /* Nice! This worked. We are done. But first, let's return the extra space we don't
991
                 * need. This should be a cheap operation, since we only lower the allocation size here,
992
                 * never increase. */
993
                n = realloc(*x, m + (size_t) l + l_separator + 1);
24,869✔
994
                if (n)
24,869✔
995
                        *x = n;
24,869✔
996
        } else {
997
                char *n;
502✔
998

999
                /* Wasn't enough. Then let's allocate exactly what we need. */
1000

1001
                if (_unlikely_((size_t) l > SIZE_MAX - (l_separator + 1))) /* overflow check #1 */
502✔
UNCOV
1002
                        goto oom;
×
1003
                if (_unlikely_(m > SIZE_MAX - ((size_t) l + l_separator + 1))) /* overflow check #2 */
502✔
UNCOV
1004
                        goto oom;
×
1005

1006
                a = m + (size_t) l + l_separator + 1;
502✔
1007
                n = realloc(*x, a);
502✔
1008
                if (!n)
502✔
UNCOV
1009
                        goto oom;
×
1010
                *x = n;
502✔
1011

1012
                va_start(ap, format);
502✔
1013
                l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
502✔
1014
                va_end(ap);
502✔
1015

1016
                assert((size_t) l < a - m - l_separator);
502✔
1017
        }
1018

1019
        return 0;
1020

UNCOV
1021
oom:
×
1022
        /* truncate the bytes added after memcpy_safe() again */
UNCOV
1023
        (*x)[m] = 0;
×
UNCOV
1024
        return -ENOMEM;
×
1025
}
1026

1027
char* strrep(const char *s, size_t n) {
16✔
1028
        char *ret, *p;
16✔
1029
        size_t l;
16✔
1030

1031
        assert(s);
16✔
1032

1033
        l = strlen(s);
16✔
1034
        if (!MUL_ASSIGN_SAFE(&l, n))
16✔
1035
                return NULL;
16✔
1036
        if (!INC_SAFE(&l, 1))
15✔
1037
                return NULL;
1038

1039
        p = ret = malloc(l);
15✔
1040
        if (!ret)
15✔
1041
                return NULL;
1042

1043
        for (size_t i = 0; i < n; i++)
41,363✔
1044
                p = stpcpy(p, s);
41,348✔
1045

1046
        *p = 0;
15✔
1047
        return ret;
15✔
1048
}
1049

1050
int split_pair(const char *s, const char *sep, char **ret_first, char **ret_second) {
29,787✔
1051
        assert(s);
29,787✔
1052
        assert(!isempty(sep));
29,787✔
1053

1054
        const char *x = strstr(s, sep);
29,787✔
1055
        if (!x)
29,787✔
1056
                return -EINVAL;
29,787✔
1057

1058
        _cleanup_free_ char *a = NULL;
28,333✔
1059
        if (ret_first) {
28,333✔
1060
                a = strndup(s, x - s);
28,331✔
1061
                if (!a)
28,331✔
1062
                        return -ENOMEM;
1063
        }
1064

1065
        _cleanup_free_ char *b = NULL;
28,333✔
1066
        if (ret_second) {
28,333✔
1067
                b = strdup(x + strlen(sep));
28,331✔
1068
                if (!b)
28,331✔
1069
                        return -ENOMEM;
1070
        }
1071

1072
        if (ret_first)
28,333✔
1073
                *ret_first = TAKE_PTR(a);
28,331✔
1074
        if (ret_second)
28,333✔
1075
                *ret_second = TAKE_PTR(b);
28,331✔
1076
        return 0;
1077
}
1078

1079
int free_and_strdup(char **p, const char *s) {
2,053,278✔
1080
        char *t;
2,053,278✔
1081

1082
        assert(p);
2,053,278✔
1083

1084
        /* Replaces a string pointer with a strdup()ed new string,
1085
         * possibly freeing the old one. */
1086

1087
        if (streq_ptr(*p, s))
2,053,278✔
1088
                return 0;
2,053,278✔
1089

1090
        if (s) {
1,610,055✔
1091
                t = strdup(s);
1,602,283✔
1092
                if (!t)
1,602,283✔
1093
                        return -ENOMEM;
1094
        } else
1095
                t = NULL;
1096

1097
        free_and_replace(*p, t);
1,610,055✔
1098

1099
        return 1;
1,610,055✔
1100
}
1101

1102
int free_and_strdup_warn(char **p, const char *s) {
105,032✔
1103
        int r;
105,032✔
1104

1105
        r = free_and_strdup(p, s);
105,032✔
1106
        if (r < 0)
105,032✔
UNCOV
1107
                return log_oom();
×
1108
        return r;
1109
}
1110

1111
int free_and_strndup(char **p, const char *s, size_t l) {
80,375✔
1112
        char *t;
80,375✔
1113

1114
        assert(p);
80,375✔
1115
        assert(s || l == 0);
80,375✔
1116

1117
        /* Replaces a string pointer with a strndup()ed new string,
1118
         * freeing the old one. */
1119

1120
        if (!*p && !s)
80,375✔
1121
                return 0;
80,375✔
1122

1123
        if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
80,375✔
1124
                return 0;
1125

1126
        if (s) {
37,713✔
1127
                t = strndup(s, l);
37,784✔
1128
                if (!t)
37,784✔
1129
                        return -ENOMEM;
1130
        } else
1131
                t = NULL;
1132

1133
        free_and_replace(*p, t);
37,785✔
1134
        return 1;
37,785✔
1135
}
1136

1137
int strdup_to_full(char **ret, const char *src) {
881,474✔
1138
        if (!src) {
881,474✔
1139
                if (ret)
326,783✔
1140
                        *ret = NULL;
326,782✔
1141

1142
                return 0;
1143
        } else {
1144
                if (ret) {
554,691✔
1145
                        char *t = strdup(src);
542,827✔
1146
                        if (!t)
542,827✔
1147
                                return -ENOMEM;
1148
                        *ret = t;
542,827✔
1149
                }
1150

1151
                return 1;
1152
        }
1153
};
1154

1155
bool string_is_safe(const char *p, StringSafeFlags flags) {
14,577,628✔
1156

1157
        /* Baseline checks are:
1158
         *   • No control characters (i.e. 0…31 + 127)
1159
         *   • UTF-8 valid (well, technically we skip this test if STRING_ASCII is set, since that is a tighter test)
1160
         */
1161

1162
        if (FLAGS_SET(flags, STRING_ALLOW_EMPTY) ? !p : isempty(p))
14,577,628✔
1163
                return false;
1164

1165
        if (!FLAGS_SET(flags, STRING_ASCII) && !utf8_is_valid(p))
29,154,164✔
1166
                return false;
1167

1168
        for (const char *t = p; *t; t++) {
272,849,485✔
1169
                /* never allow control characters, except for new line */
1170
                if ((*t > 0 && *t < ' ' && *t != '\n') || *t == 0x7f)
258,271,952✔
1171
                        return false;
1172

1173
                if (!FLAGS_SET(flags, STRING_ALLOW_NEWLINES) && *t == '\n')
258,271,927✔
1174
                        return false;
1175

1176
                if (!FLAGS_SET(flags, STRING_ALLOW_BACKSLASHES) && *t == '\\')
258,271,918✔
1177
                        return false;
1178

1179
                if (!FLAGS_SET(flags, STRING_ALLOW_QUOTES) && strchr(QUOTES, *t))
258,271,907✔
1180
                        return false;
1181

1182
                if (!FLAGS_SET(flags, STRING_ALLOW_GLOBS) && strchr(GLOB_CHARS, *t))
258,271,895✔
1183
                        return false;
1184

1185
                if (FLAGS_SET(flags, STRING_DISALLOW_WHITESPACE) && strchr(WHITESPACE, *t))
258,271,887✔
1186
                        return false;
1187

1188
                if (FLAGS_SET(flags, STRING_ASCII) && (uint8_t) *t >= 0x80)
258,271,882✔
1189
                        return false;
1190
        }
1191

1192
        if (FLAGS_SET(flags, STRING_FILENAME) && !filename_is_valid(p))
14,577,533✔
1193
                return false;
1194

1195
        if (FLAGS_SET(flags, STRING_FILENAME_PART) && !filename_part_is_valid(p))
14,577,521✔
1196
                return false;
23✔
1197

1198
        return true;
1199
}
1200

1201
char* str_realloc(char *p) {
57,493✔
1202
        /* Reallocate *p to actual size. Ignore failure, and return the original string on error. */
1203

1204
        if (!p)
57,493✔
1205
                return NULL;
1206

1207
        return realloc(p, strlen(p) + 1) ?: p;
57,493✔
1208
}
1209

1210
char* string_erase(char *x) {
129✔
1211
        if (!x)
129✔
1212
                return NULL;
1213

1214
        /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1215
         * used them. */
1216
        explicit_bzero_safe(x, strlen(x));
129✔
1217
        return x;
129✔
1218
}
1219

1220
int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
300✔
1221
        const char *p = s, *e = s;
300✔
1222
        bool truncation_applied = false;
300✔
1223
        char *copy;
300✔
1224
        size_t n = 0;
300✔
1225

1226
        assert(s);
300✔
1227
        assert(ret);
300✔
1228

1229
        /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1230
         * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1231
         * generated either. */
1232

1233
        for (;;) {
530✔
1234
                size_t k;
415✔
1235

1236
                k = strcspn(p, "\n");
415✔
1237

1238
                if (p[k] == 0) {
415✔
1239
                        if (k == 0) /* final empty line */
268✔
1240
                                break;
1241

1242
                        if (n >= n_lines) /* above threshold */
243✔
1243
                                break;
1244

1245
                        e = p + k; /* last line to include */
226✔
1246
                        break;
226✔
1247
                }
1248

1249
                assert(p[k] == '\n');
147✔
1250

1251
                if (n >= n_lines)
147✔
1252
                        break;
1253

1254
                if (k > 0)
115✔
1255
                        e = p + k;
92✔
1256

1257
                p += k + 1;
115✔
1258
                n++;
115✔
1259
        }
1260

1261
        /* e points after the last character we want to keep */
1262
        if (isempty(e))
300✔
1263
                copy = strdup(s);
230✔
1264
        else {
1265
                if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
70✔
1266
                                           * isn't a new-line or a series of them */
1267
                        truncation_applied = true;
42✔
1268

1269
                copy = strndup(s, e - s);
70✔
1270
        }
1271
        if (!copy)
300✔
1272
                return -ENOMEM;
1273

1274
        *ret = copy;
300✔
1275
        return truncation_applied;
300✔
1276
}
1277

1278
int string_extract_line(const char *s, size_t i, char **ret) {
235,723✔
1279
        const char *p = s;
235,723✔
1280
        size_t c = 0;
235,723✔
1281

1282
        assert(ret);
235,723✔
1283

1284
        /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1285
         * and == 0 if we are looking at the last line or already beyond the last line. As special
1286
         * optimization, if the first line is requested and the string only consists of one line we return
1287
         * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1288
         * common case. */
1289

1290
        for (;;) {
423,551✔
1291
                const char *q;
329,637✔
1292

1293
                q = strchr(p, '\n');
329,637✔
1294
                if (i == c) {
329,637✔
1295
                        /* The line we are looking for! */
1296

1297
                        if (q) {
231,927✔
1298
                                char *m;
3,927✔
1299

1300
                                m = strndup(p, q - p);
3,927✔
1301
                                if (!m)
3,927✔
1302
                                        return -ENOMEM;
1303

1304
                                *ret = m;
3,927✔
1305
                                return !isempty(q + 1); /* More coming? */
7,854✔
1306
                        } else
1307
                                /* Tell the caller to use the input string if equal */
1308
                                return strdup_to(ret, p != s ? p : NULL);
454,168✔
1309
                }
1310

1311
                if (!q)
97,710✔
1312
                        /* No more lines, return empty line */
1313
                        return strdup_to(ret, "");
3,796✔
1314

1315
                p = q + 1;
93,914✔
1316
                c++;
93,914✔
1317
        }
1318
}
1319

1320
int string_contains_word_strv(const char *string, const char *separators, char * const *words, const char **ret_word) {
75✔
1321
        /* In the default mode with no separators specified, we split on whitespace and coalesce separators. */
1322
        const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
75✔
1323
        const char *found = NULL;
75✔
1324
        int r;
202✔
1325

1326
        for (;;) {
329✔
1327
                _cleanup_free_ char *w = NULL;
127✔
1328

1329
                r = extract_first_word(&string, &w, separators, flags);
202✔
1330
                if (r < 0)
202✔
UNCOV
1331
                        return r;
×
1332
                if (r == 0)
202✔
1333
                        break;
1334

1335
                found = strv_find(words, w);
148✔
1336
                if (found)
148✔
1337
                        break;
1338
        }
1339

1340
        if (ret_word)
75✔
1341
                *ret_word = found;
7✔
1342
        return !!found;
75✔
1343
}
1344

1345
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
9,015✔
1346
        if (!s1 && !s2)
9,015✔
1347
                return true;
1348
        if (!s1 || !s2)
9,014✔
1349
                return false;
1350

1351
        if (!ok)
9,012✔
1352
                ok = WHITESPACE;
13✔
1353

1354
        for (; *s1 && *s2; s1++, s2++)
17,479✔
1355
                if (*s1 != *s2)
10,740✔
1356
                        break;
1357

1358
        return in_charset(s1, ok) && in_charset(s2, ok);
11,291✔
1359
}
1360

1361
char* string_replace_char(char *str, char old_char, char new_char) {
651,008✔
1362
        assert(str);
651,008✔
1363
        assert(old_char != '\0');
651,008✔
1364
        assert(new_char != '\0');
651,008✔
1365
        assert(old_char != new_char);
651,008✔
1366

1367
        for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
657,102✔
1368
                *p = new_char;
6,094✔
1369

1370
        return str;
651,008✔
1371
}
1372

1373
int make_cstring(const void *s, size_t n, MakeCStringMode mode, char **ret) {
10,294✔
1374
        char *b;
10,294✔
1375

1376
        assert(s || n == 0);
10,294✔
1377
        assert(mode >= 0);
10,294✔
1378
        assert(mode < _MAKE_CSTRING_MODE_MAX);
10,294✔
1379

1380
        /* Converts a sized character buffer into a NUL-terminated NUL string, refusing if there are embedded
1381
         * NUL bytes. Whether to expect a trailing NUL byte can be specified via 'mode' */
1382

1383
        if (n == 0) {
10,294✔
1384
                if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
20✔
1385
                        return -EINVAL;
1386

1387
                if (!ret)
19✔
1388
                        return 0;
1389

1390
                b = new0(char, 1);
19✔
1391
        } else {
1392
                const uint8_t *nul;
10,274✔
1393

1394
                nul = memchr(s, 0, n);
10,274✔
1395
                if (nul) {
10,274✔
1396
                        if (nul < (const uint8_t*) s + n - 1 || /* embedded NUL? */
29✔
1397
                            mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1398
                                return -EINVAL;
1399

1400
                        n--;
1401
                } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
10,245✔
1402
                        return -EINVAL;
1403

1404
                if (!ret)
10,263✔
1405
                        return 0;
1406

1407
                b = memdup_suffix0(s, n);
10,263✔
1408
        }
1409
        if (!b)
10,282✔
1410
                return -ENOMEM;
1411

1412
        *ret = b;
10,282✔
1413
        return 0;
10,282✔
1414
}
1415

1416
size_t strspn_from_end(const char *str, const char *accept) {
615,039✔
1417
        size_t n = 0;
615,039✔
1418

1419
        if (isempty(str))
615,039✔
1420
                return 0;
1421

1422
        if (isempty(accept))
615,036✔
1423
                return 0;
1424

1425
        for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1,187,444✔
1426
                n++;
572,409✔
1427

1428
        return n;
1429
}
1430

1431
char* strdupspn(const char *a, const char *accept) {
×
UNCOV
1432
        if (isempty(a) || isempty(accept))
×
UNCOV
1433
                return strdup("");
×
1434

UNCOV
1435
        return strndup(a, strspn(a, accept));
×
1436
}
1437

1438
char* strdupcspn(const char *a, const char *reject) {
41,782✔
1439
        if (isempty(a))
41,782✔
1440
                return strdup("");
×
1441
        if (isempty(reject))
41,782✔
UNCOV
1442
                return strdup(a);
×
1443

1444
        return strndup(a, strcspn(a, reject));
41,782✔
1445
}
1446

1447
char* find_line_startswith_internal(const char *haystack, const char *needle) {
6,749✔
1448
        assert(haystack);
6,749✔
1449
        assert(needle);
6,749✔
1450

1451
        /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1452
         * first character after it */
1453

1454
        char *p = (char*) strstr(haystack, needle);
6,749✔
1455
        if (!p)
6,749✔
1456
                return NULL;
1457

1458
        if (p > haystack)
1,449✔
1459
                while (p[-1] != '\n') {
116✔
1460
                        p = strstr(p + 1, needle);
9✔
1461
                        if (!p)
9✔
1462
                                return NULL;
1463
                }
1464

1465
        return p + strlen(needle);
1,448✔
1466
}
1467

UNCOV
1468
char* find_line_internal(const char *haystack, const char *needle) {
×
UNCOV
1469
        assert(haystack);
×
UNCOV
1470
        assert(needle);
×
1471

1472
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1473
         * beginning of the line */
1474

UNCOV
1475
        char *p = (char*) find_line_startswith(haystack, needle);
×
UNCOV
1476
        if (!p)
×
1477
                return NULL;
1478

UNCOV
1479
        if (*p == 0 || strchr(NEWLINE, *p))
×
UNCOV
1480
                return p - strlen(needle);
×
1481

1482
        return NULL;
1483
}
1484

UNCOV
1485
char* find_line_after_internal(const char *haystack, const char *needle) {
×
UNCOV
1486
        assert(haystack);
×
UNCOV
1487
        assert(needle);
×
1488

1489
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1490
         * next line after it */
1491

UNCOV
1492
        char *p = (char*) find_line_startswith(haystack, needle);
×
UNCOV
1493
        if (!p)
×
1494
                return NULL;
1495

UNCOV
1496
        if (*p == 0)
×
1497
                return p;
UNCOV
1498
        if (strchr(NEWLINE, *p))
×
UNCOV
1499
                return p + 1;
×
1500

1501
        return NULL;
1502
}
1503

1504
bool version_is_valid(const char *s, VersionFlags flags) {
78,553✔
1505

1506
        /* Validates a version string superficially. This does not proces the version string in any
1507
         * semantical way, it mostly just validates that its charset is reasonable. */
1508

1509
        if (FLAGS_SET(flags, VERSION_ALLOW_EMPTY) ? !s : isempty(s))
78,553✔
1510
                return false;
78,553✔
1511

1512
        if (!filename_part_is_valid(s))
78,548✔
1513
                return false;
1514

1515
        /* We always allow all characters specified by the UAPI.10 Version Specification, i.e. 0-9, a-z, A-Z,
1516
         * ".", "-", "~", "^".
1517
         *
1518
         * If the relevant flags are set we'll also allow "+" and "_" separators.
1519
         *
1520
         * Note that with SemVer allows 0-9, a-z, A-Z, "+", "-", ".", hence with VERSION_ALLOW_PLUS we
1521
         * implement a superset of it.
1522
         *
1523
         * If you wonder when to use which flags: when validating foreign versions (e.g. distribution
1524
         * versions in /etc/os-release or so) validate liberally, i.e. add
1525
         * VERSION_ALLOW_UNDERSCORE|VERSION_ALLOW_PLUS. When validating our own versioned objects (e.g. vpick
1526
         * or so) validate more strictly, and in particular refuse characters such as "_" and "+" that may be
1527
         * used for separating component names or boot attempt counters. Also: first – if appropriate – split
1528
         * the string into individual components. For example, if the string consists of a name and a
1529
         * version, separated by some character, only pass the version part to this function. The name part
1530
         * may pass verification, but it's cleaner to not rely on that.
1531
         *
1532
         * For details about UAPI.10 see:
1533
         *
1534
         * → https://uapi-group.org/specifications/specs/version_format_specification/ */
1535

1536
        char charset[] = ALPHANUMERICAL ".-~^" /* plus room for the two chars below: */ "\0\0";
78,541✔
1537
        size_t l = strlen(charset);
78,541✔
1538

1539
        if (FLAGS_SET(flags, VERSION_ALLOW_UNDERSCORE))
78,541✔
1540
                charset[l++] = '_';
77,873✔
1541
        if (FLAGS_SET(flags, VERSION_ALLOW_PLUS))
78,541✔
1542
                charset[l++] = '+';
77,873✔
1543

1544
        return in_charset(s, charset);
78,541✔
1545
}
1546

1547
ssize_t strlevenshtein(const char *x, const char *y) {
122✔
1548
        _cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
244✔
1549
        size_t xl, yl;
122✔
1550

1551
        /* This is inspired from the Linux kernel's Levenshtein implementation */
1552

1553
        if (streq_ptr(x, y))
122✔
1554
                return 0;
1555

1556
        xl = strlen_ptr(x);
118✔
1557
        if (xl > SSIZE_MAX)
117✔
1558
                return -E2BIG;
1559

1560
        yl = strlen_ptr(y);
118✔
1561
        if (yl > SSIZE_MAX)
117✔
1562
                return -E2BIG;
1563

1564
        if (isempty(x))
118✔
1565
                return yl;
3✔
1566
        if (isempty(y))
115✔
1567
                return xl;
1✔
1568

1569
        t0 = new0(size_t, yl + 1);
114✔
1570
        if (!t0)
114✔
1571
                return -ENOMEM;
1572
        t1 = new0(size_t, yl + 1);
114✔
1573
        if (!t1)
114✔
1574
                return -ENOMEM;
1575
        t2 = new0(size_t, yl + 1);
114✔
1576
        if (!t2)
114✔
1577
                return -ENOMEM;
1578

1579
        for (size_t i = 0; i <= yl; i++)
1,249✔
1580
                t1[i] = i;
1,135✔
1581

1582
        for (size_t i = 0; i < xl; i++) {
712✔
1583
                t2[0] = i + 1;
598✔
1584

1585
                for (size_t j = 0; j < yl; j++) {
6,439✔
1586
                        /* Substitution */
1587
                        t2[j+1] = t1[j] + (x[i] != y[j]);
5,841✔
1588

1589
                        /* Swap */
1590
                        if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
5,841✔
1591
                                t2[j+1] = t0[j-1] + 1;
14✔
1592

1593
                        /* Deletion */
1594
                        if (t2[j+1] > t1[j+1] + 1)
5,841✔
1595
                                t2[j+1] = t1[j+1] + 1;
247✔
1596

1597
                        /* Insertion */
1598
                        if (t2[j+1] > t2[j] + 1)
5,841✔
1599
                                t2[j+1] = t2[j] + 1;
880✔
1600
                }
1601

1602
                size_t *dummy = t0;
1603
                t0 = t1;
1604
                t1 = t2;
1605
                t2 = dummy;
1606
        }
1607

1608
        return t1[yl];
114✔
1609
}
1610

1611
char* strrstr_internal(const char *haystack, const char *needle) {
26,451✔
1612
        /* Like strstr() but returns the last rather than the first occurrence of "needle" in "haystack". */
1613

1614
        if (!haystack || !needle)
26,451✔
1615
                return NULL;
1616

1617
        /* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
1618
         * last char, not before. */
1619
        if (needle[0] == 0)
26,448✔
1620
                return (char*) strchr(haystack, 0);
2✔
1621

1622
        /* Special case: for single character strings, just use optimized strrchr() */
1623
        if (needle[1] == 0)
26,446✔
1624
                return (char*) strrchr(haystack, needle[0]);
3✔
1625

1626
        for (const char *p = strstr(haystack, needle), *q; p; p = q) {
26,449✔
1627
                q = strstr(p + 1, needle);
18✔
1628
                if (!q)
18✔
1629
                        return (char*) p;
1630
        }
1631
        return NULL;
1632
}
1633

1634
char* strrstr_no_case_internal(const char *haystack, const char *needle) {
41✔
1635
        if (!haystack || !needle)
41✔
1636
                return NULL;
1637

1638
        for (const char *p = strchr(haystack, 0); p > haystack; p--)
438✔
1639
                if (startswith_no_case(p, needle))
431✔
1640
                        return (char*) p;
1641

1642
        return startswith_no_case(haystack, needle) ? (char*) haystack : NULL;
7✔
1643
}
1644

1645
size_t str_common_prefix(const char *a, const char *b) {
866✔
1646
        assert(a);
866✔
1647
        assert(b);
866✔
1648

1649
        /* Returns the length of the common prefix of the two specified strings, or SIZE_MAX in case the
1650
         * strings are fully identical. */
1651

1652
        for (size_t n = 0;; n++) {
731✔
1653
                char c = a[n];
1,597✔
1654
                if (c != b[n])
1,597✔
1655
                        return n;
1656
                if (c == 0)
734✔
1657
                        return SIZE_MAX;
1658
        }
1659
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc