1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2020 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
10 /* Miscellaneous string-handling functions. Some are not required for
11 utilities and tests, and are cut out by the COMPILE_UTILITY macro. */
18 #ifndef COMPILE_UTILITY
19 /*************************************************
20 * Test for IP address *
21 *************************************************/
23 /* This used just to be a regular expression, but with IPv6 things are a bit
24 more complicated. If the address contains a colon, it is assumed to be a v6
25 address (assuming HAVE_IPV6 is set). If a mask is permitted and one is present,
26 and maskptr is not NULL, its offset is placed there.
30 maskptr NULL if no mask is permitted to follow
31 otherwise, points to an int where the offset of '/' is placed
32 if there is no / followed by trailing digits, *maskptr is set 0
34 Returns: 0 if the string is not a textual representation of an IP address
35 4 if it is an IPv4 address
36 6 if it is an IPv6 address
40 string_is_ip_address(const uschar *s, int *maskptr)
44 /* If an optional mask is permitted, check for it. If found, pass back the
49 const 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;
67 /* An IPv6 address must start with hex digit or double colon. A single
70 if (*s == ':' && *(++s) != ':') return 0;
72 /* Now read up to 8 components consisting of up to 4 hex digits each. There
73 may be one and only one appearance of double colon, which implies any number
74 of binary zero bits. The number of preceding components is held in count. */
76 for (int count = 0; count < 8; count++)
78 /* If the end of the string is reached before reading 8 components, the
79 address is valid provided a double colon has been read. This also applies
80 if we hit the / that introduces a mask or the % that introduces the
81 interface specifier (scope id) of a link-local address. */
83 if (*s == 0 || *s == '%' || *s == '/') return had_double_colon ? yield : 0;
85 /* If a component starts with an additional colon, we have hit a double
86 colon. This is permitted to appear once only, and counts as at least
87 one component. The final component may be of this form. */
91 if (had_double_colon) return 0;
92 had_double_colon = TRUE;
97 /* If the remainder of the string contains a dot but no colons, we
98 can expect a trailing IPv4 address. This is valid if either there has
99 been no double-colon and this is the 7th component (with the IPv4 address
100 being the 7th & 8th components), OR if there has been a double-colon
101 and fewer than 6 components. */
103 if (Ustrchr(s, ':') == NULL && Ustrchr(s, '.') != NULL)
105 if ((!had_double_colon && count != 6) ||
106 (had_double_colon && count > 6)) return 0;
112 /* Check for at least one and not more than 4 hex digits for this
115 if (!isxdigit(*s++)) return 0;
116 if (isxdigit(*s) && isxdigit(*(++s)) && isxdigit(*(++s))) s++;
118 /* If the component is terminated by colon and there is more to
119 follow, skip over the colon. If there is no more to follow the address is
122 if (*s == ':' && *(++s) == 0) return 0;
125 /* If about to handle a trailing IPv4 address, drop through. Otherwise
126 all is well if we are at the end of the string or at the mask or at a percent
127 sign, which introduces the interface specifier (scope id) of a link local
131 return (*s == 0 || *s == '%' ||
132 (*s == '/' && maskptr != NULL && *maskptr != 0))? yield : 0;
135 /* Test for IPv4 address, which may be the tail-end of an IPv6 address. */
137 for (int i = 0; i < 4; i++)
142 if (i != 0 && *s++ != '.') return 0;
143 n = strtol(CCS s, CSS &end, 10);
144 if (n > 255 || n < 0 || end <= s || end > s+3) return 0;
148 return !*s || (*s == '/' && maskptr && *maskptr != 0) ? yield : 0;
150 #endif /* COMPILE_UTILITY */
153 /*************************************************
154 * Format message size *
155 *************************************************/
157 /* Convert a message size in bytes to printing form, rounding
158 according to the magnitude of the number. A value of zero causes
159 a string of spaces to be returned.
162 size the message size in bytes
163 buffer where to put the answer
165 Returns: pointer to the buffer
166 a string of exactly 5 characters is normally returned
170 string_format_size(int size, uschar *buffer)
172 if (size == 0) Ustrcpy(buffer, US" ");
173 else if (size < 1024) sprintf(CS buffer, "%5d", size);
174 else if (size < 10*1024)
175 sprintf(CS buffer, "%4.1fK", (double)size / 1024.0);
176 else if (size < 1024*1024)
177 sprintf(CS buffer, "%4dK", (size + 512)/1024);
178 else if (size < 10*1024*1024)
179 sprintf(CS buffer, "%4.1fM", (double)size / (1024.0 * 1024.0));
181 sprintf(CS buffer, "%4dM", (size + 512 * 1024)/(1024*1024));
187 #ifndef COMPILE_UTILITY
188 /*************************************************
189 * Convert a number to base 62 format *
190 *************************************************/
192 /* Convert a long integer into an ASCII base 62 string. For Cygwin the value of
193 BASE_62 is actually 36. Always return exactly 6 characters plus zero, in a
196 Argument: a long integer
197 Returns: pointer to base 62 string
201 string_base62(unsigned long int value)
203 static uschar yield[7];
204 uschar *p = yield + sizeof(yield) - 1;
208 *(--p) = base62_chars[value % BASE_62];
213 #endif /* COMPILE_UTILITY */
217 /*************************************************
218 * Interpret escape sequence *
219 *************************************************/
221 /* This function is called from several places where escape sequences are to be
222 interpreted in strings.
225 pp points a pointer to the initiating "\" in the string;
226 the pointer gets updated to point to the final character
227 If the backslash is the last character in the string, it
229 Returns: the value of the character escape
233 string_interpret_escape(const uschar **pp)
235 #ifdef COMPILE_UTILITY
236 const uschar *hex_digits= CUS"0123456789abcdef";
239 const uschar *p = *pp;
241 if (ch == '\0') return **pp;
242 if (isdigit(ch) && ch != '8' && ch != '9')
245 if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
247 ch = ch * 8 + *(++p) - '0';
248 if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
249 ch = ch * 8 + *(++p) - '0';
254 case 'b': ch = '\b'; break;
255 case 'f': ch = '\f'; break;
256 case 'n': ch = '\n'; break;
257 case 'r': ch = '\r'; break;
258 case 't': ch = '\t'; break;
259 case 'v': ch = '\v'; break;
265 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
266 if (isxdigit(p[1])) ch = ch * 16 +
267 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
277 #ifndef COMPILE_UTILITY
278 /*************************************************
279 * Ensure string is printable *
280 *************************************************/
282 /* This function is called for critical strings. It checks for any
283 non-printing characters, and if any are found, it makes a new copy
284 of the string with suitable escape sequences. It is most often called by the
285 macro string_printing(), which sets flags to 0.
289 flags Bit 0: convert tabs. Bit 1: convert spaces.
291 Returns: string with non-printers encoded as printing sequences
295 string_printing2(const uschar *s, int flags)
297 int nonprintcount = 0;
306 || flags & SP_TAB && c == '\t'
307 || flags & SP_SPACE && c == ' '
312 if (nonprintcount == 0) return s;
314 /* Get a new block of store guaranteed big enough to hold the
317 tt = ss = store_get(length + nonprintcount * 3 + 1, s);
319 /* Copy everything, escaping non printers. */
325 && (!(flags & SP_TAB) || c != '\t')
326 && (!(flags & SP_SPACE) || c != ' ')
334 case '\n': *tt++ = 'n'; break;
335 case '\r': *tt++ = 'r'; break;
336 case '\b': *tt++ = 'b'; break;
337 case '\v': *tt++ = 'v'; break;
338 case '\f': *tt++ = 'f'; break;
339 case '\t': *tt++ = 't'; break;
340 default: sprintf(CS tt, "%03o", *t); tt += 3; break;
348 #endif /* COMPILE_UTILITY */
350 /*************************************************
351 * Undo printing escapes in string *
352 *************************************************/
354 /* This function is the reverse of string_printing2. It searches for
355 backslash characters and if any are found, it makes a new copy of the
356 string with escape sequences parsed. Otherwise it returns the original
362 Returns: string with printing escapes parsed back
366 string_unprinting(uschar *s)
368 uschar *p, *q, *r, *ss;
371 p = Ustrchr(s, '\\');
374 len = Ustrlen(s) + 1;
375 ss = store_get(len, s);
389 *q++ = string_interpret_escape((const uschar **)&p);
394 r = Ustrchr(p, '\\');
420 #if (defined(HAVE_LOCAL_SCAN) || defined(EXPAND_DLFUNC)) \
421 && !defined(MACRO_PREDEF) && !defined(COMPILE_UTILITY)
422 /*************************************************
423 * Copy and save string *
424 *************************************************/
427 Argument: string to copy
428 Returns: copy of string in new store with the same taint status
432 string_copy_function(const uschar * s)
434 return string_copy_taint(s, s);
437 /* As above, but explicitly specifying the result taint status
441 string_copy_taint_function(const uschar * s, const void * proto_mem)
443 return string_copy_taint(s, proto_mem);
448 /*************************************************
449 * Copy and save string, given length *
450 *************************************************/
452 /* It is assumed the data contains no zeros. A zero is added
457 n number of characters
459 Returns: copy of string in new store
463 string_copyn_function(const uschar * s, int n)
465 return string_copyn(s, n);
470 /*************************************************
471 * Copy and save string in malloc'd store *
472 *************************************************/
474 /* This function assumes that memcpy() is faster than strcpy().
476 Argument: string to copy
477 Returns: copy of string in new store
481 string_copy_malloc(const uschar * s)
483 int len = Ustrlen(s) + 1;
484 uschar * ss = store_malloc(len);
491 /*************************************************
492 * Copy string if long, inserting newlines *
493 *************************************************/
495 /* If the given string is longer than 75 characters, it is copied, and within
496 the copy, certain space characters are converted into newlines.
498 Argument: pointer to the string
499 Returns: pointer to the possibly altered string
503 string_split_message(uschar * msg)
507 if (!msg || Ustrlen(msg) <= 75) return msg;
508 s = ss = msg = string_copy(msg);
513 while (i < 75 && *ss && *ss != '\n') ss++, i++;
525 if (t[-1] == ':') { tt = t; break; }
530 if (!tt) /* Can't split behind - try ahead */
535 if (*t == ' ' || *t == '\n')
541 if (!tt) break; /* Can't find anywhere to split */
552 /*************************************************
553 * Copy returned DNS domain name, de-escaping *
554 *************************************************/
556 /* If a domain name contains top-bit characters, some resolvers return
557 the fully qualified name with those characters turned into escapes. The
558 convention is a backslash followed by _decimal_ digits. We convert these
559 back into the original binary values. This will be relevant when
560 allow_utf8_domains is set true and UTF-8 characters are used in domain
561 names. Backslash can also be used to escape other characters, though we
562 shouldn't come across them in domain names.
564 Argument: the domain name string
565 Returns: copy of string in new store, de-escaped
569 string_copy_dnsdomain(uschar * s)
572 uschar * ss = yield = store_get(Ustrlen(s) + 1, GET_TAINTED); /* always treat as tainted */
578 else if (isdigit(s[1]))
580 *ss++ = (s[1] - '0')*100 + (s[2] - '0')*10 + s[3] - '0';
592 #ifndef COMPILE_UTILITY
593 /*************************************************
594 * Copy space-terminated or quoted string *
595 *************************************************/
597 /* This function copies from a string until its end, or until whitespace is
598 encountered, unless the string begins with a double quote, in which case the
599 terminating quote is sought, and escaping within the string is done. The length
600 of a de-quoted string can be no longer than the original, since escaping always
601 turns n characters into 1 character.
603 Argument: pointer to the pointer to the first character, which gets updated
604 Returns: the new string
608 string_dequote(const uschar ** sptr)
610 const uschar * s = * sptr;
613 /* First find the end of the string */
616 while (*s && !isspace(*s)) s++;
620 while (*s && *s != '\"')
622 if (*s == '\\') (void)string_interpret_escape(&s);
628 /* Get enough store to copy into */
630 t = yield = store_get(s - *sptr + 1, *sptr);
636 while (*s && !isspace(*s)) *t++ = *s++;
640 while (*s && *s != '\"')
642 *t++ = *s == '\\' ? string_interpret_escape(&s) : *s;
648 /* Update the pointer and return the terminated copy */
654 #endif /* COMPILE_UTILITY */
658 /*************************************************
659 * Format a string and save it *
660 *************************************************/
662 /* The formatting is done by string_vformat, which checks the length of
663 everything. Taint is taken from the worst of the arguments.
666 format a printf() format - deliberately char * rather than uschar *
667 because it will most usually be a literal string
668 func caller, for debug
669 line caller, for debug
670 ... arguments for format
672 Returns: pointer to fresh piece of store containing sprintf'ed string
676 string_sprintf_trc(const char * format, const uschar * func, unsigned line, ...)
678 #ifdef COMPILE_UTILITY
679 uschar buffer[STRING_SPRINTF_BUFFER_SIZE];
680 gstring gs = { .size = STRING_SPRINTF_BUFFER_SIZE, .ptr = 0, .s = buffer };
685 unsigned flags = SVFMT_REBUFFER|SVFMT_EXTEND;
690 g = string_vformat_trc(g, func, line, STRING_SPRINTF_BUFFER_SIZE,
695 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
696 "string_sprintf expansion was longer than %d; format string was (%s)\n"
697 " called from %s %d\n",
698 STRING_SPRINTF_BUFFER_SIZE, format, func, line);
700 #ifdef COMPILE_UTILITY
701 return string_copyn(g->s, g->ptr);
703 gstring_release_unused(g);
704 return string_from_gstring(g);
710 /*************************************************
711 * Case-independent strncmp() function *
712 *************************************************/
718 n number of characters to compare
720 Returns: < 0, = 0, or > 0, according to the comparison
724 strncmpic(const uschar * s, const uschar * t, int n)
728 int c = tolower(*s++) - tolower(*t++);
735 /*************************************************
736 * Case-independent strcmp() function *
737 *************************************************/
744 Returns: < 0, = 0, or > 0, according to the comparison
748 strcmpic(const uschar * s, const uschar * t)
752 int c = tolower(*s++) - tolower(*t++);
753 if (c != 0) return c;
759 /*************************************************
760 * Case-independent strstr() function *
761 *************************************************/
763 /* The third argument specifies whether whitespace is required
764 to follow the matched string.
768 t substring to search for
769 space_follows if TRUE, match only if whitespace follows
771 Returns: pointer to substring in string, or NULL if not found
775 strstric_c(const uschar * s, const uschar * t, BOOL space_follows)
777 const uschar * p = t;
778 const uschar * yield = NULL;
779 int cl = tolower(*p);
780 int cu = toupper(*p);
784 if (*s == cl || *s == cu)
786 if (!yield) yield = s;
789 if (!space_follows || s[1] == ' ' || s[1] == '\n' ) return yield;
810 strstric(uschar * s, uschar * t, BOOL space_follows)
812 return US strstric_c(s, t, space_follows);
816 #ifdef COMPILE_UTILITY
817 /* Dummy version for this function; it should never be called */
819 gstring_grow(gstring * g, int count)
827 #ifndef COMPILE_UTILITY
828 /*************************************************
829 * Get next string from separated list *
830 *************************************************/
832 /* Leading and trailing space is removed from each item. The separator in the
833 list is controlled by the int pointed to by the separator argument as follows:
835 If the value is > 0 it is used as the separator. This is typically used for
836 sublists such as slash-separated options. The value is always a printing
839 (If the value is actually > UCHAR_MAX there is only one item in the list.
840 This is used for some cases when called via functions that sometimes
841 plough through lists, and sometimes are given single items.)
843 If the value is <= 0, the string is inspected for a leading <x, where x is an
844 ispunct() or an iscntrl() character. If found, x is used as the separator. If
847 (a) if separator == 0, ':' is used
848 (b) if separator <0, -separator is used
850 In all cases the value of the separator that is used is written back to the
851 int so that it is used on subsequent calls as we progress through the list.
853 A literal ispunct() separator can be represented in an item by doubling, but
854 there is no way to include an iscntrl() separator as part of the data.
857 listptr points to a pointer to the current start of the list; the
858 pointer gets updated to point after the end of the next item
859 separator a pointer to the separator character in an int (see above)
860 buffer where to put a copy of the next string in the list; or
861 NULL if the next string is returned in new memory
862 Note that if the list is tainted then a provided buffer must be
863 also (else we trap, with a message referencing the callsite).
864 If we do the allocation, taint is handled there.
865 buflen when buffer is not NULL, the size of buffer; otherwise ignored
867 func caller, for debug
868 line caller, for debug
870 Returns: pointer to buffer, containing the next substring,
871 or NULL if no more substrings
875 string_nextinlist_trc(const uschar ** listptr, int * separator, uschar * buffer,
876 int buflen, const uschar * func, int line)
878 int sep = *separator;
879 const uschar * s = *listptr;
884 /* This allows for a fixed specified separator to be an iscntrl() character,
885 but at the time of implementation, this is never the case. However, it's best
886 to be conservative. */
888 while (isspace(*s) && *s != sep) s++;
890 /* A change of separator is permitted, so look for a leading '<' followed by an
891 allowed character. */
895 if (*s == '<' && (ispunct(s[1]) || iscntrl(s[1])))
899 while (isspace(*s) && *s != sep) s++;
902 sep = sep ? -sep : ':';
906 /* An empty string has no list elements */
908 if (!*s) return NULL;
910 /* Note whether whether or not the separator is an iscntrl() character. */
912 sep_is_special = iscntrl(sep);
914 /* Handle the case when a buffer is provided. */
915 /*XXX need to also deal with qouted-requirements mismatch */
920 if (is_tainted(s) && !is_tainted(buffer))
921 die_tainted(US"string_nextinlist", func, line);
924 if (*s == sep && (*(++s) != sep || sep_is_special)) break;
925 if (p < buflen - 1) buffer[p++] = *s;
927 while (p > 0 && isspace(buffer[p-1])) p--;
931 /* Handle the case when a buffer is not provided. */
937 /* We know that *s != 0 at this point. However, it might be pointing to a
938 separator, which could indicate an empty string, or (if an ispunct()
939 character) could be doubled to indicate a separator character as data at the
940 start of a string. Avoid getting working memory for an empty item. */
943 if (*++s != sep || sep_is_special)
946 return string_copy(US"");
949 /* Not an empty string; the first character is guaranteed to be a data
955 for (ss = s + 1; *ss && *ss != sep; ) ss++;
956 g = string_catn(g, s, ss-s);
958 if (!*s || *++s != sep || sep_is_special) break;
961 /* Trim trailing spaces from the returned string */
963 /* while (g->ptr > 0 && isspace(g->s[g->ptr-1])) g->ptr--; */
964 while ( g->ptr > 0 && isspace(g->s[g->ptr-1])
965 && (g->ptr == 1 || g->s[g->ptr-2] != '\\') )
967 buffer = string_from_gstring(g);
968 gstring_release_unused_trc(g, CCS func, line);
971 /* Update the current pointer and return the new string */
978 static const uschar *
979 Ustrnchr(const uschar * s, int c, unsigned * len)
984 if (!*s) return NULL;
997 /************************************************
998 * Add element to separated list *
999 ************************************************/
1000 /* This function is used to build a list, returning an allocated null-terminated
1001 growable string. The given element has any embedded separator characters
1004 Despite having the same growable-string interface as string_cat() the list is
1005 always returned null-terminated.
1008 list expanding-string for the list that is being built, or NULL
1009 if this is a new list that has no contents yet
1010 sep list separator character
1011 ele new element to be appended to the list
1013 Returns: pointer to the start of the list, changed if copied for expansion.
1017 string_append_listele(gstring * list, uschar sep, const uschar * ele)
1021 if (list && list->ptr)
1022 list = string_catn(list, &sep, 1);
1024 while((sp = Ustrchr(ele, sep)))
1026 list = string_catn(list, ele, sp-ele+1);
1027 list = string_catn(list, &sep, 1);
1030 list = string_cat(list, ele);
1031 (void) string_from_gstring(list);
1037 string_append_listele_n(gstring * list, uschar sep, const uschar * ele,
1042 if (list && list->ptr)
1043 list = string_catn(list, &sep, 1);
1045 while((sp = Ustrnchr(ele, sep, &len)))
1047 list = string_catn(list, ele, sp-ele+1);
1048 list = string_catn(list, &sep, 1);
1052 list = string_catn(list, ele, len);
1053 (void) string_from_gstring(list);
1059 /* A slightly-bogus listmaker utility; the separator is a string so
1060 can be multiple chars - there is no checking for the element content
1061 containing any of the separator. */
1064 string_append2_listele_n(gstring * list, const uschar * sepstr,
1065 const uschar * ele, unsigned len)
1067 if (list && list->ptr)
1068 list = string_cat(list, sepstr);
1070 list = string_catn(list, ele, len);
1071 (void) string_from_gstring(list);
1077 /************************************************/
1078 /* Add more space to a growable-string. The caller should check
1079 first if growth is required. The gstring struct is modified on
1080 return; specifically, the string-base-pointer may have been changed.
1083 g the growable-string
1084 count amount needed for g->ptr to increase by
1088 gstring_grow(gstring * g, int count)
1091 int oldsize = g->size;
1093 /* Mostly, string_cat() is used to build small strings of a few hundred
1094 characters at most. There are times, however, when the strings are very much
1095 longer (for example, a lookup that returns a vast number of alias addresses).
1096 To try to keep things reasonable, we use increments whose size depends on the
1097 existing length of the string. */
1099 unsigned inc = oldsize < 4096 ? 127 : 1023;
1101 if (g->ptr < 0 || g->ptr > g->size || g->size >= INT_MAX/2)
1102 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1103 "internal error in gstring_grow (ptr %d size %d)", g->ptr, g->size);
1105 if (count <= 0) return;
1107 if (count >= INT_MAX/2 - g->ptr)
1108 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1109 "internal error in gstring_grow (ptr %d count %d)", g->ptr, count);
1111 g->size = (p + count + inc + 1) & ~inc; /* one for a NUL */
1113 /* Try to extend an existing allocation. If the result of calling
1114 store_extend() is false, either there isn't room in the current memory block,
1115 or this string is not the top item on the dynamic store stack. We then have
1116 to get a new chunk of store and copy the old string. When building large
1117 strings, it is helpful to call store_release() on the old string, to release
1118 memory blocks that have become empty. (The block will be freed if the string
1119 is at its start.) However, we can do this only if we know that the old string
1120 was the last item on the dynamic memory stack. This is the case if it matches
1123 if (!store_extend(g->s, oldsize, g->size))
1124 g->s = store_newblock(g->s, g->size, p);
1129 /*************************************************
1130 * Add chars to string *
1131 *************************************************/
1132 /* This function is used when building up strings of unknown length. Room is
1133 always left for a terminating zero to be added to the string that is being
1134 built. This function does not require the string that is being added to be NUL
1135 terminated, because the number of characters to add is given explicitly. It is
1136 sometimes called to extract parts of other strings.
1139 g growable-string that is being built, or NULL if not assigned yet
1140 s points to characters to add
1141 count count of characters to add; must not exceed the length of s, if s
1144 Returns: growable string, changed if copied for expansion.
1145 Note that a NUL is not added, though space is left for one. This is
1146 because string_cat() is often called multiple times to build up a
1147 string - there's no point adding the NUL till the end.
1148 NULL is a possible return.
1151 /* coverity[+alloc] */
1154 string_catn(gstring * g, const uschar * s, int count)
1159 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1160 "internal error in string_catn (count %d)", count);
1161 if (count == 0) return g;
1163 /*debug_printf("string_catn '%.*s'\n", count, s);*/
1166 unsigned inc = count < 4096 ? 127 : 1023;
1167 unsigned size = ((count + inc) & ~inc) + 1; /* round up requested count */
1168 g = string_get_tainted(size, s);
1170 else if (!g->s) /* should not happen */
1172 g->s = string_copyn(s, count);
1174 g->size = count; /*XXX suboptimal*/
1177 else if (is_incompatible(g->s, s))
1179 /* debug_printf("rebuf A\n"); */
1180 gstring_rebuffer(g, s);
1183 if (g->ptr < 0 || g->ptr > g->size)
1184 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1185 "internal error in string_catn (ptr %d size %d)", g->ptr, g->size);
1188 if (count >= g->size - p)
1189 gstring_grow(g, count);
1191 /* Because we always specify the exact number of characters to copy, we can
1192 use memcpy(), which is likely to be more efficient than strncopy() because the
1193 latter has to check for zero bytes. */
1195 memcpy(g->s + p, s, count);
1202 string_cat(gstring * g, const uschar * s)
1204 return string_catn(g, s, Ustrlen(s));
1209 /*************************************************
1210 * Append strings to another string *
1211 *************************************************/
1213 /* This function can be used to build a string from many other strings.
1214 It calls string_cat() to do the dirty work.
1217 g growable-string that is being built, or NULL if not yet assigned
1218 count the number of strings to append
1219 ... "count" uschar* arguments, which must be valid zero-terminated
1222 Returns: growable string, changed if copied for expansion.
1223 The string is not zero-terminated - see string_cat() above.
1226 __inline__ gstring *
1227 string_append(gstring * g, int count, ...)
1231 va_start(ap, count);
1234 uschar * t = va_arg(ap, uschar *);
1235 g = string_cat(g, t);
1245 /*************************************************
1246 * Format a string with length checks *
1247 *************************************************/
1249 /* This function is used to format a string with checking of the length of the
1250 output for all conversions. It protects Exim from absent-mindedness when
1251 calling functions like debug_printf and string_sprintf, and elsewhere. There
1252 are two different entry points to what is actually the same function, depending
1253 on whether the variable length list of data arguments are given explicitly or
1256 The formats are the usual printf() ones, with some omissions (never used) and
1257 three additions for strings: %S forces lower case, %T forces upper case, and
1258 %#s or %#S prints nothing for a NULL string. Without the # "NULL" is printed
1259 (useful in debugging). There is also the addition of %D and %M, which insert
1260 the date in the form used for datestamped log files.
1263 buffer a buffer in which to put the formatted string
1264 buflen the length of the buffer
1265 format the format string - deliberately char * and not uschar *
1266 ... or ap variable list of supplementary arguments
1268 Returns: TRUE if the result fitted in the buffer
1272 string_format_trc(uschar * buffer, int buflen,
1273 const uschar * func, unsigned line, const char * format, ...)
1275 gstring g = { .size = buflen, .ptr = 0, .s = buffer }, * gp;
1277 va_start(ap, format);
1278 gp = string_vformat_trc(&g, func, line, STRING_SPRINTF_BUFFER_SIZE,
1288 /* Build or append to a growing-string, sprintf-style.
1292 func called-from function name, for debug
1293 line called-from file line number, for debug
1294 limit maximum string size
1296 format printf-like format string
1297 ap variable-args pointer
1300 SVFMT_EXTEND buffer can be created or exteded as needed
1301 SVFMT_REBUFFER buffer can be recopied to tainted mem as needed
1302 SVFMT_TAINT_NOCHK do not check inputs for taint
1304 If the "extend" flag is true, the string passed in can be NULL,
1305 empty, or non-empty. Growing is subject to an overall limit given
1306 by the limit argument.
1308 If the "extend" flag is false, the string passed in may not be NULL,
1309 will not be grown, and is usable in the original place after return.
1310 The return value can be NULL to signify overflow.
1312 Returns the possibly-new (if copy for growth or taint-handling was needed)
1313 string, not nul-terminated.
1317 string_vformat_trc(gstring * g, const uschar * func, unsigned line,
1318 unsigned size_limit, unsigned flags, const char * format, va_list ap)
1320 enum ltypes { L_NORMAL=1, L_SHORT=2, L_LONG=3, L_LONGLONG=4, L_LONGDOUBLE=5, L_SIZE=6 };
1322 int width, precision, off, lim, need;
1323 const char * fp = format; /* Deliberately not unsigned */
1325 string_datestamp_offset = -1; /* Datestamp not inserted */
1326 string_datestamp_length = 0; /* Datestamp not inserted */
1327 string_datestamp_type = 0; /* Datestamp not inserted */
1329 #ifdef COMPILE_UTILITY
1330 assert(!(flags & SVFMT_EXTEND));
1334 /* Ensure we have a string, to save on checking later */
1335 if (!g) g = string_get(16);
1337 if (!(flags & SVFMT_TAINT_NOCHK) && is_incompatible(g->s, format))
1339 #ifndef MACRO_PREDEF
1340 if (!(flags & SVFMT_REBUFFER))
1341 die_tainted(US"string_vformat", func, line);
1343 /* debug_printf("rebuf B\n"); */
1344 gstring_rebuffer(g, format);
1346 #endif /*!COMPILE_UTILITY*/
1348 lim = g->size - 1; /* leave one for a nul */
1349 off = g->ptr; /* remember initial offset in gstring */
1351 /* Scan the format and handle the insertions */
1355 int length = L_NORMAL;
1358 const char *null = "NULL"; /* ) These variables */
1359 const char *item_start, *s; /* ) are deliberately */
1360 char newformat[16]; /* ) not unsigned */
1361 char * gp = CS g->s + g->ptr; /* ) */
1363 /* Non-% characters just get copied verbatim */
1367 /* Avoid string_copyn() due to COMPILE_UTILITY */
1368 if ((need = g->ptr + 1) > lim)
1370 if (!(flags & SVFMT_EXTEND) || need > size_limit) return NULL;
1374 g->s[g->ptr++] = (uschar) *fp++;
1378 /* Deal with % characters. Pick off the width and precision, for checking
1379 strings, skipping over the flag and modifier characters. */
1382 width = precision = -1;
1384 if (strchr("-+ #0", *(++fp)) != NULL)
1386 if (*fp == '#') null = "";
1390 if (isdigit((uschar)*fp))
1392 width = *fp++ - '0';
1393 while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';
1395 else if (*fp == '*')
1397 width = va_arg(ap, int);
1404 precision = va_arg(ap, int);
1408 for (precision = 0; isdigit((uschar)*fp); fp++)
1409 precision = precision*10 + *fp - '0';
1411 /* Skip over 'h', 'L', 'l', 'll' and 'z', remembering the item length */
1414 { fp++; length = L_SHORT; }
1415 else if (*fp == 'L')
1416 { fp++; length = L_LONGDOUBLE; }
1417 else if (*fp == 'l')
1419 { fp += 2; length = L_LONGLONG; }
1421 { fp++; length = L_LONG; }
1422 else if (*fp == 'z')
1423 { fp++; length = L_SIZE; }
1425 /* Handle each specific format type. */
1430 nptr = va_arg(ap, int *);
1431 *nptr = g->ptr - off;
1439 width = length > L_LONG ? 24 : 12;
1440 if ((need = g->ptr + width) > lim)
1442 if (!(flags & SVFMT_EXTEND) || need >= size_limit) return NULL;
1443 gstring_grow(g, width);
1445 gp = CS g->s + g->ptr;
1447 strncpy(newformat, item_start, fp - item_start);
1448 newformat[fp - item_start] = 0;
1450 /* Short int is promoted to int when passing through ..., so we must use
1451 int for va_arg(). */
1457 g->ptr += sprintf(gp, newformat, va_arg(ap, int)); break;
1459 g->ptr += sprintf(gp, newformat, va_arg(ap, long int)); break;
1461 g->ptr += sprintf(gp, newformat, va_arg(ap, LONGLONG_T)); break;
1463 g->ptr += sprintf(gp, newformat, va_arg(ap, size_t)); break;
1470 if ((need = g->ptr + 24) > lim)
1472 if (!(flags & SVFMT_EXTEND || need >= size_limit)) return NULL;
1473 gstring_grow(g, 24);
1475 gp = CS g->s + g->ptr;
1477 /* sprintf() saying "(nil)" for a null pointer seems unreliable.
1478 Handle it explicitly. */
1479 if ((ptr = va_arg(ap, void *)))
1481 strncpy(newformat, item_start, fp - item_start);
1482 newformat[fp - item_start] = 0;
1483 g->ptr += sprintf(gp, newformat, ptr);
1486 g->ptr += sprintf(gp, "(nil)");
1490 /* %f format is inherently insecure if the numbers that it may be
1491 handed are unknown (e.g. 1e300). However, in Exim, %f is used for
1492 printing load averages, and these are actually stored as integers
1493 (load average * 1000) so the size of the numbers is constrained.
1494 It is also used for formatting sending rates, where the simplicity
1495 of the format prevents overflow. */
1502 if (precision < 0) precision = 6;
1503 if ((need = g->ptr + precision + 8) > lim)
1505 if (!(flags & SVFMT_EXTEND || need >= size_limit)) return NULL;
1506 gstring_grow(g, precision+8);
1508 gp = CS g->s + g->ptr;
1510 strncpy(newformat, item_start, fp - item_start);
1511 newformat[fp-item_start] = 0;
1512 if (length == L_LONGDOUBLE)
1513 g->ptr += sprintf(gp, newformat, va_arg(ap, long double));
1515 g->ptr += sprintf(gp, newformat, va_arg(ap, double));
1521 if ((need = g->ptr + 1) > lim)
1523 if (!(flags & SVFMT_EXTEND || need >= size_limit)) return NULL;
1527 g->s[g->ptr++] = (uschar) '%';
1531 if ((need = g->ptr + 1) > lim)
1533 if (!(flags & SVFMT_EXTEND || need >= size_limit)) return NULL;
1537 g->s[g->ptr++] = (uschar) va_arg(ap, int);
1540 case 'D': /* Insert daily datestamp for log file names */
1541 s = CS tod_stamp(tod_log_datestamp_daily);
1542 string_datestamp_offset = g->ptr; /* Passed back via global */
1543 string_datestamp_length = Ustrlen(s); /* Passed back via global */
1544 string_datestamp_type = tod_log_datestamp_daily;
1545 slen = string_datestamp_length;
1548 case 'M': /* Insert monthly datestamp for log file names */
1549 s = CS tod_stamp(tod_log_datestamp_monthly);
1550 string_datestamp_offset = g->ptr; /* Passed back via global */
1551 string_datestamp_length = Ustrlen(s); /* Passed back via global */
1552 string_datestamp_type = tod_log_datestamp_monthly;
1553 slen = string_datestamp_length;
1557 case 'S': /* Forces *lower* case */
1558 case 'T': /* Forces *upper* case */
1559 s = va_arg(ap, char *);
1564 if (!(flags & SVFMT_TAINT_NOCHK) && is_incompatible(g->s, s))
1565 if (flags & SVFMT_REBUFFER)
1567 /* debug_printf("%s %d: untainted workarea, tainted %%s :- rebuffer\n", __FUNCTION__, __LINE__); */
1568 gstring_rebuffer(g, s);
1569 gp = CS g->s + g->ptr;
1571 #ifndef MACRO_PREDEF
1573 die_tainted(US"string_vformat", func, line);
1576 INSERT_STRING: /* Come to from %D or %M above */
1579 BOOL truncated = FALSE;
1581 /* If the width is specified, check that there is a precision
1582 set; if not, set it to the width to prevent overruns of long
1587 if (precision < 0) precision = width;
1590 /* If a width is not specified and the precision is specified, set
1591 the width to the precision, or the string length if shorted. */
1593 else if (precision >= 0)
1594 width = precision < slen ? precision : slen;
1596 /* If neither are specified, set them both to the string length. */
1599 width = precision = slen;
1601 if ((need = g->ptr + width) >= size_limit || !(flags & SVFMT_EXTEND))
1603 if (g->ptr == lim) return NULL;
1607 width = precision = lim - g->ptr - 1;
1608 if (width < 0) width = 0;
1609 if (precision < 0) precision = 0;
1612 else if (need > lim)
1614 gstring_grow(g, width);
1616 gp = CS g->s + g->ptr;
1619 g->ptr += sprintf(gp, "%*.*s", width, precision, s);
1621 while (*gp) { *gp = tolower(*gp); gp++; }
1622 else if (fp[-1] == 'T')
1623 while (*gp) { *gp = toupper(*gp); gp++; }
1625 if (truncated) return NULL;
1629 /* Some things are never used in Exim; also catches junk. */
1632 strncpy(newformat, item_start, fp - item_start);
1633 newformat[fp-item_start] = 0;
1634 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "string_format: unsupported type "
1635 "in \"%s\" in \"%s\"", newformat, format);
1640 if (g->ptr > g->size)
1641 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1642 "string_format internal error: caller %s %d", func, line);
1648 #ifndef COMPILE_UTILITY
1649 /*************************************************
1650 * Generate an "open failed" message *
1651 *************************************************/
1653 /* This function creates a message after failure to open a file. It includes a
1654 string supplied as data, adds the strerror() text, and if the failure was
1655 "Permission denied", reads and includes the euid and egid.
1658 format a text format string - deliberately not uschar *
1659 func caller, for debug
1660 line caller, for debug
1661 ... arguments for the format string
1663 Returns: a message, in dynamic store
1667 string_open_failed_trc(const uschar * func, unsigned line,
1668 const char * format, ...)
1671 gstring * g = string_get(1024);
1673 g = string_catn(g, US"failed to open ", 15);
1675 /* Use the checked formatting routine to ensure that the buffer
1676 does not overflow. It should not, since this is called only for internally
1677 specified messages. If it does, the message just gets truncated, and there
1678 doesn't seem much we can do about that. */
1680 va_start(ap, format);
1681 (void) string_vformat_trc(g, func, line, STRING_SPRINTF_BUFFER_SIZE,
1682 SVFMT_REBUFFER, format, ap);
1685 g = string_catn(g, US": ", 2);
1686 g = string_cat(g, US strerror(errno));
1688 if (errno == EACCES)
1690 int save_errno = errno;
1691 g = string_fmt_append(g, " (euid=%ld egid=%ld)",
1692 (long int)geteuid(), (long int)getegid());
1695 gstring_release_unused(g);
1696 return string_from_gstring(g);
1703 /* qsort(3), currently used to sort the environment variables
1704 for -bP environment output, needs a function to compare two pointers to string
1705 pointers. Here it is. */
1708 string_compare_by_pointer(const void *a, const void *b)
1710 return Ustrcmp(* CUSS a, * CUSS b);
1712 #endif /* COMPILE_UTILITY */
1717 /*************************************************
1718 **************************************************
1719 * Stand-alone test program *
1720 **************************************************
1721 *************************************************/
1728 printf("Testing is_ip_address\n");
1731 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1734 buffer[Ustrlen(buffer) - 1] = 0;
1735 printf("%d\n", string_is_ip_address(buffer, NULL));
1736 printf("%d %d %s\n", string_is_ip_address(buffer, &offset), offset, buffer);
1739 printf("Testing string_nextinlist\n");
1741 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1743 uschar *list = buffer;
1751 sep1 = sep2 = list[1];
1758 uschar *item1 = string_nextinlist(&lp1, &sep1, item, sizeof(item));
1759 uschar *item2 = string_nextinlist(&lp2, &sep2, NULL, 0);
1761 if (item1 == NULL && item2 == NULL) break;
1762 if (item == NULL || item2 == NULL || Ustrcmp(item1, item2) != 0)
1764 printf("***ERROR\nitem1=\"%s\"\nitem2=\"%s\"\n",
1765 (item1 == NULL)? "NULL" : CS item1,
1766 (item2 == NULL)? "NULL" : CS item2);
1769 else printf(" \"%s\"\n", CS item1);
1773 /* This is a horrible lash-up, but it serves its purpose. */
1775 printf("Testing string_format\n");
1777 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1780 long long llargs[3];
1786 BOOL countset = FASE;
1790 buffer[Ustrlen(buffer) - 1] = 0;
1792 s = Ustrchr(buffer, ',');
1793 if (s == NULL) s = buffer + Ustrlen(buffer);
1795 Ustrncpy(format, buffer, s - buffer);
1796 format[s-buffer] = 0;
1803 s = Ustrchr(ss, ',');
1804 if (s == NULL) s = ss + Ustrlen(ss);
1808 Ustrncpy(outbuf, ss, s-ss);
1809 if (Ustrchr(outbuf, '.') != NULL)
1812 dargs[n++] = Ustrtod(outbuf, NULL);
1814 else if (Ustrstr(outbuf, "ll") != NULL)
1817 llargs[n++] = strtoull(CS outbuf, NULL, 10);
1821 args[n++] = (void *)Uatoi(outbuf);
1825 else if (Ustrcmp(ss, "*") == 0)
1827 args[n++] = (void *)(&count);
1833 uschar *sss = malloc(s - ss + 1);
1834 Ustrncpy(sss, ss, s-ss);
1841 if (!dflag && !llflag)
1842 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1843 args[0], args[1], args[2])? "True" : "False");
1846 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1847 dargs[0], dargs[1], dargs[2])? "True" : "False");
1849 else printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1850 llargs[0], llargs[1], llargs[2])? "True" : "False");
1852 printf("%s\n", CS outbuf);
1853 if (countset) printf("count=%d\n", count);
1860 /* End of string.c */