Fix string_unprinting()
[exim.git] / src / src / string.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2012 */
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(const 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   const 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     p++;
379     }
380   else
381     {
382     r = Ustrchr(p, '\\');
383     if (!r)
384       {
385       off = Ustrlen(p);
386       memcpy(q, p, off);
387       p += off;
388       q += off;
389       break;
390       }
391     else
392       {
393       off = r - p;
394       memcpy(q, p, off);
395       q += off;
396       p = r;
397       }
398     }
399   }
400 *q = '\0';
401
402 return ss;
403 }
404
405
406
407
408 /*************************************************
409 *            Copy and save string                *
410 *************************************************/
411
412 /* This function assumes that memcpy() is faster than strcpy().
413
414 Argument: string to copy
415 Returns:  copy of string in new store
416 */
417
418 uschar *
419 string_copy(const uschar *s)
420 {
421 int len = Ustrlen(s) + 1;
422 uschar *ss = store_get(len);
423 memcpy(ss, s, len);
424 return ss;
425 }
426
427
428
429 /*************************************************
430 *     Copy and save string in malloc'd store     *
431 *************************************************/
432
433 /* This function assumes that memcpy() is faster than strcpy().
434
435 Argument: string to copy
436 Returns:  copy of string in new store
437 */
438
439 uschar *
440 string_copy_malloc(uschar *s)
441 {
442 int len = Ustrlen(s) + 1;
443 uschar *ss = store_malloc(len);
444 memcpy(ss, s, len);
445 return ss;
446 }
447
448
449
450 /*************************************************
451 *       Copy, lowercase and save string          *
452 *************************************************/
453
454 /*
455 Argument: string to copy
456 Returns:  copy of string in new store, with letters lowercased
457 */
458
459 uschar *
460 string_copylc(uschar *s)
461 {
462 uschar *ss = store_get(Ustrlen(s) + 1);
463 uschar *p = ss;
464 while (*s != 0) *p++ = tolower(*s++);
465 *p = 0;
466 return ss;
467 }
468
469
470
471 /*************************************************
472 *       Copy and save string, given length       *
473 *************************************************/
474
475 /* It is assumed the data contains no zeros. A zero is added
476 onto the end.
477
478 Arguments:
479   s         string to copy
480   n         number of characters
481
482 Returns:    copy of string in new store
483 */
484
485 uschar *
486 string_copyn(uschar *s, int n)
487 {
488 uschar *ss = store_get(n + 1);
489 Ustrncpy(ss, s, n);
490 ss[n] = 0;
491 return ss;
492 }
493
494
495 /*************************************************
496 * Copy, lowercase, and save string, given length *
497 *************************************************/
498
499 /* It is assumed the data contains no zeros. A zero is added
500 onto the end.
501
502 Arguments:
503   s         string to copy
504   n         number of characters
505
506 Returns:    copy of string in new store, with letters lowercased
507 */
508
509 uschar *
510 string_copynlc(uschar *s, int n)
511 {
512 uschar *ss = store_get(n + 1);
513 uschar *p = ss;
514 while (n-- > 0) *p++ = tolower(*s++);
515 *p = 0;
516 return ss;
517 }
518
519
520
521 /*************************************************
522 *    Copy string if long, inserting newlines     *
523 *************************************************/
524
525 /* If the given string is longer than 75 characters, it is copied, and within
526 the copy, certain space characters are converted into newlines.
527
528 Argument:  pointer to the string
529 Returns:   pointer to the possibly altered string
530 */
531
532 uschar *
533 string_split_message(uschar *msg)
534 {
535 uschar *s, *ss;
536
537 if (msg == NULL || Ustrlen(msg) <= 75) return msg;
538 s = ss = msg = string_copy(msg);
539
540 for (;;)
541   {
542   int i = 0;
543   while (i < 75 && *ss != 0 && *ss != '\n') ss++, i++;
544   if (*ss == 0) break;
545   if (*ss == '\n')
546     s = ++ss;
547   else
548     {
549     uschar *t = ss + 1;
550     uschar *tt = NULL;
551     while (--t > s + 35)
552       {
553       if (*t == ' ')
554         {
555         if (t[-1] == ':') { tt = t; break; }
556         if (tt == NULL) tt = t;
557         }
558       }
559
560     if (tt == NULL)          /* Can't split behind - try ahead */
561       {
562       t = ss + 1;
563       while (*t != 0)
564         {
565         if (*t == ' ' || *t == '\n')
566           { tt = t; break; }
567         t++;
568         }
569       }
570
571     if (tt == NULL) break;   /* Can't find anywhere to split */
572     *tt = '\n';
573     s = ss = tt+1;
574     }
575   }
576
577 return msg;
578 }
579
580
581
582 /*************************************************
583 *   Copy returned DNS domain name, de-escaping   *
584 *************************************************/
585
586 /* If a domain name contains top-bit characters, some resolvers return
587 the fully qualified name with those characters turned into escapes. The
588 convention is a backslash followed by _decimal_ digits. We convert these
589 back into the original binary values. This will be relevant when
590 allow_utf8_domains is set true and UTF-8 characters are used in domain
591 names. Backslash can also be used to escape other characters, though we
592 shouldn't come across them in domain names.
593
594 Argument:   the domain name string
595 Returns:    copy of string in new store, de-escaped
596 */
597
598 uschar *
599 string_copy_dnsdomain(uschar *s)
600 {
601 uschar *yield;
602 uschar *ss = yield = store_get(Ustrlen(s) + 1);
603
604 while (*s != 0)
605   {
606   if (*s != '\\')
607     {
608     *ss++ = *s++;
609     }
610   else if (isdigit(s[1]))
611     {
612     *ss++ = (s[1] - '0')*100 + (s[2] - '0')*10 + s[3] - '0';
613     s += 4;
614     }
615   else if (*(++s) != 0)
616     {
617     *ss++ = *s++;
618     }
619   }
620
621 *ss = 0;
622 return yield;
623 }
624
625
626 #ifndef COMPILE_UTILITY
627 /*************************************************
628 *     Copy space-terminated or quoted string     *
629 *************************************************/
630
631 /* This function copies from a string until its end, or until whitespace is
632 encountered, unless the string begins with a double quote, in which case the
633 terminating quote is sought, and escaping within the string is done. The length
634 of a de-quoted string can be no longer than the original, since escaping always
635 turns n characters into 1 character.
636
637 Argument:  pointer to the pointer to the first character, which gets updated
638 Returns:   the new string
639 */
640
641 uschar *
642 string_dequote(uschar **sptr)
643 {
644 uschar *s = *sptr;
645 uschar *t, *yield;
646
647 /* First find the end of the string */
648
649 if (*s != '\"')
650   {
651   while (*s != 0 && !isspace(*s)) s++;
652   }
653 else
654   {
655   s++;
656   while (*s != 0 && *s != '\"')
657     {
658     if (*s == '\\') (void)string_interpret_escape(&s);
659     s++;
660     }
661   if (*s != 0) s++;
662   }
663
664 /* Get enough store to copy into */
665
666 t = yield = store_get(s - *sptr + 1);
667 s = *sptr;
668
669 /* Do the copy */
670
671 if (*s != '\"')
672   {
673   while (*s != 0 && !isspace(*s)) *t++ = *s++;
674   }
675 else
676   {
677   s++;
678   while (*s != 0 && *s != '\"')
679     {
680     if (*s == '\\') *t++ = string_interpret_escape(&s);
681       else *t++ = *s;
682     s++;
683     }
684   if (*s != 0) s++;
685   }
686
687 /* Update the pointer and return the terminated copy */
688
689 *sptr = s;
690 *t = 0;
691 return yield;
692 }
693 #endif  /* COMPILE_UTILITY */
694
695
696
697 /*************************************************
698 *          Format a string and save it           *
699 *************************************************/
700
701 /* The formatting is done by string_format, which checks the length of
702 everything.
703
704 Arguments:
705   format    a printf() format - deliberately char * rather than uschar *
706               because it will most usually be a literal string
707   ...       arguments for format
708
709 Returns:    pointer to fresh piece of store containing sprintf'ed string
710 */
711
712 uschar *
713 string_sprintf(const char *format, ...)
714 {
715 va_list ap;
716 uschar buffer[STRING_SPRINTF_BUFFER_SIZE];
717 va_start(ap, format);
718 if (!string_vformat(buffer, sizeof(buffer), format, ap))
719   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
720     "string_sprintf expansion was longer than " SIZE_T_FMT, sizeof(buffer));
721 va_end(ap);
722 return string_copy(buffer);
723 }
724
725
726
727 /*************************************************
728 *         Case-independent strncmp() function    *
729 *************************************************/
730
731 /*
732 Arguments:
733   s         first string
734   t         second string
735   n         number of characters to compare
736
737 Returns:    < 0, = 0, or > 0, according to the comparison
738 */
739
740 int
741 strncmpic(const uschar *s, const uschar *t, int n)
742 {
743 while (n--)
744   {
745   int c = tolower(*s++) - tolower(*t++);
746   if (c) return c;
747   }
748 return 0;
749 }
750
751
752 /*************************************************
753 *         Case-independent strcmp() function     *
754 *************************************************/
755
756 /*
757 Arguments:
758   s         first string
759   t         second string
760
761 Returns:    < 0, = 0, or > 0, according to the comparison
762 */
763
764 int
765 strcmpic(const uschar *s, const uschar *t)
766 {
767 while (*s != 0)
768   {
769   int c = tolower(*s++) - tolower(*t++);
770   if (c != 0) return c;
771   }
772 return *t;
773 }
774
775
776 /*************************************************
777 *         Case-independent strstr() function     *
778 *************************************************/
779
780 /* The third argument specifies whether whitespace is required
781 to follow the matched string.
782
783 Arguments:
784   s              string to search
785   t              substring to search for
786   space_follows  if TRUE, match only if whitespace follows
787
788 Returns:         pointer to substring in string, or NULL if not found
789 */
790
791 uschar *
792 strstric(uschar *s, uschar *t, BOOL space_follows)
793 {
794 uschar *p = t;
795 uschar *yield = NULL;
796 int cl = tolower(*p);
797 int cu = toupper(*p);
798
799 while (*s)
800   {
801   if (*s == cl || *s == cu)
802     {
803     if (yield == NULL) yield = s;
804     if (*(++p) == 0)
805       {
806       if (!space_follows || s[1] == ' ' || s[1] == '\n' ) return yield;
807       yield = NULL;
808       p = t;
809       }
810     cl = tolower(*p);
811     cu = toupper(*p);
812     s++;
813     }
814   else if (yield != NULL)
815     {
816     yield = NULL;
817     p = t;
818     cl = tolower(*p);
819     cu = toupper(*p);
820     }
821   else s++;
822   }
823 return NULL;
824 }
825
826
827
828 #ifndef COMPILE_UTILITY
829 /*************************************************
830 *       Get next string from separated list      *
831 *************************************************/
832
833 /* Leading and trailing space is removed from each item. The separator in the
834 list is controlled by the int pointed to by the separator argument as follows:
835
836   If the value is > 0 it is used as the separator. This is typically used for
837   sublists such as slash-separated options. The value is always a printing
838   character.
839
840     (If the value is actually > UCHAR_MAX there is only one item in the list.
841     This is used for some cases when called via functions that sometimes
842     plough through lists, and sometimes are given single items.)
843
844   If the value is <= 0, the string is inspected for a leading <x, where x is an
845   ispunct() or an iscntrl() character. If found, x is used as the separator. If
846   not found:
847
848       (a) if separator == 0, ':' is used
849       (b) if separator <0, -separator is used
850
851   In all cases the value of the separator that is used is written back to the
852   int so that it is used on subsequent calls as we progress through the list.
853
854 A literal ispunct() separator can be represented in an item by doubling, but
855 there is no way to include an iscntrl() separator as part of the data.
856
857 Arguments:
858   listptr    points to a pointer to the current start of the list; the
859              pointer gets updated to point after the end of the next item
860   separator  a pointer to the separator character in an int (see above)
861   buffer     where to put a copy of the next string in the list; or
862                NULL if the next string is returned in new memory
863   buflen     when buffer is not NULL, the size of buffer; otherwise ignored
864
865 Returns:     pointer to buffer, containing the next substring,
866              or NULL if no more substrings
867 */
868
869 uschar *
870 string_nextinlist(uschar **listptr, int *separator, uschar *buffer, int buflen)
871 {
872 register int sep = *separator;
873 register uschar *s = *listptr;
874 BOOL sep_is_special;
875
876 if (s == NULL) return NULL;
877
878 /* This allows for a fixed specified separator to be an iscntrl() character,
879 but at the time of implementation, this is never the case. However, it's best
880 to be conservative. */
881
882 while (isspace(*s) && *s != sep) s++;
883
884 /* A change of separator is permitted, so look for a leading '<' followed by an
885 allowed character. */
886
887 if (sep <= 0)
888   {
889   if (*s == '<' && (ispunct(s[1]) || iscntrl(s[1])))
890     {
891     sep = s[1];
892     s += 2;
893     while (isspace(*s) && *s != sep) s++;
894     }
895   else
896     {
897     sep = (sep == 0)? ':' : -sep;
898     }
899   *separator = sep;
900   }
901
902 /* An empty string has no list elements */
903
904 if (*s == 0) return NULL;
905
906 /* Note whether whether or not the separator is an iscntrl() character. */
907
908 sep_is_special = iscntrl(sep);
909
910 /* Handle the case when a buffer is provided. */
911
912 if (buffer != NULL)
913   {
914   register int p = 0;
915   for (; *s != 0; s++)
916     {
917     if (*s == sep && (*(++s) != sep || sep_is_special)) break;
918     if (p < buflen - 1) buffer[p++] = *s;
919     }
920   while (p > 0 && isspace(buffer[p-1])) p--;
921   buffer[p] = 0;
922   }
923
924 /* Handle the case when a buffer is not provided. */
925
926 else
927   {
928   int size = 0;
929   int ptr = 0;
930   uschar *ss;
931
932   /* We know that *s != 0 at this point. However, it might be pointing to a
933   separator, which could indicate an empty string, or (if an ispunct()
934   character) could be doubled to indicate a separator character as data at the
935   start of a string. Avoid getting working memory for an empty item. */
936
937   if (*s == sep)
938     {
939     s++;
940     if (*s != sep || sep_is_special)
941       {
942       *listptr = s;
943       return string_copy(US"");
944       }
945     }
946
947   /* Not an empty string; the first character is guaranteed to be a data
948   character. */
949
950   for (;;)
951     {
952     for (ss = s + 1; *ss != 0 && *ss != sep; ss++);
953     buffer = string_cat(buffer, &size, &ptr, s, ss-s);
954     s = ss;
955     if (*s == 0 || *(++s) != sep || sep_is_special) break;
956     }
957   while (ptr > 0 && isspace(buffer[ptr-1])) ptr--;
958   buffer[ptr] = 0;
959   }
960
961 /* Update the current pointer and return the new string */
962
963 *listptr = s;
964 return buffer;
965 }
966 #endif  /* COMPILE_UTILITY */
967
968
969
970 #ifndef COMPILE_UTILITY
971 /*************************************************
972 *             Add chars to string                *
973 *************************************************/
974
975 /* This function is used when building up strings of unknown length. Room is
976 always left for a terminating zero to be added to the string that is being
977 built. This function does not require the string that is being added to be NUL
978 terminated, because the number of characters to add is given explicitly. It is
979 sometimes called to extract parts of other strings.
980
981 Arguments:
982   string   points to the start of the string that is being built, or NULL
983              if this is a new string that has no contents yet
984   size     points to a variable that holds the current capacity of the memory
985              block (updated if changed)
986   ptr      points to a variable that holds the offset at which to add
987              characters, updated to the new offset
988   s        points to characters to add
989   count    count of characters to add; must not exceed the length of s, if s
990              is a C string
991
992 If string is given as NULL, *size and *ptr should both be zero.
993
994 Returns:   pointer to the start of the string, changed if copied for expansion.
995            Note that a NUL is not added, though space is left for one. This is
996            because string_cat() is often called multiple times to build up a
997            string - there's no point adding the NUL till the end.
998 */
999
1000 uschar *
1001 string_cat(uschar *string, int *size, int *ptr, const uschar *s, int count)
1002 {
1003 int p = *ptr;
1004
1005 if (p + count >= *size)
1006   {
1007   int oldsize = *size;
1008
1009   /* Mostly, string_cat() is used to build small strings of a few hundred
1010   characters at most. There are times, however, when the strings are very much
1011   longer (for example, a lookup that returns a vast number of alias addresses).
1012   To try to keep things reasonable, we use increments whose size depends on the
1013   existing length of the string. */
1014
1015   int inc = (oldsize < 4096)? 100 : 1024;
1016   while (*size <= p + count) *size += inc;
1017
1018   /* New string */
1019
1020   if (string == NULL) string = store_get(*size);
1021
1022   /* Try to extend an existing allocation. If the result of calling
1023   store_extend() is false, either there isn't room in the current memory block,
1024   or this string is not the top item on the dynamic store stack. We then have
1025   to get a new chunk of store and copy the old string. When building large
1026   strings, it is helpful to call store_release() on the old string, to release
1027   memory blocks that have become empty. (The block will be freed if the string
1028   is at its start.) However, we can do this only if we know that the old string
1029   was the last item on the dynamic memory stack. This is the case if it matches
1030   store_last_get. */
1031
1032   else if (!store_extend(string, oldsize, *size))
1033     {
1034     BOOL release_ok = store_last_get[store_pool] == string;
1035     uschar *newstring = store_get(*size);
1036     memcpy(newstring, string, p);
1037     if (release_ok) store_release(string);
1038     string = newstring;
1039     }
1040   }
1041
1042 /* Because we always specify the exact number of characters to copy, we can
1043 use memcpy(), which is likely to be more efficient than strncopy() because the
1044 latter has to check for zero bytes. */
1045
1046 memcpy(string + p, s, count);
1047 *ptr = p + count;
1048 return string;
1049 }
1050 #endif  /* COMPILE_UTILITY */
1051
1052
1053
1054 #ifndef COMPILE_UTILITY
1055 /*************************************************
1056 *        Append strings to another string        *
1057 *************************************************/
1058
1059 /* This function can be used to build a string from many other strings.
1060 It calls string_cat() to do the dirty work.
1061
1062 Arguments:
1063   string   points to the start of the string that is being built, or NULL
1064              if this is a new string that has no contents yet
1065   size     points to a variable that holds the current capacity of the memory
1066              block (updated if changed)
1067   ptr      points to a variable that holds the offset at which to add
1068              characters, updated to the new offset
1069   count    the number of strings to append
1070   ...      "count" uschar* arguments, which must be valid zero-terminated
1071              C strings
1072
1073 Returns:   pointer to the start of the string, changed if copied for expansion.
1074            The string is not zero-terminated - see string_cat() above.
1075 */
1076
1077 uschar *
1078 string_append(uschar *string, int *size, int *ptr, int count, ...)
1079 {
1080 va_list ap;
1081 int i;
1082
1083 va_start(ap, count);
1084 for (i = 0; i < count; i++)
1085   {
1086   uschar *t = va_arg(ap, uschar *);
1087   string = string_cat(string, size, ptr, t, Ustrlen(t));
1088   }
1089 va_end(ap);
1090
1091 return string;
1092 }
1093 #endif
1094
1095
1096
1097 /*************************************************
1098 *        Format a string with length checks      *
1099 *************************************************/
1100
1101 /* This function is used to format a string with checking of the length of the
1102 output for all conversions. It protects Exim from absent-mindedness when
1103 calling functions like debug_printf and string_sprintf, and elsewhere. There
1104 are two different entry points to what is actually the same function, depending
1105 on whether the variable length list of data arguments are given explicitly or
1106 as a va_list item.
1107
1108 The formats are the usual printf() ones, with some omissions (never used) and
1109 two additions for strings: %S forces lower case, and %#s or %#S prints nothing
1110 for a NULL string. Without the # "NULL" is printed (useful in debugging). There
1111 is also the addition of %D and %M, which insert the date in the form used for
1112 datestamped log files.
1113
1114 Arguments:
1115   buffer       a buffer in which to put the formatted string
1116   buflen       the length of the buffer
1117   format       the format string - deliberately char * and not uschar *
1118   ... or ap    variable list of supplementary arguments
1119
1120 Returns:       TRUE if the result fitted in the buffer
1121 */
1122
1123 BOOL
1124 string_format(uschar *buffer, int buflen, const char *format, ...)
1125 {
1126 BOOL yield;
1127 va_list ap;
1128 va_start(ap, format);
1129 yield = string_vformat(buffer, buflen, format, ap);
1130 va_end(ap);
1131 return yield;
1132 }
1133
1134
1135 BOOL
1136 string_vformat(uschar *buffer, int buflen, const char *format, va_list ap)
1137 {
1138 /* We assume numbered ascending order, C does not guarantee that */
1139 enum { L_NORMAL=1, L_SHORT=2, L_LONG=3, L_LONGLONG=4, L_LONGDOUBLE=5, L_SIZE=6 };
1140
1141 BOOL yield = TRUE;
1142 int width, precision;
1143 const char *fp = format;       /* Deliberately not unsigned */
1144 uschar *p = buffer;
1145 uschar *last = buffer + buflen - 1;
1146
1147 string_datestamp_offset = -1;  /* Datestamp not inserted */
1148 string_datestamp_length = 0;   /* Datestamp not inserted */
1149 string_datestamp_type = 0;     /* Datestamp not inserted */
1150
1151 /* Scan the format and handle the insertions */
1152
1153 while (*fp != 0)
1154   {
1155   int length = L_NORMAL;
1156   int *nptr;
1157   int slen;
1158   const char *null = "NULL";   /* ) These variables */
1159   const char *item_start, *s;  /* ) are deliberately */
1160   char newformat[16];          /* ) not unsigned */
1161
1162   /* Non-% characters just get copied verbatim */
1163
1164   if (*fp != '%')
1165     {
1166     if (p >= last) { yield = FALSE; break; }
1167     *p++ = (uschar)*fp++;
1168     continue;
1169     }
1170
1171   /* Deal with % characters. Pick off the width and precision, for checking
1172   strings, skipping over the flag and modifier characters. */
1173
1174   item_start = fp;
1175   width = precision = -1;
1176
1177   if (strchr("-+ #0", *(++fp)) != NULL)
1178     {
1179     if (*fp == '#') null = "";
1180     fp++;
1181     }
1182
1183   if (isdigit((uschar)*fp))
1184     {
1185     width = *fp++ - '0';
1186     while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';
1187     }
1188   else if (*fp == '*')
1189     {
1190     width = va_arg(ap, int);
1191     fp++;
1192     }
1193
1194   if (*fp == '.')
1195     {
1196     if (*(++fp) == '*')
1197       {
1198       precision = va_arg(ap, int);
1199       fp++;
1200       }
1201     else
1202       {
1203       precision = 0;
1204       while (isdigit((uschar)*fp))
1205         precision = precision*10 + *fp++ - '0';
1206       }
1207     }
1208
1209   /* Skip over 'h', 'L', 'l', 'll' and 'z', remembering the item length */
1210
1211   if (*fp == 'h')
1212     { fp++; length = L_SHORT; }
1213   else if (*fp == 'L')
1214     { fp++; length = L_LONGDOUBLE; }
1215   else if (*fp == 'l')
1216     {
1217     if (fp[1] == 'l')
1218       {
1219       fp += 2;
1220       length = L_LONGLONG;
1221       }
1222     else
1223       {
1224       fp++;
1225       length = L_LONG;
1226       }
1227     }
1228   else if (*fp == 'z')
1229     { fp++; length = L_SIZE; }
1230
1231   /* Handle each specific format type. */
1232
1233   switch (*fp++)
1234     {
1235     case 'n':
1236     nptr = va_arg(ap, int *);
1237     *nptr = p - buffer;
1238     break;
1239
1240     case 'd':
1241     case 'o':
1242     case 'u':
1243     case 'x':
1244     case 'X':
1245     if (p >= last - ((length > L_LONG)? 24 : 12))
1246       { yield = FALSE; goto END_FORMAT; }
1247     strncpy(newformat, item_start, fp - item_start);
1248     newformat[fp - item_start] = 0;
1249
1250     /* Short int is promoted to int when passing through ..., so we must use
1251     int for va_arg(). */
1252
1253     switch(length)
1254       {
1255       case L_SHORT:
1256       case L_NORMAL:   sprintf(CS p, newformat, va_arg(ap, int)); break;
1257       case L_LONG:     sprintf(CS p, newformat, va_arg(ap, long int)); break;
1258       case L_LONGLONG: sprintf(CS p, newformat, va_arg(ap, LONGLONG_T)); break;
1259       case L_SIZE:     sprintf(CS p, newformat, va_arg(ap, size_t)); break;
1260       }
1261     while (*p) p++;
1262     break;
1263
1264     case 'p':
1265     if (p >= last - 24) { yield = FALSE; goto END_FORMAT; }
1266     strncpy(newformat, item_start, fp - item_start);
1267     newformat[fp - item_start] = 0;
1268     sprintf(CS p, newformat, va_arg(ap, void *));
1269     while (*p) p++;
1270     break;
1271
1272     /* %f format is inherently insecure if the numbers that it may be
1273     handed are unknown (e.g. 1e300). However, in Exim, %f is used for
1274     printing load averages, and these are actually stored as integers
1275     (load average * 1000) so the size of the numbers is constrained.
1276     It is also used for formatting sending rates, where the simplicity
1277     of the format prevents overflow. */
1278
1279     case 'f':
1280     case 'e':
1281     case 'E':
1282     case 'g':
1283     case 'G':
1284     if (precision < 0) precision = 6;
1285     if (p >= last - precision - 8) { yield = FALSE; goto END_FORMAT; }
1286     strncpy(newformat, item_start, fp - item_start);
1287     newformat[fp-item_start] = 0;
1288     if (length == L_LONGDOUBLE)
1289       sprintf(CS p, newformat, va_arg(ap, long double));
1290     else
1291       sprintf(CS p, newformat, va_arg(ap, double));
1292     while (*p) p++;
1293     break;
1294
1295     /* String types */
1296
1297     case '%':
1298     if (p >= last) { yield = FALSE; goto END_FORMAT; }
1299     *p++ = '%';
1300     break;
1301
1302     case 'c':
1303     if (p >= last) { yield = FALSE; goto END_FORMAT; }
1304     *p++ = va_arg(ap, int);
1305     break;
1306
1307     case 'D':                   /* Insert daily datestamp for log file names */
1308     s = CS tod_stamp(tod_log_datestamp_daily);
1309     string_datestamp_offset = p - buffer;   /* Passed back via global */
1310     string_datestamp_length = Ustrlen(s);   /* Passed back via global */
1311     string_datestamp_type = tod_log_datestamp_daily;
1312     slen = string_datestamp_length;
1313     goto INSERT_STRING;
1314
1315     case 'M':                   /* Insert monthly datestamp for log file names */
1316     s = CS tod_stamp(tod_log_datestamp_monthly);
1317     string_datestamp_offset = p - buffer;   /* Passed back via global */
1318     string_datestamp_length = Ustrlen(s);   /* Passed back via global */
1319     string_datestamp_type = tod_log_datestamp_monthly;
1320     slen = string_datestamp_length;
1321     goto INSERT_STRING;
1322
1323     case 's':
1324     case 'S':                   /* Forces *lower* case */
1325     s = va_arg(ap, char *);
1326
1327     if (s == NULL) s = null;
1328     slen = Ustrlen(s);
1329
1330     INSERT_STRING:              /* Come to from %D or %M above */
1331
1332     /* If the width is specified, check that there is a precision
1333     set; if not, set it to the width to prevent overruns of long
1334     strings. */
1335
1336     if (width >= 0)
1337       {
1338       if (precision < 0) precision = width;
1339       }
1340
1341     /* If a width is not specified and the precision is specified, set
1342     the width to the precision, or the string length if shorted. */
1343
1344     else if (precision >= 0)
1345       {
1346       width = (precision < slen)? precision : slen;
1347       }
1348
1349     /* If neither are specified, set them both to the string length. */
1350
1351     else width = precision = slen;
1352
1353     /* Check string space, and add the string to the buffer if ok. If
1354     not OK, add part of the string (debugging uses this to show as
1355     much as possible). */
1356
1357     if (p == last)
1358       {
1359       yield = FALSE;
1360       goto END_FORMAT;
1361       }
1362     if (p >= last - width)
1363       {
1364       yield = FALSE;
1365       width = precision = last - p - 1;
1366       if (width < 0) width = 0;
1367       if (precision < 0) precision = 0;
1368       }
1369     sprintf(CS p, "%*.*s", width, precision, s);
1370     if (fp[-1] == 'S')
1371       while (*p) { *p = tolower(*p); p++; }
1372     else
1373       while (*p) p++;
1374     if (!yield) goto END_FORMAT;
1375     break;
1376
1377     /* Some things are never used in Exim; also catches junk. */
1378
1379     default:
1380     strncpy(newformat, item_start, fp - item_start);
1381     newformat[fp-item_start] = 0;
1382     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "string_format: unsupported type "
1383       "in \"%s\" in \"%s\"", newformat, format);
1384     break;
1385     }
1386   }
1387
1388 /* Ensure string is complete; return TRUE if got to the end of the format */
1389
1390 END_FORMAT:
1391
1392 *p = 0;
1393 return yield;
1394 }
1395
1396
1397
1398 #ifndef COMPILE_UTILITY
1399 /*************************************************
1400 *       Generate an "open failed" message        *
1401 *************************************************/
1402
1403 /* This function creates a message after failure to open a file. It includes a
1404 string supplied as data, adds the strerror() text, and if the failure was
1405 "Permission denied", reads and includes the euid and egid.
1406
1407 Arguments:
1408   eno           the value of errno after the failure
1409   format        a text format string - deliberately not uschar *
1410   ...           arguments for the format string
1411
1412 Returns:        a message, in dynamic store
1413 */
1414
1415 uschar *
1416 string_open_failed(int eno, const char *format, ...)
1417 {
1418 va_list ap;
1419 uschar buffer[1024];
1420
1421 Ustrcpy(buffer, "failed to open ");
1422 va_start(ap, format);
1423
1424 /* Use the checked formatting routine to ensure that the buffer
1425 does not overflow. It should not, since this is called only for internally
1426 specified messages. If it does, the message just gets truncated, and there
1427 doesn't seem much we can do about that. */
1428
1429 (void)string_vformat(buffer+15, sizeof(buffer) - 15, format, ap);
1430
1431 return (eno == EACCES)?
1432   string_sprintf("%s: %s (euid=%ld egid=%ld)", buffer, strerror(eno),
1433     (long int)geteuid(), (long int)getegid()) :
1434   string_sprintf("%s: %s", buffer, strerror(eno));
1435 }
1436 #endif  /* COMPILE_UTILITY */
1437
1438
1439
1440 #ifndef COMPILE_UTILITY
1441 /*************************************************
1442 *        Generate local prt for logging          *
1443 *************************************************/
1444
1445 /* This function is a subroutine for use in string_log_address() below.
1446
1447 Arguments:
1448   addr        the address being logged
1449   yield       the current dynamic buffer pointer
1450   sizeptr     points to current size
1451   ptrptr      points to current insert pointer
1452
1453 Returns:      the new value of the buffer pointer
1454 */
1455
1456 static uschar *
1457 string_get_localpart(address_item *addr, uschar *yield, int *sizeptr,
1458   int *ptrptr)
1459 {
1460 if (testflag(addr, af_include_affixes) && addr->prefix != NULL)
1461   yield = string_cat(yield, sizeptr, ptrptr, addr->prefix,
1462     Ustrlen(addr->prefix));
1463 yield = string_cat(yield, sizeptr, ptrptr, addr->local_part,
1464   Ustrlen(addr->local_part));
1465 if (testflag(addr, af_include_affixes) && addr->suffix != NULL)
1466   yield = string_cat(yield, sizeptr, ptrptr, addr->suffix,
1467     Ustrlen(addr->suffix));
1468 return yield;
1469 }
1470
1471
1472 /*************************************************
1473 *          Generate log address list             *
1474 *************************************************/
1475
1476 /* This function generates a list consisting of an address and its parents, for
1477 use in logging lines. For saved onetime aliased addresses, the onetime parent
1478 field is used. If the address was delivered by a transport with rcpt_include_
1479 affixes set, the af_include_affixes bit will be set in the address. In that
1480 case, we include the affixes here too.
1481
1482 Arguments:
1483   addr          bottom (ultimate) address
1484   all_parents   if TRUE, include all parents
1485   success       TRUE for successful delivery
1486
1487 Returns:        a string in dynamic store
1488 */
1489
1490 uschar *
1491 string_log_address(address_item *addr, BOOL all_parents, BOOL success)
1492 {
1493 int size = 64;
1494 int ptr = 0;
1495 BOOL add_topaddr = TRUE;
1496 uschar *yield = store_get(size);
1497 address_item *topaddr;
1498
1499 /* Find the ultimate parent */
1500
1501 for (topaddr = addr; topaddr->parent != NULL; topaddr = topaddr->parent);
1502
1503 /* We start with just the local part for pipe, file, and reply deliveries, and
1504 for successful local deliveries from routers that have the log_as_local flag
1505 set. File deliveries from filters can be specified as non-absolute paths in
1506 cases where the transport is goin to complete the path. If there is an error
1507 before this happens (expansion failure) the local part will not be updated, and
1508 so won't necessarily look like a path. Add extra text for this case. */
1509
1510 if (testflag(addr, af_pfr) ||
1511       (success &&
1512        addr->router != NULL && addr->router->log_as_local &&
1513        addr->transport != NULL && addr->transport->info->local))
1514   {
1515   if (testflag(addr, af_file) && addr->local_part[0] != '/')
1516     yield = string_cat(yield, &size, &ptr, CUS"save ", 5);
1517   yield = string_get_localpart(addr, yield, &size, &ptr);
1518   }
1519
1520 /* Other deliveries start with the full address. It we have split it into local
1521 part and domain, use those fields. Some early failures can happen before the
1522 splitting is done; in those cases use the original field. */
1523
1524 else
1525   {
1526   if (addr->local_part != NULL)
1527     {
1528     yield = string_get_localpart(addr, yield, &size, &ptr);
1529     yield = string_cat(yield, &size, &ptr, US"@", 1);
1530     yield = string_cat(yield, &size, &ptr, addr->domain,
1531       Ustrlen(addr->domain) );
1532     }
1533   else
1534     {
1535     yield = string_cat(yield, &size, &ptr, addr->address, Ustrlen(addr->address));
1536     }
1537   yield[ptr] = 0;
1538
1539   /* If the address we are going to print is the same as the top address,
1540   and all parents are not being included, don't add on the top address. First
1541   of all, do a caseless comparison; if this succeeds, do a caseful comparison
1542   on the local parts. */
1543
1544   if (strcmpic(yield, topaddr->address) == 0 &&
1545       Ustrncmp(yield, topaddr->address, Ustrchr(yield, '@') - yield) == 0 &&
1546       addr->onetime_parent == NULL &&
1547       (!all_parents || addr->parent == NULL || addr->parent == topaddr))
1548     add_topaddr = FALSE;
1549   }
1550
1551 /* If all parents are requested, or this is a local pipe/file/reply, and
1552 there is at least one intermediate parent, show it in brackets, and continue
1553 with all of them if all are wanted. */
1554
1555 if ((all_parents || testflag(addr, af_pfr)) &&
1556     addr->parent != NULL &&
1557     addr->parent != topaddr)
1558   {
1559   uschar *s = US" (";
1560   address_item *addr2;
1561   for (addr2 = addr->parent; addr2 != topaddr; addr2 = addr2->parent)
1562     {
1563     yield = string_cat(yield, &size, &ptr, s, 2);
1564     yield = string_cat(yield, &size, &ptr, addr2->address, Ustrlen(addr2->address));
1565     if (!all_parents) break;
1566     s = US", ";
1567     }
1568   yield = string_cat(yield, &size, &ptr, US")", 1);
1569   }
1570
1571 /* Add the top address if it is required */
1572
1573 if (add_topaddr)
1574   {
1575   yield = string_cat(yield, &size, &ptr, US" <", 2);
1576
1577   if (addr->onetime_parent == NULL)
1578     yield = string_cat(yield, &size, &ptr, topaddr->address,
1579       Ustrlen(topaddr->address));
1580   else
1581     yield = string_cat(yield, &size, &ptr, addr->onetime_parent,
1582       Ustrlen(addr->onetime_parent));
1583
1584   yield = string_cat(yield, &size, &ptr, US">", 1);
1585   }
1586
1587 yield[ptr] = 0;  /* string_cat() leaves space */
1588 return yield;
1589 }
1590 #endif  /* COMPILE_UTILITY */
1591
1592
1593
1594
1595
1596 /*************************************************
1597 **************************************************
1598 *             Stand-alone test program           *
1599 **************************************************
1600 *************************************************/
1601
1602 #ifdef STAND_ALONE
1603 int main(void)
1604 {
1605 uschar buffer[256];
1606
1607 printf("Testing is_ip_address\n");
1608
1609 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1610   {
1611   int offset;
1612   buffer[Ustrlen(buffer) - 1] = 0;
1613   printf("%d\n", string_is_ip_address(buffer, NULL));
1614   printf("%d %d %s\n", string_is_ip_address(buffer, &offset), offset, buffer);
1615   }
1616
1617 printf("Testing string_nextinlist\n");
1618
1619 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1620   {
1621   uschar *list = buffer;
1622   uschar *lp1, *lp2;
1623   uschar item[256];
1624   int sep1 = 0;
1625   int sep2 = 0;
1626
1627   if (*list == '<')
1628     {
1629     sep1 = sep2 = list[1];
1630     list += 2;
1631     }
1632
1633   lp1 = lp2 = list;
1634   for (;;)
1635     {
1636     uschar *item1 = string_nextinlist(&lp1, &sep1, item, sizeof(item));
1637     uschar *item2 = string_nextinlist(&lp2, &sep2, NULL, 0);
1638
1639     if (item1 == NULL && item2 == NULL) break;
1640     if (item == NULL || item2 == NULL || Ustrcmp(item1, item2) != 0)
1641       {
1642       printf("***ERROR\nitem1=\"%s\"\nitem2=\"%s\"\n",
1643         (item1 == NULL)? "NULL" : CS item1,
1644         (item2 == NULL)? "NULL" : CS item2);
1645       break;
1646       }
1647     else printf("  \"%s\"\n", CS item1);
1648     }
1649   }
1650
1651 /* This is a horrible lash-up, but it serves its purpose. */
1652
1653 printf("Testing string_format\n");
1654
1655 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1656   {
1657   void *args[3];
1658   long long llargs[3];
1659   double dargs[3];
1660   int dflag = 0;
1661   int llflag = 0;
1662   int n = 0;
1663   int count;
1664   int countset = 0;
1665   uschar format[256];
1666   uschar outbuf[256];
1667   uschar *s;
1668   buffer[Ustrlen(buffer) - 1] = 0;
1669
1670   s = Ustrchr(buffer, ',');
1671   if (s == NULL) s = buffer + Ustrlen(buffer);
1672
1673   Ustrncpy(format, buffer, s - buffer);
1674   format[s-buffer] = 0;
1675
1676   if (*s == ',') s++;
1677
1678   while (*s != 0)
1679     {
1680     uschar *ss = s;
1681     s = Ustrchr(ss, ',');
1682     if (s == NULL) s = ss + Ustrlen(ss);
1683
1684     if (isdigit(*ss))
1685       {
1686       Ustrncpy(outbuf, ss, s-ss);
1687       if (Ustrchr(outbuf, '.') != NULL)
1688         {
1689         dflag = 1;
1690         dargs[n++] = Ustrtod(outbuf, NULL);
1691         }
1692       else if (Ustrstr(outbuf, "ll") != NULL)
1693         {
1694         llflag = 1;
1695         llargs[n++] = strtoull(CS outbuf, NULL, 10);
1696         }
1697       else
1698         {
1699         args[n++] = (void *)Uatoi(outbuf);
1700         }
1701       }
1702
1703     else if (Ustrcmp(ss, "*") == 0)
1704       {
1705       args[n++] = (void *)(&count);
1706       countset = 1;
1707       }
1708
1709     else
1710       {
1711       uschar *sss = malloc(s - ss + 1);
1712       Ustrncpy(sss, ss, s-ss);
1713       args[n++] = sss;
1714       }
1715
1716     if (*s == ',') s++;
1717     }
1718
1719   if (!dflag && !llflag)
1720     printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1721       args[0], args[1], args[2])? "True" : "False");
1722
1723   else if (dflag)
1724     printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1725       dargs[0], dargs[1], dargs[2])? "True" : "False");
1726
1727   else printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1728     llargs[0], llargs[1], llargs[2])? "True" : "False");
1729
1730   printf("%s\n", CS outbuf);
1731   if (countset) printf("count=%d\n", count);
1732   }
1733
1734 return 0;
1735 }
1736 #endif
1737
1738 /* End of string.c */