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