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