Hack in testing code for checking long long formatting.
[exim.git] / src / src / string.c
1 /* $Cambridge: exim/src/src/string.c,v 1.10 2006/02/23 10:25:45 ph10 Exp $ */
2
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
6
7 /* Copyright (c) University of Cambridge 1995 - 2006 */
8 /* See the file NOTICE for conditions of use and distribution. */
9
10 /* Miscellaneous string-handling functions. Some are not required for
11 utilities and tests, and are cut out by the COMPILE_UTILITY macro. */
12
13
14 #include "exim.h"
15
16
17 #ifndef COMPILE_UTILITY
18 /*************************************************
19 * Test for IP address *
20 *************************************************/
21
22 /* This used just to be a regular expression, but with IPv6 things are a bit
23 more complicated. If the address contains a colon, it is assumed to be a v6
24 address (assuming HAVE_IPV6 is set). If a mask is permitted and one is present,
25 and maskptr is not NULL, its offset is placed there.
26
27 Arguments:
28 s a string
29 maskptr NULL if no mask is permitted to follow
30 otherwise, points to an int where the offset of '/' is placed
31 if there is no / followed by trailing digits, *maskptr is set 0
32
33 Returns: 0 if the string is not a textual representation of an IP address
34 4 if it is an IPv4 address
35 6 if it is an IPv6 address
36 */
37
38 int
39 string_is_ip_address(uschar *s, int *maskptr)
40 {
41 int i;
42 int yield = 4;
43
44 /* If an optional mask is permitted, check for it. If found, pass back the
45 offset. */
46
47 if (maskptr != NULL)
48 {
49 uschar *ss = s + Ustrlen(s);
50 *maskptr = 0;
51 if (s != ss && isdigit(*(--ss)))
52 {
53 while (ss > s && isdigit(ss[-1])) ss--;
54 if (ss > s && *(--ss) == '/') *maskptr = ss - s;
55 }
56 }
57
58 /* A colon anywhere in the string => IPv6 address */
59
60 if (Ustrchr(s, ':') != NULL)
61 {
62 BOOL had_double_colon = FALSE;
63 BOOL v4end = FALSE;
64 int count = 0;
65
66 yield = 6;
67
68 /* An IPv6 address must start with hex digit or double colon. A single
69 colon is invalid. */
70
71 if (*s == ':' && *(++s) != ':') return 0;
72
73 /* Now read up to 8 components consisting of up to 4 hex digits each. There
74 may be one and only one appearance of double colon, which implies any number
75 of binary zero bits. The number of preceding components is held in count. */
76
77 for (count = 0; count < 8; count++)
78 {
79 /* If the end of the string is reached before reading 8 components, the
80 address is valid provided a double colon has been read. This also applies
81 if we hit the / that introduces a mask or the % that introduces the
82 interface specifier (scope id) of a link-local address. */
83
84 if (*s == 0 || *s == '%' || *s == '/') return had_double_colon? yield : 0;
85
86 /* If a component starts with an additional colon, we have hit a double
87 colon. This is permitted to appear once only, and counts as at least
88 one component. The final component may be of this form. */
89
90 if (*s == ':')
91 {
92 if (had_double_colon) return 0;
93 had_double_colon = TRUE;
94 s++;
95 continue;
96 }
97
98 /* If the remainder of the string contains a dot but no colons, we
99 can expect a trailing IPv4 address. This is valid if either there has
100 been no double-colon and this is the 7th component (with the IPv4 address
101 being the 7th & 8th components), OR if there has been a double-colon
102 and fewer than 6 components. */
103
104 if (Ustrchr(s, ':') == NULL && Ustrchr(s, '.') != NULL)
105 {
106 if ((!had_double_colon && count != 6) ||
107 (had_double_colon && count > 6)) return 0;
108 v4end = TRUE;
109 yield = 6;
110 break;
111 }
112
113 /* Check for at least one and not more than 4 hex digits for this
114 component. */
115
116 if (!isxdigit(*s++)) return 0;
117 if (isxdigit(*s) && isxdigit(*(++s)) && isxdigit(*(++s))) s++;
118
119 /* If the component is terminated by colon and there is more to
120 follow, skip over the colon. If there is no more to follow the address is
121 invalid. */
122
123 if (*s == ':' && *(++s) == 0) return 0;
124 }
125
126 /* If about to handle a trailing IPv4 address, drop through. Otherwise
127 all is well if we are at the end of the string or at the mask or at a percent
128 sign, which introduces the interface specifier (scope id) of a link local
129 address. */
130
131 if (!v4end)
132 return (*s == 0 || *s == '%' ||
133 (*s == '/' && maskptr != NULL && *maskptr != 0))? yield : 0;
134 }
135
136 /* Test for IPv4 address, which may be the tail-end of an IPv6 address. */
137
138 for (i = 0; i < 4; i++)
139 {
140 if (i != 0 && *s++ != '.') return 0;
141 if (!isdigit(*s++)) return 0;
142 if (isdigit(*s) && isdigit(*(++s))) s++;
143 }
144
145 return (*s == 0 || (*s == '/' && maskptr != NULL && *maskptr != 0))?
146 yield : 0;
147 }
148 #endif /* COMPILE_UTILITY */
149
150
151 /*************************************************
152 * Format message size *
153 *************************************************/
154
155 /* Convert a message size in bytes to printing form, rounding
156 according to the magnitude of the number. A value of zero causes
157 a string of spaces to be returned.
158
159 Arguments:
160 size the message size in bytes
161 buffer where to put the answer
162
163 Returns: pointer to the buffer
164 a string of exactly 5 characters is normally returned
165 */
166
167 uschar *
168 string_format_size(int size, uschar *buffer)
169 {
170 if (size == 0) Ustrcpy(CS buffer, " ");
171 else if (size < 1024) sprintf(CS buffer, "%5d", size);
172 else if (size < 10*1024)
173 sprintf(CS buffer, "%4.1fK", (double)size / 1024.0);
174 else if (size < 1024*1024)
175 sprintf(CS buffer, "%4dK", (size + 512)/1024);
176 else if (size < 10*1024*1024)
177 sprintf(CS buffer, "%4.1fM", (double)size / (1024.0 * 1024.0));
178 else
179 sprintf(CS buffer, "%4dM", (size + 512 * 1024)/(1024*1024));
180 return buffer;
181 }
182
183
184
185 #ifndef COMPILE_UTILITY
186 /*************************************************
187 * Convert a number to base 62 format *
188 *************************************************/
189
190 /* Convert a long integer into an ASCII base 62 string. For Cygwin the value of
191 BASE_62 is actually 36. Always return exactly 6 characters plus zero, in a
192 static area.
193
194 Argument: a long integer
195 Returns: pointer to base 62 string
196 */
197
198 uschar *
199 string_base62(unsigned long int value)
200 {
201 static uschar yield[7];
202 uschar *p = yield + sizeof(yield) - 1;
203 *p = 0;
204 while (p > yield)
205 {
206 *(--p) = base62_chars[value % BASE_62];
207 value /= BASE_62;
208 }
209 return yield;
210 }
211 #endif /* COMPILE_UTILITY */
212
213
214
215 #ifndef COMPILE_UTILITY
216 /*************************************************
217 * Interpret escape sequence *
218 *************************************************/
219
220 /* This function is called from several places where escape sequences are to be
221 interpreted in strings.
222
223 Arguments:
224 pp points a pointer to the initiating "\" in the string;
225 the pointer gets updated to point to the final character
226 Returns: the value of the character escape
227 */
228
229 int
230 string_interpret_escape(uschar **pp)
231 {
232 int ch;
233 uschar *p = *pp;
234 ch = *(++p);
235 if (isdigit(ch) && ch != '8' && ch != '9')
236 {
237 ch -= '0';
238 if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
239 {
240 ch = ch * 8 + *(++p) - '0';
241 if (isdigit(p[1]) && p[1] != '8' && p[1] != '9')
242 ch = ch * 8 + *(++p) - '0';
243 }
244 }
245 else switch(ch)
246 {
247 case 'n': ch = '\n'; break;
248 case 'r': ch = '\r'; break;
249 case 't': ch = '\t'; break;
250 case 'x':
251 ch = 0;
252 if (isxdigit(p[1]))
253 {
254 ch = ch * 16 +
255 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
256 if (isxdigit(p[1])) ch = ch * 16 +
257 Ustrchr(hex_digits, tolower(*(++p))) - hex_digits;
258 }
259 break;
260 }
261 *pp = p;
262 return ch;
263 }
264 #endif /* COMPILE_UTILITY */
265
266
267
268 #ifndef COMPILE_UTILITY
269 /*************************************************
270 * Ensure string is printable *
271 *************************************************/
272
273 /* This function is called for critical strings. It checks for any
274 non-printing characters, and if any are found, it makes a new copy
275 of the string with suitable escape sequences. It is most often called by the
276 macro string_printing(), which sets allow_tab TRUE.
277
278 Arguments:
279 s the input string
280 allow_tab TRUE to allow tab as a printing character
281
282 Returns: string with non-printers encoded as printing sequences
283 */
284
285 uschar *
286 string_printing2(uschar *s, BOOL allow_tab)
287 {
288 int nonprintcount = 0;
289 int length = 0;
290 uschar *t = s;
291 uschar *ss, *tt;
292
293 while (*t != 0)
294 {
295 int c = *t++;
296 if (!mac_isprint(c) || (!allow_tab && c == '\t')) nonprintcount++;
297 length++;
298 }
299
300 if (nonprintcount == 0) return s;
301
302 /* Get a new block of store guaranteed big enough to hold the
303 expanded string. */
304
305 ss = store_get(length + nonprintcount * 4 + 1);
306
307 /* Copy everying, escaping non printers. */
308
309 t = s;
310 tt = ss;
311
312 while (*t != 0)
313 {
314 int c = *t;
315 if (mac_isprint(c) && (allow_tab || c != '\t')) *tt++ = *t++; else
316 {
317 *tt++ = '\\';
318 switch (*t)
319 {
320 case '\n': *tt++ = 'n'; break;
321 case '\r': *tt++ = 'r'; break;
322 case '\b': *tt++ = 'b'; break;
323 case '\v': *tt++ = 'v'; break;
324 case '\f': *tt++ = 'f'; break;
325 case '\t': *tt++ = 't'; break;
326 default: sprintf(CS tt, "%03o", *t); tt += 3; break;
327 }
328 t++;
329 }
330 }
331 *tt = 0;
332 return ss;
333 }
334 #endif /* COMPILE_UTILITY */
335
336
337
338
339 /*************************************************
340 * Copy and save string *
341 *************************************************/
342
343 /* This function assumes that memcpy() is faster than strcpy().
344
345 Argument: string to copy
346 Returns: copy of string in new store
347 */
348
349 uschar *
350 string_copy(uschar *s)
351 {
352 int len = Ustrlen(s) + 1;
353 uschar *ss = store_get(len);
354 memcpy(ss, s, len);
355 return ss;
356 }
357
358
359
360 /*************************************************
361 * Copy and save string in malloc'd store *
362 *************************************************/
363
364 /* This function assumes that memcpy() is faster than strcpy().
365
366 Argument: string to copy
367 Returns: copy of string in new store
368 */
369
370 uschar *
371 string_copy_malloc(uschar *s)
372 {
373 int len = Ustrlen(s) + 1;
374 uschar *ss = store_malloc(len);
375 memcpy(ss, s, len);
376 return ss;
377 }
378
379
380
381 /*************************************************
382 * Copy, lowercase and save string *
383 *************************************************/
384
385 /*
386 Argument: string to copy
387 Returns: copy of string in new store, with letters lowercased
388 */
389
390 uschar *
391 string_copylc(uschar *s)
392 {
393 uschar *ss = store_get(Ustrlen(s) + 1);
394 uschar *p = ss;
395 while (*s != 0) *p++ = tolower(*s++);
396 *p = 0;
397 return ss;
398 }
399
400
401
402 /*************************************************
403 * Copy and save string, given length *
404 *************************************************/
405
406 /* It is assumed the data contains no zeros. A zero is added
407 onto the end.
408
409 Arguments:
410 s string to copy
411 n number of characters
412
413 Returns: copy of string in new store
414 */
415
416 uschar *
417 string_copyn(uschar *s, int n)
418 {
419 uschar *ss = store_get(n + 1);
420 Ustrncpy(ss, s, n);
421 ss[n] = 0;
422 return ss;
423 }
424
425
426 /*************************************************
427 * Copy, lowercase, and save string, given length *
428 *************************************************/
429
430 /* It is assumed the data contains no zeros. A zero is added
431 onto the end.
432
433 Arguments:
434 s string to copy
435 n number of characters
436
437 Returns: copy of string in new store, with letters lowercased
438 */
439
440 uschar *
441 string_copynlc(uschar *s, int n)
442 {
443 uschar *ss = store_get(n + 1);
444 uschar *p = ss;
445 while (n-- > 0) *p++ = tolower(*s++);
446 *p = 0;
447 return ss;
448 }
449
450
451
452 /*************************************************
453 * Copy returned DNS domain name, de-escaping *
454 *************************************************/
455
456 /* If a domain name contains top-bit characters, some resolvers return
457 the fully qualified name with those characters turned into escapes. The
458 convention is a backslash followed by _decimal_ digits. We convert these
459 back into the original binary values. This will be relevant when
460 allow_utf8_domains is set true and UTF-8 characters are used in domain
461 names. Backslash can also be used to escape other characters, though we
462 shouldn't come across them in domain names.
463
464 Argument: the domain name string
465 Returns: copy of string in new store, de-escaped
466 */
467
468 uschar *
469 string_copy_dnsdomain(uschar *s)
470 {
471 uschar *yield;
472 uschar *ss = yield = store_get(Ustrlen(s) + 1);
473
474 while (*s != 0)
475 {
476 if (*s != '\\')
477 {
478 *ss++ = *s++;
479 }
480 else if (isdigit(s[1]))
481 {
482 *ss++ = (s[1] - '0')*100 + (s[2] - '0')*10 + s[3] - '0';
483 s += 4;
484 }
485 else if (*(++s) != 0)
486 {
487 *ss++ = *s++;
488 }
489 }
490
491 *ss = 0;
492 return yield;
493 }
494
495
496 #ifndef COMPILE_UTILITY
497 /*************************************************
498 * Copy space-terminated or quoted string *
499 *************************************************/
500
501 /* This function copies from a string until its end, or until whitespace is
502 encountered, unless the string begins with a double quote, in which case the
503 terminating quote is sought, and escaping within the string is done. The length
504 of a de-quoted string can be no longer than the original, since escaping always
505 turns n characters into 1 character.
506
507 Argument: pointer to the pointer to the first character, which gets updated
508 Returns: the new string
509 */
510
511 uschar *
512 string_dequote(uschar **sptr)
513 {
514 uschar *s = *sptr;
515 uschar *t, *yield;
516
517 /* First find the end of the string */
518
519 if (*s != '\"')
520 {
521 while (*s != 0 && !isspace(*s)) s++;
522 }
523 else
524 {
525 s++;
526 while (*s != 0 && *s != '\"')
527 {
528 if (*s == '\\') (void)string_interpret_escape(&s);
529 s++;
530 }
531 if (*s != 0) s++;
532 }
533
534 /* Get enough store to copy into */
535
536 t = yield = store_get(s - *sptr + 1);
537 s = *sptr;
538
539 /* Do the copy */
540
541 if (*s != '\"')
542 {
543 while (*s != 0 && !isspace(*s)) *t++ = *s++;
544 }
545 else
546 {
547 s++;
548 while (*s != 0 && *s != '\"')
549 {
550 if (*s == '\\') *t++ = string_interpret_escape(&s);
551 else *t++ = *s;
552 s++;
553 }
554 if (*s != 0) s++;
555 }
556
557 /* Update the pointer and return the terminated copy */
558
559 *sptr = s;
560 *t = 0;
561 return yield;
562 }
563 #endif /* COMPILE_UTILITY */
564
565
566
567 /*************************************************
568 * Format a string and save it *
569 *************************************************/
570
571 /* The formatting is done by string_format, which checks the length of
572 everything.
573
574 Arguments:
575 format a printf() format - deliberately char * rather than uschar *
576 because it will most usually be a literal string
577 ... arguments for format
578
579 Returns: pointer to fresh piece of store containing sprintf'ed string
580 */
581
582 uschar *
583 string_sprintf(char *format, ...)
584 {
585 va_list ap;
586 uschar buffer[STRING_SPRINTF_BUFFER_SIZE];
587 va_start(ap, format);
588 if (!string_vformat(buffer, sizeof(buffer), format, ap))
589 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
590 "string_sprintf expansion was longer than %d", sizeof(buffer));
591 va_end(ap);
592 return string_copy(buffer);
593 }
594
595
596
597 /*************************************************
598 * Case-independent strncmp() function *
599 *************************************************/
600
601 /*
602 Arguments:
603 s first string
604 t second string
605 n number of characters to compare
606
607 Returns: < 0, = 0, or > 0, according to the comparison
608 */
609
610 int
611 strncmpic(uschar *s, uschar *t, int n)
612 {
613 while (n--)
614 {
615 int c = tolower(*s++) - tolower(*t++);
616 if (c) return c;
617 }
618 return 0;
619 }
620
621
622 /*************************************************
623 * Case-independent strcmp() function *
624 *************************************************/
625
626 /*
627 Arguments:
628 s first string
629 t second string
630
631 Returns: < 0, = 0, or > 0, according to the comparison
632 */
633
634 int
635 strcmpic(uschar *s, uschar *t)
636 {
637 while (*s != 0)
638 {
639 int c = tolower(*s++) - tolower(*t++);
640 if (c != 0) return c;
641 }
642 return *t;
643 }
644
645
646 /*************************************************
647 * Case-independent strstr() function *
648 *************************************************/
649
650 /* The third argument specifies whether whitespace is required
651 to follow the matched string.
652
653 Arguments:
654 s string to search
655 t substring to search for
656 space_follows if TRUE, match only if whitespace follows
657
658 Returns: pointer to substring in string, or NULL if not found
659 */
660
661 uschar *
662 strstric(uschar *s, uschar *t, BOOL space_follows)
663 {
664 uschar *p = t;
665 uschar *yield = NULL;
666 int cl = tolower(*p);
667 int cu = toupper(*p);
668
669 while (*s)
670 {
671 if (*s == cl || *s == cu)
672 {
673 if (yield == NULL) yield = s;
674 if (*(++p) == 0)
675 {
676 if (!space_follows || s[1] == ' ' || s[1] == '\n' ) return yield;
677 yield = NULL;
678 p = t;
679 }
680 cl = tolower(*p);
681 cu = toupper(*p);
682 s++;
683 }
684 else if (yield != NULL)
685 {
686 yield = NULL;
687 p = t;
688 cl = tolower(*p);
689 cu = toupper(*p);
690 }
691 else s++;
692 }
693 return NULL;
694 }
695
696
697
698 #ifndef COMPILE_UTILITY
699 /*************************************************
700 * Get next string from separated list *
701 *************************************************/
702
703 /* Leading and trailing space is removed from each item. The separator in the
704 list is controlled by the int pointed to by the separator argument as follows:
705
706 If its value is > 0 it is used as the delimiter.
707 (If its value is actually > UCHAR_MAX there is only one item in the list.
708 This is used for some cases when called via functions that sometimes
709 plough through lists, and sometimes are given single items.)
710 If its value is <= 0, the string is inspected for a leading <x, where
711 x is an ispunct() value. If found, it is used as the delimiter. If not
712 found: (a) if separator == 0, ':' is used
713 (b) if separator <0, then -separator is used
714 In all cases the value of the separator that is used is written back to
715 the int so that it is used on subsequent calls as we progress through
716 the list.
717
718 The separator can always be represented in the string by doubling.
719
720 Arguments:
721 listptr points to a pointer to the current start of the list; the
722 pointer gets updated to point after the end of the next item
723 separator a pointer to the separator character in an int (see above)
724 buffer where to put a copy of the next string in the list; or
725 NULL if the next string is returned in new memory
726 buflen when buffer is not NULL, the size of buffer; otherwise ignored
727
728 Returns: pointer to buffer, containing the next substring,
729 or NULL if no more substrings
730 */
731
732 uschar *
733 string_nextinlist(uschar **listptr, int *separator, uschar *buffer, int buflen)
734 {
735 register int p = 0;
736 register int sep = *separator;
737 register uschar *s = *listptr;
738
739 if (s == NULL) return NULL;
740 while (isspace(*s)) s++;
741
742 if (sep <= 0)
743 {
744 if (*s == '<' && ispunct(s[1]))
745 {
746 sep = s[1];
747 s += 2;
748 while (isspace(*s)) s++;
749 }
750 else
751 {
752 sep = (sep == 0)? ':' : -sep;
753 }
754 *separator = sep;
755 }
756
757 if (*s == 0) return NULL;
758
759 /* Handle the case when a buffer is provided. */
760
761 if (buffer != NULL)
762 {
763 for (; *s != 0; s++)
764 {
765 if (*s == sep && *(++s) != sep) break;
766 if (p < buflen - 1) buffer[p++] = *s;
767 }
768 while (p > 0 && isspace(buffer[p-1])) p--;
769 buffer[p] = 0;
770 }
771
772 /* Handle the case when a buffer is not provided. */
773
774 else
775 {
776 /* We know that *s != 0 at this point. However, it might be pointing to a
777 separator, which could indicate an empty string, or could be doubled to
778 indicate a separator character as data at the start of a string. */
779
780 if (*s == sep)
781 {
782 s++;
783 if (*s != sep) buffer = string_copy(US"");
784 }
785
786 if (buffer == NULL)
787 {
788 int size = 0;
789 int ptr = 0;
790 uschar *ss;
791 for (;;)
792 {
793 for (ss = s + 1; *ss != 0 && *ss != sep; ss++);
794 buffer = string_cat(buffer, &size, &ptr, s, ss-s);
795 s = ss;
796 if (*s == 0 || *(++s) != sep) break;
797 }
798 while (ptr > 0 && isspace(buffer[ptr-1])) ptr--;
799 buffer[ptr] = 0;
800 }
801 }
802
803 /* Update the current pointer and return the new string */
804
805 *listptr = s;
806 return buffer;
807 }
808 #endif /* COMPILE_UTILITY */
809
810
811
812 #ifndef COMPILE_UTILITY
813 /*************************************************
814 * Add chars to string *
815 *************************************************/
816
817 /* This function is used when building up strings of unknown length. Room is
818 always left for a terminating zero to be added to the string that is being
819 built. This function does not require the string that is being added to be NUL
820 terminated, because the number of characters to add is given explicitly. It is
821 sometimes called to extract parts of other strings.
822
823 Arguments:
824 string points to the start of the string that is being built, or NULL
825 if this is a new string that has no contents yet
826 size points to a variable that holds the current capacity of the memory
827 block (updated if changed)
828 ptr points to a variable that holds the offset at which to add
829 characters, updated to the new offset
830 s points to characters to add
831 count count of characters to add; must not exceed the length of s, if s
832 is a C string
833
834 If string is given as NULL, *size and *ptr should both be zero.
835
836 Returns: pointer to the start of the string, changed if copied for expansion.
837 Note that a NUL is not added, though space is left for one. This is
838 because string_cat() is often called multiple times to build up a
839 string - there's no point adding the NUL till the end.
840 */
841
842 uschar *
843 string_cat(uschar *string, int *size, int *ptr, const uschar *s, int count)
844 {
845 int p = *ptr;
846
847 if (p + count >= *size)
848 {
849 int oldsize = *size;
850
851 /* Mostly, string_cat() is used to build small strings of a few hundred
852 characters at most. There are times, however, when the strings are very much
853 longer (for example, a lookup that returns a vast number of alias addresses).
854 To try to keep things reasonable, we use increments whose size depends on the
855 existing length of the string. */
856
857 int inc = (oldsize < 4096)? 100 : 1024;
858 while (*size <= p + count) *size += inc;
859
860 /* New string */
861
862 if (string == NULL) string = store_get(*size);
863
864 /* Try to extend an existing allocation. If the result of calling
865 store_extend() is false, either there isn't room in the current memory block,
866 or this string is not the top item on the dynamic store stack. We then have
867 to get a new chunk of store and copy the old string. When building large
868 strings, it is helpful to call store_release() on the old string, to release
869 memory blocks that have become empty. (The block will be freed if the string
870 is at its start.) However, we can do this only if we know that the old string
871 was the last item on the dynamic memory stack. This is the case if it matches
872 store_last_get. */
873
874 else if (!store_extend(string, oldsize, *size))
875 {
876 BOOL release_ok = store_last_get[store_pool] == string;
877 uschar *newstring = store_get(*size);
878 memcpy(newstring, string, p);
879 if (release_ok) store_release(string);
880 string = newstring;
881 }
882 }
883
884 /* Because we always specify the exact number of characters to copy, we can
885 use memcpy(), which is likely to be more efficient than strncopy() because the
886 latter has to check for zero bytes. */
887
888 memcpy(string + p, s, count);
889 *ptr = p + count;
890 return string;
891 }
892 #endif /* COMPILE_UTILITY */
893
894
895
896 #ifndef COMPILE_UTILITY
897 /*************************************************
898 * Append strings to another string *
899 *************************************************/
900
901 /* This function can be used to build a string from many other strings.
902 It calls string_cat() to do the dirty work.
903
904 Arguments:
905 string points to the start of the string that is being built, or NULL
906 if this is a new string that has no contents yet
907 size points to a variable that holds the current capacity of the memory
908 block (updated if changed)
909 ptr points to a variable that holds the offset at which to add
910 characters, updated to the new offset
911 count the number of strings to append
912 ... "count" uschar* arguments, which must be valid zero-terminated
913 C strings
914
915 Returns: pointer to the start of the string, changed if copied for expansion.
916 The string is not zero-terminated - see string_cat() above.
917 */
918
919 uschar *
920 string_append(uschar *string, int *size, int *ptr, int count, ...)
921 {
922 va_list ap;
923 int i;
924
925 va_start(ap, count);
926 for (i = 0; i < count; i++)
927 {
928 uschar *t = va_arg(ap, uschar *);
929 string = string_cat(string, size, ptr, t, Ustrlen(t));
930 }
931 va_end(ap);
932
933 return string;
934 }
935 #endif
936
937
938
939 /*************************************************
940 * Format a string with length checks *
941 *************************************************/
942
943 /* This function is used to format a string with checking of the length of the
944 output for all conversions. It protects Exim from absent-mindedness when
945 calling functions like debug_printf and string_sprintf, and elsewhere. There
946 are two different entry points to what is actually the same function, depending
947 on whether the variable length list of data arguments are given explicitly or
948 as a va_list item.
949
950 The formats are the usual printf() ones, with some omissions (never used) and
951 two additions for strings: %S forces lower case, and %#s or %#S prints nothing
952 for a NULL string. Without the # "NULL" is printed (useful in debugging). There
953 is also the addition of %D, which inserts the date in the form used for
954 datestamped log files.
955
956 Arguments:
957 buffer a buffer in which to put the formatted string
958 buflen the length of the buffer
959 format the format string - deliberately char * and not uschar *
960 ... or ap variable list of supplementary arguments
961
962 Returns: TRUE if the result fitted in the buffer
963 */
964
965 BOOL
966 string_format(uschar *buffer, int buflen, char *format, ...)
967 {
968 BOOL yield;
969 va_list ap;
970 va_start(ap, format);
971 yield = string_vformat(buffer, buflen, format, ap);
972 va_end(ap);
973 return yield;
974 }
975
976
977 BOOL
978 string_vformat(uschar *buffer, int buflen, char *format, va_list ap)
979 {
980 enum { L_NORMAL, L_SHORT, L_LONG, L_LONGLONG, L_LONGDOUBLE };
981
982 BOOL yield = TRUE;
983 int width, precision;
984 char *fp = format; /* Deliberately not unsigned */
985 uschar *p = buffer;
986 uschar *last = buffer + buflen - 1;
987
988 string_datestamp_offset = -1; /* Datestamp not inserted */
989
990 /* Scan the format and handle the insertions */
991
992 while (*fp != 0)
993 {
994 int length = L_NORMAL;
995 int *nptr;
996 int slen;
997 char *null = "NULL"; /* ) These variables */
998 char *item_start, *s; /* ) are deliberately */
999 char newformat[16]; /* ) not unsigned */
1000
1001 /* Non-% characters just get copied verbatim */
1002
1003 if (*fp != '%')
1004 {
1005 if (p >= last) { yield = FALSE; break; }
1006 *p++ = (uschar)*fp++;
1007 continue;
1008 }
1009
1010 /* Deal with % characters. Pick off the width and precision, for checking
1011 strings, skipping over the flag and modifier characters. */
1012
1013 item_start = fp;
1014 width = precision = -1;
1015
1016 if (strchr("-+ #0", *(++fp)) != NULL)
1017 {
1018 if (*fp == '#') null = "";
1019 fp++;
1020 }
1021
1022 if (isdigit((uschar)*fp))
1023 {
1024 width = *fp++ - '0';
1025 while (isdigit((uschar)*fp)) width = width * 10 + *fp++ - '0';
1026 }
1027 else if (*fp == '*')
1028 {
1029 width = va_arg(ap, int);
1030 fp++;
1031 }
1032
1033 if (*fp == '.')
1034 {
1035 if (*(++fp) == '*')
1036 {
1037 precision = va_arg(ap, int);
1038 fp++;
1039 }
1040 else
1041 {
1042 precision = 0;
1043 while (isdigit((uschar)*fp))
1044 precision = precision*10 + *fp++ - '0';
1045 }
1046 }
1047
1048 /* Skip over 'h', 'L', 'l', and 'll', remembering the item length */
1049
1050 if (*fp == 'h')
1051 { fp++; length = L_SHORT; }
1052 else if (*fp == 'L')
1053 { fp++; length = L_LONGDOUBLE; }
1054 else if (*fp == 'l')
1055 {
1056 if (fp[1] == 'l')
1057 {
1058 fp += 2;
1059 length = L_LONGLONG;
1060 }
1061 else
1062 {
1063 fp++;
1064 length = L_LONG;
1065 }
1066 }
1067
1068 /* Handle each specific format type. */
1069
1070 switch (*fp++)
1071 {
1072 case 'n':
1073 nptr = va_arg(ap, int *);
1074 *nptr = p - buffer;
1075 break;
1076
1077 case 'd':
1078 case 'o':
1079 case 'u':
1080 case 'x':
1081 case 'X':
1082 if (p >= last - ((length > L_LONG)? 24 : 12))
1083 { yield = FALSE; goto END_FORMAT; }
1084 strncpy(newformat, item_start, fp - item_start);
1085 newformat[fp - item_start] = 0;
1086
1087 /* Short int is promoted to int when passing through ..., so we must use
1088 int for va_arg(). */
1089
1090 switch(length)
1091 {
1092 case L_SHORT:
1093 case L_NORMAL: sprintf(CS p, newformat, va_arg(ap, int)); break;
1094 case L_LONG: sprintf(CS p, newformat, va_arg(ap, long int)); break;
1095 case L_LONGLONG: sprintf(CS p, newformat, va_arg(ap, LONGLONG_T)); break;
1096 }
1097 while (*p) p++;
1098 break;
1099
1100 case 'p':
1101 if (p >= last - 24) { yield = FALSE; goto END_FORMAT; }
1102 strncpy(newformat, item_start, fp - item_start);
1103 newformat[fp - item_start] = 0;
1104 sprintf(CS p, newformat, va_arg(ap, void *));
1105 while (*p) p++;
1106 break;
1107
1108 /* %f format is inherently insecure if the numbers that it may be
1109 handed are unknown (e.g. 1e300). However, in Exim, %f is used for
1110 printing load averages, and these are actually stored as integers
1111 (load average * 1000) so the size of the numbers is constrained.
1112 It is also used for formatting sending rates, where the simplicity
1113 of the format prevents overflow. */
1114
1115 case 'f':
1116 case 'e':
1117 case 'E':
1118 case 'g':
1119 case 'G':
1120 if (precision < 0) precision = 6;
1121 if (p >= last - precision - 8) { yield = FALSE; goto END_FORMAT; }
1122 strncpy(newformat, item_start, fp - item_start);
1123 newformat[fp-item_start] = 0;
1124 if (length == L_LONGDOUBLE)
1125 sprintf(CS p, newformat, va_arg(ap, long double));
1126 else
1127 sprintf(CS p, newformat, va_arg(ap, double));
1128 while (*p) p++;
1129 break;
1130
1131 /* String types */
1132
1133 case '%':
1134 if (p >= last) { yield = FALSE; goto END_FORMAT; }
1135 *p++ = '%';
1136 break;
1137
1138 case 'c':
1139 if (p >= last) { yield = FALSE; goto END_FORMAT; }
1140 *p++ = va_arg(ap, int);
1141 break;
1142
1143 case 'D': /* Insert datestamp for log file names */
1144 s = CS tod_stamp(tod_log_datestamp);
1145 string_datestamp_offset = p - buffer; /* Passed back via global */
1146 goto INSERT_STRING;
1147
1148 case 's':
1149 case 'S': /* Forces *lower* case */
1150 s = va_arg(ap, char *);
1151
1152 INSERT_STRING: /* Come to from %D above */
1153 if (s == NULL) s = null;
1154 slen = Ustrlen(s);
1155
1156 /* If the width is specified, check that there is a precision
1157 set; if not, set it to the width to prevent overruns of long
1158 strings. */
1159
1160 if (width >= 0)
1161 {
1162 if (precision < 0) precision = width;
1163 }
1164
1165 /* If a width is not specified and the precision is specified, set
1166 the width to the precision, or the string length if shorted. */
1167
1168 else if (precision >= 0)
1169 {
1170 width = (precision < slen)? precision : slen;
1171 }
1172
1173 /* If neither are specified, set them both to the string length. */
1174
1175 else width = precision = slen;
1176
1177 /* Check string space, and add the string to the buffer if ok. If
1178 not OK, add part of the string (debugging uses this to show as
1179 much as possible). */
1180
1181 if (p >= last - width)
1182 {
1183 yield = FALSE;
1184 width = precision = last - p - 1;
1185 }
1186 sprintf(CS p, "%*.*s", width, precision, s);
1187 if (fp[-1] == 'S')
1188 while (*p) { *p = tolower(*p); p++; }
1189 else
1190 while (*p) p++;
1191 if (!yield) goto END_FORMAT;
1192 break;
1193
1194 /* Some things are never used in Exim; also catches junk. */
1195
1196 default:
1197 strncpy(newformat, item_start, fp - item_start);
1198 newformat[fp-item_start] = 0;
1199 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "string_format: unsupported type "
1200 "in \"%s\" in \"%s\"", newformat, format);
1201 break;
1202 }
1203 }
1204
1205 /* Ensure string is complete; return TRUE if got to the end of the format */
1206
1207 END_FORMAT:
1208
1209 *p = 0;
1210 return yield;
1211 }
1212
1213
1214
1215 #ifndef COMPILE_UTILITY
1216 /*************************************************
1217 * Generate an "open failed" message *
1218 *************************************************/
1219
1220 /* This function creates a message after failure to open a file. It includes a
1221 string supplied as data, adds the strerror() text, and if the failure was
1222 "Permission denied", reads and includes the euid and egid.
1223
1224 Arguments:
1225 eno the value of errno after the failure
1226 format a text format string - deliberately not uschar *
1227 ... arguments for the format string
1228
1229 Returns: a message, in dynamic store
1230 */
1231
1232 uschar *
1233 string_open_failed(int eno, char *format, ...)
1234 {
1235 va_list ap;
1236 uschar buffer[1024];
1237
1238 Ustrcpy(buffer, "failed to open ");
1239 va_start(ap, format);
1240
1241 /* Use the checked formatting routine to ensure that the buffer
1242 does not overflow. It should not, since this is called only for internally
1243 specified messages. If it does, the message just gets truncated, and there
1244 doesn't seem much we can do about that. */
1245
1246 (void)string_vformat(buffer+15, sizeof(buffer) - 15, format, ap);
1247
1248 return (eno == EACCES)?
1249 string_sprintf("%s: %s (euid=%ld egid=%ld)", buffer, strerror(eno),
1250 (long int)geteuid(), (long int)getegid()) :
1251 string_sprintf("%s: %s", buffer, strerror(eno));
1252 }
1253 #endif /* COMPILE_UTILITY */
1254
1255
1256
1257 #ifndef COMPILE_UTILITY
1258 /*************************************************
1259 * Generate local prt for logging *
1260 *************************************************/
1261
1262 /* This function is a subroutine for use in string_log_address() below.
1263
1264 Arguments:
1265 addr the address being logged
1266 yield the current dynamic buffer pointer
1267 sizeptr points to current size
1268 ptrptr points to current insert pointer
1269
1270 Returns: the new value of the buffer pointer
1271 */
1272
1273 static uschar *
1274 string_get_localpart(address_item *addr, uschar *yield, int *sizeptr,
1275 int *ptrptr)
1276 {
1277 if (testflag(addr, af_include_affixes) && addr->prefix != NULL)
1278 yield = string_cat(yield, sizeptr, ptrptr, addr->prefix,
1279 Ustrlen(addr->prefix));
1280 yield = string_cat(yield, sizeptr, ptrptr, addr->local_part,
1281 Ustrlen(addr->local_part));
1282 if (testflag(addr, af_include_affixes) && addr->suffix != NULL)
1283 yield = string_cat(yield, sizeptr, ptrptr, addr->suffix,
1284 Ustrlen(addr->suffix));
1285 return yield;
1286 }
1287
1288
1289 /*************************************************
1290 * Generate log address list *
1291 *************************************************/
1292
1293 /* This function generates a list consisting of an address and its parents, for
1294 use in logging lines. For saved onetime aliased addresses, the onetime parent
1295 field is used. If the address was delivered by a transport with rcpt_include_
1296 affixes set, the af_include_affixes bit will be set in the address. In that
1297 case, we include the affixes here too.
1298
1299 Arguments:
1300 addr bottom (ultimate) address
1301 all_parents if TRUE, include all parents
1302 success TRUE for successful delivery
1303
1304 Returns: a string in dynamic store
1305 */
1306
1307 uschar *
1308 string_log_address(address_item *addr, BOOL all_parents, BOOL success)
1309 {
1310 int size = 64;
1311 int ptr = 0;
1312 BOOL add_topaddr = TRUE;
1313 uschar *yield = store_get(size);
1314 address_item *topaddr;
1315
1316 /* Find the ultimate parent */
1317
1318 for (topaddr = addr; topaddr->parent != NULL; topaddr = topaddr->parent);
1319
1320 /* We start with just the local part for pipe, file, and reply deliveries, and
1321 for successful local deliveries from routers that have the log_as_local flag
1322 set. File deliveries from filters can be specified as non-absolute paths in
1323 cases where the transport is goin to complete the path. If there is an error
1324 before this happens (expansion failure) the local part will not be updated, and
1325 so won't necessarily look like a path. Add extra text for this case. */
1326
1327 if (testflag(addr, af_pfr) ||
1328 (success &&
1329 addr->router != NULL && addr->router->log_as_local &&
1330 addr->transport != NULL && addr->transport->info->local))
1331 {
1332 if (testflag(addr, af_file) && addr->local_part[0] != '/')
1333 yield = string_cat(yield, &size, &ptr, CUS"save ", 5);
1334 yield = string_get_localpart(addr, yield, &size, &ptr);
1335 }
1336
1337 /* Other deliveries start with the full address. It we have split it into local
1338 part and domain, use those fields. Some early failures can happen before the
1339 splitting is done; in those cases use the original field. */
1340
1341 else
1342 {
1343 if (addr->local_part != NULL)
1344 {
1345 yield = string_get_localpart(addr, yield, &size, &ptr);
1346 yield = string_cat(yield, &size, &ptr, US"@", 1);
1347 yield = string_cat(yield, &size, &ptr, addr->domain,
1348 Ustrlen(addr->domain) );
1349 }
1350 else
1351 {
1352 yield = string_cat(yield, &size, &ptr, addr->address, Ustrlen(addr->address));
1353 }
1354 yield[ptr] = 0;
1355
1356 /* If the address we are going to print is the same as the top address,
1357 and all parents are not being included, don't add on the top address. First
1358 of all, do a caseless comparison; if this succeeds, do a caseful comparison
1359 on the local parts. */
1360
1361 if (strcmpic(yield, topaddr->address) == 0 &&
1362 Ustrncmp(yield, topaddr->address, Ustrchr(yield, '@') - yield) == 0 &&
1363 addr->onetime_parent == NULL &&
1364 (!all_parents || addr->parent == NULL || addr->parent == topaddr))
1365 add_topaddr = FALSE;
1366 }
1367
1368 /* If all parents are requested, or this is a local pipe/file/reply, and
1369 there is at least one intermediate parent, show it in brackets, and continue
1370 with all of them if all are wanted. */
1371
1372 if ((all_parents || testflag(addr, af_pfr)) &&
1373 addr->parent != NULL &&
1374 addr->parent != topaddr)
1375 {
1376 uschar *s = US" (";
1377 address_item *addr2;
1378 for (addr2 = addr->parent; addr2 != topaddr; addr2 = addr2->parent)
1379 {
1380 yield = string_cat(yield, &size, &ptr, s, 2);
1381 yield = string_cat(yield, &size, &ptr, addr2->address, Ustrlen(addr2->address));
1382 if (!all_parents) break;
1383 s = US", ";
1384 }
1385 yield = string_cat(yield, &size, &ptr, US")", 1);
1386 }
1387
1388 /* Add the top address if it is required */
1389
1390 if (add_topaddr)
1391 {
1392 yield = string_cat(yield, &size, &ptr, US" <", 2);
1393
1394 if (addr->onetime_parent == NULL)
1395 yield = string_cat(yield, &size, &ptr, topaddr->address,
1396 Ustrlen(topaddr->address));
1397 else
1398 yield = string_cat(yield, &size, &ptr, addr->onetime_parent,
1399 Ustrlen(addr->onetime_parent));
1400
1401 yield = string_cat(yield, &size, &ptr, US">", 1);
1402 }
1403
1404 yield[ptr] = 0; /* string_cat() leaves space */
1405 return yield;
1406 }
1407 #endif /* COMPILE_UTILITY */
1408
1409
1410
1411
1412
1413 /*************************************************
1414 **************************************************
1415 * Stand-alone test program *
1416 **************************************************
1417 *************************************************/
1418
1419 #ifdef STAND_ALONE
1420 int main(void)
1421 {
1422 uschar buffer[256];
1423
1424 printf("Testing is_ip_address\n");
1425
1426 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1427 {
1428 int offset;
1429 buffer[Ustrlen(buffer) - 1] = 0;
1430 printf("%d\n", string_is_ip_address(buffer, NULL));
1431 printf("%d %d %s\n", string_is_ip_address(buffer, &offset), offset, buffer);
1432 }
1433
1434 printf("Testing string_nextinlist\n");
1435
1436 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1437 {
1438 uschar *list = buffer;
1439 uschar *lp1, *lp2;
1440 uschar item[256];
1441 int sep1 = 0;
1442 int sep2 = 0;
1443
1444 if (*list == '<')
1445 {
1446 sep1 = sep2 = list[1];
1447 list += 2;
1448 }
1449
1450 lp1 = lp2 = list;
1451 for (;;)
1452 {
1453 uschar *item1 = string_nextinlist(&lp1, &sep1, item, sizeof(item));
1454 uschar *item2 = string_nextinlist(&lp2, &sep2, NULL, 0);
1455
1456 if (item1 == NULL && item2 == NULL) break;
1457 if (item == NULL || item2 == NULL || Ustrcmp(item1, item2) != 0)
1458 {
1459 printf("***ERROR\nitem1=\"%s\"\nitem2=\"%s\"\n",
1460 (item1 == NULL)? "NULL" : CS item1,
1461 (item2 == NULL)? "NULL" : CS item2);
1462 break;
1463 }
1464 else printf(" \"%s\"\n", CS item1);
1465 }
1466 }
1467
1468 /* This is a horrible lash-up, but it serves its purpose. */
1469
1470 printf("Testing string_format\n");
1471
1472 while (fgets(CS buffer, sizeof(buffer), stdin) != NULL)
1473 {
1474 void *args[3];
1475 long long llargs[3];
1476 double dargs[3];
1477 int dflag = 0;
1478 int llflag = 0;
1479 int n = 0;
1480 int count;
1481 int countset = 0;
1482 uschar format[256];
1483 uschar outbuf[256];
1484 uschar *s;
1485 buffer[Ustrlen(buffer) - 1] = 0;
1486
1487 s = Ustrchr(buffer, ',');
1488 if (s == NULL) s = buffer + Ustrlen(buffer);
1489
1490 Ustrncpy(format, buffer, s - buffer);
1491 format[s-buffer] = 0;
1492
1493 if (*s == ',') s++;
1494
1495 while (*s != 0)
1496 {
1497 uschar *ss = s;
1498 s = Ustrchr(ss, ',');
1499 if (s == NULL) s = ss + Ustrlen(ss);
1500
1501 if (isdigit(*ss))
1502 {
1503 Ustrncpy(outbuf, ss, s-ss);
1504 if (Ustrchr(outbuf, '.') != NULL)
1505 {
1506 dflag = 1;
1507 dargs[n++] = Ustrtod(outbuf, NULL);
1508 }
1509 else if (Ustrstr(outbuf, "ll") != NULL)
1510 {
1511 llflag = 1;
1512 llargs[n++] = strtoull(CS outbuf, NULL, 10);
1513 }
1514 else
1515 {
1516 args[n++] = (void *)Uatoi(outbuf);
1517 }
1518 }
1519
1520 else if (Ustrcmp(ss, "*") == 0)
1521 {
1522 args[n++] = (void *)(&count);
1523 countset = 1;
1524 }
1525
1526 else
1527 {
1528 uschar *sss = malloc(s - ss + 1);
1529 Ustrncpy(sss, ss, s-ss);
1530 args[n++] = sss;
1531 }
1532
1533 if (*s == ',') s++;
1534 }
1535
1536 if (!dflag && !llflag)
1537 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1538 args[0], args[1], args[2])? "True" : "False");
1539
1540 else if (dflag)
1541 printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1542 dargs[0], dargs[1], dargs[2])? "True" : "False");
1543
1544 else printf("%s\n", string_format(outbuf, sizeof(outbuf), CS format,
1545 llargs[0], llargs[1], llargs[2])? "True" : "False");
1546
1547 printf("%s\n", CS outbuf);
1548 if (countset) printf("count=%d\n", count);
1549 }
1550
1551 return 0;
1552 }
1553 #endif
1554
1555 /* End of string.c */