SECURITY: Don't miss the very last byte when reading long lines from -H
[exim.git] / src / src / spool_in.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* Copyright (c) The Exim Maintainers 2020 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9 /* Functions for reading spool files. When compiling for a utility (eximon),
10 not all are needed, and some functionality can be cut out. */
11
12
13 #include "exim.h"
14
15
16
17 #ifndef COMPILE_UTILITY
18 /*************************************************
19 *           Open and lock data file              *
20 *************************************************/
21
22 /* The data file is the one that is used for locking, because the header file
23 can get replaced during delivery because of header rewriting. The file has
24 to opened with write access so that we can get an exclusive lock, but in
25 fact it won't be written to. Just in case there's a major disaster (e.g.
26 overwriting some other file descriptor with the value of this one), open it
27 with append.
28
29 As called by deliver_message() (at least) we are operating as root.
30
31 Argument: the id of the message
32 Returns:  fd if file successfully opened and locked, else -1
33
34 Side effect: message_subdir is set for the (possibly split) spool directory
35 */
36
37 int
38 spool_open_datafile(uschar *id)
39 {
40 struct stat statbuf;
41 flock_t lock_data;
42 int fd;
43
44 /* If split_spool_directory is set, first look for the file in the appropriate
45 sub-directory of the input directory. If it is not found there, try the input
46 directory itself, to pick up leftovers from before the splitting. If split_
47 spool_directory is not set, first look in the main input directory. If it is
48 not found there, try the split sub-directory, in case it is left over from a
49 splitting state. */
50
51 for (int i = 0; i < 2; i++)
52   {
53   uschar * fname;
54   int save_errno;
55
56   set_subdir_str(message_subdir, id, i);
57   fname = spool_fname(US"input", message_subdir, id, US"-D");
58   DEBUG(D_deliver) debug_printf_indent("Trying spool file %s\n", fname);
59
60   /* We protect against symlink attacks both in not propagating the
61    * file-descriptor to other processes as we exec, and also ensuring that we
62    * don't even open symlinks.
63    * No -D file inside the spool area should be a symlink.
64    */
65   if ((fd = Uopen(fname,
66 #ifdef O_CLOEXEC
67                       O_CLOEXEC |
68 #endif
69 #ifdef O_NOFOLLOW
70                       O_NOFOLLOW |
71 #endif
72                       O_RDWR | O_APPEND, 0)) >= 0)
73     break;
74   save_errno = errno;
75   if (errno == ENOENT)
76     {
77     if (i == 0) continue;
78     if (!f.queue_running)
79       log_write(0, LOG_MAIN, "Spool%s%s file %s-D not found",
80         *queue_name ? US" Q=" : US"",
81         *queue_name ? queue_name : US"",
82         id);
83     }
84   else
85     log_write(0, LOG_MAIN, "Spool error for %s: %s", fname, strerror(errno));
86   errno = save_errno;
87   return -1;
88   }
89
90 /* File is open and message_subdir is set. Set the close-on-exec flag, and lock
91 the file. We lock only the first line of the file (containing the message ID)
92 because this apparently is needed for running Exim under Cygwin. If the entire
93 file is locked in one process, a sub-process cannot access it, even when passed
94 an open file descriptor (at least, I think that's the Cygwin story). On real
95 Unix systems it doesn't make any difference as long as Exim is consistent in
96 what it locks. */
97
98 #ifndef O_CLOEXEC
99 (void)fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
100 #endif
101
102 lock_data.l_type = F_WRLCK;
103 lock_data.l_whence = SEEK_SET;
104 lock_data.l_start = 0;
105 lock_data.l_len = SPOOL_DATA_START_OFFSET;
106
107 if (fcntl(fd, F_SETLK, &lock_data) < 0)
108   {
109   log_write(L_skip_delivery, LOG_MAIN,
110       "Spool file for %s is locked (another process is handling this message)",
111       id);
112   (void)close(fd);
113   errno = 0;
114   return -1;
115   }
116
117 /* Get the size of the data; don't include the leading filename line
118 in the count, but add one for the newline before the data. */
119
120 if (fstat(fd, &statbuf) == 0)
121   {
122   message_body_size = statbuf.st_size - SPOOL_DATA_START_OFFSET;
123   message_size = message_body_size + 1;
124   }
125
126 return fd;
127 }
128 #endif  /* COMPILE_UTILITY */
129
130
131
132 /*************************************************
133 *    Read non-recipients tree from spool file    *
134 *************************************************/
135
136 /* The tree of non-recipients is written to the spool file in a form that
137 makes it easy to read back into a tree. The format is as follows:
138
139    . Each node is preceded by two letter(Y/N) indicating whether it has left
140      or right children. There's one space after the two flags, before the name.
141
142    . The left subtree (if any) then follows, then the right subtree (if any).
143
144 This function is entered with the next input line in the buffer. Note we must
145 save the right flag before recursing with the same buffer.
146
147 Once the tree is read, we re-construct the balance fields by scanning the tree.
148 I forgot to write them out originally, and the compatible fix is to do it this
149 way. This initial local recursing function does the necessary.
150
151 Arguments:
152   node      tree node
153
154 Returns:    maximum depth below the node, including the node itself
155 */
156
157 static int
158 count_below(tree_node *node)
159 {
160 int nleft, nright;
161 if (node == NULL) return 0;
162 nleft = count_below(node->left);
163 nright = count_below(node->right);
164 node->balance = (nleft > nright)? 1 : ((nright > nleft)? 2 : 0);
165 return 1 + ((nleft > nright)? nleft : nright);
166 }
167
168 /* This is the real function...
169
170 Arguments:
171   connect      pointer to the root of the tree
172   f            FILE to read data from
173   buffer       contains next input line; further lines read into it
174   buffer_size  size of the buffer
175
176 Returns:       FALSE on format error
177 */
178
179 static BOOL
180 read_nonrecipients_tree(tree_node **connect, FILE *f, uschar *buffer,
181   int buffer_size)
182 {
183 tree_node *node;
184 int n = Ustrlen(buffer);
185 BOOL right = buffer[1] == 'Y';
186
187 if (n < 5) return FALSE;    /* malformed line */
188 buffer[n-1] = 0;            /* Remove \n */
189 node = store_get(sizeof(tree_node) + n - 3, TRUE);      /* rcpt names tainted */
190 *connect = node;
191 Ustrcpy(node->name, buffer + 3);
192 node->data.ptr = NULL;
193
194 if (buffer[0] == 'Y')
195   {
196   if (Ufgets(buffer, buffer_size, f) == NULL ||
197     !read_nonrecipients_tree(&node->left, f, buffer, buffer_size))
198       return FALSE;
199   }
200 else node->left = NULL;
201
202 if (right)
203   {
204   if (Ufgets(buffer, buffer_size, f) == NULL ||
205     !read_nonrecipients_tree(&node->right, f, buffer, buffer_size))
206       return FALSE;
207   }
208 else node->right = NULL;
209
210 (void) count_below(*connect);
211 return TRUE;
212 }
213
214
215
216
217 /* Reset all the global variables to their default values. However, there is
218 one exception. DO NOT change the default value of dont_deliver, because it may
219 be forced by an external setting. */
220
221 void
222 spool_clear_header_globals(void)
223 {
224 acl_var_c = acl_var_m = NULL;
225 authenticated_id = NULL;
226 authenticated_sender = NULL;
227 f.allow_unqualified_recipient = FALSE;
228 f.allow_unqualified_sender = FALSE;
229 body_linecount = 0;
230 body_zerocount = 0;
231 f.deliver_firsttime = FALSE;
232 f.deliver_freeze = FALSE;
233 deliver_frozen_at = 0;
234 f.deliver_manual_thaw = FALSE;
235 /* f.dont_deliver must NOT be reset */
236 header_list = header_last = NULL;
237 host_lookup_deferred = FALSE;
238 host_lookup_failed = FALSE;
239 interface_address = NULL;
240 interface_port = 0;
241 f.local_error_message = FALSE;
242 #ifdef HAVE_LOCAL_SCAN
243 local_scan_data = NULL;
244 #endif
245 max_received_linelength = 0;
246 message_linecount = 0;
247 received_protocol = NULL;
248 received_count = 0;
249 recipients_list = NULL;
250 sender_address = NULL;
251 sender_fullhost = NULL;
252 sender_helo_name = NULL;
253 sender_host_address = NULL;
254 sender_host_name = NULL;
255 sender_host_port = 0;
256 sender_host_authenticated = sender_host_auth_pubname = NULL;
257 sender_ident = NULL;
258 f.sender_local = FALSE;
259 f.sender_set_untrusted = FALSE;
260 smtp_active_hostname = primary_hostname;
261 #ifndef COMPILE_UTILITY
262 f.spool_file_wireformat = FALSE;
263 #endif
264 tree_nonrecipients = NULL;
265
266 #ifdef EXPERIMENTAL_BRIGHTMAIL
267 bmi_run = 0;
268 bmi_verdicts = NULL;
269 #endif
270
271 #ifndef DISABLE_DKIM
272 dkim_signers = NULL;
273 f.dkim_disable_verify = FALSE;
274 dkim_collect_input = 0;
275 #endif
276
277 #ifndef DISABLE_TLS
278 tls_in.certificate_verified = FALSE;
279 # ifdef SUPPORT_DANE
280 tls_in.dane_verified = FALSE;
281 # endif
282 tls_in.ver = tls_in.cipher = NULL;
283 # ifndef COMPILE_UTILITY        /* tls support fns not built in */
284 tls_free_cert(&tls_in.ourcert);
285 tls_free_cert(&tls_in.peercert);
286 # endif
287 tls_in.peerdn = NULL;
288 tls_in.sni = NULL;
289 tls_in.ocsp = OCSP_NOT_REQ;
290 #endif
291
292 #ifdef WITH_CONTENT_SCAN
293 spam_bar = NULL;
294 spam_score = NULL;
295 spam_score_int = NULL;
296 #endif
297
298 #if defined(SUPPORT_I18N) && !defined(COMPILE_UTILITY)
299 message_smtputf8 = FALSE;
300 message_utf8_downconvert = 0;
301 #endif
302
303 dsn_ret = 0;
304 dsn_envid = NULL;
305 }
306
307
308 /*************************************************
309 *             Read spool header file             *
310 *************************************************/
311
312 /* This function reads a spool header file and places the data into the
313 appropriate global variables. The header portion is always read, but header
314 structures are built only if read_headers is set true. It isn't, for example,
315 while generating -bp output.
316
317 It may be possible for blocks of nulls (binary zeroes) to get written on the
318 end of a file if there is a system crash during writing. It was observed on an
319 earlier version of Exim that omitted to fsync() the files - this is thought to
320 have been the cause of that incident, but in any case, this code must be robust
321 against such an event, and if such a file is encountered, it must be treated as
322 malformed.
323
324 As called from deliver_message() (at least) we are running as root.
325
326 Arguments:
327   name          name of the header file, including the -H
328   read_headers  TRUE if in-store header structures are to be built
329   subdir_set    TRUE is message_subdir is already set
330
331 Returns:        spool_read_OK        success
332                 spool_read_notopen   open failed
333                 spool_read_enverror  error in the envelope portion
334                 spool_read_hdrerror  error in the header portion
335 */
336
337 int
338 spool_read_header(uschar *name, BOOL read_headers, BOOL subdir_set)
339 {
340 FILE * fp = NULL;
341 int n;
342 int rcount = 0;
343 long int uid, gid;
344 BOOL inheader = FALSE;
345
346 /* Reset all the global variables to their default values. However, there is
347 one exception. DO NOT change the default value of dont_deliver, because it may
348 be forced by an external setting. */
349
350 spool_clear_header_globals();
351
352 /* Generate the full name and open the file. If message_subdir is already
353 set, just look in the given directory. Otherwise, look in both the split
354 and unsplit directories, as for the data file above. */
355
356 for (int n = 0; n < 2; n++)
357   {
358   if (!subdir_set)
359     set_subdir_str(message_subdir, name, n);
360
361   if ((fp = Ufopen(spool_fname(US"input", message_subdir, name, US""), "rb")))
362     break;
363   if (n != 0 || subdir_set || errno != ENOENT)
364     return spool_read_notopen;
365   }
366
367 errno = 0;
368
369 #ifndef COMPILE_UTILITY
370 DEBUG(D_deliver) debug_printf_indent("reading spool file %s\n", name);
371 #endif  /* COMPILE_UTILITY */
372
373 /* The first line of a spool file contains the message id followed by -H (i.e.
374 the file name), in order to make the file self-identifying. */
375
376 if (Ufgets(big_buffer, big_buffer_size, fp) == NULL) goto SPOOL_READ_ERROR;
377 if (Ustrlen(big_buffer) != MESSAGE_ID_LENGTH + 3 ||
378     Ustrncmp(big_buffer, name, MESSAGE_ID_LENGTH + 2) != 0)
379   goto SPOOL_FORMAT_ERROR;
380
381 /* The next three lines in the header file are in a fixed format. The first
382 contains the login, uid, and gid of the user who caused the file to be written.
383 There are known cases where a negative gid is used, so we allow for both
384 negative uids and gids. The second contains the mail address of the message's
385 sender, enclosed in <>. The third contains the time the message was received,
386 and the number of warning messages for delivery delays that have been sent. */
387
388 if (Ufgets(big_buffer, big_buffer_size, fp) == NULL) goto SPOOL_READ_ERROR;
389
390  {
391   uschar *p = big_buffer + Ustrlen(big_buffer);
392   while (p > big_buffer && isspace(p[-1])) p--;
393   *p = 0;
394   if (!isdigit(p[-1])) goto SPOOL_FORMAT_ERROR;
395   while (p > big_buffer && (isdigit(p[-1]) || '-' == p[-1])) p--;
396   gid = Uatoi(p);
397   if (p <= big_buffer || *(--p) != ' ') goto SPOOL_FORMAT_ERROR;
398   *p = 0;
399   if (!isdigit(p[-1])) goto SPOOL_FORMAT_ERROR;
400   while (p > big_buffer && (isdigit(p[-1]) || '-' == p[-1])) p--;
401   uid = Uatoi(p);
402   if (p <= big_buffer || *(--p) != ' ') goto SPOOL_FORMAT_ERROR;
403   *p = 0;
404  }
405
406 originator_login = string_copy(big_buffer);
407 originator_uid = (uid_t)uid;
408 originator_gid = (gid_t)gid;
409
410 /* envelope from */
411 if (Ufgets(big_buffer, big_buffer_size, fp) == NULL) goto SPOOL_READ_ERROR;
412 n = Ustrlen(big_buffer);
413 if (n < 3 || big_buffer[0] != '<' || big_buffer[n-2] != '>')
414   goto SPOOL_FORMAT_ERROR;
415
416 sender_address = store_get(n-2, TRUE);  /* tainted */
417 Ustrncpy(sender_address, big_buffer+1, n-3);
418 sender_address[n-3] = 0;
419
420 /* time */
421 if (Ufgets(big_buffer, big_buffer_size, fp) == NULL) goto SPOOL_READ_ERROR;
422 if (sscanf(CS big_buffer, TIME_T_FMT " %d", &received_time.tv_sec, &warning_count) != 2)
423   goto SPOOL_FORMAT_ERROR;
424 received_time.tv_usec = 0;
425 received_time_complete = received_time;
426
427
428 message_age = time(NULL) - received_time.tv_sec;
429 #ifndef COMPILE_UTILITY
430 if (f.running_in_test_harness)
431   message_age = test_harness_fudged_queue_time(message_age);
432 #endif
433
434 #ifndef COMPILE_UTILITY
435 DEBUG(D_deliver) debug_printf_indent("user=%s uid=%ld gid=%ld sender=%s\n",
436   originator_login, (long int)originator_uid, (long int)originator_gid,
437   sender_address);
438 #endif
439
440 /* Now there may be a number of optional lines, each starting with "-". If you
441 add a new setting here, make sure you set the default above.
442
443 Because there are now quite a number of different possibilities, we use a
444 switch on the first character to avoid too many failing tests. Thanks to Nico
445 Erfurth for the patch that implemented this. I have made it even more efficient
446 by not re-scanning the first two characters.
447
448 To allow new versions of Exim that add additional flags to interwork with older
449 versions that do not understand them, just ignore any lines starting with "-"
450 that we don't recognize. Otherwise it wouldn't be possible to back off a new
451 version that left new-style flags written on the spool.
452
453 If the line starts with "--" the content of the variable is tainted.  */
454
455 for (;;)
456   {
457   int len;
458   BOOL tainted;
459   uschar * var;
460   const uschar * p;
461
462   if (Ufgets(big_buffer, big_buffer_size, fp) == NULL) goto SPOOL_READ_ERROR;
463   if (big_buffer[0] != '-') break;
464   while (  (len = Ustrlen(big_buffer)) == big_buffer_size-1
465         && big_buffer[len-1] != '\n'
466         )
467     {   /* buffer not big enough for line; certs make this possible */
468     uschar * buf;
469     if (big_buffer_size >= BIG_BUFFER_SIZE*4) goto SPOOL_READ_ERROR;
470     buf = store_get_perm(big_buffer_size *= 2, FALSE);
471     memcpy(buf, big_buffer, len);
472     big_buffer = buf;
473     if (Ufgets(big_buffer+len, big_buffer_size-len, fp) == NULL)
474       goto SPOOL_READ_ERROR;
475     }
476   big_buffer[len-1] = 0;
477
478   tainted = big_buffer[1] == '-';
479   var =  big_buffer + (tainted ? 2 : 1);
480   p = var + 1;
481
482   switch(*var)
483     {
484     case 'a':
485
486     /* Nowadays we use "-aclc" and "-aclm" for the different types of ACL
487     variable, because Exim allows any number of them, with arbitrary names.
488     The line in the spool file is "-acl[cm] <name> <length>". The name excludes
489     the c or m. */
490
491     if (Ustrncmp(p, "clc ", 4) == 0 ||
492         Ustrncmp(p, "clm ", 4) == 0)
493       {
494       uschar *name, *endptr;
495       int count;
496       tree_node *node;
497       endptr = Ustrchr(var + 5, ' ');
498       if (endptr == NULL) goto SPOOL_FORMAT_ERROR;
499       name = string_sprintf("%c%.*s", var[3],
500         (int)(endptr - var - 5), var + 5);
501       if (sscanf(CS endptr, " %d", &count) != 1) goto SPOOL_FORMAT_ERROR;
502       node = acl_var_create(name);
503       node->data.ptr = store_get(count + 1, tainted);
504       if (fread(node->data.ptr, 1, count+1, fp) < count) goto SPOOL_READ_ERROR;
505       ((uschar*)node->data.ptr)[count] = 0;
506       }
507
508     else if (Ustrcmp(p, "llow_unqualified_recipient") == 0)
509       f.allow_unqualified_recipient = TRUE;
510     else if (Ustrcmp(p, "llow_unqualified_sender") == 0)
511       f.allow_unqualified_sender = TRUE;
512
513     else if (Ustrncmp(p, "uth_id", 6) == 0)
514       authenticated_id = string_copy_taint(var + 8, tainted);
515     else if (Ustrncmp(p, "uth_sender", 10) == 0)
516       authenticated_sender = string_copy_taint(var + 12, tainted);
517     else if (Ustrncmp(p, "ctive_hostname", 14) == 0)
518       smtp_active_hostname = string_copy_taint(var + 16, tainted);
519
520     /* For long-term backward compatibility, we recognize "-acl", which was
521     used before the number of ACL variables changed from 10 to 20. This was
522     before the subsequent change to an arbitrary number of named variables.
523     This code is retained so that upgrades from very old versions can still
524     handle old-format spool files. The value given after "-acl" is a number
525     that is 0-9 for connection variables, and 10-19 for message variables. */
526
527     else if (Ustrncmp(p, "cl ", 3) == 0)
528       {
529       unsigned index, count;
530       uschar name[20];   /* Need plenty of space for %u format */
531       tree_node * node;
532       if (  sscanf(CS var + 4, "%u %u", &index, &count) != 2
533          || index >= 20
534          || count > 16384       /* arbitrary limit on variable size */
535          )
536         goto SPOOL_FORMAT_ERROR;
537       if (index < 10)
538         (void) string_format(name, sizeof(name), "%c%u", 'c', index);
539       else
540         (void) string_format(name, sizeof(name), "%c%u", 'm', index - 10);
541       node = acl_var_create(name);
542       node->data.ptr = store_get(count + 1, tainted);
543       /* We sanity-checked the count, so disable the Coverity error */
544       /* coverity[tainted_data] */
545       if (fread(node->data.ptr, 1, count+1, fp) < count) goto SPOOL_READ_ERROR;
546       (US node->data.ptr)[count] = '\0';
547       }
548     break;
549
550     case 'b':
551     if (Ustrncmp(p, "ody_linecount", 13) == 0)
552       body_linecount = Uatoi(var + 14);
553     else if (Ustrncmp(p, "ody_zerocount", 13) == 0)
554       body_zerocount = Uatoi(var + 14);
555 #ifdef EXPERIMENTAL_BRIGHTMAIL
556     else if (Ustrncmp(p, "mi_verdicts ", 12) == 0)
557       bmi_verdicts = string_copy_taint(var + 13, tainted);
558 #endif
559     break;
560
561     case 'd':
562     if (Ustrcmp(p, "eliver_firsttime") == 0)
563       f.deliver_firsttime = TRUE;
564     /* Check if the dsn flags have been set in the header file */
565     else if (Ustrncmp(p, "sn_ret", 6) == 0)
566       dsn_ret= atoi(CS var + 7);
567     else if (Ustrncmp(p, "sn_envid", 8) == 0)
568       dsn_envid = string_copy_taint(var + 10, tainted);
569     break;
570
571     case 'f':
572     if (Ustrncmp(p, "rozen", 5) == 0)
573       {
574       f.deliver_freeze = TRUE;
575       if (sscanf(CS var+6, TIME_T_FMT, &deliver_frozen_at) != 1)
576         goto SPOOL_READ_ERROR;
577       }
578     break;
579
580     case 'h':
581     if (Ustrcmp(p, "ost_lookup_deferred") == 0)
582       host_lookup_deferred = TRUE;
583     else if (Ustrcmp(p, "ost_lookup_failed") == 0)
584       host_lookup_failed = TRUE;
585     else if (Ustrncmp(p, "ost_auth_pubname", 16) == 0)
586       sender_host_auth_pubname = string_copy_taint(var + 18, tainted);
587     else if (Ustrncmp(p, "ost_auth", 8) == 0)
588       sender_host_authenticated = string_copy_taint(var + 10, tainted);
589     else if (Ustrncmp(p, "ost_name", 8) == 0)
590       sender_host_name = string_copy_taint(var + 10, tainted);
591     else if (Ustrncmp(p, "elo_name", 8) == 0)
592       sender_helo_name = string_copy_taint(var + 10, tainted);
593
594     /* We now record the port number after the address, separated by a
595     dot. For compatibility during upgrading, do nothing if there
596     isn't a value (it gets left at zero). */
597
598     else if (Ustrncmp(p, "ost_address", 11) == 0)
599       {
600       sender_host_port = host_address_extract_port(var + 13);
601       sender_host_address = string_copy_taint(var + 13, tainted);
602       }
603     break;
604
605     case 'i':
606     if (Ustrncmp(p, "nterface_address", 16) == 0)
607       {
608       interface_port = host_address_extract_port(var + 18);
609       interface_address = string_copy_taint(var + 18, tainted);
610       }
611     else if (Ustrncmp(p, "dent", 4) == 0)
612       sender_ident = string_copy_taint(var + 6, tainted);
613     break;
614
615     case 'l':
616     if (Ustrcmp(p, "ocal") == 0)
617       f.sender_local = TRUE;
618     else if (Ustrcmp(var, "localerror") == 0)
619       f.local_error_message = TRUE;
620 #ifdef HAVE_LOCAL_SCAN
621     else if (Ustrncmp(p, "ocal_scan ", 10) == 0)
622       local_scan_data = string_copy_taint(var + 11, tainted);
623 #endif
624     break;
625
626     case 'm':
627     if (Ustrcmp(p, "anual_thaw") == 0)
628       f.deliver_manual_thaw = TRUE;
629     else if (Ustrncmp(p, "ax_received_linelength", 22) == 0)
630       max_received_linelength = Uatoi(var + 23);
631     break;
632
633     case 'N':
634     if (*p == 0) f.dont_deliver = TRUE;   /* -N */
635     break;
636
637     case 'r':
638     if (Ustrncmp(p, "eceived_protocol", 16) == 0)
639       received_protocol = string_copy_taint(var + 18, tainted);
640     else if (Ustrncmp(p, "eceived_time_usec", 17) == 0)
641       {
642       unsigned usec;
643       if (sscanf(CS var + 20, "%u", &usec) == 1)
644         {
645         received_time.tv_usec = usec;
646         if (!received_time_complete.tv_sec) received_time_complete.tv_usec = usec;
647         }
648       }
649     else if (Ustrncmp(p, "eceived_time_complete", 21) == 0)
650       {
651       unsigned sec, usec;
652       if (sscanf(CS var + 23, "%u.%u", &sec, &usec) == 2)
653         {
654         received_time_complete.tv_sec = sec;
655         received_time_complete.tv_usec = usec;
656         }
657       }
658     break;
659
660     case 's':
661     if (Ustrncmp(p, "ender_set_untrusted", 19) == 0)
662       f.sender_set_untrusted = TRUE;
663 #ifdef WITH_CONTENT_SCAN
664     else if (Ustrncmp(p, "pam_bar ", 8) == 0)
665       spam_bar = string_copy_taint(var + 9, tainted);
666     else if (Ustrncmp(p, "pam_score ", 10) == 0)
667       spam_score = string_copy_taint(var + 11, tainted);
668     else if (Ustrncmp(p, "pam_score_int ", 14) == 0)
669       spam_score_int = string_copy_taint(var + 15, tainted);
670 #endif
671 #ifndef COMPILE_UTILITY
672     else if (Ustrncmp(p, "pool_file_wireformat", 20) == 0)
673       f.spool_file_wireformat = TRUE;
674 #endif
675 #if defined(SUPPORT_I18N) && !defined(COMPILE_UTILITY)
676     else if (Ustrncmp(p, "mtputf8", 7) == 0)
677       message_smtputf8 = TRUE;
678 #endif
679     break;
680
681 #ifndef DISABLE_TLS
682     case 't':
683     if (Ustrncmp(p, "ls_", 3) == 0)
684       {
685       const uschar * q = p + 3;
686       if (Ustrncmp(q, "certificate_verified", 20) == 0)
687         tls_in.certificate_verified = TRUE;
688       else if (Ustrncmp(q, "cipher", 6) == 0)
689         tls_in.cipher = string_copy_taint(q+7, tainted);
690 # ifndef COMPILE_UTILITY        /* tls support fns not built in */
691       else if (Ustrncmp(q, "ourcert", 7) == 0)
692         (void) tls_import_cert(q+8, &tls_in.ourcert);
693       else if (Ustrncmp(q, "peercert", 8) == 0)
694         (void) tls_import_cert(q+9, &tls_in.peercert);
695 # endif
696       else if (Ustrncmp(q, "peerdn", 6) == 0)
697         tls_in.peerdn = string_unprinting(string_copy_taint(q+7, tainted));
698       else if (Ustrncmp(q, "sni", 3) == 0)
699         tls_in.sni = string_unprinting(string_copy_taint(q+4, tainted));
700       else if (Ustrncmp(q, "ocsp", 4) == 0)
701         tls_in.ocsp = q[5] - '0';
702 # ifndef DISABLE_TLS_RESUME
703       else if (Ustrncmp(q, "resumption", 10) == 0)
704         tls_in.resumption = q[11] - 'A';
705 # endif
706       else if (Ustrncmp(q, "ver", 3) == 0)
707         tls_in.ver = string_copy_taint(q+4, tainted);
708       }
709     break;
710 #endif
711
712 #if defined(SUPPORT_I18N) && !defined(COMPILE_UTILITY)
713     case 'u':
714     if (Ustrncmp(p, "tf8_downcvt", 11) == 0)
715       message_utf8_downconvert = 1;
716     else if (Ustrncmp(p, "tf8_optdowncvt", 15) == 0)
717       message_utf8_downconvert = -1;
718     break;
719 #endif
720
721     default:    /* Present because some compilers complain if all */
722     break;      /* possibilities are not covered. */
723     }
724   }
725
726 /* Build sender_fullhost if required */
727
728 #ifndef COMPILE_UTILITY
729 host_build_sender_fullhost();
730 #endif  /* COMPILE_UTILITY */
731
732 #ifndef COMPILE_UTILITY
733 DEBUG(D_deliver)
734   debug_printf_indent("sender_local=%d ident=%s\n", f.sender_local,
735     sender_ident ? sender_ident : US"unset");
736 #endif  /* COMPILE_UTILITY */
737
738 /* We now have the tree of addresses NOT to deliver to, or a line
739 containing "XX", indicating no tree. */
740
741 if (Ustrncmp(big_buffer, "XX\n", 3) != 0 &&
742   !read_nonrecipients_tree(&tree_nonrecipients, fp, big_buffer, big_buffer_size))
743     goto SPOOL_FORMAT_ERROR;
744
745 #ifndef COMPILE_UTILITY
746 DEBUG(D_deliver) debug_print_tree("Non-recipients", tree_nonrecipients);
747 #endif  /* COMPILE_UTILITY */
748
749 /* After reading the tree, the next line has not yet been read into the
750 buffer. It contains the count of recipients which follow on separate lines.
751 Apply an arbitrary sanity check.*/
752
753 if (Ufgets(big_buffer, big_buffer_size, fp) == NULL) goto SPOOL_READ_ERROR;
754 if (sscanf(CS big_buffer, "%d", &rcount) != 1 || rcount > 16384)
755   goto SPOOL_FORMAT_ERROR;
756
757 #ifndef COMPILE_UTILITY
758 DEBUG(D_deliver) debug_printf_indent("recipients_count=%d\n", rcount);
759 #endif  /* COMPILE_UTILITY */
760
761 recipients_list_max = rcount;
762 recipients_list = store_get(rcount * sizeof(recipient_item), FALSE);
763
764 /* We sanitised the count and know we have enough memory, so disable
765 the Coverity error on recipients_count */
766 /* coverity[tainted_data] */
767
768 for (recipients_count = 0; recipients_count < rcount; recipients_count++)
769   {
770   int nn;
771   int pno = -1;
772   int dsn_flags = 0;
773   uschar *orcpt = NULL;
774   uschar *errors_to = NULL;
775   uschar *p;
776
777   if (Ufgets(big_buffer, big_buffer_size, fp) == NULL) goto SPOOL_READ_ERROR;
778   nn = Ustrlen(big_buffer);
779   if (nn < 2) goto SPOOL_FORMAT_ERROR;
780
781   /* Remove the newline; this terminates the address if there is no additional
782   data on the line. */
783
784   p = big_buffer + nn - 1;
785   *p-- = 0;
786
787   /* Look back from the end of the line for digits and special terminators.
788   Since an address must end with a domain, we can tell that extra data is
789   present by the presence of the terminator, which is always some character
790   that cannot exist in a domain. (If I'd thought of the need for additional
791   data early on, I'd have put it at the start, with the address at the end. As
792   it is, we have to operate backwards. Addresses are permitted to contain
793   spaces, you see.)
794
795   This code has to cope with various versions of this data that have evolved
796   over time. In all cases, the line might just contain an address, with no
797   additional data. Otherwise, the possibilities are as follows:
798
799   Exim 3 type:       <address><space><digits>,<digits>,<digits>
800
801     The second set of digits is the parent number for one_time addresses. The
802     other values were remnants of earlier experiments that were abandoned.
803
804   Exim 4 first type: <address><space><digits>
805
806     The digits are the parent number for one_time addresses.
807
808   Exim 4 new type:   <address><space><data>#<type bits>
809
810     The type bits indicate what the contents of the data are.
811
812     Bit 01 indicates that, reading from right to left, the data
813       ends with <errors_to address><space><len>,<pno> where pno is
814       the parent number for one_time addresses, and len is the length
815       of the errors_to address (zero meaning none).
816
817     Bit 02 indicates that, again reading from right to left, the data continues
818      with orcpt len(orcpt),dsn_flags
819    */
820
821   while (isdigit(*p)) p--;
822
823   /* Handle Exim 3 spool files */
824
825   if (*p == ',')
826     {
827     int dummy;
828 #if !defined (COMPILE_UTILITY)
829     DEBUG(D_deliver) debug_printf_indent("**** SPOOL_IN - Exim 3 spool file\n");
830 #endif
831     while (isdigit(*(--p)) || *p == ',');
832     if (*p == ' ')
833       {
834       *p++ = 0;
835       (void)sscanf(CS p, "%d,%d", &dummy, &pno);
836       }
837     }
838
839   /* Handle early Exim 4 spool files */
840
841   else if (*p == ' ')
842     {
843 #if !defined (COMPILE_UTILITY)
844     DEBUG(D_deliver) debug_printf_indent("**** SPOOL_IN - early Exim 4 spool file\n");
845 #endif
846     *p++ = 0;
847     (void)sscanf(CS p, "%d", &pno);
848     }
849
850   /* Handle current format Exim 4 spool files */
851
852   else if (*p == '#')
853     {
854     int flags;
855
856 #if !defined (COMPILE_UTILITY)
857     DEBUG(D_deliver) debug_printf_indent("**** SPOOL_IN - Exim standard format spoolfile\n");
858 #endif
859
860     (void)sscanf(CS p+1, "%d", &flags);
861
862     if ((flags & 0x01) != 0)      /* one_time data exists */
863       {
864       int len;
865       while (isdigit(*(--p)) || *p == ',' || *p == '-');
866       (void)sscanf(CS p+1, "%d,%d", &len, &pno);
867       *p = 0;
868       if (len > 0)
869         {
870         p -= len;
871         errors_to = string_copy_taint(p, TRUE);
872         }
873       }
874
875     *(--p) = 0;   /* Terminate address */
876     if ((flags & 0x02) != 0)      /* one_time data exists */
877       {
878       int len;
879       while (isdigit(*(--p)) || *p == ',' || *p == '-');
880       (void)sscanf(CS p+1, "%d,%d", &len, &dsn_flags);
881       *p = 0;
882       if (len > 0)
883         {
884         p -= len;
885         orcpt = string_copy_taint(p, TRUE);
886         }
887       }
888
889     *(--p) = 0;   /* Terminate address */
890     }
891 #if !defined(COMPILE_UTILITY)
892   else
893     { DEBUG(D_deliver) debug_printf_indent("**** SPOOL_IN - No additional fields\n"); }
894
895   if (orcpt || dsn_flags)
896     DEBUG(D_deliver) debug_printf_indent("**** SPOOL_IN - address: <%s> orcpt: <%s> dsn_flags: 0x%x\n",
897       big_buffer, orcpt, dsn_flags);
898   if (errors_to)
899     DEBUG(D_deliver) debug_printf_indent("**** SPOOL_IN - address: <%s> errorsto: <%s>\n",
900       big_buffer, errors_to);
901 #endif
902
903   recipients_list[recipients_count].address = string_copy_taint(big_buffer, TRUE);
904   recipients_list[recipients_count].pno = pno;
905   recipients_list[recipients_count].errors_to = errors_to;
906   recipients_list[recipients_count].orcpt = orcpt;
907   recipients_list[recipients_count].dsn_flags = dsn_flags;
908   }
909
910 /* The remainder of the spool header file contains the headers for the message,
911 separated off from the previous data by a blank line. Each header is preceded
912 by a count of its length and either a certain letter (for various identified
913 headers), space (for a miscellaneous live header) or an asterisk (for a header
914 that has been rewritten). Count the Received: headers. We read the headers
915 always, in order to check on the format of the file, but only create a header
916 list if requested to do so. */
917
918 inheader = TRUE;
919 if (Ufgets(big_buffer, big_buffer_size, fp) == NULL) goto SPOOL_READ_ERROR;
920 if (big_buffer[0] != '\n') goto SPOOL_FORMAT_ERROR;
921
922 while ((n = fgetc(fp)) != EOF)
923   {
924   header_line *h;
925   uschar flag[4];
926   int i;
927
928   if (!isdigit(n)) goto SPOOL_FORMAT_ERROR;
929   if(ungetc(n, fp) == EOF  ||  fscanf(fp, "%d%c ", &n, flag) == EOF)
930     goto SPOOL_READ_ERROR;
931   if (flag[0] != '*') message_size += n;  /* Omit non-transmitted headers */
932
933   if (read_headers)
934     {
935     h = store_get(sizeof(header_line), FALSE);
936     h->next = NULL;
937     h->type = flag[0];
938     h->slen = n;
939     h->text = store_get(n+1, TRUE);     /* tainted */
940
941     if (h->type == htype_received) received_count++;
942
943     if (header_list) header_last->next = h;
944     else header_list = h;
945     header_last = h;
946
947     for (i = 0; i < n; i++)
948       {
949       int c = fgetc(fp);
950       if (c == 0 || c == EOF) goto SPOOL_FORMAT_ERROR;
951       if (c == '\n' && h->type != htype_old) message_linecount++;
952       h->text[i] = c;
953       }
954     h->text[i] = 0;
955     }
956
957   /* Not requiring header data, just skip through the bytes */
958
959   else for (i = 0; i < n; i++)
960     {
961     int c = fgetc(fp);
962     if (c == 0 || c == EOF) goto SPOOL_FORMAT_ERROR;
963     }
964   }
965
966 /* We have successfully read the data in the header file. Update the message
967 line count by adding the body linecount to the header linecount. Close the file
968 and give a positive response. */
969
970 #ifndef COMPILE_UTILITY
971 DEBUG(D_deliver) debug_printf_indent("body_linecount=%d message_linecount=%d\n",
972   body_linecount, message_linecount);
973 #endif  /* COMPILE_UTILITY */
974
975 message_linecount += body_linecount;
976
977 fclose(fp);
978 return spool_read_OK;
979
980
981 /* There was an error reading the spool or there was missing data,
982 or there was a format error. A "read error" with no errno means an
983 unexpected EOF, which we treat as a format error. */
984
985 SPOOL_READ_ERROR:
986 if (errno != 0)
987   {
988   n = errno;
989
990 #ifndef COMPILE_UTILITY
991   DEBUG(D_any) debug_printf("Error while reading spool file %s\n", name);
992 #endif  /* COMPILE_UTILITY */
993
994   fclose(fp);
995   errno = n;
996   return inheader ? spool_read_hdrerror : spool_read_enverror;
997   }
998
999 SPOOL_FORMAT_ERROR:
1000
1001 #ifndef COMPILE_UTILITY
1002 DEBUG(D_any) debug_printf("Format error in spool file %s\n", name);
1003 #endif  /* COMPILE_UTILITY */
1004
1005 fclose(fp);
1006 errno = ERRNO_SPOOLFORMAT;
1007 return inheader? spool_read_hdrerror : spool_read_enverror;
1008 }
1009
1010
1011 #ifndef COMPILE_UTILITY
1012 /* Read out just the (envelope) sender string from the spool -H file.
1013 Remove the <> wrap and return it in allocated store.  Return NULL on error.
1014
1015 We assume that message_subdir is already set.
1016 */
1017
1018 uschar *
1019 spool_sender_from_msgid(const uschar * id)
1020 {
1021 uschar * name = string_sprintf("%s-H", id);
1022 FILE * fp;
1023 int n;
1024 uschar * yield = NULL;
1025
1026 if (!(fp = Ufopen(spool_fname(US"input", message_subdir, name, US""), "rb")))
1027   return NULL;
1028
1029 DEBUG(D_deliver) debug_printf_indent("reading spool file %s\n", name);
1030
1031 /* Skip the line with the copy of the filename, then the line with login/uid/gid.
1032 Read the next line, which should be the envelope sender.
1033 Do basic validation on that. */
1034
1035 if (  Ufgets(big_buffer, big_buffer_size, fp) != NULL
1036    && Ufgets(big_buffer, big_buffer_size, fp) != NULL
1037    && Ufgets(big_buffer, big_buffer_size, fp) != NULL
1038    && (n = Ustrlen(big_buffer)) >= 3
1039    && big_buffer[0] == '<' && big_buffer[n-2] == '>'
1040    )
1041   {
1042   yield = store_get(n-2, TRUE); /* tainted */
1043   Ustrncpy(yield, big_buffer+1, n-3);
1044   yield[n-3] = 0;
1045   }
1046 fclose(fp);
1047 return yield;
1048 }
1049 #endif  /* COMPILE_UTILITY */
1050
1051 /* vi: aw ai sw=2
1052 */
1053 /* End of spool_in.c */