1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2014 */
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(const uschar *s, int *maskptr)
42 /* If an optional mask is permitted, check for it. If found, pass back the
47 const 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(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 /*************************************************
214 * Interpret escape sequence *
215 *************************************************/
217 /* This function is called from several places where escape sequences are to be
218 interpreted in strings.
221 pp points a pointer to the initiating "\" in the string;
222 the pointer gets updated to point to the final character
223 Returns: the value of the character escape
227 string_interpret_escape(const uschar **pp)
229 #ifdef COMPILE_UTILITY
230 const uschar *hex_digits= CUS"0123456789abcdef";
233 const uschar *p = *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 'b': ch = '\b'; break;
248 case 'f': ch = '\f'; break;
249 case 'n': ch = '\n'; break;
250 case 'r': ch = '\r'; break;
251 case 't': ch = '\t'; break;
252 case 'v': ch = '\v'; break;
258 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
259 if (isxdigit(p[1])) ch = ch * 16 +
260 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
270 #ifndef COMPILE_UTILITY
271 /*************************************************
272 * Ensure string is printable *
273 *************************************************/
275 /* This function is called for critical strings. It checks for any
276 non-printing characters, and if any are found, it makes a new copy
277 of the string with suitable escape sequences. It is most often called by the
278 macro string_printing(), which sets allow_tab TRUE.
282 allow_tab TRUE to allow tab as a printing character
284 Returns: string with non-printers encoded as printing sequences
288 string_printing2(const uschar *s, BOOL allow_tab)
290 int nonprintcount = 0;
298 if (!mac_isprint(c) || (!allow_tab && c == '\t')) nonprintcount++;
302 if (nonprintcount == 0) return s;
304 /* Get a new block of store guaranteed big enough to hold the
307 ss = store_get(length + nonprintcount * 3 + 1);
309 /* Copy everying, escaping non printers. */
317 if (mac_isprint(c) && (allow_tab || c != '\t')) *tt++ = *t++; else
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;
336 #endif /* COMPILE_UTILITY */
338 /*************************************************
339 * Undo printing escapes in string *
340 *************************************************/
342 /* This function is the reverse of string_printing2. It searches for
343 backslash characters and if any are found, it makes a new copy of the
344 string with escape sequences parsed. Otherwise it returns the original
350 Returns: string with printing escapes parsed back
354 string_unprinting(uschar *s)
356 uschar *p, *q, *r, *ss;
359 p = Ustrchr(s, '\\');
362 len = Ustrlen(s) + 1;
377 *q++ = string_interpret_escape((const uschar **)&p);
382 r = Ustrchr(p, '\\');
408 /*************************************************
409 * Copy and save string *
410 *************************************************/
412 /* This function assumes that memcpy() is faster than strcpy().
414 Argument: string to copy
415 Returns: copy of string in new store
419 string_copy(const uschar *s)
421 int len = Ustrlen(s) + 1;
422 uschar *ss = store_get(len);
429 /*************************************************
430 * Copy and save string in malloc'd store *
431 *************************************************/
433 /* This function assumes that memcpy() is faster than strcpy().
435 Argument: string to copy
436 Returns: copy of string in new store
440 string_copy_malloc(const uschar *s)
442 int len = Ustrlen(s) + 1;
443 uschar *ss = store_malloc(len);
450 /*************************************************
451 * Copy, lowercase and save string *
452 *************************************************/
455 Argument: string to copy
456 Returns: copy of string in new store, with letters lowercased
460 string_copylc(const uschar *s)
462 uschar *ss = store_get(Ustrlen(s) + 1);
464 while (*s != 0) *p++ = tolower(*s++);
471 /*************************************************
472 * Copy and save string, given length *
473 *************************************************/
475 /* It is assumed the data contains no zeros. A zero is added
480 n number of characters
482 Returns: copy of string in new store
486 string_copyn(const uschar *s, int n)
488 uschar *ss = store_get(n + 1);
495 /*************************************************
496 * Copy, lowercase, and save string, given length *
497 *************************************************/
499 /* It is assumed the data contains no zeros. A zero is added
504 n number of characters
506 Returns: copy of string in new store, with letters lowercased
510 string_copynlc(uschar *s, int n)
512 uschar *ss = store_get(n + 1);
514 while (n-- > 0) *p++ = tolower(*s++);
521 /*************************************************
522 * Copy string if long, inserting newlines *
523 *************************************************/
525 /* If the given string is longer than 75 characters, it is copied, and within
526 the copy, certain space characters are converted into newlines.
528 Argument: pointer to the string
529 Returns: pointer to the possibly altered string
533 string_split_message(uschar *msg)
537 if (msg == NULL || Ustrlen(msg) <= 75) return msg;
538 s = ss = msg = string_copy(msg);
543 while (i < 75 && *ss != 0 && *ss != '\n') ss++, i++;
555 if (t[-1] == ':') { tt = t; break; }
556 if (tt == NULL) tt = t;
560 if (tt == NULL) /* Can't split behind - try ahead */
565 if (*t == ' ' || *t == '\n')
571 if (tt == NULL) break; /* Can't find anywhere to split */
582 /*************************************************
583 * Copy returned DNS domain name, de-escaping *
584 *************************************************/
586 /* If a domain name contains top-bit characters, some resolvers return
587 the fully qualified name with those characters turned into escapes. The
588 convention is a backslash followed by _decimal_ digits. We convert these
589 back into the original binary values. This will be relevant when
590 allow_utf8_domains is set true and UTF-8 characters are used in domain
591 names. Backslash can also be used to escape other characters, though we
592 shouldn't come across them in domain names.
594 Argument: the domain name string
595 Returns: copy of string in new store, de-escaped
599 string_copy_dnsdomain(uschar *s)
602 uschar *ss = yield = store_get(Ustrlen(s) + 1);
610 else if (isdigit(s[1]))
612 *ss++ = (s[1] - '0')*100 + (s[2] - '0')*10 + s[3] - '0';
615 else if (*(++s) != 0)
626 #ifndef COMPILE_UTILITY
627 /*************************************************
628 * Copy space-terminated or quoted string *
629 *************************************************/
631 /* This function copies from a string until its end, or until whitespace is
632 encountered, unless the string begins with a double quote, in which case the
633 terminating quote is sought, and escaping within the string is done. The length
634 of a de-quoted string can be no longer than the original, since escaping always
635 turns n characters into 1 character.
637 Argument: pointer to the pointer to the first character, which gets updated
638 Returns: the new string
642 string_dequote(const uschar **sptr)
644 const uschar *s = *sptr;
647 /* First find the end of the string */
651 while (*s != 0 && !isspace(*s)) s++;
656 while (*s != 0 && *s != '\"')
658 if (*s == '\\') (void)string_interpret_escape(&s);
664 /* Get enough store to copy into */
666 t = yield = store_get(s - *sptr + 1);
673 while (*s != 0 && !isspace(*s)) *t++ = *s++;
678 while (*s != 0 && *s != '\"')
680 if (*s == '\\') *t++ = string_interpret_escape(&s);
687 /* Update the pointer and return the terminated copy */
693 #endif /* COMPILE_UTILITY */
697 /*************************************************
698 * Format a string and save it *
699 *************************************************/
701 /* The formatting is done by string_format, which checks the length of
705 format a printf() format - deliberately char * rather than uschar *
706 because it will most usually be a literal string
707 ... arguments for format
709 Returns: pointer to fresh piece of store containing sprintf'ed string
713 string_sprintf(const char *format, ...)
716 uschar buffer[STRING_SPRINTF_BUFFER_SIZE];
717 va_start(ap, format);
718 if (!string_vformat(buffer, sizeof(buffer), format, ap))
719 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
720 "string_sprintf expansion was longer than " SIZE_T_FMT " (%s)",
721 sizeof(buffer), format);
723 return string_copy(buffer);
728 /*************************************************
729 * Case-independent strncmp() function *
730 *************************************************/
736 n number of characters to compare
738 Returns: < 0, = 0, or > 0, according to the comparison
742 strncmpic(const uschar *s, const uschar *t, int n)
746 int c = tolower(*s++) - tolower(*t++);
753 /*************************************************
754 * Case-independent strcmp() function *
755 *************************************************/
762 Returns: < 0, = 0, or > 0, according to the comparison
766 strcmpic(const uschar *s, const uschar *t)
770 int c = tolower(*s++) - tolower(*t++);
771 if (c != 0) return c;
777 /*************************************************
778 * Case-independent strstr() function *
779 *************************************************/
781 /* The third argument specifies whether whitespace is required
782 to follow the matched string.
786 t substring to search for
787 space_follows if TRUE, match only if whitespace follows
789 Returns: pointer to substring in string, or NULL if not found
793 strstric(uschar *s, uschar *t, BOOL space_follows)
796 uschar *yield = NULL;
797 int cl = tolower(*p);
798 int cu = toupper(*p);
802 if (*s == cl || *s == cu)
804 if (yield == NULL) yield = s;
807 if (!space_follows || s[1] == ' ' || s[1] == '\n' ) return yield;
815 else if (yield != NULL)
829 #ifndef COMPILE_UTILITY
830 /*************************************************
831 * Get next string from separated list *
832 *************************************************/
834 /* Leading and trailing space is removed from each item. The separator in the
835 list is controlled by the int pointed to by the separator argument as follows:
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
841 (If the value is actually > UCHAR_MAX there is only one item in the list.
842 This is used for some cases when called via functions that sometimes
843 plough through lists, and sometimes are given single items.)
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
849 (a) if separator == 0, ':' is used
850 (b) if separator <0, -separator is used
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.
855 A literal ispunct() separator can be represented in an item by doubling, but
856 there is no way to include an iscntrl() separator as part of the data.
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
866 Returns: pointer to buffer, containing the next substring,
867 or NULL if no more substrings
871 string_nextinlist(const uschar **listptr, int *separator, uschar *buffer, int buflen)
873 int sep = *separator;
874 const uschar *s = *listptr;
877 if (s == NULL) return NULL;
879 /* This allows for a fixed specified separator to be an iscntrl() character,
880 but at the time of implementation, this is never the case. However, it's best
881 to be conservative. */
883 while (isspace(*s) && *s != sep) s++;
885 /* A change of separator is permitted, so look for a leading '<' followed by an
886 allowed character. */
890 if (*s == '<' && (ispunct(s[1]) || iscntrl(s[1])))
894 while (isspace(*s) && *s != sep) s++;
898 sep = (sep == 0)? ':' : -sep;
903 /* An empty string has no list elements */
905 if (*s == 0) return NULL;
907 /* Note whether whether or not the separator is an iscntrl() character. */
909 sep_is_special = iscntrl(sep);
911 /* Handle the case when a buffer is provided. */
918 if (*s == sep && (*(++s) != sep || sep_is_special)) break;
919 if (p < buflen - 1) buffer[p++] = *s;
921 while (p > 0 && isspace(buffer[p-1])) p--;
925 /* Handle the case when a buffer is not provided. */
933 /* We know that *s != 0 at this point. However, it might be pointing to a
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. */
941 if (*s != sep || sep_is_special)
944 return string_copy(US"");
948 /* Not an empty string; the first character is guaranteed to be a data
953 for (ss = s + 1; *ss != 0 && *ss != sep; ss++);
954 buffer = string_cat(buffer, &size, &ptr, s, ss-s);
956 if (*s == 0 || *(++s) != sep || sep_is_special) break;
958 while (ptr > 0 && isspace(buffer[ptr-1])) ptr--;
962 /* Update the current pointer and return the new string */
967 #endif /* COMPILE_UTILITY */
970 #ifndef COMPILE_UTILITY
971 /************************************************
972 * Add element to seperated list *
973 ************************************************/
974 /* This function is used to build a list, returning
975 an allocated null-terminated growable string. The
976 given element has any embedded seperator characters
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
985 Returns: pointer to the start of the list, changed if copied for expansion.
989 string_append_listele(uschar * list, uschar sep, const uschar * ele)
997 new = string_cat(new, &sz, &off, list, Ustrlen(list));
998 new = string_cat(new, &sz, &off, &sep, 1);
1001 while((sp = Ustrchr(ele, sep)))
1003 new = string_cat(new, &sz, &off, ele, sp-ele+1);
1004 new = string_cat(new, &sz, &off, &sep, 1);
1007 new = string_cat(new, &sz, &off, ele, Ustrlen(ele));
1013 static const uschar *
1014 Ustrnchr(const uschar * s, int c, unsigned * len)
1016 unsigned siz = *len;
1019 if (!*s) return NULL;
1032 string_append_listele_n(uschar * list, uschar sep, const uschar * ele,
1035 uschar * new = NULL;
1036 int sz = 0, off = 0;
1041 new = string_cat(new, &sz, &off, list, Ustrlen(list));
1042 new = string_cat(new, &sz, &off, &sep, 1);
1045 while((sp = Ustrnchr(ele, sep, &len)))
1047 new = string_cat(new, &sz, &off, ele, sp-ele+1);
1048 new = string_cat(new, &sz, &off, &sep, 1);
1052 new = string_cat(new, &sz, &off, ele, len);
1056 #endif /* COMPILE_UTILITY */
1060 #ifndef COMPILE_UTILITY
1061 /*************************************************
1062 * Add chars to string *
1063 *************************************************/
1065 /* This function is used when building up strings of unknown length. Room is
1066 always left for a terminating zero to be added to the string that is being
1067 built. This function does not require the string that is being added to be NUL
1068 terminated, because the number of characters to add is given explicitly. It is
1069 sometimes called to extract parts of other strings.
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
1082 If string is given as NULL, *size and *ptr should both be zero.
1084 Returns: 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.
1091 string_cat(uschar *string, int *size, int *ptr, const uschar *s, int count)
1095 if (p + count >= *size)
1097 int oldsize = *size;
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. */
1105 int inc = (oldsize < 4096)? 100 : 1024;
1106 while (*size <= p + count) *size += inc;
1110 if (string == NULL) string = store_get(*size);
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
1122 else if (!store_extend(string, oldsize, *size))
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);
1132 /* Because we always specify the exact number of characters to copy, we can
1133 use memcpy(), which is likely to be more efficient than strncopy() because the
1134 latter has to check for zero bytes. */
1136 memcpy(string + p, s, count);
1140 #endif /* COMPILE_UTILITY */
1144 #ifndef COMPILE_UTILITY
1145 /*************************************************
1146 * Append strings to another string *
1147 *************************************************/
1149 /* This function can be used to build a string from many other strings.
1150 It calls string_cat() to do the dirty work.
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
1163 Returns: pointer to the start of the string, changed if copied for expansion.
1164 The string is not zero-terminated - see string_cat() above.
1168 string_append(uschar *string, int *size, int *ptr, int count, ...)
1173 va_start(ap, count);
1174 for (i = 0; i < count; i++)
1176 uschar *t = va_arg(ap, uschar *);
1177 string = string_cat(string, size, ptr, t, Ustrlen(t));
1187 /*************************************************
1188 * Format a string with length checks *
1189 *************************************************/
1191 /* This function is used to format a string with checking of the length of the
1192 output for all conversions. It protects Exim from absent-mindedness when
1193 calling functions like debug_printf and string_sprintf, and elsewhere. There
1194 are two different entry points to what is actually the same function, depending
1195 on whether the variable length list of data arguments are given explicitly or
1198 The formats are the usual printf() ones, with some omissions (never used) and
1199 two additions for strings: %S forces lower case, and %#s or %#S prints nothing
1200 for a NULL string. Without the # "NULL" is printed (useful in debugging). There
1201 is also the addition of %D and %M, which insert the date in the form used for
1202 datestamped log files.
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
1210 Returns: TRUE if the result fitted in the buffer
1214 string_format(uschar *buffer, int buflen, const char *format, ...)
1218 va_start(ap, format);
1219 yield = string_vformat(buffer, buflen, format, ap);
1226 string_vformat(uschar *buffer, int buflen, const char *format, va_list ap)
1228 /* We assume numbered ascending order, C does not guarantee that */
1229 enum { L_NORMAL=1, L_SHORT=2, L_LONG=3, L_LONGLONG=4, L_LONGDOUBLE=5, L_SIZE=6 };
1232 int width, precision;
1233 const char *fp = format; /* Deliberately not unsigned */
1235 uschar *last = buffer + buflen - 1;
1237 string_datestamp_offset = -1; /* Datestamp not inserted */
1238 string_datestamp_length = 0; /* Datestamp not inserted */
1239 string_datestamp_type = 0; /* Datestamp not inserted */
1241 /* Scan the format and handle the insertions */
1245 int length = L_NORMAL;
1248 const char *null = "NULL"; /* ) These variables */
1249 const char *item_start, *s; /* ) are deliberately */
1250 char newformat[16]; /* ) not unsigned */
1252 /* Non-% characters just get copied verbatim */
1256 if (p >= last) { yield = FALSE; break; }
1257 *p++ = (uschar)*fp++;
1261 /* Deal with % characters. Pick off the width and precision, for checking
1262 strings, skipping over the flag and modifier characters. */
1265 width = precision = -1;
1267 if (strchr("-+ #0", *(++fp)) != NULL)
1269 if (*fp == '#') null = "";
1273 if (isdigit((uschar)*fp))
1275 width = *fp++ - '0';
1276 while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';
1278 else if (*fp == '*')
1280 width = va_arg(ap, int);
1288 precision = va_arg(ap, int);
1294 while (isdigit((uschar)*fp))
1295 precision = precision*10 + *fp++ - '0';
1299 /* Skip over 'h', 'L', 'l', 'll' and 'z', remembering the item length */
1302 { fp++; length = L_SHORT; }
1303 else if (*fp == 'L')
1304 { fp++; length = L_LONGDOUBLE; }
1305 else if (*fp == 'l')
1310 length = L_LONGLONG;
1318 else if (*fp == 'z')
1319 { fp++; length = L_SIZE; }
1321 /* Handle each specific format type. */
1326 nptr = va_arg(ap, int *);
1335 if (p >= last - ((length > L_LONG)? 24 : 12))
1336 { yield = FALSE; goto END_FORMAT; }
1337 strncpy(newformat, item_start, fp - item_start);
1338 newformat[fp - item_start] = 0;
1340 /* Short int is promoted to int when passing through ..., so we must use
1341 int for va_arg(). */
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;
1348 case L_LONGLONG: sprintf(CS p, newformat, va_arg(ap, LONGLONG_T)); break;
1349 case L_SIZE: sprintf(CS p, newformat, va_arg(ap, size_t)); break;
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 *));
1362 /* %f format is inherently insecure if the numbers that it may be
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. */
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;
1378 if (length == L_LONGDOUBLE)
1379 sprintf(CS p, newformat, va_arg(ap, long double));
1381 sprintf(CS p, newformat, va_arg(ap, double));
1388 if (p >= last) { yield = FALSE; goto END_FORMAT; }
1393 if (p >= last) { yield = FALSE; goto END_FORMAT; }
1394 *p++ = va_arg(ap, int);
1397 case 'D': /* Insert daily datestamp for log file names */
1398 s = CS tod_stamp(tod_log_datestamp_daily);
1399 string_datestamp_offset = p - buffer; /* Passed back via global */
1400 string_datestamp_length = Ustrlen(s); /* Passed back via global */
1401 string_datestamp_type = tod_log_datestamp_daily;
1402 slen = string_datestamp_length;
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;
1414 case 'S': /* Forces *lower* case */
1415 s = va_arg(ap, char *);
1417 if (s == NULL) s = null;
1420 INSERT_STRING: /* Come to from %D or %M above */
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
1428 if (precision < 0) precision = width;
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. */
1434 else if (precision >= 0)
1436 width = (precision < slen)? precision : slen;
1439 /* If neither are specified, set them both to the string length. */
1441 else width = precision = slen;
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). */
1452 if (p >= last - width)
1455 width = precision = last - p - 1;
1456 if (width < 0) width = 0;
1457 if (precision < 0) precision = 0;
1459 sprintf(CS p, "%*.*s", width, precision, s);
1461 while (*p) { *p = tolower(*p); p++; }
1464 if (!yield) goto END_FORMAT;
1467 /* Some things are never used in Exim; also catches junk. */
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);
1478 /* Ensure string is complete; return TRUE if got to the end of the format */
1488 #ifndef COMPILE_UTILITY
1489 /*************************************************
1490 * Generate an "open failed" message *
1491 *************************************************/
1493 /* This function creates a message after failure to open a file. It includes a
1494 string supplied as data, adds the strerror() text, and if the failure was
1495 "Permission denied", reads and includes the euid and egid.
1498 eno the value of errno after the failure
1499 format a text format string - deliberately not uschar *
1500 ... arguments for the format string
1502 Returns: a message, in dynamic store
1506 string_open_failed(int eno, const char *format, ...)
1509 uschar buffer[1024];
1511 Ustrcpy(buffer, "failed to open ");
1512 va_start(ap, format);
1514 /* Use the checked formatting routine to ensure that the buffer
1515 does not overflow. It should not, since this is called only for internally
1516 specified messages. If it does, the message just gets truncated, and there
1517 doesn't seem much we can do about that. */
1519 (void)string_vformat(buffer+15, sizeof(buffer) - 15, format, ap);
1521 return (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));
1526 #endif /* COMPILE_UTILITY */
1530 #ifndef COMPILE_UTILITY
1531 /*************************************************
1532 * Generate local prt for logging *
1533 *************************************************/
1535 /* This function is a subroutine for use in string_log_address() below.
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
1543 Returns: the new value of the buffer pointer
1547 string_get_localpart(address_item *addr, uschar *yield, int *sizeptr,
1553 if (testflag(addr, af_include_affixes) && s)
1555 #ifdef EXPERIMENTAL_INTERNATIONAL
1556 if (testflag(addr, af_utf8_downcvt))
1557 s = string_localpart_utf8_to_alabel(s, NULL);
1559 yield = string_cat(yield, sizeptr, ptrptr, s, Ustrlen(s));
1562 s = addr->local_part;
1563 #ifdef EXPERIMENTAL_INTERNATIONAL
1564 if (testflag(addr, af_utf8_downcvt))
1565 s = string_localpart_utf8_to_alabel(s, NULL);
1567 yield = string_cat(yield, sizeptr, ptrptr, s, Ustrlen(s));
1570 if (testflag(addr, af_include_affixes) && s)
1572 #ifdef EXPERIMENTAL_INTERNATIONAL
1573 if (testflag(addr, af_utf8_downcvt))
1574 s = string_localpart_utf8_to_alabel(s, NULL);
1576 yield = string_cat(yield, sizeptr, ptrptr, s, Ustrlen(s));
1583 /*************************************************
1584 * Generate log address list *
1585 *************************************************/
1587 /* This function generates a list consisting of an address and its parents, for
1588 use in logging lines. For saved onetime aliased addresses, the onetime parent
1589 field is used. If the address was delivered by a transport with rcpt_include_
1590 affixes set, the af_include_affixes bit will be set in the address. In that
1591 case, we include the affixes here too.
1594 addr bottom (ultimate) address
1595 all_parents if TRUE, include all parents
1596 success TRUE for successful delivery
1598 Returns: a string in dynamic store
1602 string_log_address(address_item *addr, BOOL all_parents, BOOL success)
1606 BOOL add_topaddr = TRUE;
1607 uschar *yield = store_get(size);
1608 address_item *topaddr;
1610 /* Find the ultimate parent */
1612 for (topaddr = addr; topaddr->parent != NULL; topaddr = topaddr->parent);
1614 /* We start with just the local part for pipe, file, and reply deliveries, and
1615 for successful local deliveries from routers that have the log_as_local flag
1616 set. File deliveries from filters can be specified as non-absolute paths in
1617 cases where the transport is goin to complete the path. If there is an error
1618 before this happens (expansion failure) the local part will not be updated, and
1619 so won't necessarily look like a path. Add extra text for this case. */
1621 if (testflag(addr, af_pfr) ||
1623 addr->router != NULL && addr->router->log_as_local &&
1624 addr->transport != NULL && addr->transport->info->local))
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);
1631 /* Other deliveries start with the full address. It we have split it into local
1632 part and domain, use those fields. Some early failures can happen before the
1633 splitting is done; in those cases use the original field. */
1637 if (addr->local_part != NULL)
1640 yield = string_get_localpart(addr, yield, &size, &ptr);
1641 yield = string_cat(yield, &size, &ptr, US"@", 1);
1643 #ifdef EXPERIMENTAL_INTERNATIONAL
1644 if (testflag(addr, af_utf8_downcvt))
1645 s = string_localpart_utf8_to_alabel(s, NULL);
1647 yield = string_cat(yield, &size, &ptr, s, Ustrlen(s) );
1651 yield = string_cat(yield, &size, &ptr, addr->address, Ustrlen(addr->address));
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. */
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;
1667 /* If all parents are requested, or this is a local pipe/file/reply, and
1668 there is at least one intermediate parent, show it in brackets, and continue
1669 with all of them if all are wanted. */
1671 if ((all_parents || testflag(addr, af_pfr)) &&
1672 addr->parent != NULL &&
1673 addr->parent != topaddr)
1676 address_item *addr2;
1677 for (addr2 = addr->parent; addr2 != topaddr; addr2 = addr2->parent)
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;
1684 yield = string_cat(yield, &size, &ptr, US")", 1);
1687 /* Add the top address if it is required */
1691 yield = string_cat(yield, &size, &ptr, US" <", 2);
1693 if (addr->onetime_parent == NULL)
1694 yield = string_cat(yield, &size, &ptr, topaddr->address,
1695 Ustrlen(topaddr->address));
1697 yield = string_cat(yield, &size, &ptr, addr->onetime_parent,
1698 Ustrlen(addr->onetime_parent));
1700 yield = string_cat(yield, &size, &ptr, US">", 1);
1703 yield[ptr] = 0; /* string_cat() leaves space */
1706 #endif /* COMPILE_UTILITY */
1712 /*************************************************
1713 **************************************************
1714 * Stand-alone test program *
1715 **************************************************
1716 *************************************************/
1723 printf("Testing is_ip_address\n");
1725 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
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);
1733 printf("Testing string_nextinlist\n");
1735 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1737 uschar *list = buffer;
1745 sep1 = sep2 = list[1];
1752 uschar *item1 = string_nextinlist(&lp1, &sep1, item, sizeof(item));
1753 uschar *item2 = string_nextinlist(&lp2, &sep2, NULL, 0);
1755 if (item1 == NULL && item2 == NULL) break;
1756 if (item == NULL || item2 == NULL || Ustrcmp(item1, item2) != 0)
1758 printf("***ERROR\nitem1=\"%s\"\nitem2=\"%s\"\n",
1759 (item1 == NULL)? "NULL" : CS item1,
1760 (item2 == NULL)? "NULL" : CS item2);
1763 else printf(" \"%s\"\n", CS item1);
1767 /* This is a horrible lash-up, but it serves its purpose. */
1769 printf("Testing string_format\n");
1771 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1774 long long llargs[3];
1784 buffer[Ustrlen(buffer) - 1] = 0;
1786 s = Ustrchr(buffer, ',');
1787 if (s == NULL) s = buffer + Ustrlen(buffer);
1789 Ustrncpy(format, buffer, s - buffer);
1790 format[s-buffer] = 0;
1797 s = Ustrchr(ss, ',');
1798 if (s == NULL) s = ss + Ustrlen(ss);
1802 Ustrncpy(outbuf, ss, s-ss);
1803 if (Ustrchr(outbuf, '.') != NULL)
1806 dargs[n++] = Ustrtod(outbuf, NULL);
1808 else if (Ustrstr(outbuf, "ll") != NULL)
1811 llargs[n++] = strtoull(CS outbuf, NULL, 10);
1815 args[n++] = (void *)Uatoi(outbuf);
1819 else if (Ustrcmp(ss, "*") == 0)
1821 args[n++] = (void *)(&count);
1827 uschar *sss = malloc(s - ss + 1);
1828 Ustrncpy(sss, ss, s-ss);
1835 if (!dflag && !llflag)
1836 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1837 args[0], args[1], args[2])? "True" : "False");
1840 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1841 dargs[0], dargs[1], dargs[2])? "True" : "False");
1843 else printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1844 llargs[0], llargs[1], llargs[2])? "True" : "False");
1846 printf("%s\n", CS outbuf);
1847 if (countset) printf("count=%d\n", count);
1854 /* End of string.c */