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