Add directory name as new arg to EXIM_DBOPEN
[exim.git] / src / src / transports / autoreply.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2016 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8
9 #include "../exim.h"
10 #include "autoreply.h"
11
12
13
14 /* Options specific to the autoreply transport. They must be in alphabetic
15 order (note that "_" comes before the lower case letters). Those starting
16 with "*" are not settable by the user but are used by the option-reading
17 software for alternative value types. Some options are publicly visible and so
18 are stored in the driver instance block. These are flagged with opt_public. */
19
20 optionlist autoreply_transport_options[] = {
21   { "bcc",               opt_stringptr,
22       (void *)offsetof(autoreply_transport_options_block, bcc) },
23   { "cc",                opt_stringptr,
24       (void *)offsetof(autoreply_transport_options_block, cc) },
25   { "file",              opt_stringptr,
26       (void *)offsetof(autoreply_transport_options_block, file) },
27   { "file_expand",     opt_bool,
28       (void *)offsetof(autoreply_transport_options_block, file_expand) },
29   { "file_optional",     opt_bool,
30       (void *)offsetof(autoreply_transport_options_block, file_optional) },
31   { "from",              opt_stringptr,
32       (void *)offsetof(autoreply_transport_options_block, from) },
33   { "headers",           opt_stringptr,
34       (void *)offsetof(autoreply_transport_options_block, headers) },
35   { "log",               opt_stringptr,
36       (void *)offsetof(autoreply_transport_options_block, logfile) },
37   { "mode",              opt_octint,
38       (void *)offsetof(autoreply_transport_options_block, mode) },
39   { "never_mail",        opt_stringptr,
40       (void *)offsetof(autoreply_transport_options_block, never_mail) },
41   { "once",              opt_stringptr,
42       (void *)offsetof(autoreply_transport_options_block, oncelog) },
43   { "once_file_size",    opt_int,
44       (void *)offsetof(autoreply_transport_options_block, once_file_size) },
45   { "once_repeat",       opt_stringptr,
46       (void *)offsetof(autoreply_transport_options_block, once_repeat) },
47   { "reply_to",          opt_stringptr,
48       (void *)offsetof(autoreply_transport_options_block, reply_to) },
49   { "return_message",    opt_bool,
50       (void *)offsetof(autoreply_transport_options_block, return_message) },
51   { "subject",           opt_stringptr,
52       (void *)offsetof(autoreply_transport_options_block, subject) },
53   { "text",              opt_stringptr,
54       (void *)offsetof(autoreply_transport_options_block, text) },
55   { "to",                opt_stringptr,
56       (void *)offsetof(autoreply_transport_options_block, to) },
57 };
58
59 /* Size of the options list. An extern variable has to be used so that its
60 address can appear in the tables drtables.c. */
61
62 int autoreply_transport_options_count =
63   sizeof(autoreply_transport_options)/sizeof(optionlist);
64
65
66 #ifdef MACRO_PREDEF
67
68 /* Dummy values */
69 autoreply_transport_options_block autoreply_transport_option_defaults = {0};
70 void autoreply_transport_init(transport_instance *tblock) {}
71 BOOL autoreply_transport_entry(transport_instance *tblock, address_item *addr) {return FALSE;}
72
73 #else   /*!MACRO_PREDEF*/
74
75
76 /* Default private options block for the autoreply transport. */
77
78 autoreply_transport_options_block autoreply_transport_option_defaults = {
79   NULL,           /* from */
80   NULL,           /* reply_to */
81   NULL,           /* to */
82   NULL,           /* cc */
83   NULL,           /* bcc */
84   NULL,           /* subject */
85   NULL,           /* headers */
86   NULL,           /* text */
87   NULL,           /* file */
88   NULL,           /* logfile */
89   NULL,           /* oncelog */
90   NULL,           /* once_repeat */
91   NULL,           /* never_mail */
92   0600,           /* mode */
93   0,              /* once_file_size */
94   FALSE,          /* file_expand */
95   FALSE,          /* file_optional */
96   FALSE           /* return message */
97 };
98
99
100
101 /* Type of text for the checkexpand() function */
102
103 enum { cke_text, cke_hdr, cke_file };
104
105
106
107 /*************************************************
108 *          Initialization entry point            *
109 *************************************************/
110
111 /* Called for each instance, after its options have been read, to
112 enable consistency checks to be done, or anything else that needs
113 to be set up. */
114
115 void
116 autoreply_transport_init(transport_instance *tblock)
117 {
118 /*
119 autoreply_transport_options_block *ob =
120   (autoreply_transport_options_block *)(tblock->options_block);
121 */
122
123 /* If a fixed uid field is set, then a gid field must also be set. */
124
125 if (tblock->uid_set && !tblock->gid_set && tblock->expand_gid == NULL)
126   log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
127     "user set without group for the %s transport", tblock->name);
128 }
129
130
131
132
133 /*************************************************
134 *          Expand string and check               *
135 *************************************************/
136
137 /* If the expansion fails, the error is set up in the address. Expanded
138 strings must be checked to ensure they contain only printing characters
139 and white space. If not, the function fails.
140
141 Arguments:
142    s         string to expand
143    addr      address that is being worked on
144    name      transport name, for error text
145    type      type, for checking content:
146                cke_text => no check
147                cke_hdr  => header, allow \n + whitespace
148                cke_file => file name, no non-printers allowed
149
150 Returns:     expanded string if expansion succeeds;
151              NULL otherwise
152 */
153
154 static uschar *
155 checkexpand(uschar *s, address_item *addr, uschar *name, int type)
156 {
157 uschar *t;
158 uschar *ss = expand_string(s);
159
160 if (ss == NULL)
161   {
162   addr->transport_return = FAIL;
163   addr->message = string_sprintf("Expansion of \"%s\" failed in %s transport: "
164     "%s", s, name, expand_string_message);
165   return NULL;
166   }
167
168 if (type != cke_text) for (t = ss; *t != 0; t++)
169   {
170   int c = *t;
171   const uschar * sp;
172   if (mac_isprint(c)) continue;
173   if (type == cke_hdr && c == '\n' && (t[1] == ' ' || t[1] == '\t')) continue;
174   sp = string_printing(s);
175   addr->transport_return = FAIL;
176   addr->message = string_sprintf("Expansion of \"%s\" in %s transport "
177     "contains non-printing character %d", sp, name, c);
178   return NULL;
179   }
180
181 return ss;
182 }
183
184
185
186
187 /*************************************************
188 *          Check a header line for never_mail    *
189 *************************************************/
190
191 /* This is called to check to, cc, and bcc for addresses in the never_mail
192 list. Any that are found are removed.
193
194 Arguments:
195   listptr     points to the list of addresses
196   never_mail  an address list, already expanded
197
198 Returns:      nothing
199 */
200
201 static void
202 check_never_mail(uschar **listptr, const uschar *never_mail)
203 {
204 uschar *s = *listptr;
205
206 while (*s != 0)
207   {
208   uschar *error, *next;
209   uschar *e = parse_find_address_end(s, FALSE);
210   int terminator = *e;
211   int start, end, domain, rc;
212
213   /* Temporarily terminate the string at the address end while extracting
214   the operative address within. */
215
216   *e = 0;
217   next = parse_extract_address(s, &error, &start, &end, &domain, FALSE);
218   *e = terminator;
219
220   /* If there is some kind of syntax error, just give up on this header
221   line. */
222
223   if (next == NULL) break;
224
225   /* See if the address is on the never_mail list */
226
227   rc = match_address_list(next,         /* address to check */
228                           TRUE,         /* start caseless */
229                           FALSE,        /* don't expand the list */
230                           &never_mail,  /* the list */
231                           NULL,         /* no caching */
232                           -1,           /* no expand setup */
233                           0,            /* separator from list */
234                           NULL);        /* no lookup value return */
235
236   if (rc == OK)                         /* Remove this address */
237     {
238     DEBUG(D_transport)
239       debug_printf("discarding recipient %s (matched never_mail)\n", next);
240     if (terminator == ',') e++;
241     memmove(s, e, Ustrlen(e) + 1);
242     }
243   else                                  /* Skip over this address */
244     {
245     s = e;
246     if (terminator == ',') s++;
247     }
248   }
249
250 /* Check to see if we removed the last address, leaving a terminating comma
251 that needs to be removed */
252
253 s = *listptr + Ustrlen(*listptr);
254 while (s > *listptr && (isspace(s[-1]) || s[-1] == ',')) s--;
255 *s = 0;
256
257 /* Check to see if there any addresses left; if not, set NULL */
258
259 s = *listptr;
260 while (s != 0 && isspace(*s)) s++;
261 if (*s == 0) *listptr = NULL;
262 }
263
264
265
266 /*************************************************
267 *              Main entry point                  *
268 *************************************************/
269
270 /* See local README for interface details. This transport always returns
271 FALSE, indicating that the top address has the status for all - though in fact
272 this transport can handle only one address at at time anyway. */
273
274 BOOL
275 autoreply_transport_entry(
276   transport_instance *tblock,      /* data for this instantiation */
277   address_item *addr)              /* address we are working on */
278 {
279 int fd, pid, rc;
280 int cache_fd = -1;
281 int cache_size = 0;
282 int add_size = 0;
283 EXIM_DB *dbm_file = NULL;
284 BOOL file_expand, return_message;
285 uschar *from, *reply_to, *to, *cc, *bcc, *subject, *headers, *text, *file;
286 uschar *logfile, *oncelog;
287 uschar *cache_buff = NULL;
288 uschar *cache_time = NULL;
289 uschar *message_id = NULL;
290 header_line *h;
291 time_t now = time(NULL);
292 time_t once_repeat_sec = 0;
293 FILE *f;
294 FILE *ff = NULL;
295
296 autoreply_transport_options_block *ob =
297   (autoreply_transport_options_block *)(tblock->options_block);
298
299 DEBUG(D_transport) debug_printf("%s transport entered\n", tblock->name);
300
301 /* Set up for the good case */
302
303 addr->transport_return = OK;
304 addr->basic_errno = 0;
305
306 /* If the address is pointing to a reply block, then take all the data
307 from that block. It has typically been set up by a mail filter processing
308 router. Otherwise, the data must be supplied by this transport, and
309 it has to be expanded here. */
310
311 if (addr->reply != NULL)
312   {
313   DEBUG(D_transport) debug_printf("taking data from address\n");
314   from = addr->reply->from;
315   reply_to = addr->reply->reply_to;
316   to = addr->reply->to;
317   cc = addr->reply->cc;
318   bcc = addr->reply->bcc;
319   subject = addr->reply->subject;
320   headers = addr->reply->headers;
321   text = addr->reply->text;
322   file = addr->reply->file;
323   logfile = addr->reply->logfile;
324   oncelog = addr->reply->oncelog;
325   once_repeat_sec = addr->reply->once_repeat;
326   file_expand = addr->reply->file_expand;
327   expand_forbid = addr->reply->expand_forbid;
328   return_message = addr->reply->return_message;
329   }
330 else
331   {
332   uschar *oncerepeat = ob->once_repeat;
333
334   DEBUG(D_transport) debug_printf("taking data from transport\n");
335   from = ob->from;
336   reply_to = ob->reply_to;
337   to = ob->to;
338   cc = ob->cc;
339   bcc = ob->bcc;
340   subject = ob->subject;
341   headers = ob->headers;
342   text = ob->text;
343   file = ob->file;
344   logfile = ob->logfile;
345   oncelog = ob->oncelog;
346   file_expand = ob->file_expand;
347   return_message = ob->return_message;
348
349   if ((from  != NULL &&
350         (from = checkexpand(from, addr, tblock->name, cke_hdr)) == NULL) ||
351       (reply_to    != NULL &&
352         (reply_to = checkexpand(reply_to, addr, tblock->name, cke_hdr)) == NULL) ||
353       (to    != NULL &&
354         (to = checkexpand(to, addr, tblock->name, cke_hdr)) == NULL) ||
355       (cc    != NULL &&
356         (cc = checkexpand(cc, addr, tblock->name, cke_hdr)) == NULL) ||
357       (bcc   != NULL &&
358         (bcc = checkexpand(bcc, addr, tblock->name, cke_hdr)) == NULL) ||
359       (subject   != NULL &&
360         (subject = checkexpand(subject, addr, tblock->name, cke_hdr)) == NULL) ||
361       (headers != NULL &&
362         (headers = checkexpand(headers, addr, tblock->name, cke_text)) == NULL) ||
363       (text  != NULL &&
364         (text = checkexpand(text, addr, tblock->name, cke_text)) == NULL) ||
365       (file  != NULL &&
366         (file = checkexpand(file, addr, tblock->name, cke_file)) == NULL) ||
367       (logfile != NULL &&
368         (logfile = checkexpand(logfile, addr, tblock->name, cke_file)) == NULL) ||
369       (oncelog != NULL &&
370         (oncelog = checkexpand(oncelog, addr, tblock->name, cke_file)) == NULL) ||
371       (oncerepeat != NULL &&
372         (oncerepeat = checkexpand(oncerepeat, addr, tblock->name, cke_file)) == NULL))
373     return FALSE;
374
375   if (oncerepeat != NULL)
376     {
377     once_repeat_sec = readconf_readtime(oncerepeat, 0, FALSE);
378     if (once_repeat_sec < 0)
379       {
380       addr->transport_return = FAIL;
381       addr->message = string_sprintf("Invalid time value \"%s\" for "
382         "\"once_repeat\" in %s transport", oncerepeat, tblock->name);
383       return FALSE;
384       }
385     }
386   }
387
388 /* If the never_mail option is set, we have to scan all the recipients and
389 remove those that match. */
390
391 if (ob->never_mail != NULL)
392   {
393   const uschar *never_mail = expand_string(ob->never_mail);
394
395   if (never_mail == NULL)
396     {
397     addr->transport_return = FAIL;
398     addr->message = string_sprintf("Failed to expand \"%s\" for "
399       "\"never_mail\" in %s transport", ob->never_mail, tblock->name);
400     return FALSE;
401     }
402
403   if (to != NULL) check_never_mail(&to, never_mail);
404   if (cc != NULL) check_never_mail(&cc, never_mail);
405   if (bcc != NULL) check_never_mail(&bcc, never_mail);
406
407   if (to == NULL && cc == NULL && bcc == NULL)
408     {
409     DEBUG(D_transport)
410       debug_printf("*** all recipients removed by never_mail\n");
411     return OK;
412     }
413   }
414
415 /* If the -N option is set, can't do any more. */
416
417 if (dont_deliver)
418   {
419   DEBUG(D_transport)
420     debug_printf("*** delivery by %s transport bypassed by -N option\n",
421       tblock->name);
422   return FALSE;
423   }
424
425
426 /* If the oncelog field is set, we send want to send only one message to the
427 given recipient(s). This works only on the "To" field. If there is no "To"
428 field, the message is always sent. If the To: field contains more than one
429 recipient, the effect might not be quite as envisaged. If once_file_size is
430 set, instead of a dbm file, we use a regular file containing a circular buffer
431 recipient cache. */
432
433 if (oncelog != NULL && *oncelog != 0 && to != NULL)
434   {
435   time_t then = 0;
436
437   /* Handle fixed-size cache file. */
438
439   if (ob->once_file_size > 0)
440     {
441     uschar *p;
442     struct stat statbuf;
443     cache_fd = Uopen(oncelog, O_CREAT|O_RDWR, ob->mode);
444
445     if (cache_fd < 0 || fstat(cache_fd, &statbuf) != 0)
446       {
447       addr->transport_return = DEFER;
448       addr->message = string_sprintf("Failed to %s \"once\" file %s when "
449         "sending message from %s transport: %s",
450         (cache_fd < 0)? "open" : "stat", oncelog, tblock->name,
451           strerror(errno));
452       goto END_OFF;
453       }
454
455     /* Get store in the temporary pool and read the entire file into it. We get
456     an amount of store that is big enough to add the new entry on the end if we
457     need to do that. */
458
459     cache_size = statbuf.st_size;
460     add_size = sizeof(time_t) + Ustrlen(to) + 1;
461     cache_buff = store_get(cache_size + add_size);
462
463     if (read(cache_fd, cache_buff, cache_size) != cache_size)
464       {
465       addr->transport_return = DEFER;
466       addr->basic_errno = errno;
467       addr->message = US"error while reading \"once\" file";
468       goto END_OFF;
469       }
470
471     DEBUG(D_transport) debug_printf("%d bytes read from %s\n", cache_size, oncelog);
472
473     /* Scan the data for this recipient. Each entry in the file starts with
474     a time_t sized time value, followed by the address, followed by a binary
475     zero. If we find a match, put the time into "then", and the place where it
476     was found into "cache_time". Otherwise, "then" is left at zero. */
477
478     p = cache_buff;
479     while (p < cache_buff + cache_size)
480       {
481       uschar *s = p + sizeof(time_t);
482       uschar *nextp = s + Ustrlen(s) + 1;
483       if (Ustrcmp(to, s) == 0)
484         {
485         memcpy(&then, p, sizeof(time_t));
486         cache_time = p;
487         break;
488         }
489       p = nextp;
490       }
491     }
492
493   /* Use a DBM file for the list of previous recipients. */
494
495   else
496     {
497     EXIM_DATUM key_datum, result_datum;
498     uschar * dirname = string_copy(oncelog);
499     uschar * s;
500
501     if ((s = Ustrrchr(dirname, '/'))) *s = '\0';
502     EXIM_DBOPEN(oncelog, dirname, O_RDWR|O_CREAT, ob->mode, &dbm_file);
503     if (!dbm_file)
504       {
505       addr->transport_return = DEFER;
506       addr->message = string_sprintf("Failed to open %s file %s when sending "
507         "message from %s transport: %s", EXIM_DBTYPE, oncelog, tblock->name,
508         strerror(errno));
509       goto END_OFF;
510       }
511
512     EXIM_DATUM_INIT(key_datum);        /* Some DBM libraries need datums */
513     EXIM_DATUM_INIT(result_datum);     /* to be cleared */
514     EXIM_DATUM_DATA(key_datum) = CS to;
515     EXIM_DATUM_SIZE(key_datum) = Ustrlen(to) + 1;
516
517     if (EXIM_DBGET(dbm_file, key_datum, result_datum))
518       {
519       /* If the datum size is that of a binary time, we are in the new world
520       where messages are sent periodically. Otherwise the file is an old one,
521       where the datum was filled with a tod_log time, which is assumed to be
522       different in size. For that, only one message is ever sent. This change
523       introduced at Exim 3.00. In a couple of years' time the test on the size
524       can be abolished. */
525
526       if (EXIM_DATUM_SIZE(result_datum) == sizeof(time_t))
527         {
528         memcpy(&then, EXIM_DATUM_DATA(result_datum), sizeof(time_t));
529         }
530       else then = now;
531       }
532     }
533
534   /* Either "then" is set zero, if no message has yet been sent, or it
535   is set to the time of the last sending. */
536
537   if (then != 0 && (once_repeat_sec <= 0 || now - then < once_repeat_sec))
538     {
539     int log_fd;
540     DEBUG(D_transport) debug_printf("message previously sent to %s%s\n", to,
541       (once_repeat_sec > 0)? " and repeat time not reached" : "");
542     log_fd = logfile ? Uopen(logfile, O_WRONLY|O_APPEND|O_CREAT, ob->mode) : -1;
543     if (log_fd >= 0)
544       {
545       uschar *ptr = log_buffer;
546       sprintf(CS ptr, "%s\n  previously sent to %.200s\n", tod_stamp(tod_log), to);
547       while(*ptr) ptr++;
548       if(write(log_fd, log_buffer, ptr - log_buffer) != ptr-log_buffer
549         || close(log_fd))
550         DEBUG(D_transport) debug_printf("Problem writing log file %s for %s "
551           "transport\n", logfile, tblock->name);
552       }
553     goto END_OFF;
554     }
555
556   DEBUG(D_transport) debug_printf("%s %s\n", (then <= 0)?
557     "no previous message sent to" : "repeat time reached for", to);
558   }
559
560 /* We are going to send a message. Ensure any requested file is available. */
561
562 if (file != NULL)
563   {
564   ff = Ufopen(file, "rb");
565   if (ff == NULL && !ob->file_optional)
566     {
567     addr->transport_return = DEFER;
568     addr->message = string_sprintf("Failed to open file %s when sending "
569       "message from %s transport: %s", file, tblock->name, strerror(errno));
570     return FALSE;
571     }
572   }
573
574 /* Make a subprocess to send the message */
575
576 pid = child_open_exim(&fd);
577
578 /* Creation of child failed; defer this delivery. */
579
580 if (pid < 0)
581   {
582   addr->transport_return = DEFER;
583   addr->message = string_sprintf("Failed to create child process to send "
584     "message from %s transport: %s", tblock->name, strerror(errno));
585   DEBUG(D_transport) debug_printf("%s\n", addr->message);
586   return FALSE;
587   }
588
589 /* Create the message to be sent - recipients are taken from the headers,
590 as the -t option is used. The "headers" stuff *must* be last in case there
591 are newlines in it which might, if placed earlier, screw up other headers. */
592
593 f = fdopen(fd, "wb");
594
595 if (from != NULL) fprintf(f, "From: %s\n", from);
596 if (reply_to != NULL) fprintf(f, "Reply-To: %s\n", reply_to);
597 if (to != NULL) fprintf(f, "To: %s\n", to);
598 if (cc != NULL) fprintf(f, "Cc: %s\n", cc);
599 if (bcc != NULL) fprintf(f, "Bcc: %s\n", bcc);
600 if (subject != NULL) fprintf(f, "Subject: %s\n", subject);
601
602 /* Generate In-Reply-To from the message_id header; there should
603 always be one, but code defensively. */
604
605 for (h = header_list; h != NULL; h = h->next)
606   if (h->type == htype_id) break;
607
608 if (h != NULL)
609   {
610   message_id = Ustrchr(h->text, ':') + 1;
611   while (isspace(*message_id)) message_id++;
612   fprintf(f, "In-Reply-To: %s", message_id);
613   }
614
615 /* Generate a References header if there is at least one of Message-ID:,
616 References:, or In-Reply-To: (see RFC 2822). */
617
618 for (h = header_list; h != NULL; h = h->next)
619   if (h->type != htype_old && strncmpic(US"References:", h->text, 11) == 0)
620     break;
621
622 if (h == NULL)
623   for (h = header_list; h != NULL; h = h->next)
624     if (h->type != htype_old && strncmpic(US"In-Reply-To:", h->text, 12) == 0)
625       break;
626
627 /* We limit the total length of references.  Although there is no fixed
628 limit, some systems do not like headers growing beyond recognition.
629 Keep the first message ID for the thread root and the last few for
630 the position inside the thread, up to a maximum of 12 altogether. */
631
632 if (h != NULL || message_id != NULL)
633   {
634   fprintf(f, "References:");
635   if (h != NULL)
636     {
637     uschar *s, *id, *error;
638     uschar *referenced_ids[12];
639     int reference_count = 0;
640     int i;
641
642     s = Ustrchr(h->text, ':') + 1;
643     parse_allow_group = FALSE;
644     while (*s != 0 && (s = parse_message_id(s, &id, &error)) != NULL)
645       {
646       if (reference_count == sizeof(referenced_ids)/sizeof(uschar *))
647         {
648         memmove(referenced_ids + 1, referenced_ids + 2,
649            sizeof(referenced_ids) - 2*sizeof(uschar *));
650         referenced_ids[reference_count - 1] = id;
651         }
652       else referenced_ids[reference_count++] = id;
653       }
654     for (i = 0; i < reference_count; ++i) fprintf(f, " %s", referenced_ids[i]);
655     }
656
657   /* The message id will have a newline on the end of it. */
658
659   if (message_id != NULL) fprintf(f, " %s", message_id);
660     else fprintf(f, "\n");
661   }
662
663 /* Add an Auto-Submitted: header */
664
665 fprintf(f, "Auto-Submitted: auto-replied\n");
666
667 /* Add any specially requested headers */
668
669 if (headers != NULL) fprintf(f, "%s\n", headers);
670 fprintf(f, "\n");
671
672 if (text != NULL)
673   {
674   fprintf(f, "%s", CS text);
675   if (text[Ustrlen(text)-1] != '\n') fprintf(f, "\n");
676   }
677
678 if (ff != NULL)
679   {
680   while (Ufgets(big_buffer, big_buffer_size, ff) != NULL)
681     {
682     if (file_expand)
683       {
684       uschar *s = expand_string(big_buffer);
685       DEBUG(D_transport)
686         {
687         if (s == NULL)
688           debug_printf("error while expanding line from file:\n  %s\n  %s\n",
689             big_buffer, expand_string_message);
690         }
691       fprintf(f, "%s", (s == NULL)? CS big_buffer : CS s);
692       }
693     else fprintf(f, "%s", CS big_buffer);
694     }
695   (void) fclose(ff);
696   }
697
698 /* Copy the original message if required, observing the return size
699 limit if we are returning the body. */
700
701 if (return_message)
702   {
703   uschar *rubric = (tblock->headers_only)?
704     US"------ This is a copy of the message's header lines.\n"
705     : (tblock->body_only)?
706     US"------ This is a copy of the body of the message, without the headers.\n"
707     :
708     US"------ This is a copy of the message, including all the headers.\n";
709   transport_ctx tctx = {
710     fileno(f),
711     tblock,
712     addr,
713     NULL, NULL,
714     (tblock->body_only ? topt_no_headers : 0) |
715     (tblock->headers_only ? topt_no_body : 0) |
716     (tblock->return_path_add ? topt_add_return_path : 0) |
717     (tblock->delivery_date_add ? topt_add_delivery_date : 0) |
718     (tblock->envelope_to_add ? topt_add_envelope_to : 0)
719   };
720
721   if (bounce_return_size_limit > 0 && !tblock->headers_only)
722     {
723     struct stat statbuf;
724     int max = (bounce_return_size_limit/DELIVER_IN_BUFFER_SIZE + 1) *
725       DELIVER_IN_BUFFER_SIZE;
726     if (fstat(deliver_datafile, &statbuf) == 0 && statbuf.st_size > max)
727       {
728       fprintf(f, "\n%s"
729 "------ The body of the message is " OFF_T_FMT " characters long; only the first\n"
730 "------ %d or so are included here.\n\n", rubric, statbuf.st_size,
731         (max/1000)*1000);
732       }
733     else fprintf(f, "\n%s\n", rubric);
734     }
735   else fprintf(f, "\n%s\n", rubric);
736
737   fflush(f);
738   transport_count = 0;
739   transport_write_message(&tctx, bounce_return_size_limit);
740   }
741
742 /* End the message and wait for the child process to end; no timeout. */
743
744 (void)fclose(f);
745 rc = child_close(pid, 0);
746
747 /* Update the "sent to" log whatever the yield. This errs on the side of
748 missing out a message rather than risking sending more than one. We either have
749 cache_fd set to a fixed size, circular buffer file, or dbm_file set to an open
750 DBM file (or neither, if "once" is not set). */
751
752 /* Update fixed-size cache file. If cache_time is set, we found a previous
753 entry; that is the spot into which to put the current time. Otherwise we have
754 to add a new record; remove the first one in the file if the file is too big.
755 We always rewrite the entire file in a single write operation. This is
756 (hopefully) going to be the safest thing because there is no interlocking
757 between multiple simultaneous deliveries. */
758
759 if (cache_fd >= 0)
760   {
761   uschar *from = cache_buff;
762   int size = cache_size;
763
764   if (lseek(cache_fd, 0, SEEK_SET) == 0)
765     {
766     if (!cache_time)
767       {
768       cache_time = from + size;
769       memcpy(cache_time + sizeof(time_t), to, add_size - sizeof(time_t));
770       size += add_size;
771
772       if (cache_size > 0 && size > ob->once_file_size)
773         {
774         from += sizeof(time_t) + Ustrlen(from + sizeof(time_t)) + 1;
775         size -= (from - cache_buff);
776         }
777       }
778
779     memcpy(cache_time, &now, sizeof(time_t));
780     if(write(cache_fd, from, size) != size)
781       DEBUG(D_transport) debug_printf("Problem writing cache file %s for %s "
782         "transport\n", oncelog, tblock->name);
783     }
784   }
785
786 /* Update DBM file */
787
788 else if (dbm_file)
789   {
790   EXIM_DATUM key_datum, value_datum;
791   EXIM_DATUM_INIT(key_datum);          /* Some DBM libraries need to have */
792   EXIM_DATUM_INIT(value_datum);        /* cleared datums. */
793   EXIM_DATUM_DATA(key_datum) = CS to;
794   EXIM_DATUM_SIZE(key_datum) = Ustrlen(to) + 1;
795
796   /* Many OS define the datum value, sensibly, as a void *. However, there
797   are some which still have char *. By casting this address to a char * we
798   can avoid warning messages from the char * systems. */
799
800   EXIM_DATUM_DATA(value_datum) = CS (&now);
801   EXIM_DATUM_SIZE(value_datum) = (int)sizeof(time_t);
802   EXIM_DBPUT(dbm_file, key_datum, value_datum);
803   }
804
805 /* If sending failed, defer to try again - but if once is set the next
806 try will skip, of course. However, if there were no recipients in the
807 message, we do not fail. */
808
809 if (rc != 0)
810   {
811   if (rc == EXIT_NORECIPIENTS)
812     {
813     DEBUG(D_any) debug_printf("%s transport: message contained no recipients\n",
814       tblock->name);
815     }
816   else
817     {
818     addr->transport_return = DEFER;
819     addr->message = string_sprintf("Failed to send message from %s "
820       "transport (%d)", tblock->name, rc);
821     goto END_OFF;
822     }
823   }
824
825 /* Log the sending of the message if successful and required. If the file
826 fails to open, it's hard to know what to do. We cannot write to the Exim
827 log from here, since we may be running under an unprivileged uid. We don't
828 want to fail the delivery, since the message has been successfully sent. For
829 the moment, ignore open failures. Write the log entry as a single write() to a
830 file opened for appending, in order to avoid interleaving of output from
831 different processes. The log_buffer can be used exactly as for main log
832 writing. */
833
834 if (logfile != NULL)
835   {
836   int log_fd = Uopen(logfile, O_WRONLY|O_APPEND|O_CREAT, ob->mode);
837   if (log_fd >= 0)
838     {
839     uschar *ptr = log_buffer;
840     DEBUG(D_transport) debug_printf("logging message details\n");
841     sprintf(CS ptr, "%s\n", tod_stamp(tod_log));
842     while(*ptr) ptr++;
843     if (from != NULL)
844       {
845       (void)string_format(ptr, LOG_BUFFER_SIZE - (ptr-log_buffer),
846         "  From: %s\n", from);
847       while(*ptr) ptr++;
848       }
849     if (to != NULL)
850       {
851       (void)string_format(ptr, LOG_BUFFER_SIZE - (ptr-log_buffer),
852         "  To: %s\n", to);
853       while(*ptr) ptr++;
854       }
855     if (cc != NULL)
856       {
857       (void)string_format(ptr, LOG_BUFFER_SIZE - (ptr-log_buffer),
858         "  Cc: %s\n", cc);
859       while(*ptr) ptr++;
860       }
861     if (bcc != NULL)
862       {
863       (void)string_format(ptr, LOG_BUFFER_SIZE - (ptr-log_buffer),
864         "  Bcc: %s\n", bcc);
865       while(*ptr) ptr++;
866       }
867     if (subject != NULL)
868       {
869       (void)string_format(ptr, LOG_BUFFER_SIZE - (ptr-log_buffer),
870         "  Subject: %s\n", subject);
871       while(*ptr) ptr++;
872       }
873     if (headers != NULL)
874       {
875       (void)string_format(ptr, LOG_BUFFER_SIZE - (ptr-log_buffer),
876         "  %s\n", headers);
877       while(*ptr) ptr++;
878       }
879     if(write(log_fd, log_buffer, ptr - log_buffer) != ptr-log_buffer
880       || close(log_fd))
881       DEBUG(D_transport) debug_printf("Problem writing log file %s for %s "
882         "transport\n", logfile, tblock->name);
883     }
884   else DEBUG(D_transport) debug_printf("Failed to open log file %s for %s "
885     "transport: %s\n", logfile, tblock->name, strerror(errno));
886   }
887
888 END_OFF:
889 if (dbm_file) EXIM_DBCLOSE(dbm_file);
890 if (cache_fd > 0) (void)close(cache_fd);
891
892 DEBUG(D_transport) debug_printf("%s transport succeeded\n", tblock->name);
893
894 return FALSE;
895 }
896
897 #endif  /*!MACRO_PREDEF*/
898 /* End of transport/autoreply.c */