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