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