chiark / gitweb /
string-util: update strreplace() a bit, use GREEDY_REALLOC()
[elogind.git] / src / basic / string-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <stdarg.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "alloc-util.h"
28 #include "gunicode.h"
29 #include "macro.h"
30 #include "string-util.h"
31 #include "utf8.h"
32 #include "util.h"
33
34 int strcmp_ptr(const char *a, const char *b) {
35
36         /* Like strcmp(), but tries to make sense of NULL pointers */
37         if (a && b)
38                 return strcmp(a, b);
39
40         if (!a && b)
41                 return -1;
42
43         if (a && !b)
44                 return 1;
45
46         return 0;
47 }
48
49 char* endswith(const char *s, const char *postfix) {
50         size_t sl, pl;
51
52         assert(s);
53         assert(postfix);
54
55         sl = strlen(s);
56         pl = strlen(postfix);
57
58         if (pl == 0)
59                 return (char*) s + sl;
60
61         if (sl < pl)
62                 return NULL;
63
64         if (memcmp(s + sl - pl, postfix, pl) != 0)
65                 return NULL;
66
67         return (char*) s + sl - pl;
68 }
69
70 char* endswith_no_case(const char *s, const char *postfix) {
71         size_t sl, pl;
72
73         assert(s);
74         assert(postfix);
75
76         sl = strlen(s);
77         pl = strlen(postfix);
78
79         if (pl == 0)
80                 return (char*) s + sl;
81
82         if (sl < pl)
83                 return NULL;
84
85         if (strcasecmp(s + sl - pl, postfix) != 0)
86                 return NULL;
87
88         return (char*) s + sl - pl;
89 }
90
91 char* first_word(const char *s, const char *word) {
92         size_t sl, wl;
93         const char *p;
94
95         assert(s);
96         assert(word);
97
98         /* Checks if the string starts with the specified word, either
99          * followed by NUL or by whitespace. Returns a pointer to the
100          * NUL or the first character after the whitespace. */
101
102         sl = strlen(s);
103         wl = strlen(word);
104
105         if (sl < wl)
106                 return NULL;
107
108         if (wl == 0)
109                 return (char*) s;
110
111         if (memcmp(s, word, wl) != 0)
112                 return NULL;
113
114         p = s + wl;
115         if (*p == 0)
116                 return (char*) p;
117
118         if (!strchr(WHITESPACE, *p))
119                 return NULL;
120
121         p += strspn(p, WHITESPACE);
122         return (char*) p;
123 }
124
125 static size_t strcspn_escaped(const char *s, const char *reject) {
126         bool escaped = false;
127         int n;
128
129         for (n=0; s[n]; n++) {
130                 if (escaped)
131                         escaped = false;
132                 else if (s[n] == '\\')
133                         escaped = true;
134                 else if (strchr(reject, s[n]))
135                         break;
136         }
137
138         /* if s ends in \, return index of previous char */
139         return n - escaped;
140 }
141
142 /* Split a string into words. */
143 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
144         const char *current;
145
146         current = *state;
147
148         if (!*current) {
149                 assert(**state == '\0');
150                 return NULL;
151         }
152
153         current += strspn(current, separator);
154         if (!*current) {
155                 *state = current;
156                 return NULL;
157         }
158
159         if (quoted && strchr("\'\"", *current)) {
160                 char quotechars[2] = {*current, '\0'};
161
162                 *l = strcspn_escaped(current + 1, quotechars);
163                 if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
164                     (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
165                         /* right quote missing or garbage at the end */
166                         *state = current;
167                         return NULL;
168                 }
169                 *state = current++ + *l + 2;
170         } else if (quoted) {
171                 *l = strcspn_escaped(current, separator);
172                 if (current[*l] && !strchr(separator, current[*l])) {
173                         /* unfinished escape */
174                         *state = current;
175                         return NULL;
176                 }
177                 *state = current + *l;
178         } else {
179                 *l = strcspn(current, separator);
180                 *state = current + *l;
181         }
182
183         return current;
184 }
185
186 char *strnappend(const char *s, const char *suffix, size_t b) {
187         size_t a;
188         char *r;
189
190         if (!s && !suffix)
191                 return strdup("");
192
193         if (!s)
194                 return strndup(suffix, b);
195
196         if (!suffix)
197                 return strdup(s);
198
199         assert(s);
200         assert(suffix);
201
202         a = strlen(s);
203         if (b > ((size_t) -1) - a)
204                 return NULL;
205
206         r = new(char, a+b+1);
207         if (!r)
208                 return NULL;
209
210         memcpy(r, s, a);
211         memcpy(r+a, suffix, b);
212         r[a+b] = 0;
213
214         return r;
215 }
216
217 char *strappend(const char *s, const char *suffix) {
218         return strnappend(s, suffix, strlen_ptr(suffix));
219 }
220
221 char *strjoin_real(const char *x, ...) {
222         va_list ap;
223         size_t l;
224         char *r, *p;
225
226         va_start(ap, x);
227
228         if (x) {
229                 l = strlen(x);
230
231                 for (;;) {
232                         const char *t;
233                         size_t n;
234
235                         t = va_arg(ap, const char *);
236                         if (!t)
237                                 break;
238
239                         n = strlen(t);
240                         if (n > ((size_t) -1) - l) {
241                                 va_end(ap);
242                                 return NULL;
243                         }
244
245                         l += n;
246                 }
247         } else
248                 l = 0;
249
250         va_end(ap);
251
252         r = new(char, l+1);
253         if (!r)
254                 return NULL;
255
256         if (x) {
257                 p = stpcpy(r, x);
258
259                 va_start(ap, x);
260
261                 for (;;) {
262                         const char *t;
263
264                         t = va_arg(ap, const char *);
265                         if (!t)
266                                 break;
267
268                         p = stpcpy(p, t);
269                 }
270
271                 va_end(ap);
272         } else
273                 r[0] = 0;
274
275         return r;
276 }
277
278 char *strstrip(char *s) {
279         char *e;
280
281         /* Drops trailing whitespace. Modifies the string in
282          * place. Returns pointer to first non-space character */
283
284         s += strspn(s, WHITESPACE);
285
286         for (e = strchr(s, 0); e > s; e --)
287                 if (!strchr(WHITESPACE, e[-1]))
288                         break;
289
290         *e = 0;
291
292         return s;
293 }
294
295 #if 0 /// UNNEEDED by elogind
296 char *delete_chars(char *s, const char *bad) {
297         char *f, *t;
298
299         /* Drops all whitespace, regardless where in the string */
300
301         for (f = s, t = s; *f; f++) {
302                 if (strchr(bad, *f))
303                         continue;
304
305                 *(t++) = *f;
306         }
307
308         *t = 0;
309
310         return s;
311 }
312 #endif // 0
313
314 char *truncate_nl(char *s) {
315         assert(s);
316
317         s[strcspn(s, NEWLINE)] = 0;
318         return s;
319 }
320
321 #if 0 /// UNNEEDED by elogind
322 char ascii_tolower(char x) {
323
324         if (x >= 'A' && x <= 'Z')
325                 return x - 'A' + 'a';
326
327         return x;
328 }
329
330 char ascii_toupper(char x) {
331
332         if (x >= 'a' && x <= 'z')
333                 return x - 'a' + 'A';
334
335         return x;
336 }
337
338 char *ascii_strlower(char *t) {
339         char *p;
340
341         assert(t);
342
343         for (p = t; *p; p++)
344                 *p = ascii_tolower(*p);
345
346         return t;
347 }
348
349 char *ascii_strupper(char *t) {
350         char *p;
351
352         assert(t);
353
354         for (p = t; *p; p++)
355                 *p = ascii_toupper(*p);
356
357         return t;
358 }
359
360 char *ascii_strlower_n(char *t, size_t n) {
361         size_t i;
362
363         if (n <= 0)
364                 return t;
365
366         for (i = 0; i < n; i++)
367                 t[i] = ascii_tolower(t[i]);
368
369         return t;
370 }
371
372 int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
373
374         for (; n > 0; a++, b++, n--) {
375                 int x, y;
376
377                 x = (int) (uint8_t) ascii_tolower(*a);
378                 y = (int) (uint8_t) ascii_tolower(*b);
379
380                 if (x != y)
381                         return x - y;
382         }
383
384         return 0;
385 }
386
387 int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
388         int r;
389
390         r = ascii_strcasecmp_n(a, b, MIN(n, m));
391         if (r != 0)
392                 return r;
393
394         if (n < m)
395                 return -1;
396         else if (n > m)
397                 return 1;
398         else
399                 return 0;
400 }
401
402 bool chars_intersect(const char *a, const char *b) {
403         const char *p;
404
405         /* Returns true if any of the chars in a are in b. */
406         for (p = a; *p; p++)
407                 if (strchr(b, *p))
408                         return true;
409
410         return false;
411 }
412 #endif // 0
413
414 bool string_has_cc(const char *p, const char *ok) {
415         const char *t;
416
417         assert(p);
418
419         /*
420          * Check if a string contains control characters. If 'ok' is
421          * non-NULL it may be a string containing additional CCs to be
422          * considered OK.
423          */
424
425         for (t = p; *t; t++) {
426                 if (ok && strchr(ok, *t))
427                         continue;
428
429                 if (*t > 0 && *t < ' ')
430                         return true;
431
432                 if (*t == 127)
433                         return true;
434         }
435
436         return false;
437 }
438
439 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
440         size_t x;
441         char *r;
442
443         assert(s);
444         assert(percent <= 100);
445         assert(new_length >= 3);
446
447         if (old_length <= 3 || old_length <= new_length)
448                 return strndup(s, old_length);
449
450         r = new0(char, new_length+3);
451         if (!r)
452                 return NULL;
453
454         x = (new_length * percent) / 100;
455
456         if (x > new_length - 3)
457                 x = new_length - 3;
458
459         memcpy(r, s, x);
460         r[x] = 0xe2; /* tri-dot ellipsis: â€¦ */
461         r[x+1] = 0x80;
462         r[x+2] = 0xa6;
463         memcpy(r + x + 3,
464                s + old_length - (new_length - x - 1),
465                new_length - x - 1);
466
467         return r;
468 }
469
470 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
471         size_t x;
472         char *e;
473         const char *i, *j;
474         unsigned k, len, len2;
475         int r;
476
477         assert(s);
478         assert(percent <= 100);
479
480         if (new_length == (size_t) -1)
481                 return strndup(s, old_length);
482
483         assert(new_length >= 3);
484
485         /* if no multibyte characters use ascii_ellipsize_mem for speed */
486         if (ascii_is_valid(s))
487                 return ascii_ellipsize_mem(s, old_length, new_length, percent);
488
489         if (old_length <= 3 || old_length <= new_length)
490                 return strndup(s, old_length);
491
492         x = (new_length * percent) / 100;
493
494         if (x > new_length - 3)
495                 x = new_length - 3;
496
497         k = 0;
498         for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
499                 char32_t c;
500
501                 r = utf8_encoded_to_unichar(i, &c);
502                 if (r < 0)
503                         return NULL;
504                 k += unichar_iswide(c) ? 2 : 1;
505         }
506
507         if (k > x) /* last character was wide and went over quota */
508                 x++;
509
510         for (j = s + old_length; k < new_length && j > i; ) {
511                 char32_t c;
512
513                 j = utf8_prev_char(j);
514                 r = utf8_encoded_to_unichar(j, &c);
515                 if (r < 0)
516                         return NULL;
517                 k += unichar_iswide(c) ? 2 : 1;
518         }
519         assert(i <= j);
520
521         /* we don't actually need to ellipsize */
522         if (i == j)
523                 return memdup(s, old_length + 1);
524
525         /* make space for ellipsis */
526         j = utf8_next_char(j);
527
528         len = i - s;
529         len2 = s + old_length - j;
530         e = new(char, len + 3 + len2 + 1);
531         if (!e)
532                 return NULL;
533
534         /*
535         printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
536                old_length, new_length, x, len, len2, k);
537         */
538
539         memcpy(e, s, len);
540         e[len]   = 0xe2; /* tri-dot ellipsis: â€¦ */
541         e[len + 1] = 0x80;
542         e[len + 2] = 0xa6;
543
544         memcpy(e + len + 3, j, len2 + 1);
545
546         return e;
547 }
548
549 char *ellipsize(const char *s, size_t length, unsigned percent) {
550
551         if (length == (size_t) -1)
552                 return strdup(s);
553
554         return ellipsize_mem(s, strlen(s), length, percent);
555 }
556
557 bool nulstr_contains(const char *nulstr, const char *needle) {
558         const char *i;
559
560         if (!nulstr)
561                 return false;
562
563         NULSTR_FOREACH(i, nulstr)
564                 if (streq(i, needle))
565                         return true;
566
567         return false;
568 }
569
570 char* strshorten(char *s, size_t l) {
571         assert(s);
572
573         if (strnlen(s, l+1) > l)
574                 s[l] = 0;
575
576         return s;
577 }
578
579 char *strreplace(const char *text, const char *old_string, const char *new_string) {
580         size_t l, old_len, new_len, allocated = 0;
581         char *t, *ret = NULL;
582         const char *f;
583
584         assert(old_string);
585         assert(new_string);
586
587         if (!text)
588                 return NULL;
589
590         old_len = strlen(old_string);
591         new_len = strlen(new_string);
592
593         l = strlen(text);
594         if (!GREEDY_REALLOC(ret, allocated, l+1))
595                 return NULL;
596
597         f = text;
598         t = ret;
599         while (*f) {
600                 size_t d, nl;
601
602                 if (!startswith(f, old_string)) {
603                         *(t++) = *(f++);
604                         continue;
605                 }
606
607                 d = t - ret;
608                 nl = l - old_len + new_len;
609
610                 if (!GREEDY_REALLOC(ret, allocated, nl + 1))
611                         return mfree(ret);
612
613                 l = nl;
614                 t = ret + d;
615
616                 t = stpcpy(t, new_string);
617                 f += old_len;
618         }
619
620         *t = 0;
621         return ret;
622 }
623
624 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
625         const char *i, *begin = NULL;
626         enum {
627                 STATE_OTHER,
628                 STATE_ESCAPE,
629                 STATE_BRACKET
630         } state = STATE_OTHER;
631         char *obuf = NULL;
632         size_t osz = 0, isz;
633         FILE *f;
634
635         assert(ibuf);
636         assert(*ibuf);
637
638         /* Strips ANSI color and replaces TABs by 8 spaces */
639
640         isz = _isz ? *_isz : strlen(*ibuf);
641
642         f = open_memstream(&obuf, &osz);
643         if (!f)
644                 return NULL;
645
646         /* Note we use the _unlocked() stdio variants on f for performance
647          * reasons.  It's safe to do so since we created f here and it
648          * doesn't leave our scope.
649          */
650
651         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
652
653                 switch (state) {
654
655                 case STATE_OTHER:
656                         if (i >= *ibuf + isz) /* EOT */
657                                 break;
658                         else if (*i == '\x1B')
659                                 state = STATE_ESCAPE;
660                         else if (*i == '\t')
661                                 fputs_unlocked("        ", f);
662                         else
663                                 fputc_unlocked(*i, f);
664                         break;
665
666                 case STATE_ESCAPE:
667                         if (i >= *ibuf + isz) { /* EOT */
668                                 fputc_unlocked('\x1B', f);
669                                 break;
670                         } else if (*i == '[') {
671                                 state = STATE_BRACKET;
672                                 begin = i + 1;
673                         } else {
674                                 fputc_unlocked('\x1B', f);
675                                 fputc_unlocked(*i, f);
676                                 state = STATE_OTHER;
677                         }
678
679                         break;
680
681                 case STATE_BRACKET:
682
683                         if (i >= *ibuf + isz || /* EOT */
684                             (!(*i >= '0' && *i <= '9') && !IN_SET(*i, ';', 'm'))) {
685                                 fputc_unlocked('\x1B', f);
686                                 fputc_unlocked('[', f);
687                                 state = STATE_OTHER;
688                                 i = begin-1;
689                         } else if (*i == 'm')
690                                 state = STATE_OTHER;
691                         break;
692                 }
693         }
694
695         if (ferror(f)) {
696                 fclose(f);
697                 return mfree(obuf);
698         }
699
700         fclose(f);
701
702         free(*ibuf);
703         *ibuf = obuf;
704
705         if (_isz)
706                 *_isz = osz;
707
708         return obuf;
709 }
710
711 char *strextend(char **x, ...) {
712         va_list ap;
713         size_t f, l;
714         char *r, *p;
715
716         assert(x);
717
718         l = f = strlen_ptr(*x);
719
720         va_start(ap, x);
721         for (;;) {
722                 const char *t;
723                 size_t n;
724
725                 t = va_arg(ap, const char *);
726                 if (!t)
727                         break;
728
729                 n = strlen(t);
730                 if (n > ((size_t) -1) - l) {
731                         va_end(ap);
732                         return NULL;
733                 }
734
735                 l += n;
736         }
737         va_end(ap);
738
739         r = realloc(*x, l+1);
740         if (!r)
741                 return NULL;
742
743         p = r + f;
744
745         va_start(ap, x);
746         for (;;) {
747                 const char *t;
748
749                 t = va_arg(ap, const char *);
750                 if (!t)
751                         break;
752
753                 p = stpcpy(p, t);
754         }
755         va_end(ap);
756
757         *p = 0;
758         *x = r;
759
760         return r + l;
761 }
762
763 char *strrep(const char *s, unsigned n) {
764         size_t l;
765         char *r, *p;
766         unsigned i;
767
768         assert(s);
769
770         l = strlen(s);
771         p = r = malloc(l * n + 1);
772         if (!r)
773                 return NULL;
774
775         for (i = 0; i < n; i++)
776                 p = stpcpy(p, s);
777
778         *p = 0;
779         return r;
780 }
781
782 int split_pair(const char *s, const char *sep, char **l, char **r) {
783         char *x, *a, *b;
784
785         assert(s);
786         assert(sep);
787         assert(l);
788         assert(r);
789
790         if (isempty(sep))
791                 return -EINVAL;
792
793         x = strstr(s, sep);
794         if (!x)
795                 return -EINVAL;
796
797         a = strndup(s, x - s);
798         if (!a)
799                 return -ENOMEM;
800
801         b = strdup(x + strlen(sep));
802         if (!b) {
803                 free(a);
804                 return -ENOMEM;
805         }
806
807         *l = a;
808         *r = b;
809
810         return 0;
811 }
812
813 int free_and_strdup(char **p, const char *s) {
814         char *t;
815
816         assert(p);
817
818         /* Replaces a string pointer with an strdup()ed new string,
819          * possibly freeing the old one. */
820
821         if (streq_ptr(*p, s))
822                 return 0;
823
824         if (s) {
825                 t = strdup(s);
826                 if (!t)
827                         return -ENOMEM;
828         } else
829                 t = NULL;
830
831         free(*p);
832         *p = t;
833
834         return 1;
835 }
836
837 #if !HAVE_EXPLICIT_BZERO
838 /*
839  * Pointer to memset is volatile so that compiler must de-reference
840  * the pointer and can't assume that it points to any function in
841  * particular (such as memset, which it then might further "optimize")
842  * This approach is inspired by openssl's crypto/mem_clr.c.
843  */
844 typedef void *(*memset_t)(void *,int,size_t);
845
846 static volatile memset_t memset_func = memset;
847
848 void explicit_bzero(void *p, size_t l) {
849         memset_func(p, '\0', l);
850 }
851 #endif
852
853 char* string_erase(char *x) {
854         if (!x)
855                 return NULL;
856
857         /* A delicious drop of snake-oil! To be called on memory where
858          * we stored passphrases or so, after we used them. */
859         explicit_bzero(x, strlen(x));
860         return x;
861 }
862
863 char *string_free_erase(char *s) {
864         return mfree(string_erase(s));
865 }
866
867 bool string_is_safe(const char *p) {
868         const char *t;
869
870         if (!p)
871                 return false;
872
873         for (t = p; *t; t++) {
874                 if (*t > 0 && *t < ' ') /* no control characters */
875                         return false;
876
877                 if (strchr(QUOTES "\\\x7f", *t))
878                         return false;
879         }
880
881         return true;
882 }