1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2009 */
6 /* See the file NOTICE for conditions of use and distribution. */
8 /* Miscellaneous string-handling functions. Some are not required for
9 utilities and tests, and are cut out by the COMPILE_UTILITY macro. */
15 #ifndef COMPILE_UTILITY
16 /*************************************************
17 * Test for IP address *
18 *************************************************/
20 /* This used just to be a regular expression, but with IPv6 things are a bit
21 more complicated. If the address contains a colon, it is assumed to be a v6
22 address (assuming HAVE_IPV6 is set). If a mask is permitted and one is present,
23 and maskptr is not NULL, its offset is placed there.
27 maskptr NULL if no mask is permitted to follow
28 otherwise, points to an int where the offset of '/' is placed
29 if there is no / followed by trailing digits, *maskptr is set 0
31 Returns: 0 if the string is not a textual representation of an IP address
32 4 if it is an IPv4 address
33 6 if it is an IPv6 address
37 string_is_ip_address(uschar *s, int *maskptr)
42 /* If an optional mask is permitted, check for it. If found, pass back the
47 uschar *ss = s + Ustrlen(s);
49 if (s != ss && isdigit(*(--ss)))
51 while (ss > s && isdigit(ss[-1])) ss--;
52 if (ss > s && *(--ss) == '/') *maskptr = ss - s;
56 /* A colon anywhere in the string => IPv6 address */
58 if (Ustrchr(s, ':') != NULL)
60 BOOL had_double_colon = FALSE;
66 /* An IPv6 address must start with hex digit or double colon. A single
69 if (*s == ':' && *(++s) != ':') return 0;
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. */
75 for (count = 0; count < 8; count++)
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. */
82 if (*s == 0 || *s == '%' || *s == '/') return had_double_colon? yield : 0;
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. */
90 if (had_double_colon) return 0;
91 had_double_colon = TRUE;
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. */
102 if (Ustrchr(s, ':') == NULL && Ustrchr(s, '.') != NULL)
104 if ((!had_double_colon && count != 6) ||
105 (had_double_colon && count > 6)) return 0;
111 /* Check for at least one and not more than 4 hex digits for this
114 if (!isxdigit(*s++)) return 0;
115 if (isxdigit(*s) && isxdigit(*(++s)) && isxdigit(*(++s))) s++;
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
121 if (*s == ':' && *(++s) == 0) return 0;
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
130 return (*s == 0 || *s == '%' ||
131 (*s == '/' && maskptr != NULL && *maskptr != 0))? yield : 0;
134 /* Test for IPv4 address, which may be the tail-end of an IPv6 address. */
136 for (i = 0; i < 4; i++)
138 if (i != 0 && *s++ != '.') return 0;
139 if (!isdigit(*s++)) return 0;
140 if (isdigit(*s) && isdigit(*(++s))) s++;
143 return (*s == 0 || (*s == '/' && maskptr != NULL && *maskptr != 0))?
146 #endif /* COMPILE_UTILITY */
149 /*************************************************
150 * Format message size *
151 *************************************************/
153 /* Convert a message size in bytes to printing form, rounding
154 according to the magnitude of the number. A value of zero causes
155 a string of spaces to be returned.
158 size the message size in bytes
159 buffer where to put the answer
161 Returns: pointer to the buffer
162 a string of exactly 5 characters is normally returned
166 string_format_size(int size, uschar *buffer)
168 if (size == 0) Ustrcpy(CS buffer, " ");
169 else if (size < 1024) sprintf(CS buffer, "%5d", size);
170 else if (size < 10*1024)
171 sprintf(CS buffer, "%4.1fK", (double)size / 1024.0);
172 else if (size < 1024*1024)
173 sprintf(CS buffer, "%4dK", (size + 512)/1024);
174 else if (size < 10*1024*1024)
175 sprintf(CS buffer, "%4.1fM", (double)size / (1024.0 * 1024.0));
177 sprintf(CS buffer, "%4dM", (size + 512 * 1024)/(1024*1024));
183 #ifndef COMPILE_UTILITY
184 /*************************************************
185 * Convert a number to base 62 format *
186 *************************************************/
188 /* Convert a long integer into an ASCII base 62 string. For Cygwin the value of
189 BASE_62 is actually 36. Always return exactly 6 characters plus zero, in a
192 Argument: a long integer
193 Returns: pointer to base 62 string
197 string_base62(unsigned long int value)
199 static uschar yield[7];
200 uschar *p = yield + sizeof(yield) - 1;
204 *(--p) = base62_chars[value % BASE_62];
209 #endif /* COMPILE_UTILITY */
213 #ifndef COMPILE_UTILITY
214 /*************************************************
215 * Interpret escape sequence *
216 *************************************************/
218 /* This function is called from several places where escape sequences are to be
219 interpreted in strings.
222 pp points a pointer to the initiating "\" in the string;
223 the pointer gets updated to point to the final character
224 Returns: the value of the character escape
228 string_interpret_escape(uschar **pp)
233 if (isdigit(ch) && ch != '8' && ch != '9')
236 if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
238 ch = ch * 8 + *(++p) - '0';
239 if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
240 ch = ch * 8 + *(++p) - '0';
245 case 'n': ch = '\n'; break;
246 case 'r': ch = '\r'; break;
247 case 't': ch = '\t'; break;
253 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
254 if (isxdigit(p[1])) ch = ch * 16 +
255 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
262 #endif /* COMPILE_UTILITY */
266 #ifndef COMPILE_UTILITY
267 /*************************************************
268 * Ensure string is printable *
269 *************************************************/
271 /* This function is called for critical strings. It checks for any
272 non-printing characters, and if any are found, it makes a new copy
273 of the string with suitable escape sequences. It is most often called by the
274 macro string_printing(), which sets allow_tab TRUE.
278 allow_tab TRUE to allow tab as a printing character
280 Returns: string with non-printers encoded as printing sequences
284 string_printing2(uschar *s, BOOL allow_tab)
286 int nonprintcount = 0;
294 if (!mac_isprint(c) || (!allow_tab && c == '\t')) nonprintcount++;
298 if (nonprintcount == 0) return s;
300 /* Get a new block of store guaranteed big enough to hold the
303 ss = store_get(length + nonprintcount * 4 + 1);
305 /* Copy everying, escaping non printers. */
313 if (mac_isprint(c) && (allow_tab || c != '\t')) *tt++ = *t++; else
318 case '\n': *tt++ = 'n'; break;
319 case '\r': *tt++ = 'r'; break;
320 case '\b': *tt++ = 'b'; break;
321 case '\v': *tt++ = 'v'; break;
322 case '\f': *tt++ = 'f'; break;
323 case '\t': *tt++ = 't'; break;
324 default: sprintf(CS tt, "%03o", *t); tt += 3; break;
332 #endif /* COMPILE_UTILITY */
337 /*************************************************
338 * Copy and save string *
339 *************************************************/
341 /* This function assumes that memcpy() is faster than strcpy().
343 Argument: string to copy
344 Returns: copy of string in new store
348 string_copy(uschar *s)
350 int len = Ustrlen(s) + 1;
351 uschar *ss = store_get(len);
358 /*************************************************
359 * Copy and save string in malloc'd store *
360 *************************************************/
362 /* This function assumes that memcpy() is faster than strcpy().
364 Argument: string to copy
365 Returns: copy of string in new store
369 string_copy_malloc(uschar *s)
371 int len = Ustrlen(s) + 1;
372 uschar *ss = store_malloc(len);
379 /*************************************************
380 * Copy, lowercase and save string *
381 *************************************************/
384 Argument: string to copy
385 Returns: copy of string in new store, with letters lowercased
389 string_copylc(uschar *s)
391 uschar *ss = store_get(Ustrlen(s) + 1);
393 while (*s != 0) *p++ = tolower(*s++);
400 /*************************************************
401 * Copy and save string, given length *
402 *************************************************/
404 /* It is assumed the data contains no zeros. A zero is added
409 n number of characters
411 Returns: copy of string in new store
415 string_copyn(uschar *s, int n)
417 uschar *ss = store_get(n + 1);
424 /*************************************************
425 * Copy, lowercase, and save string, given length *
426 *************************************************/
428 /* It is assumed the data contains no zeros. A zero is added
433 n number of characters
435 Returns: copy of string in new store, with letters lowercased
439 string_copynlc(uschar *s, int n)
441 uschar *ss = store_get(n + 1);
443 while (n-- > 0) *p++ = tolower(*s++);
450 /*************************************************
451 * Copy string if long, inserting newlines *
452 *************************************************/
454 /* If the given string is longer than 75 characters, it is copied, and within
455 the copy, certain space characters are converted into newlines.
457 Argument: pointer to the string
458 Returns: pointer to the possibly altered string
462 string_split_message(uschar *msg)
466 if (msg == NULL || Ustrlen(msg) <= 75) return msg;
467 s = ss = msg = string_copy(msg);
472 while (i < 75 && *ss != 0 && *ss != '\n') ss++, i++;
484 if (t[-1] == ':') { tt = t; break; }
485 if (tt == NULL) tt = t;
489 if (tt == NULL) /* Can't split behind - try ahead */
494 if (*t == ' ' || *t == '\n')
500 if (tt == NULL) break; /* Can't find anywhere to split */
511 /*************************************************
512 * Copy returned DNS domain name, de-escaping *
513 *************************************************/
515 /* If a domain name contains top-bit characters, some resolvers return
516 the fully qualified name with those characters turned into escapes. The
517 convention is a backslash followed by _decimal_ digits. We convert these
518 back into the original binary values. This will be relevant when
519 allow_utf8_domains is set true and UTF-8 characters are used in domain
520 names. Backslash can also be used to escape other characters, though we
521 shouldn't come across them in domain names.
523 Argument: the domain name string
524 Returns: copy of string in new store, de-escaped
528 string_copy_dnsdomain(uschar *s)
531 uschar *ss = yield = store_get(Ustrlen(s) + 1);
539 else if (isdigit(s[1]))
541 *ss++ = (s[1] - '0')*100 + (s[2] - '0')*10 + s[3] - '0';
544 else if (*(++s) != 0)
555 #ifndef COMPILE_UTILITY
556 /*************************************************
557 * Copy space-terminated or quoted string *
558 *************************************************/
560 /* This function copies from a string until its end, or until whitespace is
561 encountered, unless the string begins with a double quote, in which case the
562 terminating quote is sought, and escaping within the string is done. The length
563 of a de-quoted string can be no longer than the original, since escaping always
564 turns n characters into 1 character.
566 Argument: pointer to the pointer to the first character, which gets updated
567 Returns: the new string
571 string_dequote(uschar **sptr)
576 /* First find the end of the string */
580 while (*s != 0 && !isspace(*s)) s++;
585 while (*s != 0 && *s != '\"')
587 if (*s == '\\') (void)string_interpret_escape(&s);
593 /* Get enough store to copy into */
595 t = yield = store_get(s - *sptr + 1);
602 while (*s != 0 && !isspace(*s)) *t++ = *s++;
607 while (*s != 0 && *s != '\"')
609 if (*s == '\\') *t++ = string_interpret_escape(&s);
616 /* Update the pointer and return the terminated copy */
622 #endif /* COMPILE_UTILITY */
626 /*************************************************
627 * Format a string and save it *
628 *************************************************/
630 /* The formatting is done by string_format, which checks the length of
634 format a printf() format - deliberately char * rather than uschar *
635 because it will most usually be a literal string
636 ... arguments for format
638 Returns: pointer to fresh piece of store containing sprintf'ed string
642 string_sprintf(const char *format, ...)
645 uschar buffer[STRING_SPRINTF_BUFFER_SIZE];
646 va_start(ap, format);
647 if (!string_vformat(buffer, sizeof(buffer), format, ap))
648 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
649 "string_sprintf expansion was longer than %d", sizeof(buffer));
651 return string_copy(buffer);
656 /*************************************************
657 * Case-independent strncmp() function *
658 *************************************************/
664 n number of characters to compare
666 Returns: < 0, = 0, or > 0, according to the comparison
670 strncmpic(const uschar *s, const uschar *t, int n)
674 int c = tolower(*s++) - tolower(*t++);
681 /*************************************************
682 * Case-independent strcmp() function *
683 *************************************************/
690 Returns: < 0, = 0, or > 0, according to the comparison
694 strcmpic(const uschar *s, const uschar *t)
698 int c = tolower(*s++) - tolower(*t++);
699 if (c != 0) return c;
705 /*************************************************
706 * Case-independent strstr() function *
707 *************************************************/
709 /* The third argument specifies whether whitespace is required
710 to follow the matched string.
714 t substring to search for
715 space_follows if TRUE, match only if whitespace follows
717 Returns: pointer to substring in string, or NULL if not found
721 strstric(uschar *s, uschar *t, BOOL space_follows)
724 uschar *yield = NULL;
725 int cl = tolower(*p);
726 int cu = toupper(*p);
730 if (*s == cl || *s == cu)
732 if (yield == NULL) yield = s;
735 if (!space_follows || s[1] == ' ' || s[1] == '\n' ) return yield;
743 else if (yield != NULL)
757 #ifndef COMPILE_UTILITY
758 /*************************************************
759 * Get next string from separated list *
760 *************************************************/
762 /* Leading and trailing space is removed from each item. The separator in the
763 list is controlled by the int pointed to by the separator argument as follows:
765 If the value is > 0 it is used as the separator. This is typically used for
766 sublists such as slash-separated options. The value is always a printing
769 (If the value is actually > UCHAR_MAX there is only one item in the list.
770 This is used for some cases when called via functions that sometimes
771 plough through lists, and sometimes are given single items.)
773 If the value is <= 0, the string is inspected for a leading <x, where x is an
774 ispunct() or an iscntrl() character. If found, x is used as the separator. If
777 (a) if separator == 0, ':' is used
778 (b) if separator <0, -separator is used
780 In all cases the value of the separator that is used is written back to the
781 int so that it is used on subsequent calls as we progress through the list.
783 A literal ispunct() separator can be represented in an item by doubling, but
784 there is no way to include an iscntrl() separator as part of the data.
787 listptr points to a pointer to the current start of the list; the
788 pointer gets updated to point after the end of the next item
789 separator a pointer to the separator character in an int (see above)
790 buffer where to put a copy of the next string in the list; or
791 NULL if the next string is returned in new memory
792 buflen when buffer is not NULL, the size of buffer; otherwise ignored
794 Returns: pointer to buffer, containing the next substring,
795 or NULL if no more substrings
799 string_nextinlist(uschar **listptr, int *separator, uschar *buffer, int buflen)
801 register int sep = *separator;
802 register uschar *s = *listptr;
805 if (s == NULL) return NULL;
807 /* This allows for a fixed specified separator to be an iscntrl() character,
808 but at the time of implementation, this is never the case. However, it's best
809 to be conservative. */
811 while (isspace(*s) && *s != sep) s++;
813 /* A change of separator is permitted, so look for a leading '<' followed by an
814 allowed character. */
818 if (*s == '<' && (ispunct(s[1]) || iscntrl(s[1])))
822 while (isspace(*s) && *s != sep) s++;
826 sep = (sep == 0)? ':' : -sep;
831 /* An empty string has no list elements */
833 if (*s == 0) return NULL;
835 /* Note whether whether or not the separator is an iscntrl() character. */
837 sep_is_special = iscntrl(sep);
839 /* Handle the case when a buffer is provided. */
846 if (*s == sep && (*(++s) != sep || sep_is_special)) break;
847 if (p < buflen - 1) buffer[p++] = *s;
849 while (p > 0 && isspace(buffer[p-1])) p--;
853 /* Handle the case when a buffer is not provided. */
861 /* We know that *s != 0 at this point. However, it might be pointing to a
862 separator, which could indicate an empty string, or (if an ispunct()
863 character) could be doubled to indicate a separator character as data at the
864 start of a string. Avoid getting working memory for an empty item. */
869 if (*s != sep || sep_is_special)
872 return string_copy(US"");
876 /* Not an empty string; the first character is guaranteed to be a data
881 for (ss = s + 1; *ss != 0 && *ss != sep; ss++);
882 buffer = string_cat(buffer, &size, &ptr, s, ss-s);
884 if (*s == 0 || *(++s) != sep || sep_is_special) break;
886 while (ptr > 0 && isspace(buffer[ptr-1])) ptr--;
890 /* Update the current pointer and return the new string */
895 #endif /* COMPILE_UTILITY */
899 #ifndef COMPILE_UTILITY
900 /*************************************************
901 * Add chars to string *
902 *************************************************/
904 /* This function is used when building up strings of unknown length. Room is
905 always left for a terminating zero to be added to the string that is being
906 built. This function does not require the string that is being added to be NUL
907 terminated, because the number of characters to add is given explicitly. It is
908 sometimes called to extract parts of other strings.
911 string points to the start of the string that is being built, or NULL
912 if this is a new string that has no contents yet
913 size points to a variable that holds the current capacity of the memory
914 block (updated if changed)
915 ptr points to a variable that holds the offset at which to add
916 characters, updated to the new offset
917 s points to characters to add
918 count count of characters to add; must not exceed the length of s, if s
921 If string is given as NULL, *size and *ptr should both be zero.
923 Returns: pointer to the start of the string, changed if copied for expansion.
924 Note that a NUL is not added, though space is left for one. This is
925 because string_cat() is often called multiple times to build up a
926 string - there's no point adding the NUL till the end.
930 string_cat(uschar *string, int *size, int *ptr, const uschar *s, int count)
934 if (p + count >= *size)
938 /* Mostly, string_cat() is used to build small strings of a few hundred
939 characters at most. There are times, however, when the strings are very much
940 longer (for example, a lookup that returns a vast number of alias addresses).
941 To try to keep things reasonable, we use increments whose size depends on the
942 existing length of the string. */
944 int inc = (oldsize < 4096)? 100 : 1024;
945 while (*size <= p + count) *size += inc;
949 if (string == NULL) string = store_get(*size);
951 /* Try to extend an existing allocation. If the result of calling
952 store_extend() is false, either there isn't room in the current memory block,
953 or this string is not the top item on the dynamic store stack. We then have
954 to get a new chunk of store and copy the old string. When building large
955 strings, it is helpful to call store_release() on the old string, to release
956 memory blocks that have become empty. (The block will be freed if the string
957 is at its start.) However, we can do this only if we know that the old string
958 was the last item on the dynamic memory stack. This is the case if it matches
961 else if (!store_extend(string, oldsize, *size))
963 BOOL release_ok = store_last_get[store_pool] == string;
964 uschar *newstring = store_get(*size);
965 memcpy(newstring, string, p);
966 if (release_ok) store_release(string);
971 /* Because we always specify the exact number of characters to copy, we can
972 use memcpy(), which is likely to be more efficient than strncopy() because the
973 latter has to check for zero bytes. */
975 memcpy(string + p, s, count);
979 #endif /* COMPILE_UTILITY */
983 #ifndef COMPILE_UTILITY
984 /*************************************************
985 * Append strings to another string *
986 *************************************************/
988 /* This function can be used to build a string from many other strings.
989 It calls string_cat() to do the dirty work.
992 string points to the start of the string that is being built, or NULL
993 if this is a new string that has no contents yet
994 size points to a variable that holds the current capacity of the memory
995 block (updated if changed)
996 ptr points to a variable that holds the offset at which to add
997 characters, updated to the new offset
998 count the number of strings to append
999 ... "count" uschar* arguments, which must be valid zero-terminated
1002 Returns: pointer to the start of the string, changed if copied for expansion.
1003 The string is not zero-terminated - see string_cat() above.
1007 string_append(uschar *string, int *size, int *ptr, int count, ...)
1012 va_start(ap, count);
1013 for (i = 0; i < count; i++)
1015 uschar *t = va_arg(ap, uschar *);
1016 string = string_cat(string, size, ptr, t, Ustrlen(t));
1026 /*************************************************
1027 * Format a string with length checks *
1028 *************************************************/
1030 /* This function is used to format a string with checking of the length of the
1031 output for all conversions. It protects Exim from absent-mindedness when
1032 calling functions like debug_printf and string_sprintf, and elsewhere. There
1033 are two different entry points to what is actually the same function, depending
1034 on whether the variable length list of data arguments are given explicitly or
1037 The formats are the usual printf() ones, with some omissions (never used) and
1038 two additions for strings: %S forces lower case, and %#s or %#S prints nothing
1039 for a NULL string. Without the # "NULL" is printed (useful in debugging). There
1040 is also the addition of %D and %M, which insert the date in the form used for
1041 datestamped log files.
1044 buffer a buffer in which to put the formatted string
1045 buflen the length of the buffer
1046 format the format string - deliberately char * and not uschar *
1047 ... or ap variable list of supplementary arguments
1049 Returns: TRUE if the result fitted in the buffer
1053 string_format(uschar *buffer, int buflen, const char *format, ...)
1057 va_start(ap, format);
1058 yield = string_vformat(buffer, buflen, format, ap);
1065 string_vformat(uschar *buffer, int buflen, const char *format, va_list ap)
1067 enum { L_NORMAL, L_SHORT, L_LONG, L_LONGLONG, L_LONGDOUBLE };
1070 int width, precision;
1071 const char *fp = format; /* Deliberately not unsigned */
1073 uschar *last = buffer + buflen - 1;
1075 string_datestamp_offset = -1; /* Datestamp not inserted */
1076 string_datestamp_length = 0; /* Datestamp not inserted */
1077 string_datestamp_type = 0; /* Datestamp not inserted */
1079 /* Scan the format and handle the insertions */
1083 int length = L_NORMAL;
1086 const char *null = "NULL"; /* ) These variables */
1087 const char *item_start, *s; /* ) are deliberately */
1088 char newformat[16]; /* ) not unsigned */
1090 /* Non-% characters just get copied verbatim */
1094 if (p >= last) { yield = FALSE; break; }
1095 *p++ = (uschar)*fp++;
1099 /* Deal with % characters. Pick off the width and precision, for checking
1100 strings, skipping over the flag and modifier characters. */
1103 width = precision = -1;
1105 if (strchr("-+ #0", *(++fp)) != NULL)
1107 if (*fp == '#') null = "";
1111 if (isdigit((uschar)*fp))
1113 width = *fp++ - '0';
1114 while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';
1116 else if (*fp == '*')
1118 width = va_arg(ap, int);
1126 precision = va_arg(ap, int);
1132 while (isdigit((uschar)*fp))
1133 precision = precision*10 + *fp++ - '0';
1137 /* Skip over 'h', 'L', 'l', and 'll', remembering the item length */
1140 { fp++; length = L_SHORT; }
1141 else if (*fp == 'L')
1142 { fp++; length = L_LONGDOUBLE; }
1143 else if (*fp == 'l')
1148 length = L_LONGLONG;
1157 /* Handle each specific format type. */
1162 nptr = va_arg(ap, int *);
1171 if (p >= last - ((length > L_LONG)? 24 : 12))
1172 { yield = FALSE; goto END_FORMAT; }
1173 strncpy(newformat, item_start, fp - item_start);
1174 newformat[fp - item_start] = 0;
1176 /* Short int is promoted to int when passing through ..., so we must use
1177 int for va_arg(). */
1182 case L_NORMAL: sprintf(CS p, newformat, va_arg(ap, int)); break;
1183 case L_LONG: sprintf(CS p, newformat, va_arg(ap, long int)); break;
1184 case L_LONGLONG: sprintf(CS p, newformat, va_arg(ap, LONGLONG_T)); break;
1190 if (p >= last - 24) { yield = FALSE; goto END_FORMAT; }
1191 strncpy(newformat, item_start, fp - item_start);
1192 newformat[fp - item_start] = 0;
1193 sprintf(CS p, newformat, va_arg(ap, void *));
1197 /* %f format is inherently insecure if the numbers that it may be
1198 handed are unknown (e.g. 1e300). However, in Exim, %f is used for
1199 printing load averages, and these are actually stored as integers
1200 (load average * 1000) so the size of the numbers is constrained.
1201 It is also used for formatting sending rates, where the simplicity
1202 of the format prevents overflow. */
1209 if (precision < 0) precision = 6;
1210 if (p >= last - precision - 8) { yield = FALSE; goto END_FORMAT; }
1211 strncpy(newformat, item_start, fp - item_start);
1212 newformat[fp-item_start] = 0;
1213 if (length == L_LONGDOUBLE)
1214 sprintf(CS p, newformat, va_arg(ap, long double));
1216 sprintf(CS p, newformat, va_arg(ap, double));
1223 if (p >= last) { yield = FALSE; goto END_FORMAT; }
1228 if (p >= last) { yield = FALSE; goto END_FORMAT; }
1229 *p++ = va_arg(ap, int);
1232 case 'D': /* Insert daily datestamp for log file names */
1233 s = CS tod_stamp(tod_log_datestamp_daily);
1234 string_datestamp_offset = p - buffer; /* Passed back via global */
1235 string_datestamp_length = Ustrlen(s); /* Passed back via global */
1236 string_datestamp_type = tod_log_datestamp_daily;
1237 slen = string_datestamp_length;
1240 case 'M': /* Insert monthly datestamp for log file names */
1241 s = CS tod_stamp(tod_log_datestamp_monthly);
1242 string_datestamp_offset = p - buffer; /* Passed back via global */
1243 string_datestamp_length = Ustrlen(s); /* Passed back via global */
1244 string_datestamp_type = tod_log_datestamp_monthly;
1245 slen = string_datestamp_length;
1249 case 'S': /* Forces *lower* case */
1250 s = va_arg(ap, char *);
1252 if (s == NULL) s = null;
1255 INSERT_STRING: /* Come to from %D or %M above */
1257 /* If the width is specified, check that there is a precision
1258 set; if not, set it to the width to prevent overruns of long
1263 if (precision < 0) precision = width;
1266 /* If a width is not specified and the precision is specified, set
1267 the width to the precision, or the string length if shorted. */
1269 else if (precision >= 0)
1271 width = (precision < slen)? precision : slen;
1274 /* If neither are specified, set them both to the string length. */
1276 else width = precision = slen;
1278 /* Check string space, and add the string to the buffer if ok. If
1279 not OK, add part of the string (debugging uses this to show as
1280 much as possible). */
1287 if (p >= last - width)
1290 width = precision = last - p - 1;
1291 if (width < 0) width = 0;
1292 if (precision < 0) precision = 0;
1294 sprintf(CS p, "%*.*s", width, precision, s);
1296 while (*p) { *p = tolower(*p); p++; }
1299 if (!yield) goto END_FORMAT;
1302 /* Some things are never used in Exim; also catches junk. */
1305 strncpy(newformat, item_start, fp - item_start);
1306 newformat[fp-item_start] = 0;
1307 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "string_format: unsupported type "
1308 "in \"%s\" in \"%s\"", newformat, format);
1313 /* Ensure string is complete; return TRUE if got to the end of the format */
1323 #ifndef COMPILE_UTILITY
1324 /*************************************************
1325 * Generate an "open failed" message *
1326 *************************************************/
1328 /* This function creates a message after failure to open a file. It includes a
1329 string supplied as data, adds the strerror() text, and if the failure was
1330 "Permission denied", reads and includes the euid and egid.
1333 eno the value of errno after the failure
1334 format a text format string - deliberately not uschar *
1335 ... arguments for the format string
1337 Returns: a message, in dynamic store
1341 string_open_failed(int eno, const char *format, ...)
1344 uschar buffer[1024];
1346 Ustrcpy(buffer, "failed to open ");
1347 va_start(ap, format);
1349 /* Use the checked formatting routine to ensure that the buffer
1350 does not overflow. It should not, since this is called only for internally
1351 specified messages. If it does, the message just gets truncated, and there
1352 doesn't seem much we can do about that. */
1354 (void)string_vformat(buffer+15, sizeof(buffer) - 15, format, ap);
1356 return (eno == EACCES)?
1357 string_sprintf("%s: %s (euid=%ld egid=%ld)", buffer, strerror(eno),
1358 (long int)geteuid(), (long int)getegid()) :
1359 string_sprintf("%s: %s", buffer, strerror(eno));
1361 #endif /* COMPILE_UTILITY */
1365 #ifndef COMPILE_UTILITY
1366 /*************************************************
1367 * Generate local prt for logging *
1368 *************************************************/
1370 /* This function is a subroutine for use in string_log_address() below.
1373 addr the address being logged
1374 yield the current dynamic buffer pointer
1375 sizeptr points to current size
1376 ptrptr points to current insert pointer
1378 Returns: the new value of the buffer pointer
1382 string_get_localpart(address_item *addr, uschar *yield, int *sizeptr,
1385 if (testflag(addr, af_include_affixes) && addr->prefix != NULL)
1386 yield = string_cat(yield, sizeptr, ptrptr, addr->prefix,
1387 Ustrlen(addr->prefix));
1388 yield = string_cat(yield, sizeptr, ptrptr, addr->local_part,
1389 Ustrlen(addr->local_part));
1390 if (testflag(addr, af_include_affixes) && addr->suffix != NULL)
1391 yield = string_cat(yield, sizeptr, ptrptr, addr->suffix,
1392 Ustrlen(addr->suffix));
1397 /*************************************************
1398 * Generate log address list *
1399 *************************************************/
1401 /* This function generates a list consisting of an address and its parents, for
1402 use in logging lines. For saved onetime aliased addresses, the onetime parent
1403 field is used. If the address was delivered by a transport with rcpt_include_
1404 affixes set, the af_include_affixes bit will be set in the address. In that
1405 case, we include the affixes here too.
1408 addr bottom (ultimate) address
1409 all_parents if TRUE, include all parents
1410 success TRUE for successful delivery
1412 Returns: a string in dynamic store
1416 string_log_address(address_item *addr, BOOL all_parents, BOOL success)
1420 BOOL add_topaddr = TRUE;
1421 uschar *yield = store_get(size);
1422 address_item *topaddr;
1424 /* Find the ultimate parent */
1426 for (topaddr = addr; topaddr->parent != NULL; topaddr = topaddr->parent);
1428 /* We start with just the local part for pipe, file, and reply deliveries, and
1429 for successful local deliveries from routers that have the log_as_local flag
1430 set. File deliveries from filters can be specified as non-absolute paths in
1431 cases where the transport is goin to complete the path. If there is an error
1432 before this happens (expansion failure) the local part will not be updated, and
1433 so won't necessarily look like a path. Add extra text for this case. */
1435 if (testflag(addr, af_pfr) ||
1437 addr->router != NULL && addr->router->log_as_local &&
1438 addr->transport != NULL && addr->transport->info->local))
1440 if (testflag(addr, af_file) && addr->local_part[0] != '/')
1441 yield = string_cat(yield, &size, &ptr, CUS"save ", 5);
1442 yield = string_get_localpart(addr, yield, &size, &ptr);
1445 /* Other deliveries start with the full address. It we have split it into local
1446 part and domain, use those fields. Some early failures can happen before the
1447 splitting is done; in those cases use the original field. */
1451 if (addr->local_part != NULL)
1453 yield = string_get_localpart(addr, yield, &size, &ptr);
1454 yield = string_cat(yield, &size, &ptr, US"@", 1);
1455 yield = string_cat(yield, &size, &ptr, addr->domain,
1456 Ustrlen(addr->domain) );
1460 yield = string_cat(yield, &size, &ptr, addr->address, Ustrlen(addr->address));
1464 /* If the address we are going to print is the same as the top address,
1465 and all parents are not being included, don't add on the top address. First
1466 of all, do a caseless comparison; if this succeeds, do a caseful comparison
1467 on the local parts. */
1469 if (strcmpic(yield, topaddr->address) == 0 &&
1470 Ustrncmp(yield, topaddr->address, Ustrchr(yield, '@') - yield) == 0 &&
1471 addr->onetime_parent == NULL &&
1472 (!all_parents || addr->parent == NULL || addr->parent == topaddr))
1473 add_topaddr = FALSE;
1476 /* If all parents are requested, or this is a local pipe/file/reply, and
1477 there is at least one intermediate parent, show it in brackets, and continue
1478 with all of them if all are wanted. */
1480 if ((all_parents || testflag(addr, af_pfr)) &&
1481 addr->parent != NULL &&
1482 addr->parent != topaddr)
1485 address_item *addr2;
1486 for (addr2 = addr->parent; addr2 != topaddr; addr2 = addr2->parent)
1488 yield = string_cat(yield, &size, &ptr, s, 2);
1489 yield = string_cat(yield, &size, &ptr, addr2->address, Ustrlen(addr2->address));
1490 if (!all_parents) break;
1493 yield = string_cat(yield, &size, &ptr, US")", 1);
1496 /* Add the top address if it is required */
1500 yield = string_cat(yield, &size, &ptr, US" <", 2);
1502 if (addr->onetime_parent == NULL)
1503 yield = string_cat(yield, &size, &ptr, topaddr->address,
1504 Ustrlen(topaddr->address));
1506 yield = string_cat(yield, &size, &ptr, addr->onetime_parent,
1507 Ustrlen(addr->onetime_parent));
1509 yield = string_cat(yield, &size, &ptr, US">", 1);
1512 yield[ptr] = 0; /* string_cat() leaves space */
1515 #endif /* COMPILE_UTILITY */
1521 /*************************************************
1522 **************************************************
1523 * Stand-alone test program *
1524 **************************************************
1525 *************************************************/
1532 printf("Testing is_ip_address\n");
1534 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1537 buffer[Ustrlen(buffer) - 1] = 0;
1538 printf("%d\n", string_is_ip_address(buffer, NULL));
1539 printf("%d %d %s\n", string_is_ip_address(buffer, &offset), offset, buffer);
1542 printf("Testing string_nextinlist\n");
1544 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1546 uschar *list = buffer;
1554 sep1 = sep2 = list[1];
1561 uschar *item1 = string_nextinlist(&lp1, &sep1, item, sizeof(item));
1562 uschar *item2 = string_nextinlist(&lp2, &sep2, NULL, 0);
1564 if (item1 == NULL && item2 == NULL) break;
1565 if (item == NULL || item2 == NULL || Ustrcmp(item1, item2) != 0)
1567 printf("***ERROR\nitem1=\"%s\"\nitem2=\"%s\"\n",
1568 (item1 == NULL)? "NULL" : CS item1,
1569 (item2 == NULL)? "NULL" : CS item2);
1572 else printf(" \"%s\"\n", CS item1);
1576 /* This is a horrible lash-up, but it serves its purpose. */
1578 printf("Testing string_format\n");
1580 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1583 long long llargs[3];
1593 buffer[Ustrlen(buffer) - 1] = 0;
1595 s = Ustrchr(buffer, ',');
1596 if (s == NULL) s = buffer + Ustrlen(buffer);
1598 Ustrncpy(format, buffer, s - buffer);
1599 format[s-buffer] = 0;
1606 s = Ustrchr(ss, ',');
1607 if (s == NULL) s = ss + Ustrlen(ss);
1611 Ustrncpy(outbuf, ss, s-ss);
1612 if (Ustrchr(outbuf, '.') != NULL)
1615 dargs[n++] = Ustrtod(outbuf, NULL);
1617 else if (Ustrstr(outbuf, "ll") != NULL)
1620 llargs[n++] = strtoull(CS outbuf, NULL, 10);
1624 args[n++] = (void *)Uatoi(outbuf);
1628 else if (Ustrcmp(ss, "*") == 0)
1630 args[n++] = (void *)(&count);
1636 uschar *sss = malloc(s - ss + 1);
1637 Ustrncpy(sss, ss, s-ss);
1644 if (!dflag && !llflag)
1645 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1646 args[0], args[1], args[2])? "True" : "False");
1649 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1650 dargs[0], dargs[1], dargs[2])? "True" : "False");
1652 else printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1653 llargs[0], llargs[1], llargs[2])? "True" : "False");
1655 printf("%s\n", CS outbuf);
1656 if (countset) printf("count=%d\n", count);
1663 /* End of string.c */