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