SPDX: license tags (mostly by guesswork)
[exim.git] / src / src / string.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-only */
9
10 /* Miscellaneous string-handling functions. Some are not required for
11 utilities and tests, and are cut out by the COMPILE_UTILITY macro. */
12
13
14 #include "exim.h"
15 #include <assert.h>
16
17
18 #ifndef COMPILE_UTILITY
19 /*************************************************
20 *            Test for IP address                 *
21 *************************************************/
22
23 /* This used just to be a regular expression, but with IPv6 things are a bit
24 more complicated. If the address contains a colon, it is assumed to be a v6
25 address (assuming HAVE_IPV6 is set). If a mask is permitted and one is present,
26 and maskptr is not NULL, its offset is placed there.
27
28 Arguments:
29   s         a string
30   maskptr   NULL if no mask is permitted to follow
31             otherwise, points to an int where the offset of '/' is placed
32             if there is no / followed by trailing digits, *maskptr is set 0
33
34 Returns:    0 if the string is not a textual representation of an IP address
35             4 if it is an IPv4 address
36             6 if it is an IPv6 address
37 */
38
39 int
40 string_is_ip_address(const uschar *s, int *maskptr)
41 {
42 int yield = 4;
43
44 /* If an optional mask is permitted, check for it. If found, pass back the
45 offset. */
46
47 if (maskptr)
48   {
49   const uschar *ss = s + Ustrlen(s);
50   *maskptr = 0;
51   if (s != ss && isdigit(*(--ss)))
52     {
53     while (ss > s && isdigit(ss[-1])) ss--;
54     if (ss > s && *(--ss) == '/') *maskptr = ss - s;
55     }
56   }
57
58 /* A colon anywhere in the string => IPv6 address */
59
60 if (Ustrchr(s, ':') != NULL)
61   {
62   BOOL had_double_colon = FALSE;
63   BOOL v4end = FALSE;
64
65   yield = 6;
66
67   /* An IPv6 address must start with hex digit or double colon. A single
68   colon is invalid. */
69
70   if (*s == ':' && *(++s) != ':') return 0;
71
72   /* Now read up to 8 components consisting of up to 4 hex digits each. There
73   may be one and only one appearance of double colon, which implies any number
74   of binary zero bits. The number of preceding components is held in count. */
75
76   for (int count = 0; count < 8; count++)
77     {
78     /* If the end of the string is reached before reading 8 components, the
79     address is valid provided a double colon has been read. This also applies
80     if we hit the / that introduces a mask or the % that introduces the
81     interface specifier (scope id) of a link-local address. */
82
83     if (*s == 0 || *s == '%' || *s == '/') return had_double_colon ? yield : 0;
84
85     /* If a component starts with an additional colon, we have hit a double
86     colon. This is permitted to appear once only, and counts as at least
87     one component. The final component may be of this form. */
88
89     if (*s == ':')
90       {
91       if (had_double_colon) return 0;
92       had_double_colon = TRUE;
93       s++;
94       continue;
95       }
96
97     /* If the remainder of the string contains a dot but no colons, we
98     can expect a trailing IPv4 address. This is valid if either there has
99     been no double-colon and this is the 7th component (with the IPv4 address
100     being the 7th & 8th components), OR if there has been a double-colon
101     and fewer than 6 components. */
102
103     if (Ustrchr(s, ':') == NULL && Ustrchr(s, '.') != NULL)
104       {
105       if ((!had_double_colon && count != 6) ||
106           (had_double_colon && count > 6)) return 0;
107       v4end = TRUE;
108       yield = 6;
109       break;
110       }
111
112     /* Check for at least one and not more than 4 hex digits for this
113     component. */
114
115     if (!isxdigit(*s++)) return 0;
116     if (isxdigit(*s) && isxdigit(*(++s)) && isxdigit(*(++s))) s++;
117
118     /* If the component is terminated by colon and there is more to
119     follow, skip over the colon. If there is no more to follow the address is
120     invalid. */
121
122     if (*s == ':' && *(++s) == 0) return 0;
123     }
124
125   /* If about to handle a trailing IPv4 address, drop through. Otherwise
126   all is well if we are at the end of the string or at the mask or at a percent
127   sign, which introduces the interface specifier (scope id) of a link local
128   address. */
129
130   if (!v4end)
131     return (*s == 0 || *s == '%' ||
132            (*s == '/' && maskptr != NULL && *maskptr != 0))? yield : 0;
133   }
134
135 /* Test for IPv4 address, which may be the tail-end of an IPv6 address. */
136
137 for (int i = 0; i < 4; i++)
138   {
139   long n;
140   uschar * end;
141
142   if (i != 0 && *s++ != '.') return 0;
143   n = strtol(CCS s, CSS &end, 10);
144   if (n > 255 || n < 0 || end <= s || end > s+3) return 0;
145   s = end;
146   }
147
148 return !*s || (*s == '/' && maskptr && *maskptr != 0) ? yield : 0;
149 }
150 #endif  /* COMPILE_UTILITY */
151
152
153 /*************************************************
154 *              Format message size               *
155 *************************************************/
156
157 /* Convert a message size in bytes to printing form, rounding
158 according to the magnitude of the number. A value of zero causes
159 a string of spaces to be returned.
160
161 Arguments:
162   size        the message size in bytes
163   buffer      where to put the answer
164
165 Returns:      pointer to the buffer
166               a string of exactly 5 characters is normally returned
167 */
168
169 uschar *
170 string_format_size(int size, uschar *buffer)
171 {
172 if (size == 0) Ustrcpy(buffer, US"     ");
173 else if (size < 1024) sprintf(CS buffer, "%5d", size);
174 else if (size < 10*1024)
175   sprintf(CS buffer, "%4.1fK", (double)size / 1024.0);
176 else if (size < 1024*1024)
177   sprintf(CS buffer, "%4dK", (size + 512)/1024);
178 else if (size < 10*1024*1024)
179   sprintf(CS buffer, "%4.1fM", (double)size / (1024.0 * 1024.0));
180 else
181   sprintf(CS buffer, "%4dM", (size + 512 * 1024)/(1024*1024));
182 return buffer;
183 }
184
185
186
187 #ifndef COMPILE_UTILITY
188 /*************************************************
189 *       Convert a number to base 62 format       *
190 *************************************************/
191
192 /* Convert a long integer into an ASCII base 62 string. For Cygwin the value of
193 BASE_62 is actually 36. Always return exactly 6 characters plus zero, in a
194 static area.
195
196 Argument: a long integer
197 Returns:  pointer to base 62 string
198 */
199
200 uschar *
201 string_base62(unsigned long int value)
202 {
203 static uschar yield[7];
204 uschar *p = yield + sizeof(yield) - 1;
205 *p = 0;
206 while (p > yield)
207   {
208   *(--p) = base62_chars[value % BASE_62];
209   value /= BASE_62;
210   }
211 return yield;
212 }
213 #endif  /* COMPILE_UTILITY */
214
215
216
217 /*************************************************
218 *          Interpret escape sequence             *
219 *************************************************/
220
221 /* This function is called from several places where escape sequences are to be
222 interpreted in strings.
223
224 Arguments:
225   pp       points a pointer to the initiating "\" in the string;
226            the pointer gets updated to point to the final character
227            If the backslash is the last character in the string, it
228            is not interpreted.
229 Returns:   the value of the character escape
230 */
231
232 int
233 string_interpret_escape(const uschar **pp)
234 {
235 #ifdef COMPILE_UTILITY
236 const uschar *hex_digits= CUS"0123456789abcdef";
237 #endif
238 int ch;
239 const uschar *p = *pp;
240 ch = *(++p);
241 if (ch == '\0') return **pp;
242 if (isdigit(ch) && ch != '8' && ch != '9')
243   {
244   ch -= '0';
245   if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
246     {
247     ch = ch * 8 + *(++p) - '0';
248     if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
249       ch = ch * 8 + *(++p) - '0';
250     }
251   }
252 else switch(ch)
253   {
254   case 'b':  ch = '\b'; break;
255   case 'f':  ch = '\f'; break;
256   case 'n':  ch = '\n'; break;
257   case 'r':  ch = '\r'; break;
258   case 't':  ch = '\t'; break;
259   case 'v':  ch = '\v'; break;
260   case 'x':
261   ch = 0;
262   if (isxdigit(p[1]))
263     {
264     ch = ch * 16 +
265       Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
266     if (isxdigit(p[1])) ch = ch * 16 +
267       Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
268     }
269   break;
270   }
271 *pp = p;
272 return ch;
273 }
274
275
276
277 #ifndef COMPILE_UTILITY
278 /*************************************************
279 *          Ensure string is printable            *
280 *************************************************/
281
282 /* This function is called for critical strings. It checks for any
283 non-printing characters, and if any are found, it makes a new copy
284 of the string with suitable escape sequences. It is most often called by the
285 macro string_printing(), which sets flags to 0.
286
287 Arguments:
288   s             the input string
289   flags         Bit 0: convert tabs.  Bit 1: convert spaces.
290
291 Returns:        string with non-printers encoded as printing sequences
292 */
293
294 const uschar *
295 string_printing2(const uschar *s, int flags)
296 {
297 int nonprintcount = 0;
298 int length = 0;
299 const uschar *t = s;
300 uschar *ss, *tt;
301
302 while (*t)
303   {
304   int c = *t++;
305   if (  !mac_isprint(c)
306      || flags & SP_TAB && c == '\t'
307      || flags & SP_SPACE && c == ' '
308      ) nonprintcount++;
309   length++;
310   }
311
312 if (nonprintcount == 0) return s;
313
314 /* Get a new block of store guaranteed big enough to hold the
315 expanded string. */
316
317 tt = ss = store_get(length + nonprintcount * 3 + 1, s);
318
319 /* Copy everything, escaping non printers. */
320
321 for (t = s; *t; )
322   {
323   int c = *t;
324   if (  mac_isprint(c)
325      && (!(flags & SP_TAB) || c != '\t')
326      && (!(flags & SP_SPACE) || c != ' ')
327      )
328     *tt++ = *t++;
329   else
330     {
331     *tt++ = '\\';
332     switch (*t)
333       {
334       case '\n': *tt++ = 'n'; break;
335       case '\r': *tt++ = 'r'; break;
336       case '\b': *tt++ = 'b'; break;
337       case '\v': *tt++ = 'v'; break;
338       case '\f': *tt++ = 'f'; break;
339       case '\t': *tt++ = 't'; break;
340       default: sprintf(CS tt, "%03o", *t); tt += 3; break;
341       }
342     t++;
343     }
344   }
345 *tt = 0;
346 return ss;
347 }
348 #endif  /* COMPILE_UTILITY */
349
350 /*************************************************
351 *        Undo printing escapes in string         *
352 *************************************************/
353
354 /* This function is the reverse of string_printing2.  It searches for
355 backslash characters and if any are found, it makes a new copy of the
356 string with escape sequences parsed.  Otherwise it returns the original
357 string.
358
359 Arguments:
360   s             the input string
361
362 Returns:        string with printing escapes parsed back
363 */
364
365 uschar *
366 string_unprinting(uschar *s)
367 {
368 uschar *p, *q, *r, *ss;
369 int len, off;
370
371 p = Ustrchr(s, '\\');
372 if (!p) return s;
373
374 len = Ustrlen(s) + 1;
375 ss = store_get(len, s);
376
377 q = ss;
378 off = p - s;
379 if (off)
380   {
381   memcpy(q, s, off);
382   q += off;
383   }
384
385 while (*p)
386   {
387   if (*p == '\\')
388     {
389     *q++ = string_interpret_escape((const uschar **)&p);
390     p++;
391     }
392   else
393     {
394     r = Ustrchr(p, '\\');
395     if (!r)
396       {
397       off = Ustrlen(p);
398       memcpy(q, p, off);
399       p += off;
400       q += off;
401       break;
402       }
403     else
404       {
405       off = r - p;
406       memcpy(q, p, off);
407       q += off;
408       p = r;
409       }
410     }
411   }
412 *q = '\0';
413
414 return ss;
415 }
416
417
418
419
420 #if (defined(HAVE_LOCAL_SCAN) || defined(EXPAND_DLFUNC)) \
421         && !defined(MACRO_PREDEF) && !defined(COMPILE_UTILITY)
422 /*************************************************
423 *            Copy and save string                *
424 *************************************************/
425
426 /*
427 Argument: string to copy
428 Returns:  copy of string in new store with the same taint status
429 */
430
431 uschar *
432 string_copy_function(const uschar * s)
433 {
434 return string_copy_taint(s, s);
435 }
436
437 /* As above, but explicitly specifying the result taint status
438 */
439
440 uschar *
441 string_copy_taint_function(const uschar * s, const void * proto_mem)
442 {
443 return string_copy_taint(s, proto_mem);
444 }
445
446
447
448 /*************************************************
449 *       Copy and save string, given length       *
450 *************************************************/
451
452 /* It is assumed the data contains no zeros. A zero is added
453 onto the end.
454
455 Arguments:
456   s         string to copy
457   n         number of characters
458
459 Returns:    copy of string in new store
460 */
461
462 uschar *
463 string_copyn_function(const uschar * s, int n)
464 {
465 return string_copyn(s, n);
466 }
467 #endif
468
469
470 /*************************************************
471 *     Copy and save string in malloc'd store     *
472 *************************************************/
473
474 /* This function assumes that memcpy() is faster than strcpy().
475
476 Argument: string to copy
477 Returns:  copy of string in new store
478 */
479
480 uschar *
481 string_copy_malloc(const uschar * s)
482 {
483 int len = Ustrlen(s) + 1;
484 uschar * ss = store_malloc(len);
485 memcpy(ss, s, len);
486 return ss;
487 }
488
489
490
491 /*************************************************
492 *    Copy string if long, inserting newlines     *
493 *************************************************/
494
495 /* If the given string is longer than 75 characters, it is copied, and within
496 the copy, certain space characters are converted into newlines.
497
498 Argument:  pointer to the string
499 Returns:   pointer to the possibly altered string
500 */
501
502 uschar *
503 string_split_message(uschar * msg)
504 {
505 uschar *s, *ss;
506
507 if (!msg || Ustrlen(msg) <= 75) return msg;
508 s = ss = msg = string_copy(msg);
509
510 for (;;)
511   {
512   int i = 0;
513   while (i < 75 && *ss && *ss != '\n') ss++, i++;
514   if (!*ss) break;
515   if (*ss == '\n')
516     s = ++ss;
517   else
518     {
519     uschar * t = ss + 1;
520     uschar * tt = NULL;
521     while (--t > s + 35)
522       {
523       if (*t == ' ')
524         {
525         if (t[-1] == ':') { tt = t; break; }
526         if (!tt) tt = t;
527         }
528       }
529
530     if (!tt)          /* Can't split behind - try ahead */
531       {
532       t = ss + 1;
533       while (*t)
534         {
535         if (*t == ' ' || *t == '\n')
536           { tt = t; break; }
537         t++;
538         }
539       }
540
541     if (!tt) break;   /* Can't find anywhere to split */
542     *tt = '\n';
543     s = ss = tt+1;
544     }
545   }
546
547 return msg;
548 }
549
550
551
552 /*************************************************
553 *   Copy returned DNS domain name, de-escaping   *
554 *************************************************/
555
556 /* If a domain name contains top-bit characters, some resolvers return
557 the fully qualified name with those characters turned into escapes. The
558 convention is a backslash followed by _decimal_ digits. We convert these
559 back into the original binary values. This will be relevant when
560 allow_utf8_domains is set true and UTF-8 characters are used in domain
561 names. Backslash can also be used to escape other characters, though we
562 shouldn't come across them in domain names.
563
564 Argument:   the domain name string
565 Returns:    copy of string in new store, de-escaped
566 */
567
568 uschar *
569 string_copy_dnsdomain(uschar * s)
570 {
571 uschar * yield;
572 uschar * ss = yield = store_get(Ustrlen(s) + 1, GET_TAINTED);   /* always treat as tainted */
573
574 while (*s)
575   {
576   if (*s != '\\')
577     *ss++ = *s++;
578   else if (isdigit(s[1]))
579     {
580     *ss++ = (s[1] - '0')*100 + (s[2] - '0')*10 + s[3] - '0';
581     s += 4;
582     }
583   else if (*++s)
584     *ss++ = *s++;
585   }
586
587 *ss = 0;
588 return yield;
589 }
590
591
592 #ifndef COMPILE_UTILITY
593 /*************************************************
594 *     Copy space-terminated or quoted string     *
595 *************************************************/
596
597 /* This function copies from a string until its end, or until whitespace is
598 encountered, unless the string begins with a double quote, in which case the
599 terminating quote is sought, and escaping within the string is done. The length
600 of a de-quoted string can be no longer than the original, since escaping always
601 turns n characters into 1 character.
602
603 Argument:  pointer to the pointer to the first character, which gets updated
604 Returns:   the new string
605 */
606
607 uschar *
608 string_dequote(const uschar ** sptr)
609 {
610 const uschar * s = * sptr;
611 uschar * t, * yield;
612
613 /* First find the end of the string */
614
615 if (*s != '\"')
616   while (*s && !isspace(*s)) s++;
617 else
618   {
619   s++;
620   while (*s && *s != '\"')
621     {
622     if (*s == '\\') (void)string_interpret_escape(&s);
623     s++;
624     }
625   if (*s) s++;
626   }
627
628 /* Get enough store to copy into */
629
630 t = yield = store_get(s - *sptr + 1, *sptr);
631 s = *sptr;
632
633 /* Do the copy */
634
635 if (*s != '\"')
636   while (*s && !isspace(*s)) *t++ = *s++;
637 else
638   {
639   s++;
640   while (*s && *s != '\"')
641     {
642     *t++ = *s == '\\' ? string_interpret_escape(&s) : *s;
643     s++;
644     }
645   if (*s) s++;
646   }
647
648 /* Update the pointer and return the terminated copy */
649
650 *sptr = s;
651 *t = 0;
652 return yield;
653 }
654 #endif  /* COMPILE_UTILITY */
655
656
657
658 /*************************************************
659 *          Format a string and save it           *
660 *************************************************/
661
662 /* The formatting is done by string_vformat, which checks the length of
663 everything.  Taint is taken from the worst of the arguments.
664
665 Arguments:
666   format    a printf() format - deliberately char * rather than uschar *
667               because it will most usually be a literal string
668   func      caller, for debug
669   line      caller, for debug
670   ...       arguments for format
671
672 Returns:    pointer to fresh piece of store containing sprintf'ed string
673 */
674
675 uschar *
676 string_sprintf_trc(const char * format, const uschar * func, unsigned line, ...)
677 {
678 #ifdef COMPILE_UTILITY
679 uschar buffer[STRING_SPRINTF_BUFFER_SIZE];
680 gstring gs = { .size = STRING_SPRINTF_BUFFER_SIZE, .ptr = 0, .s = buffer };
681 gstring * g = &gs;
682 unsigned flags = 0;
683 #else
684 gstring * g = NULL;
685 unsigned flags = SVFMT_REBUFFER|SVFMT_EXTEND;
686 #endif
687
688 va_list ap;
689 va_start(ap, line);
690 g = string_vformat_trc(g, func, line, STRING_SPRINTF_BUFFER_SIZE,
691         flags, format, ap);
692 va_end(ap);
693
694 if (!g)
695   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
696     "string_sprintf expansion was longer than %d; format string was (%s)\n"
697     " called from %s %d\n",
698     STRING_SPRINTF_BUFFER_SIZE, format, func, line);
699
700 #ifdef COMPILE_UTILITY
701 return string_copyn(g->s, g->ptr);
702 #else
703 gstring_release_unused(g);
704 return string_from_gstring(g);
705 #endif
706 }
707
708
709
710 /*************************************************
711 *         Case-independent strncmp() function    *
712 *************************************************/
713
714 /*
715 Arguments:
716   s         first string
717   t         second string
718   n         number of characters to compare
719
720 Returns:    < 0, = 0, or > 0, according to the comparison
721 */
722
723 int
724 strncmpic(const uschar * s, const uschar * t, int n)
725 {
726 while (n--)
727   {
728   int c = tolower(*s++) - tolower(*t++);
729   if (c) return c;
730   }
731 return 0;
732 }
733
734
735 /*************************************************
736 *         Case-independent strcmp() function     *
737 *************************************************/
738
739 /*
740 Arguments:
741   s         first string
742   t         second string
743
744 Returns:    < 0, = 0, or > 0, according to the comparison
745 */
746
747 int
748 strcmpic(const uschar * s, const uschar * t)
749 {
750 while (*s)
751   {
752   int c = tolower(*s++) - tolower(*t++);
753   if (c != 0) return c;
754   }
755 return *t;
756 }
757
758
759 /*************************************************
760 *         Case-independent strstr() function     *
761 *************************************************/
762
763 /* The third argument specifies whether whitespace is required
764 to follow the matched string.
765
766 Arguments:
767   s              string to search
768   t              substring to search for
769   space_follows  if TRUE, match only if whitespace follows
770
771 Returns:         pointer to substring in string, or NULL if not found
772 */
773
774 const uschar *
775 strstric_c(const uschar * s, const uschar * t, BOOL space_follows)
776 {
777 const uschar * p = t;
778 const uschar * yield = NULL;
779 int cl = tolower(*p);
780 int cu = toupper(*p);
781
782 while (*s)
783   {
784   if (*s == cl || *s == cu)
785     {
786     if (!yield) yield = s;
787     if (!*++p)
788       {
789       if (!space_follows || s[1] == ' ' || s[1] == '\n' ) return yield;
790       yield = NULL;
791       p = t;
792       }
793     cl = tolower(*p);
794     cu = toupper(*p);
795     s++;
796     }
797   else if (yield)
798     {
799     yield = NULL;
800     p = t;
801     cl = tolower(*p);
802     cu = toupper(*p);
803     }
804   else s++;
805   }
806 return NULL;
807 }
808
809 uschar *
810 strstric(uschar * s, uschar * t, BOOL space_follows)
811 {
812 return US strstric_c(s, t, space_follows);
813 }
814
815
816 #ifdef COMPILE_UTILITY
817 /* Dummy version for this function; it should never be called */
818 static void
819 gstring_grow(gstring * g, int count)
820 {
821 assert(FALSE);
822 }
823 #endif
824
825
826
827 #ifndef COMPILE_UTILITY
828 /*************************************************
829 *       Get next string from separated list      *
830 *************************************************/
831
832 /* Leading and trailing space is removed from each item. The separator in the
833 list is controlled by the int pointed to by the separator argument as follows:
834
835   If the value is > 0 it is used as the separator. This is typically used for
836   sublists such as slash-separated options. The value is always a printing
837   character.
838
839     (If the value is actually > UCHAR_MAX there is only one item in the list.
840     This is used for some cases when called via functions that sometimes
841     plough through lists, and sometimes are given single items.)
842
843   If the value is <= 0, the string is inspected for a leading <x, where x is an
844   ispunct() or an iscntrl() character. If found, x is used as the separator. If
845   not found:
846
847       (a) if separator == 0, ':' is used
848       (b) if separator <0, -separator is used
849
850   In all cases the value of the separator that is used is written back to the
851   int so that it is used on subsequent calls as we progress through the list.
852
853 A literal ispunct() separator can be represented in an item by doubling, but
854 there is no way to include an iscntrl() separator as part of the data.
855
856 Arguments:
857   listptr    points to a pointer to the current start of the list; the
858              pointer gets updated to point after the end of the next item
859   separator  a pointer to the separator character in an int (see above)
860   buffer     where to put a copy of the next string in the list; or
861                NULL if the next string is returned in new memory
862              Note that if the list is tainted then a provided buffer must be
863              also (else we trap, with a message referencing the callsite).
864              If we do the allocation, taint is handled there.
865   buflen     when buffer is not NULL, the size of buffer; otherwise ignored
866
867   func       caller, for debug
868   line       caller, for debug
869
870 Returns:     pointer to buffer, containing the next substring,
871              or NULL if no more substrings
872 */
873
874 uschar *
875 string_nextinlist_trc(const uschar ** listptr, int * separator, uschar * buffer,
876   int buflen, const uschar * func, int line)
877 {
878 int sep = *separator;
879 const uschar * s = *listptr;
880 BOOL sep_is_special;
881
882 if (!s) return NULL;
883
884 /* This allows for a fixed specified separator to be an iscntrl() character,
885 but at the time of implementation, this is never the case. However, it's best
886 to be conservative. */
887
888 while (isspace(*s) && *s != sep) s++;
889
890 /* A change of separator is permitted, so look for a leading '<' followed by an
891 allowed character. */
892
893 if (sep <= 0)
894   {
895   if (*s == '<' && (ispunct(s[1]) || iscntrl(s[1])))
896     {
897     sep = s[1];
898     if (*++s) ++s;
899     while (isspace(*s) && *s != sep) s++;
900     }
901   else
902     sep = sep ? -sep : ':';
903   *separator = sep;
904   }
905
906 /* An empty string has no list elements */
907
908 if (!*s) return NULL;
909
910 /* Note whether whether or not the separator is an iscntrl() character. */
911
912 sep_is_special = iscntrl(sep);
913
914 /* Handle the case when a buffer is provided. */
915 /*XXX need to also deal with qouted-requirements mismatch */
916
917 if (buffer)
918   {
919   int p = 0;
920   if (is_tainted(s) && !is_tainted(buffer))
921     die_tainted(US"string_nextinlist", func, line);
922   for (; *s; s++)
923     {
924     if (*s == sep && (*(++s) != sep || sep_is_special)) break;
925     if (p < buflen - 1) buffer[p++] = *s;
926     }
927   while (p > 0 && isspace(buffer[p-1])) p--;
928   buffer[p] = '\0';
929   }
930
931 /* Handle the case when a buffer is not provided. */
932
933 else
934   {
935   gstring * g = NULL;
936
937   /* We know that *s != 0 at this point. However, it might be pointing to a
938   separator, which could indicate an empty string, or (if an ispunct()
939   character) could be doubled to indicate a separator character as data at the
940   start of a string. Avoid getting working memory for an empty item. */
941
942   if (*s == sep)
943     if (*++s != sep || sep_is_special)
944       {
945       *listptr = s;
946       return string_copy(US"");
947       }
948
949   /* Not an empty string; the first character is guaranteed to be a data
950   character. */
951
952   for (;;)
953     {
954     const uschar * ss;
955     for (ss = s + 1; *ss && *ss != sep; ) ss++;
956     g = string_catn(g, s, ss-s);
957     s = ss;
958     if (!*s || *++s != sep || sep_is_special) break;
959     }
960
961   /* Trim trailing spaces from the returned string */
962
963   /* while (g->ptr > 0 && isspace(g->s[g->ptr-1])) g->ptr--; */
964   while (  g->ptr > 0 && isspace(g->s[g->ptr-1])
965         && (g->ptr == 1 || g->s[g->ptr-2] != '\\') )
966     g->ptr--;
967   buffer = string_from_gstring(g);
968   gstring_release_unused_trc(g, CCS func, line);
969   }
970
971 /* Update the current pointer and return the new string */
972
973 *listptr = s;
974 return buffer;
975 }
976
977
978 static const uschar *
979 Ustrnchr(const uschar * s, int c, unsigned * len)
980 {
981 unsigned siz = *len;
982 while (siz)
983   {
984   if (!*s) return NULL;
985   if (*s == c)
986     {
987     *len = siz;
988     return s;
989     }
990   s++;
991   siz--;
992   }
993 return NULL;
994 }
995
996
997 /************************************************
998 *       Add element to separated list           *
999 ************************************************/
1000 /* This function is used to build a list, returning an allocated null-terminated
1001 growable string. The given element has any embedded separator characters
1002 doubled.
1003
1004 Despite having the same growable-string interface as string_cat() the list is
1005 always returned null-terminated.
1006
1007 Arguments:
1008   list  expanding-string for the list that is being built, or NULL
1009         if this is a new list that has no contents yet
1010   sep   list separator character
1011   ele   new element to be appended to the list
1012
1013 Returns:  pointer to the start of the list, changed if copied for expansion.
1014 */
1015
1016 gstring *
1017 string_append_listele(gstring * list, uschar sep, const uschar * ele)
1018 {
1019 uschar * sp;
1020
1021 if (list && list->ptr)
1022   list = string_catn(list, &sep, 1);
1023
1024 while((sp = Ustrchr(ele, sep)))
1025   {
1026   list = string_catn(list, ele, sp-ele+1);
1027   list = string_catn(list, &sep, 1);
1028   ele = sp+1;
1029   }
1030 list = string_cat(list, ele);
1031 (void) string_from_gstring(list);
1032 return list;
1033 }
1034
1035
1036 gstring *
1037 string_append_listele_n(gstring * list, uschar sep, const uschar * ele,
1038  unsigned len)
1039 {
1040 const uschar * sp;
1041
1042 if (list && list->ptr)
1043   list = string_catn(list, &sep, 1);
1044
1045 while((sp = Ustrnchr(ele, sep, &len)))
1046   {
1047   list = string_catn(list, ele, sp-ele+1);
1048   list = string_catn(list, &sep, 1);
1049   ele = sp+1;
1050   len--;
1051   }
1052 list = string_catn(list, ele, len);
1053 (void) string_from_gstring(list);
1054 return list;
1055 }
1056
1057
1058
1059 /* A slightly-bogus listmaker utility; the separator is a string so
1060 can be multiple chars - there is no checking for the element content
1061 containing any of the separator. */
1062
1063 gstring *
1064 string_append2_listele_n(gstring * list, const uschar * sepstr,
1065  const uschar * ele, unsigned len)
1066 {
1067 if (list && list->ptr)
1068   list = string_cat(list, sepstr);
1069
1070 list = string_catn(list, ele, len);
1071 (void) string_from_gstring(list);
1072 return list;
1073 }
1074
1075
1076
1077 /************************************************/
1078 /* Add more space to a growable-string.  The caller should check
1079 first if growth is required.  The gstring struct is modified on
1080 return; specifically, the string-base-pointer may have been changed.
1081
1082 Arguments:
1083   g             the growable-string
1084   count         amount needed for g->ptr to increase by
1085 */
1086
1087 static void
1088 gstring_grow(gstring * g, int count)
1089 {
1090 int p = g->ptr;
1091 int oldsize = g->size;
1092
1093 /* Mostly, string_cat() is used to build small strings of a few hundred
1094 characters at most. There are times, however, when the strings are very much
1095 longer (for example, a lookup that returns a vast number of alias addresses).
1096 To try to keep things reasonable, we use increments whose size depends on the
1097 existing length of the string. */
1098
1099 unsigned inc = oldsize < 4096 ? 127 : 1023;
1100
1101 if (g->ptr < 0 || g->ptr > g->size || g->size >= INT_MAX/2)
1102   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1103     "internal error in gstring_grow (ptr %d size %d)", g->ptr, g->size);
1104
1105 if (count <= 0) return;
1106
1107 if (count >= INT_MAX/2 - g->ptr)
1108   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1109     "internal error in gstring_grow (ptr %d count %d)", g->ptr, count);
1110
1111 g->size = (p + count + inc + 1) & ~inc;         /* one for a NUL */
1112
1113 /* Try to extend an existing allocation. If the result of calling
1114 store_extend() is false, either there isn't room in the current memory block,
1115 or this string is not the top item on the dynamic store stack. We then have
1116 to get a new chunk of store and copy the old string. When building large
1117 strings, it is helpful to call store_release() on the old string, to release
1118 memory blocks that have become empty. (The block will be freed if the string
1119 is at its start.) However, we can do this only if we know that the old string
1120 was the last item on the dynamic memory stack. This is the case if it matches
1121 store_last_get. */
1122
1123 if (!store_extend(g->s, oldsize, g->size))
1124   g->s = store_newblock(g->s, g->size, p);
1125 }
1126
1127
1128
1129 /*************************************************
1130 *             Add chars to string                *
1131 *************************************************/
1132 /* This function is used when building up strings of unknown length. Room is
1133 always left for a terminating zero to be added to the string that is being
1134 built. This function does not require the string that is being added to be NUL
1135 terminated, because the number of characters to add is given explicitly. It is
1136 sometimes called to extract parts of other strings.
1137
1138 Arguments:
1139   g        growable-string that is being built, or NULL if not assigned yet
1140   s        points to characters to add
1141   count    count of characters to add; must not exceed the length of s, if s
1142              is a C string.
1143
1144 Returns:   growable string, changed if copied for expansion.
1145            Note that a NUL is not added, though space is left for one. This is
1146            because string_cat() is often called multiple times to build up a
1147            string - there's no point adding the NUL till the end.
1148            NULL is a possible return.
1149
1150 */
1151 /* coverity[+alloc] */
1152
1153 gstring *
1154 string_catn(gstring * g, const uschar * s, int count)
1155 {
1156 int p;
1157
1158 if (count < 0)
1159   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1160     "internal error in string_catn (count %d)", count);
1161 if (count == 0) return g;
1162
1163 /*debug_printf("string_catn '%.*s'\n", count, s);*/
1164 if (!g)
1165   {
1166   unsigned inc = count < 4096 ? 127 : 1023;
1167   unsigned size = ((count + inc) &  ~inc) + 1;  /* round up requested count */
1168   g = string_get_tainted(size, s);
1169   }
1170 else if (!g->s)                 /* should not happen */
1171   {
1172   g->s = string_copyn(s, count);
1173   g->ptr = count;
1174   g->size = count;      /*XXX suboptimal*/
1175   return g;
1176   }
1177 else if (is_incompatible(g->s, s))
1178   {
1179 /* debug_printf("rebuf A\n"); */
1180   gstring_rebuffer(g, s);
1181   }
1182
1183 if (g->ptr < 0 || g->ptr > g->size)
1184   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1185     "internal error in string_catn (ptr %d size %d)", g->ptr, g->size);
1186
1187 p = g->ptr;
1188 if (count >= g->size - p)
1189   gstring_grow(g, count);
1190
1191 /* Because we always specify the exact number of characters to copy, we can
1192 use memcpy(), which is likely to be more efficient than strncopy() because the
1193 latter has to check for zero bytes. */
1194
1195 memcpy(g->s + p, s, count);
1196 g->ptr = p + count;
1197 return g;
1198 }
1199
1200
1201 gstring *
1202 string_cat(gstring * g, const uschar * s)
1203 {
1204 return string_catn(g, s, Ustrlen(s));
1205 }
1206
1207
1208
1209 /*************************************************
1210 *        Append strings to another string        *
1211 *************************************************/
1212
1213 /* This function can be used to build a string from many other strings.
1214 It calls string_cat() to do the dirty work.
1215
1216 Arguments:
1217   g        growable-string that is being built, or NULL if not yet assigned
1218   count    the number of strings to append
1219   ...      "count" uschar* arguments, which must be valid zero-terminated
1220              C strings
1221
1222 Returns:   growable string, changed if copied for expansion.
1223            The string is not zero-terminated - see string_cat() above.
1224 */
1225
1226 __inline__ gstring *
1227 string_append(gstring * g, int count, ...)
1228 {
1229 va_list ap;
1230
1231 va_start(ap, count);
1232 while (count-- > 0)
1233   {
1234   uschar * t = va_arg(ap, uschar *);
1235   g = string_cat(g, t);
1236   }
1237 va_end(ap);
1238
1239 return g;
1240 }
1241 #endif
1242
1243
1244
1245 /*************************************************
1246 *        Format a string with length checks      *
1247 *************************************************/
1248
1249 /* This function is used to format a string with checking of the length of the
1250 output for all conversions. It protects Exim from absent-mindedness when
1251 calling functions like debug_printf and string_sprintf, and elsewhere. There
1252 are two different entry points to what is actually the same function, depending
1253 on whether the variable length list of data arguments are given explicitly or
1254 as a va_list item.
1255
1256 The formats are the usual printf() ones, with some omissions (never used) and
1257 three additions for strings: %S forces lower case, %T forces upper case, and
1258 %#s or %#S prints nothing for a NULL string. Without the # "NULL" is printed
1259 (useful in debugging). There is also the addition of %D and %M, which insert
1260 the date in the form used for datestamped log files.
1261
1262 Arguments:
1263   buffer       a buffer in which to put the formatted string
1264   buflen       the length of the buffer
1265   format       the format string - deliberately char * and not uschar *
1266   ... or ap    variable list of supplementary arguments
1267
1268 Returns:       TRUE if the result fitted in the buffer
1269 */
1270
1271 BOOL
1272 string_format_trc(uschar * buffer, int buflen,
1273   const uschar * func, unsigned line, const char * format, ...)
1274 {
1275 gstring g = { .size = buflen, .ptr = 0, .s = buffer }, * gp;
1276 va_list ap;
1277 va_start(ap, format);
1278 gp = string_vformat_trc(&g, func, line, STRING_SPRINTF_BUFFER_SIZE,
1279         0, format, ap);
1280 va_end(ap);
1281 g.s[g.ptr] = '\0';
1282 return !!gp;
1283 }
1284
1285
1286
1287
1288 /* Build or append to a growing-string, sprintf-style.
1289
1290 Arguments:
1291         g       a growable-string
1292         func    called-from function name, for debug
1293         line    called-from file line number, for debug
1294         limit   maximum string size
1295         flags   see below
1296         format  printf-like format string
1297         ap      variable-args pointer
1298
1299 Flags:
1300         SVFMT_EXTEND            buffer can be created or exteded as needed
1301         SVFMT_REBUFFER          buffer can be recopied to tainted mem as needed
1302         SVFMT_TAINT_NOCHK       do not check inputs for taint
1303
1304 If the "extend" flag is true, the string passed in can be NULL,
1305 empty, or non-empty.  Growing is subject to an overall limit given
1306 by the limit argument.
1307
1308 If the "extend" flag is false, the string passed in may not be NULL,
1309 will not be grown, and is usable in the original place after return.
1310 The return value can be NULL to signify overflow.
1311
1312 Returns the possibly-new (if copy for growth or taint-handling was needed)
1313 string, not nul-terminated.
1314 */
1315
1316 gstring *
1317 string_vformat_trc(gstring * g, const uschar * func, unsigned line,
1318   unsigned size_limit, unsigned flags, const char * format, va_list ap)
1319 {
1320 enum ltypes { L_NORMAL=1, L_SHORT=2, L_LONG=3, L_LONGLONG=4, L_LONGDOUBLE=5, L_SIZE=6 };
1321
1322 int width, precision, off, lim, need;
1323 const char * fp = format;       /* Deliberately not unsigned */
1324
1325 string_datestamp_offset = -1;   /* Datestamp not inserted */
1326 string_datestamp_length = 0;    /* Datestamp not inserted */
1327 string_datestamp_type = 0;      /* Datestamp not inserted */
1328
1329 #ifdef COMPILE_UTILITY
1330 assert(!(flags & SVFMT_EXTEND));
1331 assert(g);
1332 #else
1333
1334 /* Ensure we have a string, to save on checking later */
1335 if (!g) g = string_get(16);
1336
1337 if (!(flags & SVFMT_TAINT_NOCHK) && is_incompatible(g->s, format))
1338   {
1339 #ifndef MACRO_PREDEF
1340   if (!(flags & SVFMT_REBUFFER))
1341     die_tainted(US"string_vformat", func, line);
1342 #endif
1343 /* debug_printf("rebuf B\n"); */
1344   gstring_rebuffer(g, format);
1345   }
1346 #endif  /*!COMPILE_UTILITY*/
1347
1348 lim = g->size - 1;      /* leave one for a nul */
1349 off = g->ptr;           /* remember initial offset in gstring */
1350
1351 /* Scan the format and handle the insertions */
1352
1353 while (*fp)
1354   {
1355   int length = L_NORMAL;
1356   int * nptr;
1357   int slen;
1358   const char *null = "NULL";            /* ) These variables */
1359   const char *item_start, *s;           /* ) are deliberately */
1360   char newformat[16];                   /* ) not unsigned */
1361   char * gp = CS g->s + g->ptr;         /* ) */
1362
1363   /* Non-% characters just get copied verbatim */
1364
1365   if (*fp != '%')
1366     {
1367     /* Avoid string_copyn() due to COMPILE_UTILITY */
1368     if ((need = g->ptr + 1) > lim)
1369       {
1370       if (!(flags & SVFMT_EXTEND) || need > size_limit) return NULL;
1371       gstring_grow(g, 1);
1372       lim = g->size - 1;
1373       }
1374     g->s[g->ptr++] = (uschar) *fp++;
1375     continue;
1376     }
1377
1378   /* Deal with % characters. Pick off the width and precision, for checking
1379   strings, skipping over the flag and modifier characters. */
1380
1381   item_start = fp;
1382   width = precision = -1;
1383
1384   if (strchr("-+ #0", *(++fp)) != NULL)
1385     {
1386     if (*fp == '#') null = "";
1387     fp++;
1388     }
1389
1390   if (isdigit((uschar)*fp))
1391     {
1392     width = *fp++ - '0';
1393     while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';
1394     }
1395   else if (*fp == '*')
1396     {
1397     width = va_arg(ap, int);
1398     fp++;
1399     }
1400
1401   if (*fp == '.')
1402     if (*(++fp) == '*')
1403       {
1404       precision = va_arg(ap, int);
1405       fp++;
1406       }
1407     else
1408       for (precision = 0; isdigit((uschar)*fp); fp++)
1409         precision = precision*10 + *fp - '0';
1410
1411   /* Skip over 'h', 'L', 'l', 'll' and 'z', remembering the item length */
1412
1413   if (*fp == 'h')
1414     { fp++; length = L_SHORT; }
1415   else if (*fp == 'L')
1416     { fp++; length = L_LONGDOUBLE; }
1417   else if (*fp == 'l')
1418     if (fp[1] == 'l')
1419       { fp += 2; length = L_LONGLONG; }
1420     else
1421       { fp++; length = L_LONG; }
1422   else if (*fp == 'z')
1423     { fp++; length = L_SIZE; }
1424
1425   /* Handle each specific format type. */
1426
1427   switch (*fp++)
1428     {
1429     case 'n':
1430       nptr = va_arg(ap, int *);
1431       *nptr = g->ptr - off;
1432       break;
1433
1434     case 'd':
1435     case 'o':
1436     case 'u':
1437     case 'x':
1438     case 'X':
1439       width = length > L_LONG ? 24 : 12;
1440       if ((need = g->ptr + width) > lim)
1441         {
1442         if (!(flags & SVFMT_EXTEND) || need >= size_limit) return NULL;
1443         gstring_grow(g, width);
1444         lim = g->size - 1;
1445         gp = CS g->s + g->ptr;
1446         }
1447       strncpy(newformat, item_start, fp - item_start);
1448       newformat[fp - item_start] = 0;
1449
1450       /* Short int is promoted to int when passing through ..., so we must use
1451       int for va_arg(). */
1452
1453       switch(length)
1454         {
1455         case L_SHORT:
1456         case L_NORMAL:
1457           g->ptr += sprintf(gp, newformat, va_arg(ap, int)); break;
1458         case L_LONG:
1459           g->ptr += sprintf(gp, newformat, va_arg(ap, long int)); break;
1460         case L_LONGLONG:
1461           g->ptr += sprintf(gp, newformat, va_arg(ap, LONGLONG_T)); break;
1462         case L_SIZE:
1463           g->ptr += sprintf(gp, newformat, va_arg(ap, size_t)); break;
1464         }
1465       break;
1466
1467     case 'p':
1468       {
1469       void * ptr;
1470       if ((need = g->ptr + 24) > lim)
1471         {
1472         if (!(flags & SVFMT_EXTEND || need >= size_limit)) return NULL;
1473         gstring_grow(g, 24);
1474         lim = g->size - 1;
1475         gp = CS g->s + g->ptr;
1476         }
1477       /* sprintf() saying "(nil)" for a null pointer seems unreliable.
1478       Handle it explicitly. */
1479       if ((ptr = va_arg(ap, void *)))
1480         {
1481         strncpy(newformat, item_start, fp - item_start);
1482         newformat[fp - item_start] = 0;
1483         g->ptr += sprintf(gp, newformat, ptr);
1484         }
1485       else
1486         g->ptr += sprintf(gp, "(nil)");
1487       }
1488     break;
1489
1490     /* %f format is inherently insecure if the numbers that it may be
1491     handed are unknown (e.g. 1e300). However, in Exim, %f is used for
1492     printing load averages, and these are actually stored as integers
1493     (load average * 1000) so the size of the numbers is constrained.
1494     It is also used for formatting sending rates, where the simplicity
1495     of the format prevents overflow. */
1496
1497     case 'f':
1498     case 'e':
1499     case 'E':
1500     case 'g':
1501     case 'G':
1502       if (precision < 0) precision = 6;
1503       if ((need = g->ptr + precision + 8) > lim)
1504         {
1505         if (!(flags & SVFMT_EXTEND || need >= size_limit)) return NULL;
1506         gstring_grow(g, precision+8);
1507         lim = g->size - 1;
1508         gp = CS g->s + g->ptr;
1509         }
1510       strncpy(newformat, item_start, fp - item_start);
1511       newformat[fp-item_start] = 0;
1512       if (length == L_LONGDOUBLE)
1513         g->ptr += sprintf(gp, newformat, va_arg(ap, long double));
1514       else
1515         g->ptr += sprintf(gp, newformat, va_arg(ap, double));
1516       break;
1517
1518     /* String types */
1519
1520     case '%':
1521       if ((need = g->ptr + 1) > lim)
1522         {
1523         if (!(flags & SVFMT_EXTEND || need >= size_limit)) return NULL;
1524         gstring_grow(g, 1);
1525         lim = g->size - 1;
1526         }
1527       g->s[g->ptr++] = (uschar) '%';
1528       break;
1529
1530     case 'c':
1531       if ((need = g->ptr + 1) > lim)
1532         {
1533         if (!(flags & SVFMT_EXTEND || need >= size_limit)) return NULL;
1534         gstring_grow(g, 1);
1535         lim = g->size - 1;
1536         }
1537       g->s[g->ptr++] = (uschar) va_arg(ap, int);
1538       break;
1539
1540     case 'D':                   /* Insert daily datestamp for log file names */
1541       s = CS tod_stamp(tod_log_datestamp_daily);
1542       string_datestamp_offset = g->ptr;         /* Passed back via global */
1543       string_datestamp_length = Ustrlen(s);     /* Passed back via global */
1544       string_datestamp_type = tod_log_datestamp_daily;
1545       slen = string_datestamp_length;
1546       goto INSERT_STRING;
1547
1548     case 'M':                   /* Insert monthly datestamp for log file names */
1549       s = CS tod_stamp(tod_log_datestamp_monthly);
1550       string_datestamp_offset = g->ptr;         /* Passed back via global */
1551       string_datestamp_length = Ustrlen(s);     /* Passed back via global */
1552       string_datestamp_type = tod_log_datestamp_monthly;
1553       slen = string_datestamp_length;
1554       goto INSERT_STRING;
1555
1556     case 's':
1557     case 'S':                   /* Forces *lower* case */
1558     case 'T':                   /* Forces *upper* case */
1559       s = va_arg(ap, char *);
1560
1561       if (!s) s = null;
1562       slen = Ustrlen(s);
1563
1564       if (!(flags & SVFMT_TAINT_NOCHK) && is_incompatible(g->s, s))
1565         if (flags & SVFMT_REBUFFER)
1566           {
1567 /* debug_printf("%s %d: untainted workarea, tainted %%s :- rebuffer\n", __FUNCTION__, __LINE__); */
1568           gstring_rebuffer(g, s);
1569           gp = CS g->s + g->ptr;
1570           }
1571 #ifndef MACRO_PREDEF
1572         else
1573           die_tainted(US"string_vformat", func, line);
1574 #endif
1575
1576     INSERT_STRING:              /* Come to from %D or %M above */
1577
1578       {
1579       BOOL truncated = FALSE;
1580
1581       /* If the width is specified, check that there is a precision
1582       set; if not, set it to the width to prevent overruns of long
1583       strings. */
1584
1585       if (width >= 0)
1586         {
1587         if (precision < 0) precision = width;
1588         }
1589
1590       /* If a width is not specified and the precision is specified, set
1591       the width to the precision, or the string length if shorted. */
1592
1593       else if (precision >= 0)
1594         width = precision < slen ? precision : slen;
1595
1596       /* If neither are specified, set them both to the string length. */
1597
1598       else
1599         width = precision = slen;
1600
1601       if ((need = g->ptr + width) >= size_limit || !(flags & SVFMT_EXTEND))
1602         {
1603         if (g->ptr == lim) return NULL;
1604         if (need > lim)
1605           {
1606           truncated = TRUE;
1607           width = precision = lim - g->ptr - 1;
1608           if (width < 0) width = 0;
1609           if (precision < 0) precision = 0;
1610           }
1611         }
1612       else if (need > lim)
1613         {
1614         gstring_grow(g, width);
1615         lim = g->size - 1;
1616         gp = CS g->s + g->ptr;
1617         }
1618
1619       g->ptr += sprintf(gp, "%*.*s", width, precision, s);
1620       if (fp[-1] == 'S')
1621         while (*gp) { *gp = tolower(*gp); gp++; }
1622       else if (fp[-1] == 'T')
1623         while (*gp) { *gp = toupper(*gp); gp++; }
1624
1625       if (truncated) return NULL;
1626       break;
1627       }
1628
1629     /* Some things are never used in Exim; also catches junk. */
1630
1631     default:
1632       strncpy(newformat, item_start, fp - item_start);
1633       newformat[fp-item_start] = 0;
1634       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "string_format: unsupported type "
1635         "in \"%s\" in \"%s\"", newformat, format);
1636       break;
1637     }
1638   }
1639
1640 if (g->ptr > g->size)
1641   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1642     "string_format internal error: caller %s %d", func, line);
1643 return g;
1644 }
1645
1646
1647
1648 #ifndef COMPILE_UTILITY
1649 /*************************************************
1650 *       Generate an "open failed" message        *
1651 *************************************************/
1652
1653 /* This function creates a message after failure to open a file. It includes a
1654 string supplied as data, adds the strerror() text, and if the failure was
1655 "Permission denied", reads and includes the euid and egid.
1656
1657 Arguments:
1658   format        a text format string - deliberately not uschar *
1659   func          caller, for debug
1660   line          caller, for debug
1661   ...           arguments for the format string
1662
1663 Returns:        a message, in dynamic store
1664 */
1665
1666 uschar *
1667 string_open_failed_trc(const uschar * func, unsigned line,
1668   const char * format, ...)
1669 {
1670 va_list ap;
1671 gstring * g = string_get(1024);
1672
1673 g = string_catn(g, US"failed to open ", 15);
1674
1675 /* Use the checked formatting routine to ensure that the buffer
1676 does not overflow. It should not, since this is called only for internally
1677 specified messages. If it does, the message just gets truncated, and there
1678 doesn't seem much we can do about that. */
1679
1680 va_start(ap, format);
1681 (void) string_vformat_trc(g, func, line, STRING_SPRINTF_BUFFER_SIZE,
1682         SVFMT_REBUFFER, format, ap);
1683 va_end(ap);
1684
1685 g = string_catn(g, US": ", 2);
1686 g = string_cat(g, US strerror(errno));
1687
1688 if (errno == EACCES)
1689   {
1690   int save_errno = errno;
1691   g = string_fmt_append(g, " (euid=%ld egid=%ld)",
1692     (long int)geteuid(), (long int)getegid());
1693   errno = save_errno;
1694   }
1695 gstring_release_unused(g);
1696 return string_from_gstring(g);
1697 }
1698
1699
1700
1701
1702
1703 /* qsort(3), currently used to sort the environment variables
1704 for -bP environment output, needs a function to compare two pointers to string
1705 pointers. Here it is. */
1706
1707 int
1708 string_compare_by_pointer(const void *a, const void *b)
1709 {
1710 return Ustrcmp(* CUSS a, * CUSS b);
1711 }
1712 #endif /* COMPILE_UTILITY */
1713
1714
1715
1716
1717 /*************************************************
1718 **************************************************
1719 *             Stand-alone test program           *
1720 **************************************************
1721 *************************************************/
1722
1723 #ifdef STAND_ALONE
1724 int main(void)
1725 {
1726 uschar buffer[256];
1727
1728 printf("Testing is_ip_address\n");
1729 store_init();
1730
1731 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1732   {
1733   int offset;
1734   buffer[Ustrlen(buffer) - 1] = 0;
1735   printf("%d\n", string_is_ip_address(buffer, NULL));
1736   printf("%d %d %s\n", string_is_ip_address(buffer, &offset), offset, buffer);
1737   }
1738
1739 printf("Testing string_nextinlist\n");
1740
1741 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1742   {
1743   uschar *list = buffer;
1744   uschar *lp1, *lp2;
1745   uschar item[256];
1746   int sep1 = 0;
1747   int sep2 = 0;
1748
1749   if (*list == '<')
1750     {
1751     sep1 = sep2 = list[1];
1752     list += 2;
1753     }
1754
1755   lp1 = lp2 = list;
1756   for (;;)
1757     {
1758     uschar *item1 = string_nextinlist(&lp1, &sep1, item, sizeof(item));
1759     uschar *item2 = string_nextinlist(&lp2, &sep2, NULL, 0);
1760
1761     if (item1 == NULL && item2 == NULL) break;
1762     if (item == NULL || item2 == NULL || Ustrcmp(item1, item2) != 0)
1763       {
1764       printf("***ERROR\nitem1=\"%s\"\nitem2=\"%s\"\n",
1765         (item1 == NULL)? "NULL" : CS item1,
1766         (item2 == NULL)? "NULL" : CS item2);
1767       break;
1768       }
1769     else printf("  \"%s\"\n", CS item1);
1770     }
1771   }
1772
1773 /* This is a horrible lash-up, but it serves its purpose. */
1774
1775 printf("Testing string_format\n");
1776
1777 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1778   {
1779   void *args[3];
1780   long long llargs[3];
1781   double dargs[3];
1782   int dflag = 0;
1783   int llflag = 0;
1784   int n = 0;
1785   int count;
1786   int countset = 0;
1787   uschar format[256];
1788   uschar outbuf[256];
1789   uschar *s;
1790   buffer[Ustrlen(buffer) - 1] = 0;
1791
1792   s = Ustrchr(buffer, ',');
1793   if (s == NULL) s = buffer + Ustrlen(buffer);
1794
1795   Ustrncpy(format, buffer, s - buffer);
1796   format[s-buffer] = 0;
1797
1798   if (*s == ',') s++;
1799
1800   while (*s != 0)
1801     {
1802     uschar *ss = s;
1803     s = Ustrchr(ss, ',');
1804     if (s == NULL) s = ss + Ustrlen(ss);
1805
1806     if (isdigit(*ss))
1807       {
1808       Ustrncpy(outbuf, ss, s-ss);
1809       if (Ustrchr(outbuf, '.') != NULL)
1810         {
1811         dflag = 1;
1812         dargs[n++] = Ustrtod(outbuf, NULL);
1813         }
1814       else if (Ustrstr(outbuf, "ll") != NULL)
1815         {
1816         llflag = 1;
1817         llargs[n++] = strtoull(CS outbuf, NULL, 10);
1818         }
1819       else
1820         {
1821         args[n++] = (void *)Uatoi(outbuf);
1822         }
1823       }
1824
1825     else if (Ustrcmp(ss, "*") == 0)
1826       {
1827       args[n++] = (void *)(&count);
1828       countset = 1;
1829       }
1830
1831     else
1832       {
1833       uschar *sss = malloc(s - ss + 1);
1834       Ustrncpy(sss, ss, s-ss);
1835       args[n++] = sss;
1836       }
1837
1838     if (*s == ',') s++;
1839     }
1840
1841   if (!dflag && !llflag)
1842     printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1843       args[0], args[1], args[2])? "True" : "False");
1844
1845   else if (dflag)
1846     printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1847       dargs[0], dargs[1], dargs[2])? "True" : "False");
1848
1849   else printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1850     llargs[0], llargs[1], llargs[2])? "True" : "False");
1851
1852   printf("%s\n", CS outbuf);
1853   if (countset) printf("count=%d\n", count);
1854   }
1855
1856 return 0;
1857 }
1858 #endif
1859
1860 /* End of string.c */