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