1 /* $Cambridge: exim/src/src/string.c,v 1.12 2007/02/07 11:24:56 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) University of Cambridge 1995 - 2007 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* Miscellaneous string-handling functions. Some are not required for
11 utilities and tests, and are cut out by the COMPILE_UTILITY macro. */
17 #ifndef COMPILE_UTILITY
18 /*************************************************
19 * Test for IP address *
20 *************************************************/
22 /* This used just to be a regular expression, but with IPv6 things are a bit
23 more complicated. If the address contains a colon, it is assumed to be a v6
24 address (assuming HAVE_IPV6 is set). If a mask is permitted and one is present,
25 and maskptr is not NULL, its offset is placed there.
29 maskptr NULL if no mask is permitted to follow
30 otherwise, points to an int where the offset of '/' is placed
31 if there is no / followed by trailing digits, *maskptr is set 0
33 Returns: 0 if the string is not a textual representation of an IP address
34 4 if it is an IPv4 address
35 6 if it is an IPv6 address
39 string_is_ip_address(uschar *s, int *maskptr)
44 /* If an optional mask is permitted, check for it. If found, pass back the
49 uschar *ss = s + Ustrlen(s);
51 if (s != ss && isdigit(*(--ss)))
53 while (ss > s && isdigit(ss[-1])) ss--;
54 if (ss > s && *(--ss) == '/') *maskptr = ss - s;
58 /* A colon anywhere in the string => IPv6 address */
60 if (Ustrchr(s, ':') != NULL)
62 BOOL had_double_colon = FALSE;
68 /* An IPv6 address must start with hex digit or double colon. A single
71 if (*s == ':' && *(++s) != ':') return 0;
73 /* Now read up to 8 components consisting of up to 4 hex digits each. There
74 may be one and only one appearance of double colon, which implies any number
75 of binary zero bits. The number of preceding components is held in count. */
77 for (count = 0; count < 8; count++)
79 /* If the end of the string is reached before reading 8 components, the
80 address is valid provided a double colon has been read. This also applies
81 if we hit the / that introduces a mask or the % that introduces the
82 interface specifier (scope id) of a link-local address. */
84 if (*s == 0 || *s == '%' || *s == '/') return had_double_colon? yield : 0;
86 /* If a component starts with an additional colon, we have hit a double
87 colon. This is permitted to appear once only, and counts as at least
88 one component. The final component may be of this form. */
92 if (had_double_colon) return 0;
93 had_double_colon = TRUE;
98 /* If the remainder of the string contains a dot but no colons, we
99 can expect a trailing IPv4 address. This is valid if either there has
100 been no double-colon and this is the 7th component (with the IPv4 address
101 being the 7th & 8th components), OR if there has been a double-colon
102 and fewer than 6 components. */
104 if (Ustrchr(s, ':') == NULL && Ustrchr(s, '.') != NULL)
106 if ((!had_double_colon && count != 6) ||
107 (had_double_colon && count > 6)) return 0;
113 /* Check for at least one and not more than 4 hex digits for this
116 if (!isxdigit(*s++)) return 0;
117 if (isxdigit(*s) && isxdigit(*(++s)) && isxdigit(*(++s))) s++;
119 /* If the component is terminated by colon and there is more to
120 follow, skip over the colon. If there is no more to follow the address is
123 if (*s == ':' && *(++s) == 0) return 0;
126 /* If about to handle a trailing IPv4 address, drop through. Otherwise
127 all is well if we are at the end of the string or at the mask or at a percent
128 sign, which introduces the interface specifier (scope id) of a link local
132 return (*s == 0 || *s == '%' ||
133 (*s == '/' && maskptr != NULL && *maskptr != 0))? yield : 0;
136 /* Test for IPv4 address, which may be the tail-end of an IPv6 address. */
138 for (i = 0; i < 4; i++)
140 if (i != 0 && *s++ != '.') return 0;
141 if (!isdigit(*s++)) return 0;
142 if (isdigit(*s) && isdigit(*(++s))) s++;
145 return (*s == 0 || (*s == '/' && maskptr != NULL && *maskptr != 0))?
148 #endif /* COMPILE_UTILITY */
151 /*************************************************
152 * Format message size *
153 *************************************************/
155 /* Convert a message size in bytes to printing form, rounding
156 according to the magnitude of the number. A value of zero causes
157 a string of spaces to be returned.
160 size the message size in bytes
161 buffer where to put the answer
163 Returns: pointer to the buffer
164 a string of exactly 5 characters is normally returned
168 string_format_size(int size, uschar *buffer)
170 if (size == 0) Ustrcpy(CS buffer, " ");
171 else if (size < 1024) sprintf(CS buffer, "%5d", size);
172 else if (size < 10*1024)
173 sprintf(CS buffer, "%4.1fK", (double)size / 1024.0);
174 else if (size < 1024*1024)
175 sprintf(CS buffer, "%4dK", (size + 512)/1024);
176 else if (size < 10*1024*1024)
177 sprintf(CS buffer, "%4.1fM", (double)size / (1024.0 * 1024.0));
179 sprintf(CS buffer, "%4dM", (size + 512 * 1024)/(1024*1024));
185 #ifndef COMPILE_UTILITY
186 /*************************************************
187 * Convert a number to base 62 format *
188 *************************************************/
190 /* Convert a long integer into an ASCII base 62 string. For Cygwin the value of
191 BASE_62 is actually 36. Always return exactly 6 characters plus zero, in a
194 Argument: a long integer
195 Returns: pointer to base 62 string
199 string_base62(unsigned long int value)
201 static uschar yield[7];
202 uschar *p = yield + sizeof(yield) - 1;
206 *(--p) = base62_chars[value % BASE_62];
211 #endif /* COMPILE_UTILITY */
215 #ifndef COMPILE_UTILITY
216 /*************************************************
217 * Interpret escape sequence *
218 *************************************************/
220 /* This function is called from several places where escape sequences are to be
221 interpreted in strings.
224 pp points a pointer to the initiating "\" in the string;
225 the pointer gets updated to point to the final character
226 Returns: the value of the character escape
230 string_interpret_escape(uschar **pp)
235 if (isdigit(ch) && ch != '8' && ch != '9')
238 if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
240 ch = ch * 8 + *(++p) - '0';
241 if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
242 ch = ch * 8 + *(++p) - '0';
247 case 'n': ch = '\n'; break;
248 case 'r': ch = '\r'; break;
249 case 't': ch = '\t'; break;
255 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
256 if (isxdigit(p[1])) ch = ch * 16 +
257 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
264 #endif /* COMPILE_UTILITY */
268 #ifndef COMPILE_UTILITY
269 /*************************************************
270 * Ensure string is printable *
271 *************************************************/
273 /* This function is called for critical strings. It checks for any
274 non-printing characters, and if any are found, it makes a new copy
275 of the string with suitable escape sequences. It is most often called by the
276 macro string_printing(), which sets allow_tab TRUE.
280 allow_tab TRUE to allow tab as a printing character
282 Returns: string with non-printers encoded as printing sequences
286 string_printing2(uschar *s, BOOL allow_tab)
288 int nonprintcount = 0;
296 if (!mac_isprint(c) || (!allow_tab && c == '\t')) nonprintcount++;
300 if (nonprintcount == 0) return s;
302 /* Get a new block of store guaranteed big enough to hold the
305 ss = store_get(length + nonprintcount * 4 + 1);
307 /* Copy everying, escaping non printers. */
315 if (mac_isprint(c) && (allow_tab || c != '\t')) *tt++ = *t++; else
320 case '\n': *tt++ = 'n'; break;
321 case '\r': *tt++ = 'r'; break;
322 case '\b': *tt++ = 'b'; break;
323 case '\v': *tt++ = 'v'; break;
324 case '\f': *tt++ = 'f'; break;
325 case '\t': *tt++ = 't'; break;
326 default: sprintf(CS tt, "%03o", *t); tt += 3; break;
334 #endif /* COMPILE_UTILITY */
339 /*************************************************
340 * Copy and save string *
341 *************************************************/
343 /* This function assumes that memcpy() is faster than strcpy().
345 Argument: string to copy
346 Returns: copy of string in new store
350 string_copy(uschar *s)
352 int len = Ustrlen(s) + 1;
353 uschar *ss = store_get(len);
360 /*************************************************
361 * Copy and save string in malloc'd store *
362 *************************************************/
364 /* This function assumes that memcpy() is faster than strcpy().
366 Argument: string to copy
367 Returns: copy of string in new store
371 string_copy_malloc(uschar *s)
373 int len = Ustrlen(s) + 1;
374 uschar *ss = store_malloc(len);
381 /*************************************************
382 * Copy, lowercase and save string *
383 *************************************************/
386 Argument: string to copy
387 Returns: copy of string in new store, with letters lowercased
391 string_copylc(uschar *s)
393 uschar *ss = store_get(Ustrlen(s) + 1);
395 while (*s != 0) *p++ = tolower(*s++);
402 /*************************************************
403 * Copy and save string, given length *
404 *************************************************/
406 /* It is assumed the data contains no zeros. A zero is added
411 n number of characters
413 Returns: copy of string in new store
417 string_copyn(uschar *s, int n)
419 uschar *ss = store_get(n + 1);
426 /*************************************************
427 * Copy, lowercase, and save string, given length *
428 *************************************************/
430 /* It is assumed the data contains no zeros. A zero is added
435 n number of characters
437 Returns: copy of string in new store, with letters lowercased
441 string_copynlc(uschar *s, int n)
443 uschar *ss = store_get(n + 1);
445 while (n-- > 0) *p++ = tolower(*s++);
452 /*************************************************
453 * Copy string if long, inserting newlines *
454 *************************************************/
456 /* If the given string is longer than 75 characters, it is copied, and within
457 the copy, certain space characters are converted into newlines.
459 Argument: pointer to the string
460 Returns: pointer to the possibly altered string
464 string_split_message(uschar *msg)
468 if (msg == NULL || Ustrlen(msg) <= 75) return msg;
469 s = ss = msg = string_copy(msg);
474 while (i < 75 && *ss != 0 && *ss != '\n') ss++, i++;
486 if (t[-1] == ':') { tt = t; break; }
487 if (tt == NULL) tt = t;
491 if (tt == NULL) /* Can't split behind - try ahead */
496 if (*t == ' ' || *t == '\n')
502 if (tt == NULL) break; /* Can't find anywhere to split */
513 /*************************************************
514 * Copy returned DNS domain name, de-escaping *
515 *************************************************/
517 /* If a domain name contains top-bit characters, some resolvers return
518 the fully qualified name with those characters turned into escapes. The
519 convention is a backslash followed by _decimal_ digits. We convert these
520 back into the original binary values. This will be relevant when
521 allow_utf8_domains is set true and UTF-8 characters are used in domain
522 names. Backslash can also be used to escape other characters, though we
523 shouldn't come across them in domain names.
525 Argument: the domain name string
526 Returns: copy of string in new store, de-escaped
530 string_copy_dnsdomain(uschar *s)
533 uschar *ss = yield = store_get(Ustrlen(s) + 1);
541 else if (isdigit(s[1]))
543 *ss++ = (s[1] - '0')*100 + (s[2] - '0')*10 + s[3] - '0';
546 else if (*(++s) != 0)
557 #ifndef COMPILE_UTILITY
558 /*************************************************
559 * Copy space-terminated or quoted string *
560 *************************************************/
562 /* This function copies from a string until its end, or until whitespace is
563 encountered, unless the string begins with a double quote, in which case the
564 terminating quote is sought, and escaping within the string is done. The length
565 of a de-quoted string can be no longer than the original, since escaping always
566 turns n characters into 1 character.
568 Argument: pointer to the pointer to the first character, which gets updated
569 Returns: the new string
573 string_dequote(uschar **sptr)
578 /* First find the end of the string */
582 while (*s != 0 && !isspace(*s)) s++;
587 while (*s != 0 && *s != '\"')
589 if (*s == '\\') (void)string_interpret_escape(&s);
595 /* Get enough store to copy into */
597 t = yield = store_get(s - *sptr + 1);
604 while (*s != 0 && !isspace(*s)) *t++ = *s++;
609 while (*s != 0 && *s != '\"')
611 if (*s == '\\') *t++ = string_interpret_escape(&s);
618 /* Update the pointer and return the terminated copy */
624 #endif /* COMPILE_UTILITY */
628 /*************************************************
629 * Format a string and save it *
630 *************************************************/
632 /* The formatting is done by string_format, which checks the length of
636 format a printf() format - deliberately char * rather than uschar *
637 because it will most usually be a literal string
638 ... arguments for format
640 Returns: pointer to fresh piece of store containing sprintf'ed string
644 string_sprintf(char *format, ...)
647 uschar buffer[STRING_SPRINTF_BUFFER_SIZE];
648 va_start(ap, format);
649 if (!string_vformat(buffer, sizeof(buffer), format, ap))
650 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
651 "string_sprintf expansion was longer than %d", sizeof(buffer));
653 return string_copy(buffer);
658 /*************************************************
659 * Case-independent strncmp() function *
660 *************************************************/
666 n number of characters to compare
668 Returns: < 0, = 0, or > 0, according to the comparison
672 strncmpic(uschar *s, uschar *t, int n)
676 int c = tolower(*s++) - tolower(*t++);
683 /*************************************************
684 * Case-independent strcmp() function *
685 *************************************************/
692 Returns: < 0, = 0, or > 0, according to the comparison
696 strcmpic(uschar *s, uschar *t)
700 int c = tolower(*s++) - tolower(*t++);
701 if (c != 0) return c;
707 /*************************************************
708 * Case-independent strstr() function *
709 *************************************************/
711 /* The third argument specifies whether whitespace is required
712 to follow the matched string.
716 t substring to search for
717 space_follows if TRUE, match only if whitespace follows
719 Returns: pointer to substring in string, or NULL if not found
723 strstric(uschar *s, uschar *t, BOOL space_follows)
726 uschar *yield = NULL;
727 int cl = tolower(*p);
728 int cu = toupper(*p);
732 if (*s == cl || *s == cu)
734 if (yield == NULL) yield = s;
737 if (!space_follows || s[1] == ' ' || s[1] == '\n' ) return yield;
745 else if (yield != NULL)
759 #ifndef COMPILE_UTILITY
760 /*************************************************
761 * Get next string from separated list *
762 *************************************************/
764 /* Leading and trailing space is removed from each item. The separator in the
765 list is controlled by the int pointed to by the separator argument as follows:
767 If its value is > 0 it is used as the delimiter.
768 (If its value is actually > UCHAR_MAX there is only one item in the list.
769 This is used for some cases when called via functions that sometimes
770 plough through lists, and sometimes are given single items.)
771 If its value is <= 0, the string is inspected for a leading <x, where
772 x is an ispunct() value. If found, it is used as the delimiter. If not
773 found: (a) if separator == 0, ':' is used
774 (b) if separator <0, then -separator is used
775 In all cases the value of the separator that is used is written back to
776 the int so that it is used on subsequent calls as we progress through
779 The separator can always be represented in the string by doubling.
782 listptr points to a pointer to the current start of the list; the
783 pointer gets updated to point after the end of the next item
784 separator a pointer to the separator character in an int (see above)
785 buffer where to put a copy of the next string in the list; or
786 NULL if the next string is returned in new memory
787 buflen when buffer is not NULL, the size of buffer; otherwise ignored
789 Returns: pointer to buffer, containing the next substring,
790 or NULL if no more substrings
794 string_nextinlist(uschar **listptr, int *separator, uschar *buffer, int buflen)
797 register int sep = *separator;
798 register uschar *s = *listptr;
800 if (s == NULL) return NULL;
801 while (isspace(*s)) s++;
805 if (*s == '<' && ispunct(s[1]))
809 while (isspace(*s)) s++;
813 sep = (sep == 0)? ':' : -sep;
818 if (*s == 0) return NULL;
820 /* Handle the case when a buffer is provided. */
826 if (*s == sep && *(++s) != sep) break;
827 if (p < buflen - 1) buffer[p++] = *s;
829 while (p > 0 && isspace(buffer[p-1])) p--;
833 /* Handle the case when a buffer is not provided. */
837 /* We know that *s != 0 at this point. However, it might be pointing to a
838 separator, which could indicate an empty string, or could be doubled to
839 indicate a separator character as data at the start of a string. */
844 if (*s != sep) buffer = string_copy(US"");
854 for (ss = s + 1; *ss != 0 && *ss != sep; ss++);
855 buffer = string_cat(buffer, &size, &ptr, s, ss-s);
857 if (*s == 0 || *(++s) != sep) break;
859 while (ptr > 0 && isspace(buffer[ptr-1])) ptr--;
864 /* Update the current pointer and return the new string */
869 #endif /* COMPILE_UTILITY */
873 #ifndef COMPILE_UTILITY
874 /*************************************************
875 * Add chars to string *
876 *************************************************/
878 /* This function is used when building up strings of unknown length. Room is
879 always left for a terminating zero to be added to the string that is being
880 built. This function does not require the string that is being added to be NUL
881 terminated, because the number of characters to add is given explicitly. It is
882 sometimes called to extract parts of other strings.
885 string points to the start of the string that is being built, or NULL
886 if this is a new string that has no contents yet
887 size points to a variable that holds the current capacity of the memory
888 block (updated if changed)
889 ptr points to a variable that holds the offset at which to add
890 characters, updated to the new offset
891 s points to characters to add
892 count count of characters to add; must not exceed the length of s, if s
895 If string is given as NULL, *size and *ptr should both be zero.
897 Returns: pointer to the start of the string, changed if copied for expansion.
898 Note that a NUL is not added, though space is left for one. This is
899 because string_cat() is often called multiple times to build up a
900 string - there's no point adding the NUL till the end.
904 string_cat(uschar *string, int *size, int *ptr, const uschar *s, int count)
908 if (p + count >= *size)
912 /* Mostly, string_cat() is used to build small strings of a few hundred
913 characters at most. There are times, however, when the strings are very much
914 longer (for example, a lookup that returns a vast number of alias addresses).
915 To try to keep things reasonable, we use increments whose size depends on the
916 existing length of the string. */
918 int inc = (oldsize < 4096)? 100 : 1024;
919 while (*size <= p + count) *size += inc;
923 if (string == NULL) string = store_get(*size);
925 /* Try to extend an existing allocation. If the result of calling
926 store_extend() is false, either there isn't room in the current memory block,
927 or this string is not the top item on the dynamic store stack. We then have
928 to get a new chunk of store and copy the old string. When building large
929 strings, it is helpful to call store_release() on the old string, to release
930 memory blocks that have become empty. (The block will be freed if the string
931 is at its start.) However, we can do this only if we know that the old string
932 was the last item on the dynamic memory stack. This is the case if it matches
935 else if (!store_extend(string, oldsize, *size))
937 BOOL release_ok = store_last_get[store_pool] == string;
938 uschar *newstring = store_get(*size);
939 memcpy(newstring, string, p);
940 if (release_ok) store_release(string);
945 /* Because we always specify the exact number of characters to copy, we can
946 use memcpy(), which is likely to be more efficient than strncopy() because the
947 latter has to check for zero bytes. */
949 memcpy(string + p, s, count);
953 #endif /* COMPILE_UTILITY */
957 #ifndef COMPILE_UTILITY
958 /*************************************************
959 * Append strings to another string *
960 *************************************************/
962 /* This function can be used to build a string from many other strings.
963 It calls string_cat() to do the dirty work.
966 string points to the start of the string that is being built, or NULL
967 if this is a new string that has no contents yet
968 size points to a variable that holds the current capacity of the memory
969 block (updated if changed)
970 ptr points to a variable that holds the offset at which to add
971 characters, updated to the new offset
972 count the number of strings to append
973 ... "count" uschar* arguments, which must be valid zero-terminated
976 Returns: pointer to the start of the string, changed if copied for expansion.
977 The string is not zero-terminated - see string_cat() above.
981 string_append(uschar *string, int *size, int *ptr, int count, ...)
987 for (i = 0; i < count; i++)
989 uschar *t = va_arg(ap, uschar *);
990 string = string_cat(string, size, ptr, t, Ustrlen(t));
1000 /*************************************************
1001 * Format a string with length checks *
1002 *************************************************/
1004 /* This function is used to format a string with checking of the length of the
1005 output for all conversions. It protects Exim from absent-mindedness when
1006 calling functions like debug_printf and string_sprintf, and elsewhere. There
1007 are two different entry points to what is actually the same function, depending
1008 on whether the variable length list of data arguments are given explicitly or
1011 The formats are the usual printf() ones, with some omissions (never used) and
1012 two additions for strings: %S forces lower case, and %#s or %#S prints nothing
1013 for a NULL string. Without the # "NULL" is printed (useful in debugging). There
1014 is also the addition of %D, which inserts the date in the form used for
1015 datestamped log files.
1018 buffer a buffer in which to put the formatted string
1019 buflen the length of the buffer
1020 format the format string - deliberately char * and not uschar *
1021 ... or ap variable list of supplementary arguments
1023 Returns: TRUE if the result fitted in the buffer
1027 string_format(uschar *buffer, int buflen, char *format, ...)
1031 va_start(ap, format);
1032 yield = string_vformat(buffer, buflen, format, ap);
1039 string_vformat(uschar *buffer, int buflen, char *format, va_list ap)
1041 enum { L_NORMAL, L_SHORT, L_LONG, L_LONGLONG, L_LONGDOUBLE };
1044 int width, precision;
1045 char *fp = format; /* Deliberately not unsigned */
1047 uschar *last = buffer + buflen - 1;
1049 string_datestamp_offset = -1; /* Datestamp not inserted */
1051 /* Scan the format and handle the insertions */
1055 int length = L_NORMAL;
1058 char *null = "NULL"; /* ) These variables */
1059 char *item_start, *s; /* ) are deliberately */
1060 char newformat[16]; /* ) not unsigned */
1062 /* Non-% characters just get copied verbatim */
1066 if (p >= last) { yield = FALSE; break; }
1067 *p++ = (uschar)*fp++;
1071 /* Deal with % characters. Pick off the width and precision, for checking
1072 strings, skipping over the flag and modifier characters. */
1075 width = precision = -1;
1077 if (strchr("-+ #0", *(++fp)) != NULL)
1079 if (*fp == '#') null = "";
1083 if (isdigit((uschar)*fp))
1085 width = *fp++ - '0';
1086 while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';
1088 else if (*fp == '*')
1090 width = va_arg(ap, int);
1098 precision = va_arg(ap, int);
1104 while (isdigit((uschar)*fp))
1105 precision = precision*10 + *fp++ - '0';
1109 /* Skip over 'h', 'L', 'l', and 'll', remembering the item length */
1112 { fp++; length = L_SHORT; }
1113 else if (*fp == 'L')
1114 { fp++; length = L_LONGDOUBLE; }
1115 else if (*fp == 'l')
1120 length = L_LONGLONG;
1129 /* Handle each specific format type. */
1134 nptr = va_arg(ap, int *);
1143 if (p >= last - ((length > L_LONG)? 24 : 12))
1144 { yield = FALSE; goto END_FORMAT; }
1145 strncpy(newformat, item_start, fp - item_start);
1146 newformat[fp - item_start] = 0;
1148 /* Short int is promoted to int when passing through ..., so we must use
1149 int for va_arg(). */
1154 case L_NORMAL: sprintf(CS p, newformat, va_arg(ap, int)); break;
1155 case L_LONG: sprintf(CS p, newformat, va_arg(ap, long int)); break;
1156 case L_LONGLONG: sprintf(CS p, newformat, va_arg(ap, LONGLONG_T)); break;
1162 if (p >= last - 24) { yield = FALSE; goto END_FORMAT; }
1163 strncpy(newformat, item_start, fp - item_start);
1164 newformat[fp - item_start] = 0;
1165 sprintf(CS p, newformat, va_arg(ap, void *));
1169 /* %f format is inherently insecure if the numbers that it may be
1170 handed are unknown (e.g. 1e300). However, in Exim, %f is used for
1171 printing load averages, and these are actually stored as integers
1172 (load average * 1000) so the size of the numbers is constrained.
1173 It is also used for formatting sending rates, where the simplicity
1174 of the format prevents overflow. */
1181 if (precision < 0) precision = 6;
1182 if (p >= last - precision - 8) { yield = FALSE; goto END_FORMAT; }
1183 strncpy(newformat, item_start, fp - item_start);
1184 newformat[fp-item_start] = 0;
1185 if (length == L_LONGDOUBLE)
1186 sprintf(CS p, newformat, va_arg(ap, long double));
1188 sprintf(CS p, newformat, va_arg(ap, double));
1195 if (p >= last) { yield = FALSE; goto END_FORMAT; }
1200 if (p >= last) { yield = FALSE; goto END_FORMAT; }
1201 *p++ = va_arg(ap, int);
1204 case 'D': /* Insert datestamp for log file names */
1205 s = CS tod_stamp(tod_log_datestamp);
1206 string_datestamp_offset = p - buffer; /* Passed back via global */
1210 case 'S': /* Forces *lower* case */
1211 s = va_arg(ap, char *);
1213 INSERT_STRING: /* Come to from %D above */
1214 if (s == NULL) s = null;
1217 /* If the width is specified, check that there is a precision
1218 set; if not, set it to the width to prevent overruns of long
1223 if (precision < 0) precision = width;
1226 /* If a width is not specified and the precision is specified, set
1227 the width to the precision, or the string length if shorted. */
1229 else if (precision >= 0)
1231 width = (precision < slen)? precision : slen;
1234 /* If neither are specified, set them both to the string length. */
1236 else width = precision = slen;
1238 /* Check string space, and add the string to the buffer if ok. If
1239 not OK, add part of the string (debugging uses this to show as
1240 much as possible). */
1242 if (p >= last - width)
1245 width = precision = last - p - 1;
1247 sprintf(CS p, "%*.*s", width, precision, s);
1249 while (*p) { *p = tolower(*p); p++; }
1252 if (!yield) goto END_FORMAT;
1255 /* Some things are never used in Exim; also catches junk. */
1258 strncpy(newformat, item_start, fp - item_start);
1259 newformat[fp-item_start] = 0;
1260 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "string_format: unsupported type "
1261 "in \"%s\" in \"%s\"", newformat, format);
1266 /* Ensure string is complete; return TRUE if got to the end of the format */
1276 #ifndef COMPILE_UTILITY
1277 /*************************************************
1278 * Generate an "open failed" message *
1279 *************************************************/
1281 /* This function creates a message after failure to open a file. It includes a
1282 string supplied as data, adds the strerror() text, and if the failure was
1283 "Permission denied", reads and includes the euid and egid.
1286 eno the value of errno after the failure
1287 format a text format string - deliberately not uschar *
1288 ... arguments for the format string
1290 Returns: a message, in dynamic store
1294 string_open_failed(int eno, char *format, ...)
1297 uschar buffer[1024];
1299 Ustrcpy(buffer, "failed to open ");
1300 va_start(ap, format);
1302 /* Use the checked formatting routine to ensure that the buffer
1303 does not overflow. It should not, since this is called only for internally
1304 specified messages. If it does, the message just gets truncated, and there
1305 doesn't seem much we can do about that. */
1307 (void)string_vformat(buffer+15, sizeof(buffer) - 15, format, ap);
1309 return (eno == EACCES)?
1310 string_sprintf("%s: %s (euid=%ld egid=%ld)", buffer, strerror(eno),
1311 (long int)geteuid(), (long int)getegid()) :
1312 string_sprintf("%s: %s", buffer, strerror(eno));
1314 #endif /* COMPILE_UTILITY */
1318 #ifndef COMPILE_UTILITY
1319 /*************************************************
1320 * Generate local prt for logging *
1321 *************************************************/
1323 /* This function is a subroutine for use in string_log_address() below.
1326 addr the address being logged
1327 yield the current dynamic buffer pointer
1328 sizeptr points to current size
1329 ptrptr points to current insert pointer
1331 Returns: the new value of the buffer pointer
1335 string_get_localpart(address_item *addr, uschar *yield, int *sizeptr,
1338 if (testflag(addr, af_include_affixes) && addr->prefix != NULL)
1339 yield = string_cat(yield, sizeptr, ptrptr, addr->prefix,
1340 Ustrlen(addr->prefix));
1341 yield = string_cat(yield, sizeptr, ptrptr, addr->local_part,
1342 Ustrlen(addr->local_part));
1343 if (testflag(addr, af_include_affixes) && addr->suffix != NULL)
1344 yield = string_cat(yield, sizeptr, ptrptr, addr->suffix,
1345 Ustrlen(addr->suffix));
1350 /*************************************************
1351 * Generate log address list *
1352 *************************************************/
1354 /* This function generates a list consisting of an address and its parents, for
1355 use in logging lines. For saved onetime aliased addresses, the onetime parent
1356 field is used. If the address was delivered by a transport with rcpt_include_
1357 affixes set, the af_include_affixes bit will be set in the address. In that
1358 case, we include the affixes here too.
1361 addr bottom (ultimate) address
1362 all_parents if TRUE, include all parents
1363 success TRUE for successful delivery
1365 Returns: a string in dynamic store
1369 string_log_address(address_item *addr, BOOL all_parents, BOOL success)
1373 BOOL add_topaddr = TRUE;
1374 uschar *yield = store_get(size);
1375 address_item *topaddr;
1377 /* Find the ultimate parent */
1379 for (topaddr = addr; topaddr->parent != NULL; topaddr = topaddr->parent);
1381 /* We start with just the local part for pipe, file, and reply deliveries, and
1382 for successful local deliveries from routers that have the log_as_local flag
1383 set. File deliveries from filters can be specified as non-absolute paths in
1384 cases where the transport is goin to complete the path. If there is an error
1385 before this happens (expansion failure) the local part will not be updated, and
1386 so won't necessarily look like a path. Add extra text for this case. */
1388 if (testflag(addr, af_pfr) ||
1390 addr->router != NULL && addr->router->log_as_local &&
1391 addr->transport != NULL && addr->transport->info->local))
1393 if (testflag(addr, af_file) && addr->local_part[0] != '/')
1394 yield = string_cat(yield, &size, &ptr, CUS"save ", 5);
1395 yield = string_get_localpart(addr, yield, &size, &ptr);
1398 /* Other deliveries start with the full address. It we have split it into local
1399 part and domain, use those fields. Some early failures can happen before the
1400 splitting is done; in those cases use the original field. */
1404 if (addr->local_part != NULL)
1406 yield = string_get_localpart(addr, yield, &size, &ptr);
1407 yield = string_cat(yield, &size, &ptr, US"@", 1);
1408 yield = string_cat(yield, &size, &ptr, addr->domain,
1409 Ustrlen(addr->domain) );
1413 yield = string_cat(yield, &size, &ptr, addr->address, Ustrlen(addr->address));
1417 /* If the address we are going to print is the same as the top address,
1418 and all parents are not being included, don't add on the top address. First
1419 of all, do a caseless comparison; if this succeeds, do a caseful comparison
1420 on the local parts. */
1422 if (strcmpic(yield, topaddr->address) == 0 &&
1423 Ustrncmp(yield, topaddr->address, Ustrchr(yield, '@') - yield) == 0 &&
1424 addr->onetime_parent == NULL &&
1425 (!all_parents || addr->parent == NULL || addr->parent == topaddr))
1426 add_topaddr = FALSE;
1429 /* If all parents are requested, or this is a local pipe/file/reply, and
1430 there is at least one intermediate parent, show it in brackets, and continue
1431 with all of them if all are wanted. */
1433 if ((all_parents || testflag(addr, af_pfr)) &&
1434 addr->parent != NULL &&
1435 addr->parent != topaddr)
1438 address_item *addr2;
1439 for (addr2 = addr->parent; addr2 != topaddr; addr2 = addr2->parent)
1441 yield = string_cat(yield, &size, &ptr, s, 2);
1442 yield = string_cat(yield, &size, &ptr, addr2->address, Ustrlen(addr2->address));
1443 if (!all_parents) break;
1446 yield = string_cat(yield, &size, &ptr, US")", 1);
1449 /* Add the top address if it is required */
1453 yield = string_cat(yield, &size, &ptr, US" <", 2);
1455 if (addr->onetime_parent == NULL)
1456 yield = string_cat(yield, &size, &ptr, topaddr->address,
1457 Ustrlen(topaddr->address));
1459 yield = string_cat(yield, &size, &ptr, addr->onetime_parent,
1460 Ustrlen(addr->onetime_parent));
1462 yield = string_cat(yield, &size, &ptr, US">", 1);
1465 yield[ptr] = 0; /* string_cat() leaves space */
1468 #endif /* COMPILE_UTILITY */
1474 /*************************************************
1475 **************************************************
1476 * Stand-alone test program *
1477 **************************************************
1478 *************************************************/
1485 printf("Testing is_ip_address\n");
1487 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1490 buffer[Ustrlen(buffer) - 1] = 0;
1491 printf("%d\n", string_is_ip_address(buffer, NULL));
1492 printf("%d %d %s\n", string_is_ip_address(buffer, &offset), offset, buffer);
1495 printf("Testing string_nextinlist\n");
1497 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1499 uschar *list = buffer;
1507 sep1 = sep2 = list[1];
1514 uschar *item1 = string_nextinlist(&lp1, &sep1, item, sizeof(item));
1515 uschar *item2 = string_nextinlist(&lp2, &sep2, NULL, 0);
1517 if (item1 == NULL && item2 == NULL) break;
1518 if (item == NULL || item2 == NULL || Ustrcmp(item1, item2) != 0)
1520 printf("***ERROR\nitem1=\"%s\"\nitem2=\"%s\"\n",
1521 (item1 == NULL)? "NULL" : CS item1,
1522 (item2 == NULL)? "NULL" : CS item2);
1525 else printf(" \"%s\"\n", CS item1);
1529 /* This is a horrible lash-up, but it serves its purpose. */
1531 printf("Testing string_format\n");
1533 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1536 long long llargs[3];
1546 buffer[Ustrlen(buffer) - 1] = 0;
1548 s = Ustrchr(buffer, ',');
1549 if (s == NULL) s = buffer + Ustrlen(buffer);
1551 Ustrncpy(format, buffer, s - buffer);
1552 format[s-buffer] = 0;
1559 s = Ustrchr(ss, ',');
1560 if (s == NULL) s = ss + Ustrlen(ss);
1564 Ustrncpy(outbuf, ss, s-ss);
1565 if (Ustrchr(outbuf, '.') != NULL)
1568 dargs[n++] = Ustrtod(outbuf, NULL);
1570 else if (Ustrstr(outbuf, "ll") != NULL)
1573 llargs[n++] = strtoull(CS outbuf, NULL, 10);
1577 args[n++] = (void *)Uatoi(outbuf);
1581 else if (Ustrcmp(ss, "*") == 0)
1583 args[n++] = (void *)(&count);
1589 uschar *sss = malloc(s - ss + 1);
1590 Ustrncpy(sss, ss, s-ss);
1597 if (!dflag && !llflag)
1598 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1599 args[0], args[1], args[2])? "True" : "False");
1602 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1603 dargs[0], dargs[1], dargs[2])? "True" : "False");
1605 else printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1606 llargs[0], llargs[1], llargs[2])? "True" : "False");
1608 printf("%s\n", CS outbuf);
1609 if (countset) printf("count=%d\n", count);
1616 /* End of string.c */