Use compressed form of ipv6 in $sender_host_address under -bh. Bug 3027
[exim.git] / src / src / header.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2023 */
6 /* Copyright (c) University of Cambridge 1995 - 2016 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
9
10
11 #include "exim.h"
12
13
14 /*************************************************
15 *         Test a header for matching name        *
16 *************************************************/
17
18 /* This function tests the name of a header. It is made into a function because
19 it isn't just a string comparison: spaces and tabs are permitted between the
20 name and the colon. The h->text field should nowadays never be NULL, but check
21 it just in case.
22
23 Arguments:
24   h         points to the header
25   name      the name to test
26   len       the length of the name
27   notdel    if TRUE, force FALSE for deleted headers
28
29 Returns:    TRUE or FALSE
30 */
31
32 BOOL
33 header_testname(const header_line * h, const uschar * name, int len,
34   BOOL notdel)
35 {
36 uschar *tt;
37 if (h->type == '*' && notdel) return FALSE;
38 if (!h->text || strncmpic(h->text, name, len) != 0) return FALSE;
39 tt = h->text + len;
40 while (*tt == ' ' || *tt == '\t') tt++;
41 return *tt == ':';
42 }
43
44 /* This is a copy of the function above, only that it is possible to pass
45    only the beginning of a header name. It simply does a front-anchored
46    substring match. Arguments and Return codes are the same as for
47    header_testname() above. */
48
49 BOOL
50 header_testname_incomplete(const header_line * h, const uschar * name,
51     int len, BOOL notdel)
52 {
53 if (h->type == '*' && notdel) return FALSE;
54 if (!h->text || strncmpic(h->text, name, len) != 0) return FALSE;
55 return TRUE;
56 }
57
58
59 /*************************************************
60 *         Add new header backend function        *
61 *************************************************/
62
63 /* The header_last variable points to the last header during message reception
64 and delivery; otherwise it is NULL. We add new headers only when header_last is
65 not NULL. The function may get called sometimes when it is NULL (e.g. during
66 address verification where rewriting options exist). When called from a filter,
67 there may be multiple header lines in a single string.
68
69 This is an internal static function that is the common back end to the external
70 functions defined below. The general interface allows the header to be inserted
71 before or after a given occurrence of a given header.
72
73 (a) if "name" is NULL, the header is added at the end of all the existing
74     headers if "after" is true, or at the start if it is false. The "topnot"
75     flag is not used.
76
77 (b) If "name" is not NULL, the first existing header with that name is sought.
78     If "after" is false, the new header is added before it. If "after" is true,
79     a check is made for adjacent headers with the same name, and the new header
80     is added after the last of them. If a header of the given name is not
81     found, the new header is added first if "topnot" is true, and at the bottom
82     otherwise.
83
84 Arguments:
85   after     TRUE for "after", FALSE for "before"
86   name      name if adding at a specific header, else NULL
87   topnot    TRUE to add at top if no header found
88   type      Exim header type character (htype_something)
89   format    sprintf format
90   ap        va_list value for format arguments
91
92 Returns:    pointer to header struct (last one, if multiple added)
93 */
94
95 static header_line *
96 header_add_backend(BOOL after, uschar *name, BOOL topnot, int type,
97   const char *format, va_list ap)
98 {
99 header_line *h, *new = NULL;
100 header_line **hptr;
101
102 uschar * p, * q, * buf;
103 gstring gs;
104
105 if (!header_last) return NULL;
106
107 gs.s = buf = store_get(HEADER_ADD_BUFFER_SIZE, GET_UNTAINTED);
108 gs.size = HEADER_ADD_BUFFER_SIZE;
109 gs.ptr = 0;
110
111 if (!string_vformat(&gs, SVFMT_REBUFFER, format, ap))
112   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "string too long in header_add: "
113     "%.100Y ...", &gs);
114
115 if (gs.s != buf) store_release_above(buf);
116 gstring_release_unused(&gs);
117 string_from_gstring(&gs);
118
119 /* Find where to insert this header */
120
121 if (!name)
122   if (after)
123     {
124     hptr = &header_last->next;
125     h = NULL;
126     }
127   else
128     {
129     hptr = &header_list;
130
131     /* header_list->text can be NULL if we get here between when the new
132     received header is allocated and when it is actually filled in. We want
133     that header to be first, so skip it for now. */
134
135     if (!header_list->text)
136       hptr = &header_list->next;
137     h = *hptr;
138     }
139
140 else
141   {
142   int len = Ustrlen(name);
143
144   /* Find the first non-deleted header with the correct name. */
145
146   for (hptr = &header_list; (h = *hptr); hptr = &h->next)
147     if (header_testname(h, name, len, TRUE))
148       break;
149
150   /* Handle the case where no header is found. To insert at the bottom, nothing
151   needs to be done. */
152
153   if (!h)
154     {
155     if (topnot)
156       {
157       hptr = &header_list;
158       h = header_list;
159       }
160     }
161
162   /* Handle the case where a header is found. Check for more if "after" is
163   true. In this case, we want to include deleted headers in the block. */
164
165   else if (after)
166     for (;;)
167       {
168       if (!h->next || !header_testname(h, name, len, FALSE)) break;
169       hptr = &h->next;
170       h = h->next;
171       }
172   }
173
174 /* Loop for multiple header lines, taking care about continuations. At this
175 point, we have hptr pointing to the link field that will point to the new
176 header, and h containing the following header, or NULL. */
177
178 for (p = q = gs.s; *p; p = q)
179   {
180   for (;;)
181     {
182     q = Ustrchr(q, '\n');
183     if (!q) q = p + Ustrlen(p);
184     if (*(++q) != ' ' && *q != '\t') break;
185     }
186
187   new = store_get(sizeof(header_line), GET_UNTAINTED);
188   new->text = string_copyn(p, q - p);
189   new->slen = q - p;
190   new->type = type;
191   new->next = h;
192
193   *hptr = new;
194   hptr = &new->next;
195
196   if (!h) header_last = new;
197   }
198 return new;
199 }
200
201
202 /*************************************************
203 *      Add new header anywhere in the chain      *
204 *************************************************/
205
206 /* This is an external interface to header_add_backend().
207
208 Arguments:
209   after     TRUE for "after", FALSE for "before"
210   name      name if adding at a specific header, else NULL
211   topnot    TRUE to add at top if no header found
212   type      Exim header type character (htype_something)
213   format    sprintf format
214   ...       format arguments
215
216 Returns:    pointer to header struct added
217 */
218
219 header_line *
220 header_add_at_position_internal(BOOL after, uschar *name, BOOL topnot, int type,
221   const char *format, ...)
222 {
223 header_line * h;
224 va_list ap;
225 va_start(ap, format);
226 h = header_add_backend(after, name, topnot, type, format, ap);
227 va_end(ap);
228 return h;
229 }
230
231
232 /* Documented external i/f for local_scan */
233 void
234 header_add_at_position(BOOL after, uschar *name, BOOL topnot, int type,
235   const char *format, ...)
236 {
237 va_list ap;
238 va_start(ap, format);
239 (void) header_add_backend(after, name, topnot, type, format, ap);
240 va_end(ap);
241 }
242
243 /*************************************************
244 *            Add new header on end of chain      *
245 *************************************************/
246
247 /* This is now a convenience interface to header_add_backend().
248
249 Arguments:
250   type      Exim header type character
251   format    sprintf format
252   ...       arguments for the format
253
254 Returns:    nothing
255 */
256
257 void
258 header_add(int type, const char *format, ...)
259 {
260 va_list ap;
261 va_start(ap, format);
262 (void) header_add_backend(TRUE, NULL, FALSE, type, format, ap);
263 va_end(ap);
264 }
265
266
267
268 /*************************************************
269 *        Remove (mark as old) a header           *
270 *************************************************/
271
272 /* This function is used by the filter code; it is also exported in the
273 local_scan() API. If no header is found, the function does nothing.
274
275 Arguments:
276   occ           the occurrence number for multiply-defined headers
277                   <= 0 means "all"; deleted headers are not counted
278   name          the header name
279
280 Returns:        nothing
281 */
282
283 void
284 header_remove(int occ, const uschar *name)
285 {
286 int hcount = 0;
287 int len = Ustrlen(name);
288 for (header_line * h = header_list; h; h = h->next)
289   if (header_testname(h, name, len, TRUE) && (occ <= 0 || ++hcount == occ))
290     {
291     h->type = htype_old;
292     if (occ > 0) return;
293     }
294 }
295
296
297
298 /*************************************************
299 *          Check the name of a header            *
300 *************************************************/
301
302 /* This function scans a table of header field names that Exim recognizes, and
303 returns the identification of a match. If "resent" is true, the header is known
304 to start with "resent-". In that case, the function matches only those fields
305 that are allowed to appear with resent- in front of them.
306
307 Arguments:
308   h             points to the header line
309   is_resent     TRUE if the name starts "Resent-"
310
311 Returns:        One of the htype_ enum values, identifying the header
312 */
313
314 int
315 header_checkname(header_line *h, BOOL is_resent)
316 {
317 uschar *text = h->text;
318 header_name *bot = header_names;
319 header_name *top = header_names + header_names_size;
320
321 if (is_resent) text += 7;
322
323 while (bot < top)
324   {
325   header_name *mid = bot + (top - bot)/2;
326   int c = strncmpic(text, mid->name, mid->len);
327
328   if (c == 0)
329     {
330     uschar * s = text + mid->len;
331     if (Uskip_whitespace(&s) == ':')
332       return (!is_resent || mid->allow_resent)? mid->htype : htype_other;
333     c = 1;
334     }
335
336   if (c > 0) bot = mid + 1; else top = mid;
337   }
338
339 return htype_other;
340 }
341
342
343 /*************************************************
344 *       Scan a header for certain strings        *
345 *************************************************/
346
347 /* This function is used for the "personal" test. It scans a particular header
348 line for any one of a number of strings, matched caselessly either as plain
349 strings, or as regular expressions. If the header line contains a list of
350 addresses, each match is applied only to the operative part of each address in
351 the header, and non-regular expressions must be exact matches.
352
353 The patterns can be provided either as a chain of string_item structures, or
354 inline in the argument list, or both. If there is more than one header of the
355 same name, they are all searched.
356
357 Arguments:
358   name           header name, including the trailing colon
359   has_addresses  TRUE if the header contains a list of addresses
360   cond           value to return if the header contains any of the strings
361   strings        points to a chain of string_item blocks
362   count          number of inline strings
363   ...            the inline strings
364
365 Returns:         cond if the header exists and contains one of the strings;
366                    otherwise !cond
367 */
368
369
370 /* First we have a local subroutine to handle a single pattern */
371
372 static BOOL
373 one_pattern_match(uschar * name, int slen, BOOL has_addresses, uschar * pattern)
374 {
375 BOOL yield = FALSE;
376 const pcre2_code *re = NULL;
377
378 /* If the pattern is a regex, compile it. Bomb out if compiling fails; these
379 patterns are all constructed internally and should be valid. */
380
381 if (*pattern == '^') re = regex_must_compile(pattern, MCS_CASELESS, FALSE);
382
383 /* Scan for the required header(s) and scan each one */
384
385 for (header_line * h = header_list; !yield && h; h = h->next)
386   {
387   if (h->type == htype_old || slen > h->slen ||
388       strncmpic(name, h->text, slen) != 0)
389     continue;
390
391   /* If the header is a list of addresses, extract each one in turn, and scan
392   it. A non-regex scan must be an exact match for the address. */
393
394   if (has_addresses)
395     {
396     uschar *s = h->text + slen;
397
398     while (!yield && *s)
399       {
400       uschar *error, *next;
401       uschar *e = parse_find_address_end(s, FALSE);
402       int terminator = *e;
403       int start, end, domain;
404
405       /* Temporarily terminate the string at the address end while extracting
406       the operative address within. */
407
408       *e = 0;
409       next = parse_extract_address(s, &error, &start, &end, &domain, FALSE);
410       *e = terminator;
411
412       /* Move on, ready for the next address */
413
414       s = e;
415       if (*s == ',') s++;
416
417       /* If there is some kind of syntax error, just give up on this header
418       line. */
419
420       if (!next) break;
421
422       /* Otherwise, test for the pattern; a non-regex must be an exact match */
423
424       yield = re
425         ? regex_match(re, next, -1, NULL)
426         : (strcmpic(next, pattern) == 0);
427       }
428     }
429
430   /* For headers that are not lists of addresses, scan the entire header line,
431   and just require "contains" for non-regex patterns. */
432
433   else
434     {
435     yield = re
436       ? regex_match(re, h->text, h->slen, NULL)
437       : (strstric(h->text, pattern, FALSE) != NULL);
438     }
439   }
440
441 return yield;
442 }
443
444
445 /* The externally visible interface */
446
447 BOOL
448 header_match(uschar * name, BOOL has_addresses, BOOL cond, string_item * strings,
449   int count, ...)
450 {
451 va_list ap;
452 int slen = Ustrlen(name);
453
454 for (string_item * s = strings; s; s = s->next)
455   if (one_pattern_match(name, slen, has_addresses, s->text))
456     return cond;
457
458 va_start(ap, count);
459 for (int i = 0; i < count; i++)
460   if (one_pattern_match(name, slen, has_addresses, va_arg(ap, uschar *)))
461     {
462     va_end(ap);
463     return cond;
464     }
465 va_end(ap);
466
467 return !cond;
468 }
469
470
471
472 /* Wrap and truncate a string for use as a header.
473 Convert either the sequence "\n" or a real newline into newline plus indent.
474 If that still takes us past the column limit, look for the last space
475 and split there too.
476 Limit to the given max total char count.
477
478 Return: string or NULL */
479
480 uschar *
481 wrap_header(const uschar * s, unsigned cols, unsigned maxchars,
482   const uschar * indent, unsigned indent_cols)
483 {
484 gstring * g = NULL;
485
486 if (maxchars == 0) maxchars = INT_MAX;
487 if (cols == 0) cols = INT_MAX;
488
489 if (s && *s)
490   {
491   int sleft = Ustrlen(s);
492   for(unsigned llen = 0; ; llen = indent_cols)
493     {
494     const uschar * t;
495     unsigned ltail = 0, glen;
496
497     if ((t = Ustrchr(s, '\\')) && t[1] == 'n')
498       ltail = 2;
499     else if ((t = Ustrchr(s, '\n')))
500       ltail = 1;
501     else
502       t = s + sleft;
503
504     if ((llen + t - s) > cols)          /* more than a linesworth of s */
505       {                                 /* look backward for whitespace */
506       for (const uschar * u = s + cols - llen; u > s + 10; --u) if (isspace(*u))
507         {
508         llen = u - s;
509         while (u > s+1 && isspace(u[-1])) --u;  /* find start of whitespace */
510         g = string_catn(g, s, u - s);
511         s += ++llen;                            /* skip the space */
512         while (*s && isspace(*s))               /* and any trailing */
513           s++, llen++;
514         goto LDONE;
515         }
516                                         /* no whitespace */
517       if (llen < cols)
518         {                                       /* just linebreak at 80 */
519         llen = cols - llen;
520         g = string_catn(g, s, llen);
521         s += llen;
522         }
523       else
524         llen = 0;
525       LDONE: ;
526       }
527     else                                /* rest of s fits in line */
528       {
529       llen = t - s;
530       g = string_catn(g, s, llen);
531       s = t + ltail;
532       }
533
534     if (!*s)
535       break;                            /* no trailing linebreak */
536     if ((glen = gstring_length(g)) >= maxchars)
537       {
538       gstring_trim(g, glen - maxchars);
539       break;                            /* no trailing linebreak */
540       }
541     sleft -= llen;
542     g = string_catn(g, US"\n", 1);
543     g = string_catn(g, indent, 1);
544     }
545   }
546 gstring_release_unused(g);
547 return string_from_gstring(g);
548 }
549
550
551 /* End of header.c */