Appendfile: release regex-match store every thousand files. Bug 3047
[exim.git] / src / src / transports / appendfile.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 - 2020 */
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 #include "appendfile.h"
13
14 #ifdef SUPPORT_MAILDIR
15 #include "tf_maildir.h"
16 #endif
17
18
19 /* Options specific to the appendfile transport. They must be in alphabetic
20 order (note that "_" comes before the lower case letters). Some of them are
21 stored in the publicly visible instance block - these are flagged with the
22 opt_public flag. */
23 #define LOFF(field) OPT_OFF(appendfile_transport_options_block, field)
24
25 optionlist appendfile_transport_options[] = {
26 #ifdef SUPPORT_MAILDIR
27   { "*expand_maildir_use_size_file", opt_stringptr, LOFF(expand_maildir_use_size_file) },
28 #endif
29   { "*set_use_fcntl_lock",opt_bool | opt_hidden, LOFF(set_use_fcntl) },
30   { "*set_use_flock_lock",opt_bool | opt_hidden, LOFF(set_use_flock) },
31   { "*set_use_lockfile", opt_bool | opt_hidden, LOFF(set_use_lockfile) },
32 #ifdef SUPPORT_MBX
33   { "*set_use_mbx_lock", opt_bool | opt_hidden, LOFF(set_use_mbx_lock) },
34 #endif
35   { "allow_fifo",        opt_bool,      LOFF(allow_fifo) },
36   { "allow_symlink",     opt_bool,      LOFF(allow_symlink) },
37   { "batch_id",          opt_stringptr | opt_public, OPT_OFF(transport_instance, batch_id) },
38   { "batch_max",         opt_int | opt_public, OPT_OFF(transport_instance, batch_max) },
39   { "check_group",       opt_bool,      LOFF(check_group) },
40   { "check_owner",       opt_bool,      LOFF(check_owner) },
41   { "check_string",      opt_stringptr, LOFF(check_string) },
42   { "create_directory",  opt_bool,      LOFF(create_directory) },
43   { "create_file",       opt_stringptr, LOFF(create_file_string) },
44   { "directory",         opt_stringptr, LOFF(dirname) },
45   { "directory_file",    opt_stringptr, LOFF(dirfilename) },
46   { "directory_mode",    opt_octint,    LOFF(dirmode) },
47   { "escape_string",     opt_stringptr, LOFF(escape_string) },
48   { "file",              opt_stringptr, LOFF(filename) },
49   { "file_format",       opt_stringptr, LOFF(file_format) },
50   { "file_must_exist",   opt_bool,      LOFF(file_must_exist) },
51   { "lock_fcntl_timeout", opt_time,     LOFF(lock_fcntl_timeout) },
52   { "lock_flock_timeout", opt_time,     LOFF(lock_flock_timeout) },
53   { "lock_interval",     opt_time,      LOFF(lock_interval) },
54   { "lock_retries",      opt_int,       LOFF(lock_retries) },
55   { "lockfile_mode",     opt_octint,    LOFF(lockfile_mode) },
56   { "lockfile_timeout",  opt_time,      LOFF(lockfile_timeout) },
57   { "mailbox_filecount", opt_stringptr, LOFF(mailbox_filecount_string) },
58   { "mailbox_size",      opt_stringptr, LOFF(mailbox_size_string) },
59 #ifdef SUPPORT_MAILDIR
60   { "maildir_format",    opt_bool,      LOFF(maildir_format ) } ,
61   { "maildir_quota_directory_regex", opt_stringptr, LOFF(maildir_dir_regex) },
62   { "maildir_retries",   opt_int,       LOFF(maildir_retries) },
63   { "maildir_tag",       opt_stringptr, LOFF(maildir_tag) },
64   { "maildir_use_size_file", opt_expand_bool, LOFF(maildir_use_size_file ) } ,
65   { "maildirfolder_create_regex", opt_stringptr, LOFF(maildirfolder_create_regex ) },
66 #endif  /* SUPPORT_MAILDIR */
67 #ifdef SUPPORT_MAILSTORE
68   { "mailstore_format",  opt_bool,      LOFF(mailstore_format ) },
69   { "mailstore_prefix",  opt_stringptr, LOFF(mailstore_prefix ) },
70   { "mailstore_suffix",  opt_stringptr, LOFF(mailstore_suffix ) },
71 #endif  /* SUPPORT_MAILSTORE */
72 #ifdef SUPPORT_MBX
73   { "mbx_format",        opt_bool,      LOFF(mbx_format ) } ,
74 #endif  /* SUPPORT_MBX */
75   { "message_prefix",    opt_stringptr, LOFF(message_prefix) },
76   { "message_suffix",    opt_stringptr, LOFF(message_suffix) },
77   { "mode",              opt_octint,    LOFF(mode) },
78   { "mode_fail_narrower",opt_bool,      LOFF(mode_fail_narrower) },
79   { "notify_comsat",     opt_bool,      LOFF(notify_comsat) },
80   { "quota",             opt_stringptr, LOFF(quota) },
81   { "quota_directory",   opt_stringptr, LOFF(quota_directory) },
82   { "quota_filecount",   opt_stringptr, LOFF(quota_filecount) },
83   { "quota_is_inclusive", opt_bool,     LOFF(quota_is_inclusive) },
84   { "quota_size_regex",   opt_stringptr, LOFF(quota_size_regex) },
85   { "quota_warn_message", opt_stringptr | opt_public, OPT_OFF(transport_instance, warn_message) },
86   { "quota_warn_threshold", opt_stringptr, LOFF(quota_warn_threshold) },
87   { "use_bsmtp",         opt_bool,      LOFF(use_bsmtp) },
88   { "use_crlf",          opt_bool,      LOFF(use_crlf) },
89   { "use_fcntl_lock",    opt_bool_set,  LOFF(use_fcntl) },
90   { "use_flock_lock",    opt_bool_set,  LOFF(use_flock) },
91   { "use_lockfile",      opt_bool_set,  LOFF(use_lockfile) },
92 #ifdef SUPPORT_MBX
93   { "use_mbx_lock",      opt_bool_set,  LOFF(use_mbx_lock) },
94 #endif  /* SUPPORT_MBX */
95 };
96
97 /* Size of the options list. An extern variable has to be used so that its
98 address can appear in the tables drtables.c. */
99
100 int appendfile_transport_options_count =
101   sizeof(appendfile_transport_options)/sizeof(optionlist);
102
103
104 #ifdef MACRO_PREDEF
105
106 /* Dummy values */
107 appendfile_transport_options_block appendfile_transport_option_defaults = {0};
108 void appendfile_transport_init(transport_instance *tblock) {}
109 BOOL appendfile_transport_entry(transport_instance *tblock, address_item *addr) {return FALSE;}
110
111 #else   /*!MACRO_PREDEF*/
112
113 /* Default private options block for the appendfile transport. */
114
115 appendfile_transport_options_block appendfile_transport_option_defaults = {
116   /* all non-mentioned members zero/null/false */
117   .dirfilename = US"q${base62:$tod_epoch}-$inode",
118   .create_file_string = US"anywhere",
119   .maildir_dir_regex = US"^(?:cur|new|\\..*)$",
120   .mailbox_size_value = -1,
121   .mailbox_filecount_value = -1,
122   .mode = APPENDFILE_MODE,
123   .dirmode = APPENDFILE_DIRECTORY_MODE,
124   .lockfile_mode = APPENDFILE_LOCKFILE_MODE,
125   .lockfile_timeout = 30*60,
126   .lock_retries = 10,
127    .lock_interval = 3,
128   .maildir_retries = 10,
129   .create_file = create_anywhere,
130   .check_owner = TRUE,
131   .create_directory = TRUE,
132   .notify_comsat = FALSE,
133   .use_lockfile = TRUE,
134   .use_fcntl = TRUE,
135   .mode_fail_narrower = TRUE,
136   .quota_is_inclusive = TRUE,
137 };
138
139
140 /* Encodings for mailbox formats, and their names. MBX format is actually
141 supported only if SUPPORT_MBX is set. */
142
143 enum { mbf_unix, mbf_mbx, mbf_smail, mbf_maildir, mbf_mailstore };
144
145 static const char *mailbox_formats[] = {
146   "unix", "mbx", "smail", "maildir", "mailstore" };
147
148
149 /* Check warn threshold only if quota size set or not a percentage threshold
150    percentage check should only be done if quota > 0 */
151
152 #define THRESHOLD_CHECK  (ob->quota_warn_threshold_value > 0 && \
153   (!ob->quota_warn_threshold_is_percent || ob->quota_value > 0))
154
155
156 /* Free memory allocated by PCRE2 every so often, because a recent version
157 is now using 20kB for every match call */
158
159 #define RESET_STORE_FILECNT     1000
160
161 /*************************************************
162 *              Setup entry point                 *
163 *************************************************/
164
165 /* Called for each delivery in the privileged state, just before the uid/gid
166 are changed and the main entry point is called. We use this function to
167 expand any quota settings, so that it can access files that may not be readable
168 by the user. It is also used to pick up external mailbox size information, if
169 set.
170
171 Arguments:
172   tblock     points to the transport instance
173   addrlist   addresses about to be delivered (not used)
174   dummy      not used (doesn't pass back data)
175   uid        the uid that will be set (not used)
176   gid        the gid that will be set (not used)
177   errmsg     where to put an error message
178
179 Returns:     OK, FAIL, or DEFER
180 */
181
182 static int
183 appendfile_transport_setup(transport_instance *tblock, address_item *addrlist,
184   transport_feedback *dummy, uid_t uid, gid_t gid, uschar **errmsg)
185 {
186 appendfile_transport_options_block *ob =
187   (appendfile_transport_options_block *)(tblock->options_block);
188 uschar *q = ob->quota;
189 double default_value = 0.0;
190
191 if (ob->expand_maildir_use_size_file)
192         ob->maildir_use_size_file = expand_check_condition(ob->expand_maildir_use_size_file,
193                 US"`maildir_use_size_file` in transport", tblock->name);
194
195 /* Loop for quota, quota_filecount, quota_warn_threshold, mailbox_size,
196 mailbox_filecount */
197
198 for (int i = 0; i < 5; i++)
199   {
200   double d = default_value;
201   int no_check = 0;
202   uschar *which = NULL;
203
204   if (q)
205     {
206     uschar * rest, * s;
207
208     if (!(s =  expand_string(q)))
209       {
210       *errmsg = string_sprintf("Expansion of \"%s\" in %s transport failed: "
211         "%s", q, tblock->name, expand_string_message);
212       return f.search_find_defer ? DEFER : FAIL;
213       }
214
215     d = Ustrtod(s, &rest);
216
217     /* Handle following characters K, M, G, %, the latter being permitted
218     for quota_warn_threshold only. A threshold with no quota setting is
219     just ignored. */
220
221     if (tolower(*rest) == 'k') { d *= 1024.0; rest++; }
222     else if (tolower(*rest) == 'm') { d *= 1024.0*1024.0; rest++; }
223     else if (tolower(*rest) == 'g') { d *= 1024.0*1024.0*1024.0; rest++; }
224     else if (*rest == '%' && i == 2)
225       {
226       if (ob->quota_value <= 0 && !ob->maildir_use_size_file)
227         d = 0;
228       else if ((int)d < 0 || (int)d > 100)
229         {
230         *errmsg = string_sprintf("Invalid quota_warn_threshold percentage (%d)"
231           " for %s transport", (int)d, tblock->name);
232         return FAIL;
233         }
234       ob->quota_warn_threshold_is_percent = TRUE;
235       rest++;
236       }
237
238
239     /* For quota and quota_filecount there may be options
240     appended. Currently only "no_check", so we can be lazy parsing it */
241     if (i < 2 && Ustrstr(rest, "/no_check") == rest)
242       {
243        no_check = 1;
244        rest += sizeof("/no_check") - 1;
245       }
246
247     Uskip_whitespace(&rest);
248
249     if (*rest)
250       {
251       *errmsg = string_sprintf("Malformed value \"%s\" (expansion of \"%s\") "
252         "in %s transport", s, q, tblock->name);
253       return FAIL;
254       }
255     }
256
257   /* Set each value, checking for possible overflow. */
258
259   switch (i)
260     {
261     case 0:
262       if (d >= 2.0*1024.0*1024.0*1024.0 && sizeof(off_t) <= 4)
263         which = US"quota";
264       ob->quota_value = (off_t)d;
265       ob->quota_no_check = no_check;
266       q = ob->quota_filecount;
267       break;
268
269     case 1:
270       if (d >= 2.0*1024.0*1024.0*1024.0)
271         which = US"quota_filecount";
272       ob->quota_filecount_value = (int)d;
273       ob->quota_filecount_no_check = no_check;
274       q = ob->quota_warn_threshold;
275       break;
276
277     case 2:
278       if (d >= 2.0*1024.0*1024.0*1024.0 && sizeof(off_t) <= 4)
279           which = US"quota_warn_threshold";
280       ob->quota_warn_threshold_value = (off_t)d;
281       q = ob->mailbox_size_string;
282       default_value = -1.0;
283       break;
284
285     case 3:
286       if (d >= 2.0*1024.0*1024.0*1024.0 && sizeof(off_t) <= 4)
287         which = US"mailbox_size";;
288       ob->mailbox_size_value = (off_t)d;
289       q = ob->mailbox_filecount_string;
290       break;
291
292     case 4:
293       if (d >= 2.0*1024.0*1024.0*1024.0)
294         which = US"mailbox_filecount";
295       ob->mailbox_filecount_value = (int)d;
296       break;
297     }
298
299   if (which)
300     {
301     *errmsg = string_sprintf("%s value %.10g is too large (overflow) in "
302       "%s transport", which, d, tblock->name);
303     return FAIL;
304     }
305   }
306
307 return OK;
308 }
309
310
311
312 /*************************************************
313 *          Initialization entry point            *
314 *************************************************/
315
316 /* Called for each instance, after its options have been read, to
317 enable consistency checks to be done, or anything else that needs
318 to be set up. */
319
320 void
321 appendfile_transport_init(transport_instance *tblock)
322 {
323 appendfile_transport_options_block *ob =
324   (appendfile_transport_options_block *)(tblock->options_block);
325 uschar * s;
326
327 /* Set up the setup entry point, to be called in the privileged state */
328
329 tblock->setup = appendfile_transport_setup;
330
331 /* Lock_retries must be greater than zero */
332
333 if (ob->lock_retries == 0) ob->lock_retries = 1;
334
335 /* Only one of a file name or directory name must be given. */
336
337 if (ob->filename && ob->dirname)
338   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s transport:\n  "
339   "only one of \"file\" or \"directory\" can be specified", tblock->name);
340
341 /* If a file name was specified, neither quota_filecount nor quota_directory
342 must be given. */
343
344 if (ob->filename)
345   {
346   if (ob->quota_filecount)
347     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s transport:\n  "
348       "quota_filecount must not be set without \"directory\"", tblock->name);
349   if (ob->quota_directory)
350     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s transport:\n  "
351       "quota_directory must not be set without \"directory\"", tblock->name);
352   }
353
354 /* The default locking depends on whether MBX is set or not. Change the
355 built-in default if none of the lock options has been explicitly set. At least
356 one form of locking is required in all cases, but mbx locking changes the
357 meaning of fcntl and flock locking. */
358
359 /* Not all operating systems provide flock(). For those that do, if flock is
360 requested, the default for fcntl is FALSE. */
361
362 if (ob->use_flock)
363   {
364   #ifdef NO_FLOCK
365   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s transport:\n  "
366     "flock() support was not available in the operating system when this "
367     "binary was built", tblock->name);
368   #endif  /* NO_FLOCK */
369   if (!ob->set_use_fcntl) ob->use_fcntl = FALSE;
370   }
371
372 #ifdef SUPPORT_MBX
373 if (ob->mbx_format)
374   if (!ob->set_use_lockfile && !ob->set_use_fcntl && !ob->set_use_flock &&
375       !ob->set_use_mbx_lock)
376     {
377     ob->use_lockfile = ob->use_flock = FALSE;
378     ob->use_mbx_lock = ob->use_fcntl = TRUE;
379     }
380   else if (ob->use_mbx_lock)
381     {
382     if (!ob->set_use_lockfile) ob->use_lockfile = FALSE;
383     if (!ob->set_use_fcntl) ob->use_fcntl = FALSE;
384     if (!ob->set_use_flock) ob->use_flock = FALSE;
385     if (!ob->use_fcntl && !ob->use_flock) ob->use_fcntl = TRUE;
386     }
387 #endif  /* SUPPORT_MBX */
388
389 if (!ob->use_fcntl && !ob->use_flock && !ob->use_lockfile && !ob->use_mbx_lock)
390   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s transport:\n  "
391     "no locking configured", tblock->name);
392
393 /* Unset timeouts for non-used locking types */
394
395 if (!ob->use_fcntl) ob->lock_fcntl_timeout = 0;
396 if (!ob->use_flock) ob->lock_flock_timeout = 0;
397
398 /* If a directory name was specified, only one of maildir or mailstore may be
399 specified, and if quota_filecount or quota_directory is given, quota must
400 be set. */
401
402 if (ob->dirname)
403   {
404   if (ob->maildir_format && ob->mailstore_format)
405     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s transport:\n  "
406       "only one of maildir and mailstore may be specified", tblock->name);
407   if (ob->quota_filecount != NULL && ob->quota == NULL)
408     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s transport:\n  "
409       "quota must be set if quota_filecount is set", tblock->name);
410   if (ob->quota_directory != NULL && ob->quota == NULL)
411     log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s transport:\n  "
412       "quota must be set if quota_directory is set", tblock->name);
413   }
414
415 /* If a fixed uid field is set, then a gid field must also be set. */
416
417 if (tblock->uid_set && !tblock->gid_set && !tblock->expand_gid)
418   log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
419     "user set without group for the %s transport", tblock->name);
420
421 /* If "create_file" is set, check that a valid option is given, and set the
422 integer variable. */
423
424 if ((s = ob->create_file_string ) && *s)
425   {
426   int val = 0;
427   if (Ustrcmp(s, "anywhere") == 0)                      val = create_anywhere;
428   else if (*s == '/' || Ustrcmp(s, "belowhome") == 0)   val = create_belowhome;
429   else if (Ustrcmp(s, "inhome") == 0)                   val = create_inhome;
430   else
431     log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
432       "invalid value given for \"create_file\" for the %s transport: '%s'",
433       tblock->name, s);
434   ob->create_file = val;
435   }
436
437 /* If quota_warn_threshold is set, set up default for warn_message. It may
438 not be used if the actual threshold for a given delivery ends up as zero,
439 of if it's given as a percentage and there's no quota setting. */
440
441 if (ob->quota_warn_threshold)
442   {
443   if (!tblock->warn_message) tblock->warn_message = US
444     "To: $local_part@$domain\n"
445     "Subject: Your mailbox\n\n"
446     "This message is automatically created by mail delivery software (Exim).\n\n"
447     "The size of your mailbox has exceeded a warning threshold that is\n"
448     "set by the system administrator.\n";
449   }
450
451 /* If batch SMTP is set, force the check and escape strings, and arrange that
452 headers are also escaped. */
453
454 if (ob->use_bsmtp)
455   {
456   ob->check_string = US".";
457   ob->escape_string = US"..";
458   ob->options |= topt_escape_headers;
459   }
460
461 /* If not batch SMTP, not maildir, not mailstore, and directory is not set,
462 insert default values for for the affixes and the check/escape strings. */
463
464 else if (!ob->dirname && !ob->maildir_format && !ob->mailstore_format)
465   {
466   if (!ob->message_prefix) ob->message_prefix =
467     US"From ${if def:return_path{$return_path}{MAILER-DAEMON}} ${tod_bsdinbox}\n";
468   if (!ob->message_suffix) ob->message_suffix = US"\n";
469   if (!ob->check_string) ob->check_string = US"From ";
470   if (!ob->escape_string) ob->escape_string = US">From ";
471
472   }
473
474 /* Set up the bitwise options for transport_write_message from the various
475 driver options. Only one of body_only and headers_only can be set. */
476
477 ob->options |=
478   (tblock->body_only ? topt_no_headers : 0) |
479   (tblock->headers_only ? topt_no_body : 0) |
480   (tblock->return_path_add ? topt_add_return_path : 0) |
481   (tblock->delivery_date_add ? topt_add_delivery_date : 0) |
482   (tblock->envelope_to_add ? topt_add_envelope_to : 0) |
483   ((ob->use_crlf || ob->mbx_format) ? topt_use_crlf : 0);
484 }
485
486
487
488 /*************************************************
489 *                  Notify comsat                 *
490 *************************************************/
491
492 /* The comsat daemon is the thing that provides asynchronous notification of
493 the arrival of local messages, if requested by the user by "biff y". It is a
494 BSD thing that uses a TCP/IP protocol for communication. A message consisting
495 of the text "user@offset" must be sent, where offset is the place in the
496 mailbox where new mail starts. There is no scope for telling it which file to
497 look at, which makes it a less than useful if mail is being delivered into a
498 non-standard place such as the user's home directory. In fact, it doesn't seem
499 to pay much attention to the offset.
500
501 Arguments:
502   user       user name
503   offset     offset in mailbox
504
505 Returns:     nothing
506 */
507
508 static void
509 notify_comsat(const uschar * user, off_t offset)
510 {
511 struct servent *sp;
512 host_item host;
513 uschar * s;
514
515 DEBUG(D_transport) debug_printf("notify_comsat called\n");
516
517 s = string_sprintf("%.200s@" OFF_T_FMT "\n", user, offset);
518
519 if ((sp = getservbyname("biff", "udp")) == NULL)
520   {
521   DEBUG(D_transport) debug_printf("biff/udp is an unknown service");
522   return;
523   }
524
525 host.name = US"localhost";
526 host.next = NULL;
527
528
529 /* This code is all set up to look up "localhost" and use all its addresses
530 until one succeeds. However, it appears that at least on some systems, comsat
531 doesn't listen on the ::1 address. So for the moment, just force the address to
532 be 127.0.0.1. At some future stage, when IPv6 really is superseding IPv4, this
533 can be changed. (But actually, comsat is probably dying out anyway.) */
534
535 /******
536 if (host_find_byname(&host, NULL, 0, NULL, FALSE) == HOST_FIND_FAILED)
537   {
538   DEBUG(D_transport) debug_printf("\"localhost\" unknown\n");
539   return;
540   }
541 ******/
542
543 host.address = US"127.0.0.1";
544
545
546 for (host_item * h = &host; h; h = h->next)
547   {
548   int sock, rc;
549   int host_af = Ustrchr(h->address, ':') != NULL ? AF_INET6 : AF_INET;
550
551   DEBUG(D_transport) debug_printf("calling comsat on %s\n", h->address);
552
553   if ((sock = ip_socket(SOCK_DGRAM, host_af)) < 0) continue;
554
555   /* Connect never fails for a UDP socket, so don't set a timeout. */
556
557   (void)ip_connect(sock, host_af, h->address, ntohs(sp->s_port), 0, NULL);
558   rc = send(sock, s, Ustrlen(s) + 1, 0);
559   (void)close(sock);
560
561   if (rc >= 0) break;
562   DEBUG(D_transport)
563     debug_printf("send to comsat failed for %s: %s\n", strerror(errno),
564       h->address);
565   }
566 }
567
568
569
570 /*************************************************
571 *     Check the format of a file                 *
572 *************************************************/
573
574 /* This function is called when file_format is set, to check that an existing
575 file has the right format. The format string contains text/transport pairs. The
576 string matching is literal. we just read big_buffer_size bytes, because this is
577 all about the first few bytes of a file.
578
579 Arguments:
580   cfd          the open file
581   tblock       the transport block
582   addr         the address block - for inserting error data
583
584 Returns:       pointer to the required transport, or NULL
585 */
586
587 transport_instance *
588 check_file_format(int cfd, transport_instance *tblock, address_item *addr)
589 {
590 const uschar *format =
591   ((appendfile_transport_options_block *)(tblock->options_block))->file_format;
592 uschar data[256];
593 int len = read(cfd, data, sizeof(data));
594 int sep = 0;
595 uschar *s;
596
597 DEBUG(D_transport) debug_printf("checking file format\n");
598
599 /* An empty file matches the current transport */
600
601 if (len == 0) return tblock;
602
603 /* Search the formats for a match */
604
605 /* not expanded so cannot be tainted */
606 while ((s = string_nextinlist(&format, &sep, big_buffer, big_buffer_size)))
607   {
608   int slen = Ustrlen(s);
609   BOOL match = len >= slen && Ustrncmp(data, s, slen) == 0;
610   uschar *tp = string_nextinlist(&format, &sep, big_buffer, big_buffer_size);
611
612   if (match && tp)
613     {
614     for (transport_instance * tt = transports; tt; tt = tt->next)
615       if (Ustrcmp(tp, tt->name) == 0)
616         {
617         DEBUG(D_transport)
618           debug_printf("file format -> %s transport\n", tt->name);
619         return tt;
620         }
621     addr->basic_errno = ERRNO_BADTRANSPORT;
622     addr->message = string_sprintf("%s transport (for %.*s format) not found",
623       tp, slen, data);
624     return NULL;
625     }
626   }
627
628 /* Failed to find a match */
629
630 addr->basic_errno = ERRNO_FORMATUNKNOWN;
631 addr->message = US"mailbox file format unrecognized";
632 return NULL;
633 }
634
635
636
637
638 /*************************************************
639 *       Check directory's files for quota        *
640 *************************************************/
641
642 /* This function is called if quota is set for one of the delivery modes that
643 delivers into a specific directory. It scans the directory and stats all the
644 files in order to get a total size and count. This is an expensive thing to do,
645 but some people are prepared to bear the cost. Alternatively, if size_regex is
646 set, it is used as a regex to try to extract the size from the file name, a
647 strategy that some people use on maildir files on systems where the users have
648 no shell access.
649
650 The function is global, because it is also called from tf_maildir.c for maildir
651 folders (which should contain only regular files).
652
653 Note: Any problems can be written to debugging output, but cannot be written to
654 the log, because we are running as an unprivileged user here.
655
656 Arguments:
657   dirname       the name of the directory
658   countptr      where to add the file count (because this function recurses)
659   re            a compiled regex to get the size from a name
660
661 Returns:        the sum of the sizes of the stattable files
662                 zero if the directory cannot be opened
663 */
664
665 off_t
666 check_dir_size(const uschar * dirname, int * countptr, const pcre2_code * re)
667 {
668 DIR * dir;
669 off_t sum = 0;
670 int count = *countptr, lcount = RESET_STORE_FILECNT;
671 rmark reset_point = store_mark();
672
673 if (!(dir = exim_opendir(dirname))) return 0;
674
675 for (struct dirent * ent; ent = readdir(dir); )
676   {
677   uschar * path, * name = US ent->d_name;
678   struct stat statbuf;
679
680   if (Ustrcmp(name, ".") == 0 || Ustrcmp(name, "..") == 0) continue;
681
682   count++;
683   if (--lcount == 0)
684     {
685     store_reset(reset_point); reset_point = store_mark();
686     lcount = RESET_STORE_FILECNT;
687     }
688
689   /* If there's a regex, try to find the size using it */
690
691   if (re)
692     {
693     pcre2_match_data * md = pcre2_match_data_create(2, pcre_gen_ctx);
694     int rc = pcre2_match(re, (PCRE2_SPTR)name, PCRE2_ZERO_TERMINATED,
695                           0, 0, md, pcre_gen_mtc_ctx);
696     PCRE2_SIZE * ovec = pcre2_get_ovector_pointer(md);
697     if (  rc >= 0
698        && (rc = pcre2_get_ovector_count(md)) >= 2)
699       {
700       uschar *endptr;
701       off_t size = (off_t)Ustrtod(name + ovec[2], &endptr);
702       if (endptr == name + ovec[3])
703         {
704         sum += size;
705         DEBUG(D_transport)
706           debug_printf("check_dir_size: size from %s is " OFF_T_FMT "\n", name,
707             size);
708         /* pcre2_match_data_free(md);   gen ctx needs no free */
709         continue;
710         }
711       }
712     /* pcre2_match_data_free(md);       gen ctx needs no free */
713     DEBUG(D_transport)
714       debug_printf("check_dir_size: regex did not match %s\n", name);
715     }
716
717   /* No regex or no match for the regex, or captured non-digits */
718
719   path = string_sprintf("%s/%s", dirname, name);
720
721   if (Ustat(path, &statbuf) < 0)
722     {
723     DEBUG(D_transport)
724       debug_printf("check_dir_size: stat error %d for %s: %s\n", errno, path,
725         strerror(errno));
726     }
727   else
728     if ((statbuf.st_mode & S_IFMT) == S_IFREG)
729       sum += statbuf.st_size / statbuf.st_nlink;
730     else if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
731       sum += check_dir_size(path, &count, re);
732   }
733
734 closedir(dir);
735 DEBUG(D_transport)
736   debug_printf("check_dir_size: dir=%s sum=" OFF_T_FMT " count=%d\n", dirname,
737     sum, count);
738
739 store_reset(reset_point);
740 *countptr = count;
741 return sum;
742 }
743
744
745
746
747 /*************************************************
748 *         Apply a lock to a file descriptor      *
749 *************************************************/
750
751 /* This function applies a lock to a file descriptor, using a blocking or
752 non-blocking lock, depending on the timeout value. It can apply either or
753 both of a fcntl() and a flock() lock. However, not all OS support flock();
754 for those that don't, the use_flock option cannot be set.
755
756 Arguments:
757   fd          the file descriptor
758   fcntltype   type of lock, specified as F_WRLCK or F_RDLCK (that is, in
759                 fcntl() format); the flock() type is deduced if needed
760   dofcntl     do fcntl() locking
761   fcntltime   non-zero to use blocking fcntl()
762   doflock     do flock() locking
763   flocktime   non-zero to use blocking flock()
764
765 Returns:      yield of the fcntl() or flock() call, with errno preserved;
766               sigalrm_seen set if there has been a timeout
767 */
768
769 static int
770 apply_lock(int fd, int fcntltype, BOOL dofcntl, int fcntltime, BOOL doflock,
771     int flocktime)
772 {
773 int yield = 0;
774 int save_errno;
775 struct flock lock_data;
776 lock_data.l_type = fcntltype;
777 lock_data.l_whence = lock_data.l_start = lock_data.l_len = 0;
778
779 sigalrm_seen = FALSE;
780
781 if (dofcntl)
782   {
783   if (fcntltime > 0)
784     {
785     ALARM(fcntltime);
786     yield = fcntl(fd, F_SETLKW, &lock_data);
787     save_errno = errno;
788     ALARM_CLR(0);
789     errno = save_errno;
790     }
791   else yield = fcntl(fd, F_SETLK, &lock_data);
792   }
793
794 #ifndef NO_FLOCK
795 if (doflock && (yield >= 0))
796   {
797   int flocktype = (fcntltype == F_WRLCK) ? LOCK_EX : LOCK_SH;
798   if (flocktime > 0)
799     {
800     ALARM(flocktime);
801     yield = flock(fd, flocktype);
802     save_errno = errno;
803     ALARM_CLR(0);
804     errno = save_errno;
805     }
806   else yield = flock(fd, flocktype | LOCK_NB);
807   }
808 #endif  /* NO_FLOCK */
809
810 return yield;
811 }
812
813
814
815
816 #ifdef SUPPORT_MBX
817 /*************************************************
818 *         Copy message into MBX mailbox          *
819 *************************************************/
820
821 /* This function is called when a message intended for a MBX mailbox has been
822 written to a temporary file. We can now get the size of the message and then
823 copy it in MBX format to the mailbox.
824
825 Arguments:
826   to_fd        fd to write to (the real mailbox)
827   from_fd      fd to read from (the temporary file)
828   saved_size   current size of mailbox
829
830 Returns:       OK if all went well, DEFER otherwise, with errno preserved
831                the number of bytes written are added to transport_count
832                  by virtue of calling transport_write_block()
833 */
834
835 /* Values taken from c-client */
836
837 #define MBX_HDRSIZE            2048
838 #define MBX_NUSERFLAGS           30
839
840 static int
841 copy_mbx_message(int to_fd, int from_fd, off_t saved_size)
842 {
843 int used;
844 off_t size;
845 struct stat statbuf;
846 transport_ctx tctx = { .u={.fd = to_fd}, .options = topt_not_socket };
847
848 /* If the current mailbox size is zero, write a header block */
849
850 if (saved_size == 0)
851   {
852   uschar *s;
853   memset (deliver_out_buffer, '\0', MBX_HDRSIZE);
854   sprintf(CS(s = deliver_out_buffer), "*mbx*\015\012%08lx00000000\015\012",
855     (long int)time(NULL));
856   for (int i = 0; i < MBX_NUSERFLAGS; i++)
857     sprintf (CS(s += Ustrlen(s)), "\015\012");
858   if (!transport_write_block (&tctx, deliver_out_buffer, MBX_HDRSIZE, FALSE))
859     return DEFER;
860   }
861
862 DEBUG(D_transport) debug_printf("copying MBX message from temporary file\n");
863
864 /* Now construct the message's header from the time and the RFC822 file
865 size, including CRLFs, which is the size of the input (temporary) file. */
866
867 if (fstat(from_fd, &statbuf) < 0) return DEFER;
868 size = statbuf.st_size;
869
870 sprintf (CS deliver_out_buffer, "%s," OFF_T_FMT ";%08lx%04x-%08x\015\012",
871   tod_stamp(tod_mbx), size, 0L, 0, 0);
872 used = Ustrlen(deliver_out_buffer);
873
874 /* Rewind the temporary file, and copy it over in chunks. */
875
876 if (lseek(from_fd, 0 , SEEK_SET) < 0) return DEFER;
877
878 while (size > 0)
879   {
880   int len = read(from_fd, deliver_out_buffer + used,
881     DELIVER_OUT_BUFFER_SIZE - used);
882   if (len <= 0)
883     {
884     if (len == 0) errno = ERRNO_MBXLENGTH;
885     return DEFER;
886     }
887   if (!transport_write_block(&tctx, deliver_out_buffer, used + len, FALSE))
888     return DEFER;
889   size -= len;
890   used = 0;
891   }
892
893 return OK;
894 }
895 #endif  /* SUPPORT_MBX */
896
897
898
899 /*************************************************
900 *            Check creation is permitted         *
901 *************************************************/
902
903 /* This function checks whether a given file name is permitted to be created,
904 as controlled by the create_file option. If no home directory is set, however,
905 we can't do any tests.
906
907 Arguments:
908   filename     the file name
909   create_file  the ob->create_file option
910   deliver_dir  the delivery directory
911
912 Returns:       TRUE if creation is permitted
913 */
914
915 static BOOL
916 check_creation(uschar *filename, int create_file, const uschar * deliver_dir)
917 {
918 BOOL yield = TRUE;
919
920 if (deliver_dir  &&  create_file != create_anywhere)
921   {
922   int len = Ustrlen(deliver_dir);
923   uschar *file = filename;
924
925   while (file[0] == '/' && file[1] == '/') file++;
926   if (  Ustrncmp(file, deliver_dir, len) != 0
927      || file[len] != '/'
928      ||    Ustrchr(file+len+2, '/') != NULL
929         && (  create_file != create_belowhome
930            || Ustrstr(file+len, "/../") != NULL
931            )
932      ) yield = FALSE;
933
934   /* If yield is TRUE, the file name starts with the home directory, and does
935   not contain any instances of "/../" in the "belowhome" case. However, it may
936   still contain symbolic links. We can check for this by making use of
937   realpath(), which most Unixes seem to have (but make it possible to cut this
938   out). We can't just use realpath() on the whole file name, because we know
939   the file itself doesn't exist, and intermediate directories may also not
940   exist. What we want to know is the real path of the longest existing part of
941   the path. That must match the home directory's beginning, whichever is the
942   shorter. */
943
944   #ifndef NO_REALPATH
945   if (yield && create_file == create_belowhome)
946     {
947     uschar *next;
948     uschar *rp = NULL;
949     for (uschar * slash = Ustrrchr(file, '/');  /* There is known to be one */
950          !rp && slash > file;                   /* Stop if reached beginning */
951          slash = next)
952       {
953       *slash = 0;
954       rp = US realpath(CS file, CS big_buffer);
955       next = Ustrrchr(file, '/');
956       *slash = '/';
957       }
958
959     /* If rp == NULL it means that none of the relevant directories exist.
960     This is not a problem here - it means that no symbolic links can exist,
961     which is all we are worried about. Otherwise, we must compare it
962     against the start of the home directory. However, that may itself
963     contain symbolic links, so we have to "realpath" it as well, if
964     possible. */
965
966     if (rp)
967       {
968       uschar hdbuffer[PATH_MAX+1];
969       const uschar * rph = deliver_dir;
970       int rlen = Ustrlen(big_buffer);
971
972       if ((rp = US realpath(CS deliver_dir, CS hdbuffer)))
973         {
974         rph = hdbuffer;
975         len = Ustrlen(rph);
976         }
977
978       if (rlen > len) rlen = len;
979       if (Ustrncmp(rph, big_buffer, rlen) != 0)
980         {
981         yield = FALSE;
982         DEBUG(D_transport) debug_printf("Real path \"%s\" does not match \"%s\"\n",
983           big_buffer, deliver_dir);
984         }
985       }
986     }
987   #endif  /* NO_REALPATH */
988   }
989
990 return yield;
991 }
992
993
994
995 /*************************************************
996 *              Main entry point                  *
997 *************************************************/
998
999 /* See local README for general interface details. This transport always
1000 returns FALSE, indicating that the status which has been placed in the first
1001 address should be copied to any other addresses in a batch.
1002
1003 Appendfile delivery is tricky and has led to various security problems in other
1004 mailers. The logic used here is therefore laid out in some detail. When this
1005 function is called, we are running in a subprocess which has had its gid and
1006 uid set to the appropriate values. Therefore, we cannot write directly to the
1007 exim logs. Any errors must be handled by setting appropriate return codes.
1008 Note that the default setting for addr->transport_return is DEFER, so it need
1009 not be set unless some other value is required.
1010
1011 The code below calls geteuid() rather than getuid() to get the current uid
1012 because in weird configurations not running setuid root there may be a
1013 difference. In the standard configuration, where setuid() has been used in the
1014 delivery process, there will be no difference between the uid and the euid.
1015
1016 (1)  If the af_file flag is set, this is a delivery to a file after .forward or
1017      alias expansion. Otherwise, there must be a configured file name or
1018      directory name.
1019
1020 The following items apply in the case when a file name (as opposed to a
1021 directory name) is given, that is, when appending to a single file:
1022
1023 (2f) Expand the file name.
1024
1025 (3f) If the file name is /dev/null, return success (optimization).
1026
1027 (4f) If the file_format options is set, open the file for reading, and check
1028      that the bytes at the start of the file match one of the given strings.
1029      If the check indicates a transport other than the current one should be
1030      used, pass control to that other transport. Otherwise continue. An empty
1031      or non-existent file matches the current transport. The file is closed
1032      after the check.
1033
1034 (5f) If a lock file is required, create it (see extensive separate comments
1035      below about the algorithm for doing this). It is important to do this
1036      before opening the mailbox if NFS is in use.
1037
1038 (6f) Stat the file, using lstat() rather than stat(), in order to pick up
1039      details of any symbolic link.
1040
1041 (7f) If the file already exists:
1042
1043      Check the owner and group if necessary, and defer if they are wrong.
1044
1045      If it is a symbolic link AND the allow_symlink option is set (NOT the
1046      default), go back to (6f) but this time use stat() instead of lstat().
1047
1048      If it's not a regular file (or FIFO when permitted), defer delivery.
1049
1050      Check permissions. If the required permissions are *less* than the
1051      existing ones, or supplied by the address (often by the user via filter),
1052      chmod() the file. Otherwise, defer.
1053
1054      Save the inode number.
1055
1056      Open with O_RDRW + O_APPEND, thus failing if the file has vanished.
1057
1058      If open fails because the file does not exist, go to (6f); on any other
1059      failure, defer.
1060
1061      Check the inode number hasn't changed - I realize this isn't perfect (an
1062      inode can be reused) but it's cheap and will catch some of the races.
1063
1064      Check it's still a regular file (or FIFO if permitted).
1065
1066      Check that the owner and permissions haven't changed.
1067
1068      If file_format is set, check that the file still matches the format for
1069      the current transport. If not, defer delivery.
1070
1071 (8f) If file does not exist initially:
1072
1073      Open with O_WRONLY + O_EXCL + O_CREAT with configured mode, unless we know
1074      this is via a symbolic link (only possible if allow_symlinks is set), in
1075      which case don't use O_EXCL, as it doesn't work.
1076
1077      If open fails because the file already exists, go to (6f). To avoid
1078      looping for ever in a situation where the file is continuously being
1079      created and deleted, all of this happens inside a loop that operates
1080      lock_retries times and includes the fcntl and flock locking. If the
1081      loop completes without the file getting opened, defer and request
1082      freezing, because something really weird is happening.
1083
1084      If open fails for any other reason, defer for subsequent delivery except
1085      when this is a file delivery resulting from an alias or forward expansion
1086      and the error is EPERM or ENOENT or EACCES, in which case FAIL as this is
1087      most likely a user rather than a configuration error.
1088
1089 (9f) We now have the file checked and open for writing. If so configured, lock
1090      it using fcntl, flock, or MBX locking rules. If this fails, close the file
1091      and goto (6f), up to lock_retries times, after sleeping for a while. If it
1092      still fails, give up and defer delivery.
1093
1094 (10f)Save the access time (for subsequent restoration) and the size of the
1095      file, for comsat and for re-setting if delivery fails in the middle -
1096      e.g. for quota exceeded.
1097
1098 The following items apply in the case when a directory name is given:
1099
1100 (2d) Create a new file in the directory using a temporary name, by opening for
1101      writing and with O_CREAT. If maildir format is being used, the file
1102      is created in a temporary subdirectory with a prescribed name. If
1103      mailstore format is being used, the envelope file is first created with a
1104      temporary name, then the data file.
1105
1106 The following items apply in all cases:
1107
1108 (11) We now have the file open for writing, and locked if it was given as a
1109      file name. Write the message and flush the file, unless there is a setting
1110      of the local quota option, in which case we can check for its excession
1111      without doing any writing.
1112
1113      In the case of MBX format mailboxes, the message is first written to a
1114      temporary file, in order to get its correct length. This is then copied to
1115      the real file, preceded by an MBX header.
1116
1117      If there is a quota error on writing, defer the address. Timeout logic
1118      will determine for how long retries are attempted. We restore the mailbox
1119      to its original length if it's a single file. There doesn't seem to be a
1120      uniform error code for quota excession (it even differs between SunOS4
1121      and some versions of SunOS5) so a system-dependent macro called
1122      ERRNO_QUOTA is used for it, and the value gets put into errno_quota at
1123      compile time.
1124
1125      For any other error (most commonly disk full), do the same.
1126
1127 The following applies after appending to a file:
1128
1129 (12f)Restore the atime; notify_comsat if required; close the file (which
1130      unlocks it if it was locked). Delete the lock file if it exists.
1131
1132 The following applies after writing a unique file in a directory:
1133
1134 (12d)For maildir format, rename the file into the new directory. For mailstore
1135      format, rename the envelope file to its correct name. Otherwise, generate
1136      a unique name from the directory_file option, and rename to that, possibly
1137      trying a few times if the file exists and re-expanding the name gives a
1138      different string.
1139
1140 This transport yields FAIL only when a file name is generated by an alias or
1141 forwarding operation and attempting to open it gives EPERM, ENOENT, or EACCES.
1142 All other failures return DEFER (in addr->transport_return). */
1143
1144
1145 BOOL
1146 appendfile_transport_entry(
1147   transport_instance *tblock,      /* data for this instantiation */
1148   address_item *addr)              /* address we are working on */
1149 {
1150 appendfile_transport_options_block *ob =
1151   (appendfile_transport_options_block *)(tblock->options_block);
1152 struct stat statbuf;
1153 const uschar * deliver_dir;
1154 uschar *fdname = NULL;
1155 uschar *filename = NULL;
1156 uschar *hitchname = NULL;
1157 uschar *dataname = NULL;
1158 uschar *lockname = NULL;
1159 uschar *newname = NULL;
1160 uschar *nametag = NULL;
1161 uschar *cr = US"";
1162 uschar *filecount_msg = US"";
1163 uschar *path;
1164 struct utimbuf times;
1165 struct timeval msg_tv;
1166 BOOL disable_quota = FALSE;
1167 BOOL isdirectory = FALSE;
1168 BOOL isfifo = FALSE;
1169 BOOL wait_for_tick = FALSE;
1170 uid_t uid = geteuid();     /* See note above */
1171 gid_t gid = getegid();
1172 int mbformat;
1173 int mode = (addr->mode > 0) ? addr->mode : ob->mode;
1174 off_t saved_size = -1;
1175 off_t mailbox_size = ob->mailbox_size_value;
1176 int mailbox_filecount = ob->mailbox_filecount_value;
1177 int hd = -1;
1178 int fd = -1;
1179 int yield = FAIL;
1180 int i;
1181
1182 #ifdef SUPPORT_MBX
1183 int save_fd = 0;
1184 int mbx_lockfd = -1;
1185 uschar mbx_lockname[40];
1186 FILE *temp_file = NULL;
1187 #endif  /* SUPPORT_MBX */
1188
1189 #ifdef SUPPORT_MAILDIR
1190 int maildirsize_fd = -1;      /* fd for maildirsize file */
1191 int maildir_save_errno;
1192 #endif
1193
1194
1195 DEBUG(D_transport) debug_printf("appendfile transport entered\n");
1196
1197 /* An "address_file" or "address_directory" transport is used to deliver to
1198 files specified via .forward or an alias file. Prior to release 4.20, the
1199 "file" and "directory" options were ignored in this case. This has been changed
1200 to allow the redirection data to specify what is in effect a folder, whose
1201 location is determined by the options on the transport.
1202
1203 Compatibility with the case when neither option is set is retained by forcing a
1204 value for the file or directory name. A directory delivery is assumed if the
1205 last character of the path from the router is '/'.
1206
1207 The file path is in the local part of the address, but not in the $local_part
1208 variable (that holds the parent local part). It is, however, in the
1209 $address_file variable. Below, we update the local part in the address if it
1210 changes by expansion, so that the final path ends up in the log. */
1211
1212 if (testflag(addr, af_file) && !ob->filename && !ob->dirname)
1213   {
1214   fdname = US"$address_file";
1215   if (address_file[Ustrlen(address_file)-1] == '/' ||
1216       ob->maildir_format ||
1217       ob->mailstore_format)
1218     isdirectory = TRUE;
1219   }
1220
1221 /* Handle (a) an "address file" delivery where "file" or "directory" is
1222 explicitly set and (b) a non-address_file delivery, where one of "file" or
1223 "directory" must be set; initialization ensures that they are not both set. */
1224
1225 if (!fdname)
1226   {
1227   if (!(fdname = ob->filename))
1228     {
1229     fdname = ob->dirname;
1230     isdirectory = TRUE;
1231     }
1232   if (!fdname)
1233     {
1234     addr->message = string_sprintf("Mandatory file or directory option "
1235       "missing from %s transport", tblock->name);
1236     goto ret_panic;
1237     }
1238   }
1239
1240 /* Maildir and mailstore require a directory */
1241
1242 if ((ob->maildir_format || ob->mailstore_format) && !isdirectory)
1243   {
1244   addr->message = string_sprintf("mail%s_format requires \"directory\" "
1245     "to be specified for the %s transport",
1246     ob->maildir_format ? "dir" : "store", tblock->name);
1247   goto ret_panic;
1248   }
1249
1250 if (!(path = expand_string(fdname)))
1251   {
1252   addr->message = string_sprintf("Expansion of \"%s\" (file or directory "
1253     "name for %s transport) failed: %s", fdname, tblock->name,
1254     expand_string_message);
1255   goto ret_panic;
1256   }
1257
1258 if (path[0] != '/')
1259   {
1260   addr->message = string_sprintf("appendfile: file or directory name "
1261     "\"%s\" is not absolute", path);
1262   addr->basic_errno = ERRNO_NOTABSOLUTE;
1263   return FALSE;
1264   }
1265
1266 /* For a file delivery, make sure the local part in the address(es) is updated
1267 to the true local part. */
1268
1269 if (testflag(addr, af_file))
1270   for (address_item * addr2 = addr; addr2; addr2 = addr2->next)
1271     addr2->local_part = string_copy(path);
1272
1273 /* The available mailbox formats depend on whether it is a directory or a file
1274 delivery. */
1275
1276 if (isdirectory)
1277   {
1278   mbformat =
1279   #ifdef SUPPORT_MAILDIR
1280     ob->maildir_format ? mbf_maildir :
1281   #endif
1282   #ifdef SUPPORT_MAILSTORE
1283     ob->mailstore_format ? mbf_mailstore :
1284   #endif
1285     mbf_smail;
1286   }
1287 else
1288   {
1289   mbformat =
1290   #ifdef SUPPORT_MBX
1291     ob->mbx_format ? mbf_mbx :
1292   #endif
1293     mbf_unix;
1294   }
1295
1296 DEBUG(D_transport)
1297   {
1298   debug_printf("appendfile: mode=%o notify_comsat=%d quota=" OFF_T_FMT
1299     "%s%s"
1300     " warning=" OFF_T_FMT "%s\n"
1301     "  %s=%s format=%s\n  message_prefix=%s\n  message_suffix=%s\n  "
1302     "maildir_use_size_file=%s\n",
1303     mode, ob->notify_comsat, ob->quota_value,
1304     ob->quota_no_check ? " (no_check)" : "",
1305     ob->quota_filecount_no_check ? " (no_check_filecount)" : "",
1306     ob->quota_warn_threshold_value,
1307     ob->quota_warn_threshold_is_percent ? "%" : "",
1308     isdirectory ? "directory" : "file",
1309     path, mailbox_formats[mbformat],
1310     !ob->message_prefix ? US"null" : string_printing(ob->message_prefix),
1311     !ob->message_suffix ? US"null" : string_printing(ob->message_suffix),
1312     ob->maildir_use_size_file ? "yes" : "no");
1313
1314   if (!isdirectory) debug_printf("  locking by %s%s%s%s%s\n",
1315     ob->use_lockfile ? "lockfile " : "",
1316     ob->use_mbx_lock ? "mbx locking (" : "",
1317     ob->use_fcntl ? "fcntl " : "",
1318     ob->use_flock ? "flock" : "",
1319     ob->use_mbx_lock ? ")" : "");
1320   }
1321
1322 /* If the -N option is set, can't do any more. */
1323
1324 if (f.dont_deliver)
1325   {
1326   DEBUG(D_transport)
1327     debug_printf("*** delivery by %s transport bypassed by -N option\n",
1328       tblock->name);
1329   addr->transport_return = OK;
1330   return FALSE;
1331   }
1332
1333 /* If an absolute path was given for create_file the it overrides deliver_home
1334 (here) and de-taints the filename (below, after check_creation() */
1335
1336 deliver_dir = *ob->create_file_string == '/'
1337   ? ob->create_file_string : deliver_home;
1338
1339 /* Handle the case of a file name. If the file name is /dev/null, we can save
1340 ourselves some effort and just give a success return right away. */
1341
1342 if (!isdirectory)
1343   {
1344   BOOL use_lstat = TRUE;
1345   BOOL file_opened = FALSE;
1346   BOOL allow_creation_here = TRUE;
1347
1348   if (Ustrcmp(path, "/dev/null") == 0)
1349     {
1350     addr->transport_return = OK;
1351     return FALSE;
1352     }
1353
1354   /* Set the name of the file to be opened, and the file to which the data
1355   is written, and find out if we are permitted to create a non-existent file.
1356   If the create_file option is an absolute path and the file was within it,
1357   de-taint.  Chaeck for a tainted path. */
1358
1359   if (  (allow_creation_here = check_creation(path, ob->create_file, deliver_dir))
1360      && ob->create_file == create_belowhome)
1361     if (is_tainted(path))
1362       {
1363       DEBUG(D_transport) debug_printf("de-tainting path '%s'\n", path);
1364       path = string_copy_taint(path, GET_UNTAINTED);
1365       }
1366
1367   if (is_tainted(path)) goto tainted_ret_panic;
1368   dataname = filename = path;
1369
1370   /* If ob->create_directory is set, attempt to create the directories in
1371   which this mailbox lives, but only if we are permitted to create the file
1372   itself. We know we are dealing with an absolute path, because this was
1373   checked above. */
1374
1375   if (ob->create_directory && allow_creation_here)
1376     {
1377     uschar *p = Ustrrchr(path, '/');
1378     p = string_copyn(path, p - path);
1379     if (!directory_make(NULL, p, ob->dirmode, FALSE))
1380       {
1381       addr->basic_errno = errno;
1382       addr->message =
1383         string_sprintf("failed to create directories for %s: %s", path,
1384           exim_errstr(errno));
1385       DEBUG(D_transport) debug_printf("%s transport: %s\n", tblock->name, path);
1386       return FALSE;
1387       }
1388     }
1389
1390   /* If file_format is set we must check that any existing file matches one of
1391   the configured formats by checking the bytes it starts with. A match then
1392   indicates a specific transport - if it is not this one, pass control to it.
1393   Otherwise carry on here. An empty or non-existent file matches the current
1394   transport. We don't need to distinguish between non-existence and other open
1395   failures because if an existing file fails to open here, it will also fail
1396   again later when O_RDWR is used. */
1397
1398   if (ob->file_format)
1399     {
1400     int cfd = Uopen(path, O_RDONLY, 0);
1401     if (cfd >= 0)
1402       {
1403       transport_instance *tt = check_file_format(cfd, tblock, addr);
1404       (void)close(cfd);
1405
1406       /* If another transport is indicated, call it and return; if no transport
1407       was found, just return - the error data will have been set up.*/
1408
1409       if (tt != tblock)
1410         {
1411         if (tt)
1412           {
1413           set_process_info("delivering %s to %s using %s", message_id,
1414             addr->local_part, tt->name);
1415           debug_print_string(tt->debug_string);
1416           addr->transport = tt;
1417           (tt->info->code)(tt, addr);
1418           }
1419         return FALSE;
1420         }
1421       }
1422     }
1423
1424   /* The locking of mailbox files is worse than the naming of cats, which is
1425   known to be "a difficult matter" (T.S. Eliot) and just as cats must have
1426   three different names, so several different styles of locking are used.
1427
1428   Research in other programs that lock mailboxes shows that there is no
1429   universally standard method. Having mailboxes NFS-mounted on the system that
1430   is delivering mail is not the best thing, but people do run like this,
1431   and so the code must do its best to cope.
1432
1433   Three different locking mechanisms are supported. The initialization function
1434   checks that at least one is configured.
1435
1436   LOCK FILES
1437
1438   Unless no_use_lockfile is set, we attempt to build a lock file in a way that
1439   will work over NFS. Only after that is done do we actually open the mailbox
1440   and apply locks to it (if configured).
1441
1442   Originally, Exim got the file opened before doing anything about locking.
1443   However, a very occasional problem was observed on Solaris 2 when delivering
1444   over NFS. It is seems that when a file is opened with O_APPEND, the file size
1445   gets remembered at open time. If another process on another host (that's
1446   important) has the file open and locked and writes to it and then releases
1447   the lock while the first process is waiting to get the lock, the first
1448   process may fail to write at the new end point of the file - despite the very
1449   definite statement about O_APPEND in the man page for write(). Experiments
1450   have reproduced this problem, but I do not know any way of forcing a host to
1451   update its attribute cache for an open NFS file. It would be nice if it did
1452   so when a lock was taken out, but this does not seem to happen. Anyway, to
1453   reduce the risk of this problem happening, we now create the lock file
1454   (if configured) *before* opening the mailbox. That will prevent two different
1455   Exims opening the file simultaneously. It may not prevent clashes with MUAs,
1456   however, but Pine at least seems to operate in the same way.
1457
1458   Lockfiles should normally be used when NFS is involved, because of the above
1459   problem.
1460
1461   The logic for creating the lock file is:
1462
1463   . The name of the lock file is <mailbox-name>.lock
1464
1465   . First, create a "hitching post" name by adding the primary host name,
1466     current time and pid to the lock file name. This should be unique.
1467
1468   . Create the hitching post file using WRONLY + CREAT + EXCL.
1469
1470   . If that fails EACCES, we assume it means that the user is unable to create
1471     files in the mail spool directory. Some installations might operate in this
1472     manner, so there is a configuration option to allow this state not to be an
1473     error - we proceed to lock using fcntl only, after the file is open.
1474
1475   . Otherwise, an error causes a deferment of the address.
1476
1477   . Hard link the hitching post to the lock file name.
1478
1479   . If the link succeeds, we have successfully created the lock file. Simply
1480     close and unlink the hitching post file.
1481
1482   . If the link does not succeed, proceed as follows:
1483
1484     o Fstat the hitching post file, and then close and unlink it.
1485
1486     o Now examine the stat data. If the number of links to the file is exactly
1487       2, the linking succeeded but for some reason, e.g. an NFS server crash,
1488       the return never made it back, so the link() function gave a failure
1489       return.
1490
1491   . This method allows for the lock file to be created by some other process
1492     right up to the moment of the attempt to hard link it, and is also robust
1493     against NFS server crash-reboots, which would probably result in timeouts
1494     in the middle of link().
1495
1496   . System crashes may cause lock files to get left lying around, and some means
1497     of flushing them is required. The approach of writing a pid (used by smail
1498     and by elm) into the file isn't useful when NFS may be in use. Pine uses a
1499     timeout, which seems a better approach. Since any program that writes to a
1500     mailbox using a lock file should complete its task very quickly, Pine
1501     removes lock files that are older than 5 minutes. We allow the value to be
1502     configurable on the transport.
1503
1504   FCNTL LOCKING
1505
1506   If use_fcntl_lock is set, then Exim gets an exclusive fcntl() lock on the
1507   mailbox once it is open. This is done by default with a non-blocking lock.
1508   Failures to lock cause retries after a sleep, but only for a certain number
1509   of tries. A blocking lock is deliberately not used so that we don't hold the
1510   mailbox open. This minimizes the possibility of the NFS problem described
1511   under LOCK FILES above, if for some reason NFS deliveries are happening
1512   without lock files. However, the use of a non-blocking lock and sleep, though
1513   the safest approach, does not give the best performance on very busy systems.
1514   A blocking lock plus timeout does better. Therefore Exim has an option to
1515   allow it to work this way. If lock_fcntl_timeout is set greater than zero, it
1516   enables the use of blocking fcntl() calls.
1517
1518   FLOCK LOCKING
1519
1520   If use_flock_lock is set, then Exim gets an exclusive flock() lock in the
1521   same manner as for fcntl locking above. No-blocking/timeout is also set as
1522   above in lock_flock_timeout. Not all operating systems provide or support
1523   flock(). For those that don't (as determined by the definition of LOCK_SH in
1524   /usr/include/sys/file.h), use_flock_lock may not be set. For some OS, flock()
1525   is implemented (not precisely) on top of fcntl(), which means there's no
1526   point in actually using it.
1527
1528   MBX LOCKING
1529
1530   If use_mbx_lock is set (this is supported only if SUPPORT_MBX is defined)
1531   then the rules used for locking in c-client are used. Exim takes out a shared
1532   lock on the mailbox file, and an exclusive lock on the file whose name is
1533   /tmp/.<device-number>.<inode-number>. The shared lock on the mailbox stops
1534   any other MBX client from getting an exclusive lock on it and expunging it.
1535   It also stops any other MBX client from unlinking the /tmp lock when it has
1536   finished with it.
1537
1538   The exclusive lock on the /tmp file prevents any other MBX client from
1539   updating the mailbox in any way. When writing is finished, if an exclusive
1540   lock on the mailbox can be obtained, indicating there are no current sharers,
1541   the /tmp file is unlinked.
1542
1543   MBX locking can use either fcntl() or flock() locking. If neither
1544   use_fcntl_lock or use_flock_lock is set, it defaults to using fcntl() only.
1545   The calls for getting these locks are by default non-blocking, as for non-mbx
1546   locking, but can be made blocking by setting lock_fcntl_timeout and/or
1547   lock_flock_timeout as appropriate.  As MBX delivery doesn't work over NFS, it
1548   probably makes sense to set timeouts for any MBX deliveries. */
1549
1550
1551   /* Build a lock file if configured to do so - the existence of a lock
1552   file is subsequently checked by looking for a non-negative value of the
1553   file descriptor hd - even though the file is no longer open. */
1554
1555   if (ob->use_lockfile)
1556     {
1557     /* cf. exim_lock.c */
1558     lockname = string_sprintf("%s.lock", filename);
1559     hitchname = string_sprintf( "%s.%s.%08x.%08x", lockname, primary_hostname,
1560       (unsigned int)(time(NULL)), (unsigned int)getpid());
1561
1562     DEBUG(D_transport) debug_printf("lock name: %s\nhitch name: %s\n", lockname,
1563       hitchname);
1564
1565     /* Lock file creation retry loop */
1566
1567     for (i = 0; i < ob->lock_retries; sleep(ob->lock_interval), i++)
1568       {
1569       int rc;
1570
1571       hd = Uopen(hitchname, O_WRONLY | O_CREAT | O_EXCL, ob->lockfile_mode);
1572       if (hd < 0)
1573         {
1574         addr->basic_errno = errno;
1575         addr->message =
1576           string_sprintf("creating lock file hitching post %s "
1577             "(euid=%ld egid=%ld)", hitchname, (long int)geteuid(),
1578             (long int)getegid());
1579         return FALSE;
1580         }
1581
1582       /* Attempt to hitch the hitching post to the lock file. If link()
1583       succeeds (the common case, we hope) all is well. Otherwise, fstat the
1584       file, and get rid of the hitching post. If the number of links was 2,
1585       the link was created, despite the failure of link(). If the hitch was
1586       not successful, try again, having unlinked the lock file if it is too
1587       old.
1588
1589       There's a version of Linux (2.0.27) which doesn't update its local cache
1590       of the inode after link() by default - which many think is a bug - but
1591       if the link succeeds, this code will be OK. It just won't work in the
1592       case when link() fails after having actually created the link. The Linux
1593       NFS person is fixing this; a temporary patch is available if anyone is
1594       sufficiently worried. */
1595
1596       if ((rc = Ulink(hitchname, lockname)) != 0) fstat(hd, &statbuf);
1597       (void)close(hd);
1598       Uunlink(hitchname);
1599       if (rc != 0 && statbuf.st_nlink != 2)
1600         {
1601         if (ob->lockfile_timeout > 0 && Ustat(lockname, &statbuf) == 0 &&
1602             time(NULL) - statbuf.st_ctime > ob->lockfile_timeout)
1603           {
1604           DEBUG(D_transport) debug_printf("unlinking timed-out lock file\n");
1605           Uunlink(lockname);
1606           }
1607         DEBUG(D_transport) debug_printf("link of hitching post failed - retrying\n");
1608         continue;
1609         }
1610
1611       DEBUG(D_transport) debug_printf("lock file created\n");
1612       break;
1613       }
1614
1615     /* Check for too many tries at creating the lock file */
1616
1617     if (i >= ob->lock_retries)
1618       {
1619       addr->basic_errno = ERRNO_LOCKFAILED;
1620       addr->message = string_sprintf("failed to lock mailbox %s (lock file)",
1621         filename);
1622       return FALSE;
1623       }
1624     }
1625
1626
1627   /* We now have to get the file open. First, stat() it and act on existence or
1628   non-existence. This is in a loop to handle the case of a file's being created
1629   or deleted as we watch, and also to handle retries when the locking fails.
1630   Rather than holding the file open while waiting for the fcntl() and/or
1631   flock() lock, we close and do the whole thing again. This should be safer,
1632   especially for NFS files, which might get altered from other hosts, making
1633   their cached sizes incorrect.
1634
1635   With the default settings, no symlinks are permitted, but there is an option
1636   to permit symlinks for those sysadmins that know what they are doing.
1637   Shudder. However, insist that the initial symlink is owned by the right user.
1638   Thus lstat() is used initially; if a symlink is discovered, the loop is
1639   repeated such that stat() is used, to look at the end file. */
1640
1641   for (i = 0; i < ob->lock_retries; i++)
1642     {
1643     int sleep_before_retry = TRUE;
1644     file_opened = FALSE;
1645
1646     if ((use_lstat ? Ulstat(filename, &statbuf) : Ustat(filename, &statbuf)) != 0)
1647       {
1648       /* Let's hope that failure to stat (other than non-existence) is a
1649       rare event. */
1650
1651       if (errno != ENOENT)
1652         {
1653         addr->basic_errno = errno;
1654         addr->message = string_sprintf("attempting to stat mailbox %s",
1655           filename);
1656         goto RETURN;
1657         }
1658
1659       /* File does not exist. If it is required to pre-exist this state is an
1660       error. */
1661
1662       if (ob->file_must_exist)
1663         {
1664         addr->basic_errno = errno;
1665         addr->message = string_sprintf("mailbox %s does not exist, "
1666           "but file_must_exist is set", filename);
1667         goto RETURN;
1668         }
1669
1670       /* If not permitted to create this file because it isn't in or below
1671       the home directory, generate an error. */
1672
1673       if (!allow_creation_here)
1674         {
1675         addr->basic_errno = ERRNO_BADCREATE;
1676         addr->message = string_sprintf("mailbox %s does not exist, "
1677           "but creation outside the home directory is not permitted",
1678           filename);
1679         goto RETURN;
1680         }
1681
1682       /* Attempt to create and open the file. If open fails because of
1683       pre-existence, go round the loop again. For any other error, defer the
1684       address, except for an alias or forward generated file name with EPERM,
1685       ENOENT, or EACCES, as those are most likely to be user errors rather
1686       than Exim config errors. When a symbolic link is permitted and points
1687       to a non-existent file, we get here with use_lstat = FALSE. In this case
1688       we mustn't use O_EXCL, since it doesn't work. The file is opened RDRW for
1689       consistency and because MBX locking requires it in order to be able to
1690       get a shared lock. */
1691
1692       fd = Uopen(filename, O_RDWR | O_APPEND | O_CREAT |
1693         (use_lstat ? O_EXCL : 0), mode);
1694       if (fd < 0)
1695         {
1696         if (errno == EEXIST) continue;
1697         addr->basic_errno = errno;
1698         addr->message = string_sprintf("while creating mailbox %s",
1699           filename);
1700         if (testflag(addr, af_file) &&
1701             (errno == EPERM || errno == ENOENT || errno == EACCES))
1702           addr->transport_return = FAIL;
1703         goto RETURN;
1704         }
1705
1706       /* We have successfully created and opened the file. Ensure that the group
1707       and the mode are correct. */
1708
1709       if (exim_chown(filename, uid, gid) || Uchmod(filename, mode))
1710         {
1711         addr->basic_errno = errno;
1712         addr->message = string_sprintf("while setting perms on mailbox %s",
1713           filename);
1714         addr->transport_return = FAIL;
1715         goto RETURN;
1716         }
1717       }
1718
1719
1720     /* The file already exists. Test its type, ownership, and permissions, and
1721     save the inode for checking later. If symlinks are permitted (not the
1722     default or recommended state) it may be a symlink that already exists.
1723     Check its ownership and then look for the file at the end of the link(s).
1724     This at least prevents one user creating a symlink for another user in
1725     a sticky directory. */
1726
1727     else
1728       {
1729       int oldmode = (int)statbuf.st_mode;
1730       ino_t inode = statbuf.st_ino;
1731       BOOL islink = (oldmode & S_IFMT) == S_IFLNK;
1732
1733       isfifo = FALSE;        /* In case things are changing */
1734
1735       /* Check owner if required - the default. */
1736
1737       if (ob->check_owner && statbuf.st_uid != uid)
1738         {
1739         addr->basic_errno = ERRNO_BADUGID;
1740         addr->message = string_sprintf("mailbox %s%s has wrong uid "
1741           "(%ld != %ld)", filename,
1742           islink ? " (symlink)" : "",
1743           (long int)(statbuf.st_uid), (long int)uid);
1744         goto RETURN;
1745         }
1746
1747       /* Group is checked only if check_group is set. */
1748
1749       if (ob->check_group && statbuf.st_gid != gid)
1750         {
1751         addr->basic_errno = ERRNO_BADUGID;
1752         addr->message = string_sprintf("mailbox %s%s has wrong gid (%d != %d)",
1753           filename, islink ? " (symlink)" : "", statbuf.st_gid, gid);
1754         goto RETURN;
1755         }
1756
1757       /* Just in case this is a sticky-bit mail directory, we don't want
1758       users to be able to create hard links to other users' files. */
1759
1760       if (statbuf.st_nlink != 1)
1761         {
1762         addr->basic_errno = ERRNO_NOTREGULAR;
1763         addr->message = string_sprintf("mailbox %s%s has too many links (%lu)",
1764           filename, islink ? " (symlink)" : "", (unsigned long)statbuf.st_nlink);
1765         goto RETURN;
1766
1767         }
1768
1769       /* If symlinks are permitted (not recommended), the lstat() above will
1770       have found the symlink. Its ownership has just been checked; go round
1771       the loop again, using stat() instead of lstat(). That will never yield a
1772       mode of S_IFLNK. */
1773
1774       if (islink && ob->allow_symlink)
1775         {
1776         use_lstat = FALSE;
1777         i--;                   /* Don't count this time round */
1778         continue;
1779         }
1780
1781       /* An actual file exists. Check that it is a regular file, or FIFO
1782       if permitted. */
1783
1784       if (ob->allow_fifo && (oldmode & S_IFMT) == S_IFIFO) isfifo = TRUE;
1785
1786       else if ((oldmode & S_IFMT) != S_IFREG)
1787         {
1788         addr->basic_errno = ERRNO_NOTREGULAR;
1789         addr->message = string_sprintf("mailbox %s is not a regular file%s",
1790           filename, ob->allow_fifo ? " or named pipe" : "");
1791         goto RETURN;
1792         }
1793
1794       /* If the mode is not what it would be for a newly created file, change
1795       the permissions if the mode is supplied for the address. Otherwise,
1796       reduce but do not extend the permissions. If the newly created
1797       permissions are greater than the existing permissions, don't change
1798       things when the mode is not from the address. */
1799
1800       if ((oldmode &= 07777) != mode)
1801         {
1802         int diffs = oldmode ^ mode;
1803         if (addr->mode > 0 || (diffs & oldmode) == diffs)
1804           {
1805           DEBUG(D_transport) debug_printf("chmod %o %s\n", mode, filename);
1806           if (Uchmod(filename, mode) < 0)
1807             {
1808             addr->basic_errno = errno;
1809             addr->message = string_sprintf("attempting to chmod mailbox %s",
1810               filename);
1811             goto RETURN;
1812             }
1813           oldmode = mode;
1814           }
1815
1816         /* Mode not from address, and newly-created permissions are greater
1817         than existing permissions. Default is to complain, but it can be
1818         configured to go ahead and try to deliver anyway if that's what
1819         the administration wants. */
1820
1821         else if (ob->mode_fail_narrower)
1822           {
1823           addr->basic_errno = ERRNO_BADMODE;
1824           addr->message = string_sprintf("mailbox %s has the wrong mode %o "
1825             "(%o expected)", filename, oldmode, mode);
1826           goto RETURN;
1827           }
1828         }
1829
1830       /* We are happy with the existing file. Open it, and then do further
1831       tests to ensure that it is the same file that we were just looking at.
1832       If the file does not now exist, restart this loop, going back to using
1833       lstat again. For an NFS error, just defer; other opening errors are
1834       more serious. The file is opened RDWR so that its format can be checked,
1835       and also MBX locking requires the use of a shared (read) lock. However,
1836       a FIFO is opened WRONLY + NDELAY so that it fails if there is no process
1837       reading the pipe. */
1838
1839       fd = Uopen(filename, isfifo ? (O_WRONLY|O_NDELAY) : (O_RDWR|O_APPEND),
1840         mode);
1841       if (fd < 0)
1842         {
1843         if (errno == ENOENT)
1844           {
1845           use_lstat = TRUE;
1846           continue;
1847           }
1848         addr->basic_errno = errno;
1849         if (isfifo)
1850           addr->message = string_sprintf("while opening named pipe %s "
1851             "(could mean no process is reading it)", filename);
1852         else if (errno != EWOULDBLOCK)
1853           addr->message = string_sprintf("while opening mailbox %s", filename);
1854         goto RETURN;
1855         }
1856
1857       /* This fstat really shouldn't fail, as we have an open file! There's a
1858       dilemma here. We use fstat in order to be sure we are peering at the file
1859       we have got open. However, that won't tell us if the file was reached
1860       via a symbolic link. We checked this above, but there is a race exposure
1861       if the link was created between the previous lstat and the open. However,
1862       it would have to be created with the same inode in order to pass the
1863       check below. If ob->allow_symlink is set, causing the use of stat rather
1864       than lstat above, symbolic links may be there anyway, and the checking is
1865       weaker. */
1866
1867       if (fstat(fd, &statbuf) < 0)
1868         {
1869         addr->basic_errno = errno;
1870         addr->message = string_sprintf("attempting to stat open mailbox %s",
1871           filename);
1872         goto RETURN;
1873         }
1874
1875       /* Check the inode; this is isn't a perfect check, but gives some
1876       confidence. */
1877
1878       if (inode != statbuf.st_ino)
1879         {
1880         addr->basic_errno = ERRNO_INODECHANGED;
1881         addr->message = string_sprintf("opened mailbox %s inode number changed "
1882           "from " INO_T_FMT " to " INO_T_FMT, filename, inode, statbuf.st_ino);
1883         addr->special_action = SPECIAL_FREEZE;
1884         goto RETURN;
1885         }
1886
1887       /* Check it's still a regular file or FIFO, and the uid, gid, and
1888       permissions have not changed. */
1889
1890       if ((!isfifo && (statbuf.st_mode & S_IFMT) != S_IFREG) ||
1891           (isfifo && (statbuf.st_mode & S_IFMT) != S_IFIFO))
1892         {
1893         addr->basic_errno = ERRNO_NOTREGULAR;
1894         addr->message =
1895           string_sprintf("opened mailbox %s is no longer a %s", filename,
1896             isfifo ? "named pipe" : "regular file");
1897         addr->special_action = SPECIAL_FREEZE;
1898         goto RETURN;
1899         }
1900
1901       if ((ob->check_owner && statbuf.st_uid != uid) ||
1902           (ob->check_group && statbuf.st_gid != gid))
1903         {
1904         addr->basic_errno = ERRNO_BADUGID;
1905         addr->message =
1906           string_sprintf("opened mailbox %s has wrong uid or gid", filename);
1907         addr->special_action = SPECIAL_FREEZE;
1908         goto RETURN;
1909         }
1910
1911       if ((statbuf.st_mode & 07777) != oldmode)
1912         {
1913         addr->basic_errno = ERRNO_BADMODE;
1914         addr->message = string_sprintf("opened mailbox %s has wrong mode %o "
1915           "(%o expected)", filename, statbuf.st_mode & 07777, mode);
1916         addr->special_action = SPECIAL_FREEZE;
1917         goto RETURN;
1918         }
1919
1920       /* If file_format is set, check that the format of the file has not
1921       changed. Error data is set by the testing function. */
1922
1923       if (ob->file_format  &&  check_file_format(fd, tblock, addr) != tblock)
1924         {
1925         addr->message = US"open mailbox has changed format";
1926         goto RETURN;
1927         }
1928
1929       /* The file is OK. Carry on to do the locking. */
1930       }
1931
1932     /* We now have an open file, and must lock it using fcntl(), flock() or MBX
1933     locking rules if configured to do so. If a lock file is also required, it
1934     was created above and hd was left >= 0. At least one form of locking is
1935     required by the initialization function. If locking fails here, close the
1936     file and go round the loop all over again, after waiting for a bit, unless
1937     blocking locking was used. */
1938
1939     file_opened = TRUE;
1940     if ((ob->lock_fcntl_timeout > 0) || (ob->lock_flock_timeout > 0))
1941       sleep_before_retry = FALSE;
1942
1943     /* Simple fcntl() and/or flock() locking */
1944
1945     if (!ob->use_mbx_lock && (ob->use_fcntl || ob->use_flock))
1946       {
1947       if (apply_lock(fd, F_WRLCK, ob->use_fcntl, ob->lock_fcntl_timeout,
1948          ob->use_flock, ob->lock_flock_timeout) >= 0) break;
1949       }
1950
1951     /* MBX locking rules */
1952
1953     #ifdef SUPPORT_MBX
1954     else if (ob->use_mbx_lock)
1955       {
1956       int mbx_tmp_oflags;
1957       struct stat lstatbuf, statbuf2;
1958       if (apply_lock(fd, F_RDLCK, ob->use_fcntl, ob->lock_fcntl_timeout,
1959            ob->use_flock, ob->lock_flock_timeout) >= 0 &&
1960            fstat(fd, &statbuf) >= 0)
1961         {
1962         sprintf(CS mbx_lockname, "/tmp/.%lx.%lx", (long)statbuf.st_dev,
1963           (long)statbuf.st_ino);
1964
1965         /*
1966          * 2010-05-29: SECURITY
1967          * Dan Rosenberg reported the presence of a race-condition in the
1968          * original code here.  Beware that many systems still allow symlinks
1969          * to be followed in /tmp so an attacker can create a symlink pointing
1970          * elsewhere between a stat and an open, which we should avoid
1971          * following.
1972          *
1973          * It's unfortunate that we can't just use all the heavily debugged
1974          * locking from above.
1975          *
1976          * Also: remember to mirror changes into exim_lock.c */
1977
1978         /* first leave the old pre-check in place, it provides better
1979          * diagnostics for common cases */
1980         if (Ulstat(mbx_lockname, &statbuf) >= 0)
1981           {
1982           if ((statbuf.st_mode & S_IFMT) == S_IFLNK)
1983             {
1984             addr->basic_errno = ERRNO_LOCKFAILED;
1985             addr->message = string_sprintf("symbolic link on MBX lock file %s",
1986               mbx_lockname);
1987             goto RETURN;
1988             }
1989           if (statbuf.st_nlink > 1)
1990             {
1991             addr->basic_errno = ERRNO_LOCKFAILED;
1992             addr->message = string_sprintf("hard link to MBX lock file %s",
1993               mbx_lockname);
1994             goto RETURN;
1995             }
1996           }
1997
1998         /* If we could just declare "we must be the ones who create this
1999          * file" then a hitching post in a subdir would work, since a
2000          * subdir directly in /tmp/ which we create wouldn't follow links
2001          * but this isn't our locking logic, so we can't safely change the
2002          * file existence rules. */
2003
2004         /* On systems which support O_NOFOLLOW, it's the easiest and most
2005          * obviously correct security fix */
2006         mbx_tmp_oflags = O_RDWR | O_CREAT;
2007 #ifdef O_NOFOLLOW
2008         mbx_tmp_oflags |= O_NOFOLLOW;
2009 #endif
2010         mbx_lockfd = Uopen(mbx_lockname, mbx_tmp_oflags, ob->lockfile_mode);
2011         if (mbx_lockfd < 0)
2012           {
2013           addr->basic_errno = ERRNO_LOCKFAILED;
2014           addr->message = string_sprintf("failed to open MBX lock file %s :%s",
2015             mbx_lockname, strerror(errno));
2016           goto RETURN;
2017           }
2018
2019         if (Ulstat(mbx_lockname, &lstatbuf) < 0)
2020           {
2021           addr->basic_errno = ERRNO_LOCKFAILED;
2022           addr->message = string_sprintf("attempting to lstat open MBX "
2023              "lock file %s: %s", mbx_lockname, strerror(errno));
2024           goto RETURN;
2025           }
2026         if (fstat(mbx_lockfd, &statbuf2) < 0)
2027           {
2028           addr->basic_errno = ERRNO_LOCKFAILED;
2029           addr->message = string_sprintf("attempting to stat fd of open MBX "
2030               "lock file %s: %s", mbx_lockname, strerror(errno));
2031           goto RETURN;
2032           }
2033
2034         /*
2035          * At this point:
2036          *  statbuf: if exists, is file which existed prior to opening the
2037          *           lockfile, might have been replaced since then
2038          *  statbuf2: result of stat'ing the open fd, is what was actually
2039          *            opened
2040          *  lstatbuf: result of lstat'ing the filename immediately after
2041          *            the open but there's a race condition again between
2042          *            those two steps: before open, symlink to foo, after
2043          *            open but before lstat have one of:
2044          *             * was no symlink, so is the opened file
2045          *               (we created it, no messing possible after that point)
2046          *             * hardlink to foo
2047          *             * symlink elsewhere
2048          *             * hardlink elsewhere
2049          *             * new file/other
2050          * Don't want to compare to device of /tmp because some modern systems
2051          * have regressed to having /tmp be the safe actual filesystem as
2052          * valuable data, so is mostly worthless, unless we assume that *only*
2053          * Linux systems do this and that all Linux has O_NOFOLLOW.  Something
2054          * for further consideration.
2055          * No point in doing a readlink on the lockfile as that will always be
2056          * at a different point in time from when we open it, so tells us
2057          * nothing; attempts to clean up and delete after ourselves would risk
2058          * deleting a *third* filename.
2059          */
2060         if ((statbuf2.st_nlink > 1) ||
2061             (lstatbuf.st_nlink > 1) ||
2062             (!S_ISREG(lstatbuf.st_mode)) ||
2063             (lstatbuf.st_dev != statbuf2.st_dev) ||
2064             (lstatbuf.st_ino != statbuf2.st_ino))
2065           {
2066           addr->basic_errno = ERRNO_LOCKFAILED;
2067           addr->message = string_sprintf("RACE CONDITION detected: "
2068               "mismatch post-initial-checks between \"%s\" and opened "
2069               "fd lead us to abort!", mbx_lockname);
2070           goto RETURN;
2071           }
2072
2073         (void)Uchmod(mbx_lockname, ob->lockfile_mode);
2074
2075         if (apply_lock(mbx_lockfd, F_WRLCK, ob->use_fcntl,
2076             ob->lock_fcntl_timeout, ob->use_flock, ob->lock_flock_timeout) >= 0)
2077           {
2078           struct stat ostatbuf;
2079
2080           /* This tests for a specific race condition. Ensure that we still
2081           have the same file. */
2082
2083           if (Ulstat(mbx_lockname, &statbuf) == 0 &&
2084               fstat(mbx_lockfd, &ostatbuf) == 0 &&
2085               statbuf.st_dev == ostatbuf.st_dev &&
2086               statbuf.st_ino == ostatbuf.st_ino)
2087             break;
2088           DEBUG(D_transport) debug_printf("MBX lockfile %s changed "
2089             "between creation and locking\n", mbx_lockname);
2090           }
2091
2092         DEBUG(D_transport) debug_printf("failed to lock %s: %s\n", mbx_lockname,
2093           strerror(errno));
2094         (void)close(mbx_lockfd);
2095         mbx_lockfd = -1;
2096         }
2097       else
2098         {
2099         DEBUG(D_transport) debug_printf("failed to fstat or get read lock on %s: %s\n",
2100           filename, strerror(errno));
2101         }
2102       }
2103     #endif  /* SUPPORT_MBX */
2104
2105     else break;   /* No on-file locking required; break the open/lock loop */
2106
2107     DEBUG(D_transport)
2108       debug_printf("fcntl(), flock(), or MBX locking failed - retrying\n");
2109
2110     (void)close(fd);
2111     fd = -1;
2112     use_lstat = TRUE;             /* Reset to use lstat first */
2113
2114
2115     /* If a blocking call timed out, break the retry loop if the total time
2116     so far is not less than than retries * interval. Use the larger of the
2117     flock() and fcntl() timeouts. */
2118
2119     if (sigalrm_seen &&
2120         (i+1) * ((ob->lock_fcntl_timeout > ob->lock_flock_timeout)?
2121           ob->lock_fcntl_timeout : ob->lock_flock_timeout) >=
2122           ob->lock_retries * ob->lock_interval)
2123       i = ob->lock_retries;
2124
2125     /* Wait a bit before retrying, except when it was a blocked fcntl() or
2126     flock() that caused the problem. */
2127
2128     if (i < ob->lock_retries && sleep_before_retry) sleep(ob->lock_interval);
2129     }
2130
2131   /* Test for exceeding the maximum number of tries. Either the file remains
2132   locked, or, if we haven't got it open, something is terribly wrong... */
2133
2134   if (i >= ob->lock_retries)
2135     {
2136     if (!file_opened)
2137       {
2138       addr->basic_errno = ERRNO_EXISTRACE;
2139       addr->message = string_sprintf("mailbox %s: existence unclear", filename);
2140       addr->special_action = SPECIAL_FREEZE;
2141       }
2142     else
2143       {
2144       addr->basic_errno = ERRNO_LOCKFAILED;
2145       addr->message = string_sprintf("failed to lock mailbox %s (fcntl/flock)",
2146         filename);
2147       }
2148     goto RETURN;
2149     }
2150
2151   DEBUG(D_transport) debug_printf("mailbox %s is locked\n", filename);
2152
2153   /* Save access time (for subsequent restoration), modification time (for
2154   restoration if updating fails), size of file (for comsat and for re-setting if
2155   delivery fails in the middle - e.g. for quota exceeded). */
2156
2157   if (fstat(fd, &statbuf) < 0)
2158     {
2159     addr->basic_errno = errno;
2160     addr->message = string_sprintf("while fstatting opened mailbox %s",
2161       filename);
2162     goto RETURN;
2163     }
2164
2165   times.actime = statbuf.st_atime;
2166   times.modtime = statbuf.st_mtime;
2167   saved_size = statbuf.st_size;
2168   if (mailbox_size < 0) mailbox_size = saved_size;
2169   mailbox_filecount = 0;  /* Not actually relevant for single-file mailbox */
2170   }
2171
2172 /* Prepare for writing to a new file (as opposed to appending to an old one).
2173 There are several different formats, but there is preliminary stuff concerned
2174 with quotas that applies to all of them. Finding the current size by directory
2175 scanning is expensive; for maildirs some fudges have been invented:
2176
2177   (1) A regex can be used to extract a file size from its name;
2178   (2) If maildir_use_size is set, a maildirsize file is used to cache the
2179       mailbox size.
2180 */
2181
2182 else
2183   {
2184   uschar *check_path;           /* Default quota check path */
2185   const pcre2_code * re = NULL;     /* Regex for file size from file name */
2186
2187   if (!check_creation(string_sprintf("%s/any", path),
2188                       ob->create_file, deliver_dir))
2189     {
2190     addr->basic_errno = ERRNO_BADCREATE;
2191     addr->message = string_sprintf("tried to create file in %s, but "
2192       "file creation outside the home directory is not permitted", path);
2193     goto RETURN;
2194     }
2195
2196   /* If the create_file option is an absolute path and the file was within
2197   it, de-taint. Otherwise check for taint. */
2198
2199   if (is_tainted(path))
2200     if (ob->create_file == create_belowhome)
2201       {
2202       DEBUG(D_transport) debug_printf("de-tainting path '%s'\n", path);
2203       path = string_copy_taint(path, GET_UNTAINTED);
2204       }
2205     else
2206       goto tainted_ret_panic;
2207
2208   check_path = path;
2209
2210   #ifdef SUPPORT_MAILDIR
2211   /* For a maildir delivery, ensure that all the relevant directories exist,
2212   and a maildirfolder file if necessary. */
2213
2214   if (mbformat == mbf_maildir && !maildir_ensure_directories(path, addr,
2215     ob->create_directory, ob->dirmode, ob->maildirfolder_create_regex))
2216       return FALSE;
2217   #endif  /* SUPPORT_MAILDIR */
2218
2219   /* If we are going to do a quota check, of if maildir_use_size_file is set
2220   for a maildir delivery, compile the regular expression if there is one. We
2221   may also need to adjust the path that is used. We need to do this for
2222   maildir_use_size_file even if the quota is unset, because we still want to
2223   create the file. When maildir support is not compiled,
2224   ob->maildir_use_size_file is always FALSE. */
2225
2226   if (ob->quota_value > 0 || THRESHOLD_CHECK || ob->maildir_use_size_file)
2227     {
2228     /* Compile the regex if there is one. */
2229
2230     if (ob->quota_size_regex)
2231       {
2232       if (!(re = regex_compile(ob->quota_size_regex,
2233                   MCS_NOFLAGS, &addr->message, pcre_gen_cmp_ctx)))
2234         return FALSE;
2235
2236       DEBUG(D_transport) debug_printf("using regex for file sizes: %s\n",
2237         ob->quota_size_regex);
2238       }
2239
2240     /* Use an explicitly configured directory if set */
2241
2242     if (ob->quota_directory)
2243       {
2244       if (!(check_path = expand_string(ob->quota_directory)))
2245         {
2246         addr->message = string_sprintf("Expansion of \"%s\" (quota_directory "
2247          "name for %s transport) failed: %s", ob->quota_directory,
2248           tblock->name, expand_string_message);
2249         goto ret_panic;
2250         }
2251
2252       if (check_path[0] != '/')
2253         {
2254         addr->message = string_sprintf("appendfile: quota_directory name "
2255           "\"%s\" is not absolute", check_path);
2256         addr->basic_errno = ERRNO_NOTABSOLUTE;
2257         return FALSE;
2258         }
2259       }
2260
2261     #ifdef SUPPORT_MAILDIR
2262     /* Otherwise, if we are handling a maildir delivery, and the directory
2263     contains a file called maildirfolder, this is a maildir++ feature telling
2264     us that this is a sub-directory of the real inbox. We should therefore do
2265     the quota check on the parent directory. Beware of the special case when
2266     the directory name itself ends in a slash. */
2267
2268     else if (mbformat == mbf_maildir)
2269       {
2270       struct stat statbuf;
2271       if (Ustat(string_sprintf("%s/maildirfolder", path), &statbuf) >= 0)
2272         {
2273         uschar *new_check_path = string_copy(check_path);
2274         uschar *slash = Ustrrchr(new_check_path, '/');
2275         if (slash)
2276           {
2277           if (!slash[1])
2278             {
2279             *slash = 0;
2280             slash = Ustrrchr(new_check_path, '/');
2281             }
2282           if (slash)
2283             {
2284             *slash = 0;
2285             check_path = new_check_path;
2286             DEBUG(D_transport) debug_printf("maildirfolder file exists: "
2287               "quota check directory changed to %s\n", check_path);
2288             }
2289           }
2290         }
2291       }
2292     #endif  /* SUPPORT_MAILDIR */
2293     }
2294
2295   /* If we are using maildirsize files, we need to ensure that such a file
2296   exists and, if necessary, recalculate its contents. As a byproduct of this,
2297   we obtain the current size of the maildir. If no quota is to be enforced
2298   (ob->quota_value == 0), we still need the size if a threshold check will
2299   happen later.
2300
2301   Another regular expression is used to determine which directories inside the
2302   maildir are going to be counted. */
2303
2304   #ifdef SUPPORT_MAILDIR
2305   if (ob->maildir_use_size_file)
2306     {
2307     const pcre2_code * dir_regex = NULL;
2308
2309     if (ob->maildir_dir_regex)
2310       {
2311       int check_path_len = Ustrlen(check_path);
2312
2313       if (!(dir_regex = regex_compile(ob->maildir_dir_regex,
2314             MCS_NOFLAGS, &addr->message, pcre_gen_cmp_ctx)))
2315         return FALSE;
2316
2317       DEBUG(D_transport)
2318         debug_printf("using regex for maildir directory selection: %s\n",
2319           ob->maildir_dir_regex);
2320
2321       /* Check to see if we are delivering into an ignored directory, that is,
2322       if the delivery path starts with the quota check path, and the rest
2323       of the deliver path matches the regex; if so, set a flag to disable quota
2324       checking and maildirsize updating. */
2325
2326       if (Ustrncmp(path, check_path, check_path_len) == 0)
2327         {
2328         uschar *s = path + check_path_len;
2329         while (*s == '/') s++;
2330         s = *s ? string_sprintf("%s/new", s) : US"new";
2331         if (!regex_match(dir_regex, s, -1, NULL))
2332           {
2333           disable_quota = TRUE;
2334           DEBUG(D_transport) debug_printf("delivery directory does not match "
2335             "maildir_quota_directory_regex: disabling quota\n");
2336           }
2337         }
2338       }
2339
2340     /* Quota enforcement; create and check the file. There is some discussion
2341     about whether this should happen if the quota is unset. At present, Exim
2342     always creates the file. If we ever want to change this, uncomment
2343     appropriate lines below, possibly doing a check on some option. */
2344
2345 /*  if (???? || ob->quota_value > 0) */
2346
2347     if (!disable_quota)
2348       {
2349       off_t size;
2350       int filecount;
2351
2352       if ((maildirsize_fd = maildir_ensure_sizefile(check_path, ob,  re, dir_regex,
2353           &size, &filecount)) == -1)
2354         {
2355         addr->basic_errno = errno;
2356         addr->message = string_sprintf("while opening or reading "
2357           "%s/maildirsize", check_path);
2358         return FALSE;
2359         }
2360       /* can also return -2, which means that the file was removed because of
2361       raciness; but in this case, the size & filecount will still have been
2362       updated. */
2363
2364       if (mailbox_size < 0) mailbox_size = size;
2365       if (mailbox_filecount < 0) mailbox_filecount = filecount;
2366       }
2367
2368     /* No quota enforcement; ensure file does *not* exist; calculate size if
2369     needed. */
2370
2371 /*  else
2372  *    {
2373  *    time_t old_latest;
2374  *    (void)unlink(CS string_sprintf("%s/maildirsize", check_path));
2375  *    if (THRESHOLD_CHECK)
2376  *      mailbox_size = maildir_compute_size(check_path, &mailbox_filecount, &old_latest,
2377  *         re, dir_regex, FALSE);
2378  *    }
2379 */
2380
2381     }
2382   #endif  /* SUPPORT_MAILDIR */
2383
2384   /* Otherwise if we are going to do a quota check later on, and the mailbox
2385   size is not set, find the current size of the mailbox. Ditto for the file
2386   count. Note that ob->quota_filecount_value cannot be set without
2387   ob->quota_value being set. */
2388
2389   if (  !disable_quota
2390      && (ob->quota_value > 0 || THRESHOLD_CHECK)
2391      && (  mailbox_size < 0
2392         || mailbox_filecount < 0 && ob->quota_filecount_value > 0
2393     )   )
2394     {
2395     off_t size;
2396     int filecount = 0;
2397     DEBUG(D_transport)
2398       debug_printf("quota checks on directory %s\n", check_path);
2399     size = check_dir_size(check_path, &filecount,  re);
2400     if (mailbox_size < 0) mailbox_size = size;
2401     if (mailbox_filecount < 0) mailbox_filecount = filecount;
2402     }
2403
2404   /* Handle the case of creating a unique file in a given directory (not in
2405   maildir or mailstore format - this is how smail did it). A temporary name is
2406   used to create the file. Later, when it is written, the name is changed to a
2407   unique one. There is no need to lock the file. An attempt is made to create
2408   the directory if it does not exist. */
2409
2410   if (mbformat == mbf_smail)
2411     {
2412     DEBUG(D_transport)
2413       debug_printf("delivering to new file in %s\n", path);
2414     filename = dataname =
2415       string_sprintf("%s/temp.%d.%s", path, (int)getpid(), primary_hostname);
2416     fd = Uopen(filename, O_WRONLY|O_CREAT, mode);
2417     if (fd < 0 &&                                 /* failed to open, and */
2418         (errno != ENOENT ||                       /* either not non-exist */
2419          !ob->create_directory ||                 /* or not allowed to make */
2420          !directory_make(NULL, path, ob->dirmode, FALSE) ||  /* or failed to create dir */
2421          (fd = Uopen(filename, O_WRONLY|O_CREAT|O_EXCL, mode)) < 0)) /* or then failed to open */
2422       {
2423       addr->basic_errno = errno;
2424       addr->message = string_sprintf("while creating file %s", filename);
2425       return FALSE;
2426       }
2427     }
2428
2429   #ifdef SUPPORT_MAILDIR
2430
2431   /* Handle the case of a unique file in maildir format. The file is written to
2432   the tmp subdirectory, with a prescribed form of name. */
2433
2434   else if (mbformat == mbf_maildir)
2435     {
2436     DEBUG(D_transport)
2437       debug_printf("delivering in maildir format in %s\n", path);
2438
2439     nametag = ob->maildir_tag;
2440
2441     /* Check that nametag expands successfully; a hard failure causes a panic
2442     return. The actual expansion for use happens again later, when
2443     $message_size is accurately known. */
2444
2445     if (nametag && !expand_string(nametag) && !f.expand_string_forcedfail)
2446       {
2447       addr->message = string_sprintf("Expansion of \"%s\" (maildir_tag "
2448         "for %s transport) failed: %s", nametag, tblock->name,
2449         expand_string_message);
2450       goto ret_panic;
2451       }
2452
2453     /* We ensured the existence of all the relevant directories above. Attempt
2454     to open the temporary file a limited number of times. I think this rather
2455     scary-looking for statement is actually OK. If open succeeds, the loop is
2456     broken; if not, there is a test on the value of i. Get the time again
2457     afresh each time round the loop. Its value goes into a variable that is
2458     checked at the end, to make sure we don't release this process until the
2459     clock has ticked. */
2460
2461     for (int i = 1;; i++)
2462       {
2463       uschar *basename;
2464
2465       (void)gettimeofday(&msg_tv, NULL);
2466       basename = string_sprintf(TIME_T_FMT ".M%luP" PID_T_FMT ".%s",
2467         msg_tv.tv_sec, msg_tv.tv_usec, getpid(), primary_hostname);
2468
2469       filename = dataname = string_sprintf("tmp/%s", basename);
2470       newname = string_sprintf("new/%s", basename);
2471
2472       if (Ustat(filename, &statbuf) == 0)
2473         errno = EEXIST;
2474       else if (errno == ENOENT)
2475         {
2476         if ((fd = Uopen(filename, O_WRONLY | O_CREAT | O_EXCL, mode)) >= 0)
2477           break;
2478         DEBUG (D_transport) debug_printf ("open failed for %s: %s\n",
2479           filename, strerror(errno));
2480         }
2481
2482       /* Too many retries - give up */
2483
2484       if (i >= ob->maildir_retries)
2485         {
2486         addr->message = string_sprintf ("failed to open %s (%d tr%s)",
2487           filename, i, (i == 1) ? "y" : "ies");
2488         addr->basic_errno = errno;
2489         if (errno == errno_quota || errno == ENOSPC)
2490           addr->user_message = US"mailbox is full";
2491         return FALSE;
2492         }
2493
2494       /* Open or stat failed but we haven't tried too many times yet. */
2495
2496       sleep(2);
2497       }
2498
2499     /* Note that we have to ensure the clock has ticked before leaving */
2500
2501     wait_for_tick = TRUE;
2502
2503     /* Why are these here? Put in because they are present in the non-maildir
2504     directory case above. */
2505
2506     if (exim_chown(filename, uid, gid) || Uchmod(filename, mode))
2507       {
2508       addr->basic_errno = errno;
2509       addr->message = string_sprintf("while setting perms on maildir %s",
2510         filename);
2511       return FALSE;
2512       }
2513     }
2514
2515   #endif  /* SUPPORT_MAILDIR */
2516
2517   #ifdef SUPPORT_MAILSTORE
2518
2519   /* Handle the case of a unique file in mailstore format. First write the
2520   envelope to a temporary file, then open the main file. The unique base name
2521   for the files consists of the message id plus the pid of this delivery
2522   process. */
2523
2524   else
2525     {
2526     FILE * env_file;
2527     mailstore_basename = string_sprintf("%s/%s-%s", path, message_id,
2528       string_base62_64((long int)getpid()));
2529
2530     DEBUG(D_transport)
2531       debug_printf("delivering in mailstore format in %s\n", path);
2532
2533     filename = string_sprintf("%s.tmp", mailstore_basename);
2534     newname  = string_sprintf("%s.env", mailstore_basename);
2535     dataname = string_sprintf("%s.msg", mailstore_basename);
2536
2537     fd = Uopen(filename, O_WRONLY|O_CREAT|O_EXCL, mode);
2538     if (  fd < 0                                /* failed to open, and */
2539        && (   errno != ENOENT                   /* either not non-exist */
2540           || !ob->create_directory              /* or not allowed to make */
2541           || !directory_make(NULL, path, ob->dirmode, FALSE)  /* or failed to create dir */
2542           || (fd = Uopen(filename, O_WRONLY|O_CREAT|O_EXCL, mode)) < 0 /* or then failed to open */
2543        )  )
2544       {
2545       addr->basic_errno = errno;
2546       addr->message = string_sprintf("while creating file %s", filename);
2547       return FALSE;
2548       }
2549
2550     /* Why are these here? Put in because they are present in the non-maildir
2551     directory case above. */
2552
2553     if (exim_chown(filename, uid, gid) || Uchmod(filename, mode))
2554       {
2555       addr->basic_errno = errno;
2556       addr->message = string_sprintf("while setting perms on file %s",
2557         filename);
2558       return FALSE;
2559       }
2560
2561     /* Built a C stream from the open file descriptor. */
2562
2563     if (!(env_file = fdopen(fd, "wb")))
2564       {
2565       addr->basic_errno = errno;
2566       addr->message = string_sprintf("fdopen of %s ("
2567         "for %s transport) failed", filename, tblock->name);
2568       (void)close(fd);
2569       Uunlink(filename);
2570       goto ret_panic;
2571       }
2572
2573     /* Write the envelope file, then close it. */
2574
2575     if (ob->mailstore_prefix)
2576       {
2577       uschar *s = expand_string(ob->mailstore_prefix);
2578       if (!s)
2579         {
2580         if (!f.expand_string_forcedfail)
2581           {
2582           addr->message = string_sprintf("Expansion of \"%s\" (mailstore "
2583             "prefix for %s transport) failed: %s", ob->mailstore_prefix,
2584             tblock->name, expand_string_message);
2585           (void)fclose(env_file);
2586           Uunlink(filename);
2587           goto ret_panic;
2588           }
2589         }
2590       else
2591         {
2592         int n = Ustrlen(s);
2593         fprintf(env_file, "%s", CS s);
2594         if (n == 0 || s[n-1] != '\n') fprintf(env_file, "\n");
2595         }
2596       }
2597
2598     fprintf(env_file, "%s\n", sender_address);
2599
2600     for (address_item * taddr = addr; taddr; taddr = taddr->next)
2601       fprintf(env_file, "%s@%s\n", taddr->local_part, taddr->domain);
2602
2603     if (ob->mailstore_suffix)
2604       {
2605       uschar *s = expand_string(ob->mailstore_suffix);
2606       if (!s)
2607         {
2608         if (!f.expand_string_forcedfail)
2609           {
2610           addr->message = string_sprintf("Expansion of \"%s\" (mailstore "
2611             "suffix for %s transport) failed: %s", ob->mailstore_suffix,
2612             tblock->name, expand_string_message);
2613           (void)fclose(env_file);
2614           Uunlink(filename);
2615           goto ret_panic;
2616           }
2617         }
2618       else
2619         {
2620         int n = Ustrlen(s);
2621         fprintf(env_file, "%s", CS s);
2622         if (n == 0 || s[n-1] != '\n') fprintf(env_file, "\n");
2623         }
2624       }
2625
2626     if (fclose(env_file) != 0)
2627       {
2628       addr->basic_errno = errno;
2629       addr->message = string_sprintf("while closing %s", filename);
2630       Uunlink(filename);
2631       return FALSE;
2632       }
2633
2634     DEBUG(D_transport) debug_printf("Envelope file %s written\n", filename);
2635
2636     /* Now open the data file, and ensure that it has the correct ownership and
2637     mode. */
2638
2639     if ((fd = Uopen(dataname, O_WRONLY|O_CREAT|O_EXCL, mode)) < 0)
2640       {
2641       addr->basic_errno = errno;
2642       addr->message = string_sprintf("while creating file %s", dataname);
2643       Uunlink(filename);
2644       return FALSE;
2645       }
2646     if (exim_chown(dataname, uid, gid) || Uchmod(dataname, mode))
2647       {
2648       addr->basic_errno = errno;
2649       addr->message = string_sprintf("while setting perms on file %s",
2650         dataname);
2651       return FALSE;
2652       }
2653     }
2654
2655   #endif  /* SUPPORT_MAILSTORE */
2656
2657
2658   /* In all cases of writing to a new file, ensure that the file which is
2659   going to be renamed has the correct ownership and mode. */
2660
2661   if (exim_chown(filename, uid, gid) || Uchmod(filename, mode))
2662     {
2663     addr->basic_errno = errno;
2664     addr->message = string_sprintf("while setting perms on file %s",
2665       filename);
2666     return FALSE;
2667     }
2668   }
2669
2670
2671 /* At last we can write the message to the file, preceded by any configured
2672 prefix line, and followed by any configured suffix line. If there are any
2673 writing errors, we must defer. */
2674
2675 DEBUG(D_transport) debug_printf("writing to file %s\n", dataname);
2676
2677 yield = OK;
2678 errno = 0;
2679
2680 /* If there is a local quota setting, check that we are not going to exceed it
2681 with this message if quota_is_inclusive is set; if it is not set, the check
2682 is for the mailbox already being over quota (i.e. the current message is not
2683 included in the check). */
2684
2685 if (!disable_quota && ob->quota_value > 0)
2686   {
2687   DEBUG(D_transport)
2688     {
2689     debug_printf("Exim quota = " OFF_T_FMT " old size = " OFF_T_FMT
2690       " this message = %d (%sincluded)\n",
2691       ob->quota_value, mailbox_size, message_size,
2692       ob->quota_is_inclusive ? "" : "not ");
2693     debug_printf("  file count quota = %d count = %d\n",
2694       ob->quota_filecount_value, mailbox_filecount);
2695     }
2696
2697   if (mailbox_size + (ob->quota_is_inclusive ? message_size:0) > ob->quota_value)
2698     if (!ob->quota_no_check)
2699       {
2700       DEBUG(D_transport) debug_printf("mailbox quota exceeded\n");
2701       yield = DEFER;
2702       errno = ERRNO_EXIMQUOTA;
2703       }
2704     else
2705       DEBUG(D_transport) debug_printf("mailbox quota exceeded but ignored\n");
2706
2707   if (ob->quota_filecount_value > 0
2708            && mailbox_filecount + (ob->quota_is_inclusive ? 1:0) >
2709               ob->quota_filecount_value)
2710     if (!ob->quota_filecount_no_check)
2711       {
2712       DEBUG(D_transport) debug_printf("mailbox file count quota exceeded\n");
2713       yield = DEFER;
2714       errno = ERRNO_EXIMQUOTA;
2715       filecount_msg = US" filecount";
2716       }
2717     else DEBUG(D_transport) if (ob->quota_filecount_no_check)
2718       debug_printf("mailbox file count quota exceeded but ignored\n");
2719
2720   }
2721
2722 if (verify_mode)
2723   {
2724   addr->basic_errno = errno;
2725   addr->message = US"Over quota";
2726   addr->transport_return = yield;
2727   DEBUG(D_transport)
2728     debug_printf("appendfile (verify) yields %d with errno=%d more_errno=%d\n",
2729       yield, addr->basic_errno, addr->more_errno);
2730
2731   goto RETURN;
2732   }
2733
2734 /* If we are writing in MBX format, what we actually do is to write the message
2735 to a temporary file, and then copy it to the real file once we know its size.
2736 This is the most straightforward way of getting the correct length in the
2737 separator line. So, what we do here is to save the real file descriptor, and
2738 replace it with one for a temporary file. The temporary file gets unlinked once
2739 opened, so that it goes away on closure. */
2740
2741 #ifdef SUPPORT_MBX
2742 if (yield == OK && ob->mbx_format)
2743   {
2744   if (!(temp_file = tmpfile()))
2745     {
2746     addr->basic_errno = errno;
2747     addr->message = US"while setting up temporary file";
2748     yield = DEFER;
2749     goto RETURN;
2750     }
2751   save_fd = fd;
2752   fd = fileno(temp_file);
2753   DEBUG(D_transport) debug_printf("writing to temporary file\n");
2754   }
2755 #endif  /* SUPPORT_MBX */
2756
2757 /* Zero the count of bytes written. It is incremented by the transport_xxx()
2758 functions. */
2759
2760 transport_count = 0;
2761 transport_newlines = 0;
2762
2763 /* Write any configured prefix text first */
2764
2765 if (yield == OK && ob->message_prefix && *ob->message_prefix)
2766   {
2767   uschar *prefix = expand_string(ob->message_prefix);
2768   if (!prefix)
2769     {
2770     errno = ERRNO_EXPANDFAIL;
2771     addr->transport_return = PANIC;
2772     addr->message = string_sprintf("Expansion of \"%s\" (prefix for %s "
2773       "transport) failed", ob->message_prefix, tblock->name);
2774     yield = DEFER;
2775     }
2776   else if (!transport_write_string(fd, "%s", prefix)) yield = DEFER;
2777   }
2778
2779 /* If the use_bsmtp option is on, we need to write SMTP prefix information. The
2780 various different values for batching are handled outside; if there is more
2781 than one address available here, all must be included. If any address is a
2782 file, use its parent in the RCPT TO. */
2783
2784 if (yield == OK && ob->use_bsmtp)
2785   {
2786   transport_count = 0;
2787   transport_newlines = 0;
2788   if (ob->use_crlf) cr = US"\r";
2789   if (!transport_write_string(fd, "MAIL FROM:<%s>%s\n", return_path, cr))
2790     yield = DEFER;
2791   else
2792     {
2793     transport_newlines++;
2794     for (address_item * a = addr; a; a = a->next)
2795       {
2796       address_item * b = testflag(a, af_pfr) ? a->parent : a;
2797       if (!transport_write_string(fd, "RCPT TO:<%s>%s\n",
2798         transport_rcpt_address(b, tblock->rcpt_include_affixes), cr))
2799           { yield = DEFER; break; }
2800       transport_newlines++;
2801       }
2802     if (yield == OK && !transport_write_string(fd, "DATA%s\n", cr))
2803       yield = DEFER;
2804     else
2805       transport_newlines++;
2806     }
2807   }
2808
2809 /* Now the message itself. The options for transport_write_message were set up
2810 at initialization time. */
2811
2812 if (yield == OK)
2813   {
2814   transport_ctx tctx = {
2815     .u = {.fd=fd},
2816     .tblock = tblock,
2817     .addr = addr,
2818     .check_string = ob->check_string,
2819     .escape_string = ob->escape_string,
2820     .options =  ob->options | topt_not_socket
2821   };
2822   if (!transport_write_message(&tctx, 0))
2823     yield = DEFER;
2824   }
2825
2826 /* Now a configured suffix. */
2827
2828 if (yield == OK && ob->message_suffix && *ob->message_suffix)
2829   {
2830   uschar *suffix = expand_string(ob->message_suffix);
2831   if (!suffix)
2832     {
2833     errno = ERRNO_EXPANDFAIL;
2834     addr->transport_return = PANIC;
2835     addr->message = string_sprintf("Expansion of \"%s\" (suffix for %s "
2836       "transport) failed", ob->message_suffix, tblock->name);
2837     yield = DEFER;
2838     }
2839   else if (!transport_write_string(fd, "%s", suffix)) yield = DEFER;
2840   }
2841
2842 /* If batch smtp, write the terminating dot. */
2843
2844 if (yield == OK && ob->use_bsmtp)
2845   if (!transport_write_string(fd, ".%s\n", cr)) yield = DEFER;
2846   else transport_newlines++;
2847
2848 /* If MBX format is being used, all that writing was to the temporary file.
2849 However, if there was an earlier failure (Exim quota exceeded, for example),
2850 the temporary file won't have got opened - and no writing will have been done.
2851 If writing was OK, we restore the fd, and call a function that copies the
2852 message in MBX format into the real file. Otherwise use the temporary name in
2853 any messages. */
2854
2855 #ifdef SUPPORT_MBX
2856 if (temp_file && ob->mbx_format)
2857   {
2858   int mbx_save_errno;
2859   fd = save_fd;
2860
2861   if (yield == OK)
2862     {
2863     transport_count = 0;   /* Reset transport count for actual write */
2864     /* No need to reset transport_newlines as we're just using a block copy
2865      * routine so the number won't be affected */
2866     yield = copy_mbx_message(fd, fileno(temp_file), saved_size);
2867     }
2868   else if (errno >= 0) dataname = US"temporary file";
2869
2870   /* Preserve errno while closing the temporary file. */
2871
2872   mbx_save_errno = errno;
2873   (void)fclose(temp_file);
2874   errno = mbx_save_errno;
2875   }
2876 #endif  /* SUPPORT_MBX */
2877
2878 /* Force out the remaining data to check for any errors; some OS don't allow
2879 fsync() to be called for a FIFO. */
2880
2881 if (yield == OK && !isfifo && EXIMfsync(fd) < 0) yield = DEFER;
2882
2883 /* Update message_size and message_linecount to the accurate count of bytes
2884 written, including added headers. Note; we subtract 1 from message_linecount as
2885 this variable doesn't count the new line between the header and the body of the
2886 message. */
2887
2888 message_size = transport_count;
2889 message_linecount = transport_newlines - 1;
2890
2891 /* If using a maildir++ quota file, add this message's size to it, and
2892 close the file descriptor, except when the quota has been disabled because we
2893 are delivering into an uncounted folder. */
2894
2895 #ifdef SUPPORT_MAILDIR
2896 if (!disable_quota)
2897   {
2898   if (yield == OK && maildirsize_fd >= 0)
2899     maildir_record_length(maildirsize_fd, message_size);
2900   maildir_save_errno = errno;    /* Preserve errno while closing the file */
2901   if (maildirsize_fd >= 0)
2902     (void)close(maildirsize_fd);
2903   errno = maildir_save_errno;
2904   }
2905 #endif  /* SUPPORT_MAILDIR */
2906
2907 /* If there is a quota warning threshold and we are have crossed it with this
2908 message, set the SPECIAL_WARN flag in the address, to cause a warning message
2909 to be sent. */
2910
2911 if (!disable_quota && THRESHOLD_CHECK)
2912   {
2913   off_t threshold = ob->quota_warn_threshold_value;
2914   if (ob->quota_warn_threshold_is_percent)
2915     threshold = (off_t)(((double)ob->quota_value * threshold) / 100);
2916   DEBUG(D_transport)
2917     debug_printf("quota = " OFF_T_FMT
2918       " threshold = " OFF_T_FMT
2919       " old size = " OFF_T_FMT
2920       " message size = %d\n",
2921       ob->quota_value, threshold, mailbox_size,
2922       message_size);
2923   if (mailbox_size <= threshold && mailbox_size + message_size > threshold)
2924     addr->special_action = SPECIAL_WARN;
2925
2926   /******* You might think that the test ought to be this:
2927   *
2928   * if (ob->quota_value > 0 && threshold > 0 && mailbox_size > 0 &&
2929   *     mailbox_size <= threshold && mailbox_size + message_size > threshold)
2930   *
2931   * (indeed, I was sent a patch with that in). However, it is possible to
2932   * have a warning threshold without actually imposing a quota, and I have
2933   * therefore kept Exim backwards compatible.
2934   ********/
2935
2936   }
2937
2938 /* Handle error while writing the file. Control should come here directly after
2939 the error, with the reason in errno. In the case of expansion failure in prefix
2940 or suffix, it will be ERRNO_EXPANDFAIL. */
2941
2942 if (yield != OK)
2943   {
2944   addr->special_action = SPECIAL_NONE;     /* Cancel any quota warning */
2945
2946   /* Save the error number. If positive, it will ultimately cause a strerror()
2947   call to generate some text. */
2948
2949   addr->basic_errno = errno;
2950
2951   /* For system or Exim quota excession, or disk full, set more_errno to the
2952   time since the file was last read. If delivery was into a directory, the
2953   time since last read logic is not relevant, in general. However, for maildir
2954   deliveries we can approximate it by looking at the last modified time of the
2955   "new" subdirectory. Since Exim won't be adding new messages, a change to the
2956   "new" subdirectory implies that an MUA has moved a message from there to the
2957   "cur" directory. */
2958
2959   if (errno == errno_quota || errno == ERRNO_EXIMQUOTA || errno == ENOSPC)
2960     {
2961     addr->more_errno = 0;
2962     if (!isdirectory) addr->more_errno = (int)(time(NULL) - times.actime);
2963
2964     #ifdef SUPPORT_MAILDIR
2965     else if (mbformat == mbf_maildir)
2966       {
2967       struct stat statbuf;
2968       if (Ustat("new", &statbuf) < 0)
2969         {
2970         DEBUG(D_transport) debug_printf("maildir quota exceeded: "
2971           "stat error %d for \"new\": %s\n", errno, strerror(errno));
2972         }
2973       else   /* Want a repeatable time when in test harness */
2974         addr->more_errno = f.running_in_test_harness ? 10 :
2975           (int)time(NULL) - statbuf.st_mtime;
2976
2977       DEBUG(D_transport)
2978         debug_printf("maildir: time since \"new\" directory modified = %s\n",
2979         readconf_printtime(addr->more_errno));
2980       }
2981     #endif /* SUPPORT_MAILDIR */
2982     }
2983
2984   /* Handle system quota excession. Add an explanatory phrase for the error
2985   message, since some systems don't have special quota-excession errors,
2986   and on those that do, "quota" doesn't always mean anything to the user. */
2987
2988   if (errno == errno_quota)
2989     {
2990     #ifndef EDQUOT
2991     addr->message = string_sprintf("mailbox is full "
2992       "(quota exceeded while writing to file %s)", filename);
2993     #else
2994     addr->message = US"mailbox is full";
2995     #endif  /* EDQUOT */
2996     addr->user_message = US"mailbox is full";
2997     DEBUG(D_transport) debug_printf("System quota exceeded for %s%s%s\n",
2998       dataname,
2999       isdirectory ? US"" : US": time since file read = ",
3000       isdirectory ? US"" : readconf_printtime(addr->more_errno));
3001     }
3002
3003   /* Handle Exim's own quota-imposition */
3004
3005   else if (errno == ERRNO_EXIMQUOTA)
3006     {
3007     addr->message = string_sprintf("mailbox is full "
3008       "(MTA-imposed%s quota exceeded while writing to %s)", filecount_msg,
3009         dataname);
3010     addr->user_message = US"mailbox is full";
3011     DEBUG(D_transport) debug_printf("Exim%s quota exceeded for %s%s%s\n",
3012       filecount_msg, dataname,
3013       isdirectory ? US"" : US": time since file read = ",
3014       isdirectory ? US"" : readconf_printtime(addr->more_errno));
3015     }
3016
3017   /* Handle a process failure while writing via a filter; the return
3018   from child_close() is in more_errno. */
3019
3020   else if (errno == ERRNO_FILTER_FAIL)
3021     {
3022     yield = PANIC;
3023     addr->message = string_sprintf("transport filter process failed (%d) "
3024       "while writing to %s%s", addr->more_errno, dataname,
3025       (addr->more_errno == EX_EXECFAILED) ? ": unable to execute command" : "");
3026     }
3027
3028   /* Handle failure to expand header changes */
3029
3030   else if (errno == ERRNO_CHHEADER_FAIL)
3031     {
3032     yield = PANIC;
3033     addr->message =
3034       string_sprintf("failed to expand headers_add or headers_remove while "
3035         "writing to %s: %s", dataname, expand_string_message);
3036     }
3037
3038   /* Handle failure to complete writing of a data block */
3039
3040   else if (errno == ERRNO_WRITEINCOMPLETE)
3041     addr->message = string_sprintf("failed to write data block while "
3042       "writing to %s", dataname);
3043
3044   /* Handle length mismatch on MBX copying */
3045
3046   #ifdef SUPPORT_MBX
3047   else if (errno == ERRNO_MBXLENGTH)
3048     addr->message = string_sprintf("length mismatch while copying MBX "
3049       "temporary file to %s", dataname);
3050   #endif  /* SUPPORT_MBX */
3051
3052   /* For other errors, a general-purpose explanation, if the message is
3053   not already set. */
3054
3055   else if (addr->message == NULL)
3056     addr->message = string_sprintf("error while writing to %s", dataname);
3057
3058   /* For a file, reset the file size to what it was before we started, leaving
3059   the last modification time unchanged, so it will get reset also. All systems
3060   investigated so far have ftruncate(), whereas not all have the F_FREESP
3061   fcntl() call (BSDI & FreeBSD do not). */
3062
3063   if (!isdirectory && ftruncate(fd, saved_size))
3064     DEBUG(D_transport) debug_printf("Error resetting file size\n");
3065   }
3066
3067 /* Handle successful writing - we want the modification time to be now for
3068 appended files. Remove the default backstop error number. For a directory, now
3069 is the time to rename the file with a unique name. As soon as such a name
3070 appears it may get used by another process, so we close the file first and
3071 check that all is well. */
3072
3073 else
3074   {
3075   times.modtime = time(NULL);
3076   addr->basic_errno = 0;
3077
3078   /* Handle the case of writing to a new file in a directory. This applies
3079   to all single-file formats - maildir, mailstore, and "smail format". */
3080
3081   if (isdirectory)
3082     {
3083     if (fstat(fd, &statbuf) < 0)
3084       {
3085       addr->basic_errno = errno;
3086       addr->message = string_sprintf("while fstatting opened message file %s",
3087         filename);
3088       yield = DEFER;
3089       }
3090
3091     else if (close(fd) < 0)
3092       {
3093       addr->basic_errno = errno;
3094       addr->message = string_sprintf("close() error for %s",
3095         (ob->mailstore_format) ? dataname : filename);
3096       yield = DEFER;
3097       }
3098
3099     /* File is successfully written and closed. Arrange to rename it. For the
3100     different kinds of single-file delivery, some games can be played with the
3101     name. The message size is by this time set to the accurate value so that
3102     its value can be used in expansions. */
3103
3104     else
3105       {
3106       uschar *renamename = newname;
3107       fd = -1;
3108
3109       DEBUG(D_transport) debug_printf("renaming temporary file\n");
3110
3111       /* If there is no rename name set, we are in a non-maildir, non-mailstore
3112       situation. The name is built by expanding the directory_file option, and
3113       we make the inode number available for use in this. The expansion was
3114       checked for syntactic validity above, before we wrote the file.
3115
3116       We have to be careful here, in case the file name exists. (In the other
3117       cases, the names used are constructed to be unique.) The rename()
3118       function just replaces an existing file - we don't want that! So instead
3119       of calling rename(), we must use link() and unlink().
3120
3121       In this case, if the link fails because of an existing file, we wait
3122       for one second and try the expansion again, to see if it produces a
3123       different value. Do this up to 5 times unless the name stops changing.
3124       This makes it possible to build values that are based on the time, and
3125       still cope with races from multiple simultaneous deliveries. */
3126
3127       if (!newname)
3128         {
3129         uschar *renameleaf;
3130         uschar *old_renameleaf = US"";
3131
3132         for (int i = 0; ; sleep(1), i++)
3133           {
3134           deliver_inode = statbuf.st_ino;
3135           renameleaf = expand_string(ob->dirfilename);
3136           deliver_inode = 0;
3137
3138           if (!renameleaf)
3139             {
3140             addr->transport_return = PANIC;
3141             addr->message = string_sprintf("Expansion of \"%s\" "
3142               "(directory_file for %s transport) failed: %s",
3143               ob->dirfilename, tblock->name, expand_string_message);
3144             goto RETURN;
3145             }
3146
3147           renamename = string_sprintf("%s/%s", path, renameleaf);
3148           if (Ulink(filename, renamename) < 0)
3149             {
3150             DEBUG(D_transport) debug_printf("link failed: %s\n",
3151               strerror(errno));
3152             if (errno != EEXIST || i >= 4 ||
3153                 Ustrcmp(renameleaf, old_renameleaf) == 0)
3154               {
3155               addr->basic_errno = errno;
3156               addr->message = string_sprintf("while renaming %s as %s",
3157                 filename, renamename);
3158               yield = DEFER;
3159               break;
3160               }
3161             old_renameleaf = renameleaf;
3162             DEBUG(D_transport) debug_printf("%s exists - trying again\n",
3163               renamename);
3164             }
3165           else
3166             {
3167             Uunlink(filename);
3168             filename = NULL;
3169             break;
3170             }
3171           }        /* re-expand loop */
3172         }          /* not mailstore or maildir */
3173
3174       /* For maildir and mailstore formats, the new name was created earlier,
3175       except that for maildir, there is the possibility of adding a "tag" on
3176       the end of the name by expanding the value of nametag. This usually
3177       includes a reference to the message size. The expansion of nametag was
3178       checked above, before the file was opened. It either succeeded, or
3179       provoked a soft failure. So any failure here can be treated as soft.
3180       Ignore non-printing characters and / and put a colon at the start if the
3181       first character is alphanumeric. */
3182
3183       else
3184         {
3185         if (nametag)
3186           {
3187           uschar *iptr = expand_string(nametag);
3188           if (iptr)
3189             {
3190             uschar *etag = store_get(Ustrlen(iptr) + 2, iptr);
3191             uschar *optr = etag;
3192             for ( ; *iptr; iptr++)
3193               if (mac_isgraph(*iptr) && *iptr != '/')
3194                 {
3195                 if (optr == etag && isalnum(*iptr)) *optr++ = ':';
3196                 *optr++ = *iptr;
3197                 }
3198             *optr = 0;
3199             renamename = string_sprintf("%s%s", newname, etag);
3200             }
3201           }
3202
3203         /* Do the rename. If the name is too long and a tag exists, try again
3204         without the tag. */
3205
3206         if (Urename(filename, renamename) < 0 &&
3207                (nametag == NULL || errno != ENAMETOOLONG ||
3208                (renamename = newname, Urename(filename, renamename) < 0)))
3209           {
3210           addr->basic_errno = errno;
3211           addr->message = string_sprintf("while renaming %s as %s",
3212             filename, renamename);
3213           yield = DEFER;
3214           }
3215
3216         /* Rename succeeded */
3217
3218         else
3219           {
3220           DEBUG(D_transport) debug_printf("renamed %s as %s\n", filename,
3221             renamename);
3222           filename = dataname = NULL;   /* Prevents attempt to unlink at end */
3223           }
3224         }        /* maildir or mailstore */
3225       }          /* successful write + close */
3226     }            /* isdirectory */
3227   }              /* write success */
3228
3229
3230 /* For a file, restore the last access time (atime), and set the modification
3231 time as required - changed if write succeeded, unchanged if not. */
3232
3233 if (!isdirectory) utime(CS filename, &times);
3234
3235 /* Notify comsat if configured to do so. It only makes sense if the configured
3236 file is the one that the comsat daemon knows about. */
3237
3238 if (ob->notify_comsat && yield == OK && deliver_localpart)
3239   notify_comsat(deliver_localpart, saved_size);
3240
3241 /* Pass back the final return code in the address structure */
3242
3243 DEBUG(D_transport)
3244   debug_printf("appendfile yields %d with errno=%d more_errno=%d\n",
3245     yield, addr->basic_errno, addr->more_errno);
3246
3247 addr->transport_return = yield;
3248
3249 /* Close the file, which will release the fcntl lock. For a directory write it
3250 is closed above, except in cases of error which goto RETURN, when we also need
3251 to remove the original file(s). For MBX locking, if all has gone well, before
3252 closing the file, see if we can get an exclusive lock on it, in which case we
3253 can unlink the /tmp lock file before closing it. This is always a non-blocking
3254 lock; there's no need to wait if we can't get it. If everything has gone right
3255 but close fails, defer the message. Then unlink the lock file, if present. This
3256 point in the code is jumped to from a number of places when errors are
3257 detected, in order to get the file closed and the lock file tidied away. */
3258
3259 RETURN:
3260
3261 #ifdef SUPPORT_MBX
3262 if (mbx_lockfd >= 0)
3263   {
3264   if (yield == OK && apply_lock(fd, F_WRLCK, ob->use_fcntl, 0,
3265       ob->use_flock, 0) >= 0)
3266     {
3267     DEBUG(D_transport)
3268       debug_printf("unlinking MBX lock file %s\n", mbx_lockname);
3269     Uunlink(mbx_lockname);
3270     }
3271   (void)close(mbx_lockfd);
3272   }
3273 #endif  /* SUPPORT_MBX */
3274
3275 if (fd >= 0 && close(fd) < 0 && yield == OK)
3276   {
3277   addr->basic_errno = errno;
3278   addr->message = string_sprintf("while closing %s", filename);
3279   addr->transport_return = DEFER;
3280   }
3281
3282 if (hd >= 0) Uunlink(lockname);
3283
3284 /* We get here with isdirectory and filename set only in error situations. */
3285
3286 if (isdirectory && filename)
3287   {
3288   Uunlink(filename);
3289   if (dataname != filename) Uunlink(dataname);
3290   }
3291
3292 /* If wait_for_tick is TRUE, we have done a delivery where the uniqueness of a
3293 file name relies on time + pid. We must not allow the process to finish until
3294 the clock has move on by at least one microsecond. Usually we expect this
3295 already to be the case, but machines keep getting faster... */
3296
3297 if (wait_for_tick) exim_wait_tick(&msg_tv, 1);
3298
3299 /* A return of FALSE means that if there was an error, a common error was
3300 put in the first address of a batch. */
3301
3302 return FALSE;
3303
3304 tainted_ret_panic:
3305   addr->message = string_sprintf("Tainted '%s' (file or directory "
3306       "name for %s transport) not permitted", path, tblock->name);
3307 ret_panic:
3308   addr->transport_return = PANIC;
3309   return FALSE;
3310 }
3311
3312 #endif  /*!MACRO_PREDEF*/
3313 /* End of transport/appendfile.c */