Retries: rework DB keys, and fix exinext IPv6. Bug 3086
[exim.git] / src / src / retry.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2023 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
9
10 /* Functions concerned with retrying unsuccessful deliveries. */
11
12
13 #include "exim.h"
14
15
16
17 /*************************************************
18 *         Check the ultimate address timeout     *
19 *************************************************/
20
21 /* This function tests whether a message has been on the queue longer than
22 the maximum retry time for a particular host or address.
23
24 Arguments:
25   retry_key     the key to look up a retry rule
26   domain        the domain to look up a domain retry rule
27   retry_record  contains error information for finding rule
28   now           the time
29
30 Returns:        TRUE if the ultimate timeout has been reached
31 */
32
33 BOOL
34 retry_ultimate_address_timeout(const uschar * retry_key, const uschar *domain,
35   dbdata_retry *retry_record, time_t now)
36 {
37 BOOL address_timeout;
38 retry_config * retry;
39
40 DEBUG(D_retry)
41   {
42   debug_printf("retry time not reached: checking ultimate address timeout\n");
43   debug_printf("  now=" TIME_T_FMT " first_failed=" TIME_T_FMT
44                 " next_try=" TIME_T_FMT " expired=%c\n",
45                 now, retry_record->first_failed,
46                 retry_record->next_try, retry_record->expired ? 'T' : 'F');
47   }
48
49 retry = retry_find_config(retry_key+2, domain,
50     retry_record->basic_errno, retry_record->more_errno);
51
52 if (retry && retry->rules)
53   {
54   retry_rule *last_rule;
55   for (last_rule = retry->rules; last_rule->next; last_rule = last_rule->next) ;
56   DEBUG(D_retry)
57     debug_printf("  received_time=" TIME_T_FMT " diff=%d timeout=%d\n",
58       received_time.tv_sec, (int)(now - received_time.tv_sec), last_rule->timeout);
59   address_timeout = (now - received_time.tv_sec > last_rule->timeout);
60   }
61 else
62   {
63   DEBUG(D_retry)
64     debug_printf("no retry rule found: assume timed out\n");
65   address_timeout = TRUE;
66   }
67
68 DEBUG(D_retry)
69   if (address_timeout)
70     debug_printf("on queue longer than maximum retry for address - "
71       "allowing delivery\n");
72
73 return address_timeout;
74 }
75
76
77
78 const uschar *
79 retry_host_key_build(const host_item * host, BOOL incl_ip,
80   const uschar * portstring)
81 {
82 const uschar * s = host->name;
83 gstring * g = string_is_ip_address(s, NULL)
84   ? string_fmt_append(NULL, "T:[%s]", s)    /* wrap a name which is a bare ip */
85   : string_fmt_append(NULL, "T:%s",   s);
86
87 s = host->address;
88 if (incl_ip)
89   g = Ustrchr(s, ':')
90     ? string_fmt_append(g, ":[%s]", s)      /* wrap an ipv6  */
91     : string_fmt_append(g, ":%s",   s);
92
93 if (portstring)
94   g = string_cat(g, portstring);
95
96 gstring_release_unused(g);
97 return string_from_gstring(g);
98 }
99
100
101 /*************************************************
102 *     Set status of a host+address item          *
103 *************************************************/
104
105 /* This function is passed a host_item which contains a host name and an
106 IP address string. Its job is to set the status of the address if it is not
107 already set (indicated by hstatus_unknown). The possible values are:
108
109    hstatus_usable    the address is not listed in the unusable tree, and does
110                      not have a retry record, OR the time is past the next
111                      try time, OR the message has been on the queue for more
112                      than the maximum retry time for a failing host
113
114    hstatus_unusable  the address is listed in the unusable tree, or does have
115                      a retry record, and the time is not yet at the next retry
116                      time.
117
118    hstatus_unusable_expired  as above, but also the retry time has expired
119                      for this address.
120
121 The reason a delivery is permitted when a message has been around for a very
122 long time is to allow the ultimate address timeout to operate after a delivery
123 failure. Otherwise some messages may stick around without being tried for too
124 long.
125
126 If a host retry record is retrieved from the hints database, the time of last
127 trying is filled into the last_try field of the host block. If a host is
128 generally usable, a check is made to see if there is a retry delay on this
129 specific message at this host.
130
131 If a non-standard port is being used, it is added to the retry key.
132
133 Arguments:
134   domain              the address domain
135   host                pointer to a host item
136   portstring          "" for standard port, ":xxxx" for a non-standard port
137   include_ip_address  TRUE to include the address in the key - this is
138                         usual, but sometimes is not wanted
139   retry_host_key      where to put a pointer to the key for the host-specific
140                         retry record, if one is read and the host is usable
141   retry_message_key   where to put a pointer to the key for the message+host
142                         retry record, if one is read and the host is usable
143
144 Returns:    TRUE if the host has expired but is usable because
145              its retry time has come
146 */
147
148 BOOL
149 retry_check_address(const uschar *domain, host_item *host, uschar *portstring,
150   BOOL include_ip_address,
151   const uschar **retry_host_key, const uschar **retry_message_key)
152 {
153 BOOL yield = FALSE;
154 time_t now = time(NULL);
155 const uschar * host_key, * message_key;
156 open_db dbblock, * dbm_file;
157 tree_node * node;
158 dbdata_retry * host_retry_record, * message_retry_record;
159
160 *retry_host_key = *retry_message_key = NULL;
161
162 DEBUG(D_transport|D_retry) debug_printf("checking retry status of %s\n", host->name);
163
164 /* Do nothing if status already set; otherwise initialize status as usable. */
165
166 if (host->status != hstatus_unknown) return FALSE;
167 host->status = hstatus_usable;
168
169 /* Generate the host key for the unusable tree and the retry database. Ensure
170 host names are lower cased (that's what %S does).
171 Generate the message-specific key too.
172 Be sure to maintain lack-of-spaces in retry keys; exinext depends on it. */
173
174 host_key = retry_host_key_build(host, include_ip_address, portstring);
175 message_key = string_sprintf("%s:%s", host_key, message_id);
176
177 /* Search the tree of unusable IP addresses. This is filled in when deliveries
178 fail, because the retry database itself is not updated until the end of all
179 deliveries (so as to do it all in one go). The tree records addresses that have
180 become unusable during this delivery process (i.e. those that will get put into
181 the retry database when it is updated). */
182
183 if ((node = tree_search(tree_unusable, host_key)))
184   {
185   DEBUG(D_transport|D_retry) debug_printf("found in tree of unusables\n");
186   host->status = (node->data.val > 255)?
187     hstatus_unusable_expired : hstatus_unusable;
188   host->why = node->data.val & 255;
189   return FALSE;
190   }
191
192 /* Open the retry database, giving up if there isn't one. Otherwise, search for
193 the retry records, and then close the database again. */
194
195 if (!(dbm_file = dbfn_open(US"retry", O_RDONLY, &dbblock, FALSE, TRUE)))
196   {
197   DEBUG(D_deliver|D_retry|D_hints_lookup)
198     debug_printf("no retry data available\n");
199   return FALSE;
200   }
201 host_retry_record = dbfn_read(dbm_file, host_key);
202 message_retry_record = dbfn_read(dbm_file, message_key);
203 dbfn_close(dbm_file);
204
205 /* Ignore the data if it is too old - too long since it was written */
206
207 if (!host_retry_record)
208   {
209   DEBUG(D_transport|D_retry) debug_printf("no host retry record\n");
210   }
211 else if (now - host_retry_record->time_stamp > retry_data_expire)
212   {
213   host_retry_record = NULL;
214   DEBUG(D_transport|D_retry) debug_printf("host retry record too old\n");
215   }
216
217 if (!message_retry_record)
218   {
219   DEBUG(D_transport|D_retry) debug_printf("no message retry record\n");
220   }
221 else if (now - message_retry_record->time_stamp > retry_data_expire)
222   {
223   message_retry_record = NULL;
224   DEBUG(D_transport|D_retry) debug_printf("message retry record too old\n");
225   }
226
227 /* If there's a host-specific retry record, check for reaching the retry
228 time (or forcing). If not, and the host is not expired, check for the message
229 having been around for longer than the maximum retry time for this host or
230 address. Allow the delivery if it has. Otherwise set the appropriate unusable
231 flag and return FALSE. Otherwise arrange to return TRUE if this is an expired
232 host. */
233
234 if (host_retry_record)
235   {
236   *retry_host_key = host_key;
237
238   /* We have not reached the next try time. Check for the ultimate address
239   timeout if the host has not expired. */
240
241   if (now < host_retry_record->next_try && !f.deliver_force)
242     {
243     if (!host_retry_record->expired &&
244         retry_ultimate_address_timeout(host_key, domain,
245           host_retry_record, now))
246       return FALSE;
247
248     /* We have not hit the ultimate address timeout; host is unusable. */
249
250     host->status = (host_retry_record->expired)?
251       hstatus_unusable_expired : hstatus_unusable;
252     host->why = hwhy_retry;
253     host->last_try = host_retry_record->last_try;
254     return FALSE;
255     }
256
257   /* Host is usable; set return TRUE if expired. */
258
259   yield = host_retry_record->expired;
260   }
261
262 /* It's OK to try the host. If there's a message-specific retry record, check
263 for reaching its retry time (or forcing). If not, mark the host unusable,
264 unless the ultimate address timeout has been reached. */
265
266 if (message_retry_record)
267   {
268   *retry_message_key = message_key;
269   if (now < message_retry_record->next_try && !f.deliver_force)
270     {
271     if (!retry_ultimate_address_timeout(host_key, domain,
272         message_retry_record, now))
273       {
274       host->status = hstatus_unusable;
275       host->why = hwhy_retry;
276       }
277     return FALSE;
278     }
279   }
280
281 return yield;
282 }
283
284
285
286
287 /*************************************************
288 *           Add a retry item to an address       *
289 *************************************************/
290
291 /* Retry items are chained onto an address when it is deferred either by router
292 or by a transport, or if it succeeds or fails and there was a previous retry
293 item that now needs to be deleted. Sometimes there can be both kinds of item:
294 for example, if routing was deferred but then succeeded, and delivery then
295 deferred. In that case there is a delete item for the routing retry, and an
296 updating item for the delivery.
297
298 (But note that that is only visible at the outer level, because in remote
299 delivery subprocesses, the address starts "clean", with no retry items carried
300 in.)
301
302 These items are used at the end of a delivery attempt to update the retry
303 database. The keys start R: for routing delays and T: for transport delays.
304
305 Arguments:
306   addr    the address block onto which to hang the item
307   key     the retry key
308   flags   delete, host, and message flags, copied into the block
309
310 Returns:  nothing
311 */
312
313 void
314 retry_add_item(address_item * addr, const uschar * key, int flags)
315 {
316 retry_item * rti = store_get(sizeof(retry_item), GET_UNTAINTED);
317 host_item * host = addr->host_used;
318
319 rti->next = addr->retries;
320 addr->retries = rti;
321 rti->key = key;
322 rti->basic_errno = addr->basic_errno;
323 rti->more_errno = addr->more_errno;
324 rti->message = host
325   ? string_sprintf("H=%s [%s]: %s", host->name, host->address, addr->message)
326   : addr->message;
327 rti->flags = flags;
328
329 DEBUG(D_transport|D_retry)
330   {
331   int letter = rti->more_errno & 255;
332   debug_printf("added retry item for %s: errno=%d more_errno=", rti->key,
333     rti->basic_errno);
334   if (letter == 'A' || letter == 'M')
335     debug_printf("%d,%c", (rti->more_errno >> 8) & 255, letter);
336   else
337     debug_printf("%d", rti->more_errno);
338   debug_printf(" flags=%d\n", flags);
339   }
340 }
341
342
343
344 /*************************************************
345 *        Find retry configuration data           *
346 *************************************************/
347
348 /* Search the in-store retry information for the first retry item that applies
349 to a given destination. If the key contains an @ we are probably handling a
350 local delivery and have a complete address to search for; this happens when
351 retry_use_local_part is set on a router. Otherwise, the key is likely to be a
352 host name for a remote delivery, or a domain name for a local delivery. We
353 prepend *@ on the front of it so that it will match a retry item whose address
354 item pattern is independent of the local part. The alternate key, if set, is
355 always just a domain, so we treat it likewise.
356
357 Arguments:
358   key          key for which retry info is wanted
359   alternate    alternative key, always just a domain
360   basic_errno  specific error predicate on the retry rule, or zero
361   more_errno   additional data for errno predicate
362
363 Returns:       pointer to retry rule, or NULL
364 */
365
366 retry_config *
367 retry_find_config(const uschar * key, const uschar * alternate, int basic_errno,
368   int more_errno)
369 {
370 const uschar * colon = Ustrchr(key, ':');
371 retry_config * yield;
372
373 /* If there's a colon in the key, there are two possibilities:
374
375 (1) This is a key for a host, ip address, and possibly port, in the format
376
377       hostname:ip+port
378
379     In this case, we copy the host name (which could be an [ip], including
380     being an [ipv6], and we drop the []).
381
382 (2) This is a key for a pipe, file, or autoreply delivery, in the format
383
384       pipe-or-file-or-auto:x@y
385
386     where x@y is the original address that provoked the delivery. The pipe or
387     file or auto will start with | or / or >, whereas a host name will start
388     with a letter or a digit. In this case we want to use the original address
389     to search for a retry rule. */
390
391 if (colon)
392   key = isalnum(*key)
393     ? string_copyn(key, colon-key)      /* the hostname */
394     : *key == '['
395     ? string_copyn(key+1, Ustrchr(key, ']')-1-key)      /* the ip */
396     : Ustrrchr(key, ':') + 1;           /* Take from the last colon */
397
398 /* Sort out the keys */
399
400 if (!Ustrchr(key, '@')) key = string_sprintf("*@%s", key);
401 if (alternate)    alternate = string_sprintf("*@%s", alternate);
402
403 /* Scan the configured retry items. */
404
405 for (yield = retries; yield; yield = yield->next)
406   {
407   const uschar *plist = yield->pattern;
408   const uschar *slist = yield->senders;
409
410   /* If a specific error is set for this item, check that we are handling that
411   specific error, and if so, check any additional error information if
412   required. */
413
414   if (yield->basic_errno != 0)
415     {
416     /* Special code is required for quota errors, as these can either be system
417     quota errors, or Exim's own quota imposition, which has a different error
418     number. Full partitions are also treated in the same way as quota errors.
419     */
420
421     if (yield->basic_errno == ERRNO_EXIMQUOTA)
422       {
423       if ((basic_errno != ERRNO_EXIMQUOTA && basic_errno != errno_quota &&
424            basic_errno != ENOSPC) ||
425           (yield->more_errno != 0 && yield->more_errno > more_errno))
426         continue;
427       }
428
429     /* The TLSREQUIRED error also covers TLSFAILURE. These are subtly different
430     errors, but not worth separating at this level. */
431
432     else if (yield->basic_errno == ERRNO_TLSREQUIRED)
433       {
434       if (basic_errno != ERRNO_TLSREQUIRED && basic_errno != ERRNO_TLSFAILURE)
435         continue;
436       }
437
438     /* Handle 4xx responses to MAIL, RCPT, or DATA. The code that was received
439     is in the 2nd least significant byte of more_errno (with 400 subtracted).
440     The required value is coded in the 2nd least significant byte of the
441     yield->more_errno field as follows:
442
443       255     => any 4xx code
444       >= 100  => the decade must match the value less 100
445       < 100   => the exact value must match
446     */
447
448     else if (yield->basic_errno == ERRNO_MAIL4XX ||
449              yield->basic_errno == ERRNO_RCPT4XX ||
450              yield->basic_errno == ERRNO_DATA4XX)
451       {
452       int wanted;
453       if (basic_errno != yield->basic_errno) continue;
454       wanted = (yield->more_errno >> 8) & 255;
455       if (wanted != 255)
456         {
457         int evalue = (more_errno >> 8) & 255;
458         if (wanted >= 100)
459           {
460           if ((evalue/10)*10 != wanted - 100) continue;
461           }
462         else if (evalue != wanted) continue;
463         }
464       }
465
466     /* There are some special cases for timeouts */
467
468     else if (yield->basic_errno == ETIMEDOUT)
469       {
470       if (basic_errno != ETIMEDOUT) continue;
471
472       /* Just RTEF_CTOUT in the rule => don't care about 'A'/'M' addresses */
473       if (yield->more_errno == RTEF_CTOUT)
474         {
475         if ((more_errno & RTEF_CTOUT) == 0) continue;
476         }
477
478       else if (yield->more_errno != 0)
479         {
480         int cf_errno = more_errno;
481         if ((yield->more_errno & RTEF_CTOUT) == 0) cf_errno &= ~RTEF_CTOUT;
482         if (yield->more_errno != cf_errno) continue;
483         }
484       }
485
486     /* Default checks for exact match */
487
488     else
489       {
490       if (yield->basic_errno != basic_errno ||
491          (yield->more_errno != 0 && yield->more_errno != more_errno))
492        continue;
493       }
494     }
495
496   /* If the "senders" condition is set, check it. Note that sender_address may
497   be null during -brt checking, in which case we do not use this rule. */
498
499   if (  slist
500      && (  !sender_address
501         || match_address_list_basic(sender_address, &slist, 0) != OK
502      )  )
503     continue;
504
505   /* Check for a match between the address list item at the start of this retry
506   rule and either the main or alternate keys. */
507
508   if (  match_address_list_basic(key, &plist, UCHAR_MAX+1) == OK
509      || (  alternate
510         && match_address_list_basic(alternate, &plist, UCHAR_MAX+1) == OK
511      )  )
512     break;
513   }
514
515 return yield;
516 }
517
518
519
520
521 /*************************************************
522 *              Update retry database             *
523 *************************************************/
524
525 /* Update the retry data for any directing/routing/transporting that was
526 deferred, or delete it for those that succeeded after a previous defer. This is
527 done all in one go to minimize opening/closing/locking of the database file.
528
529 Note that, because SMTP delivery involves a list of destinations to try, there
530 may be defer-type retry information for some of them even when the message was
531 successfully delivered. Likewise if it eventually failed.
532
533 This function may move addresses from the defer to the failed queue if the
534 ultimate retry time has expired.
535
536 Arguments:
537   addr_defer    queue of deferred addresses
538   addr_failed   queue of failed addresses
539   addr_succeed  queue of successful addresses
540
541 Returns:        nothing
542 */
543
544 void
545 retry_update(address_item ** addr_defer, address_item ** addr_failed,
546   address_item ** addr_succeed)
547 {
548 open_db dbblock;
549 open_db *dbm_file = NULL;
550 time_t now = time(NULL);
551
552 DEBUG(D_retry) debug_printf("Processing retry items\n");
553
554 /* Three-times loop to handle succeeded, failed, and deferred addresses.
555 Deferred addresses must be handled after failed ones, because some may be moved
556 to the failed chain if they have timed out. */
557
558 for (int i = 0; i < 3; i++)
559   {
560   address_item * endaddr, *addr;
561   address_item * last_first = NULL;
562   address_item ** paddr = i==0 ? addr_succeed : i==1 ? addr_failed : addr_defer;
563   address_item ** saved_paddr = NULL;
564
565   DEBUG(D_retry) debug_printf("%s addresses:\n",
566     i == 0 ? "Succeeded" : i == 1 ? "Failed" : "Deferred");
567
568   /* Loop for each address on the chain. For deferred addresses, the whole
569   address times out unless one of its retry addresses has a retry rule that
570   hasn't yet timed out. Deferred addresses should not be requesting deletion
571   of retry items, but just in case they do by accident, treat that case
572   as "not timed out".
573
574   As well as handling the addresses themselves, we must also process any
575   retry items for any parent addresses - these are typically "delete" items,
576   because the parent must have succeeded in order to generate the child. */
577
578   while ((endaddr = *paddr))
579     {
580     BOOL timed_out = FALSE;
581
582     for (addr = endaddr; addr; addr = addr->parent)
583       {
584       int update_count = 0;
585       int timedout_count = 0;
586
587       DEBUG(D_retry) debug_printf(" %s%s\n", addr->address,
588         addr->retries ? "" : ": no retry items");
589
590       /* Loop for each retry item. */
591
592       for (retry_item * rti = addr->retries; rti; rti = rti->next)
593         {
594         uschar *message;
595         int message_length, message_space, failing_interval, next_try;
596         retry_rule *rule, *final_rule;
597         retry_config *retry;
598         dbdata_retry *retry_record;
599
600         /* Open the retry database if it is not already open; failure to open
601         the file is logged, but otherwise ignored - deferred addresses will
602         get retried at the next opportunity. Not opening earlier than this saves
603         opening if no addresses have retry items - common when none have yet
604         reached their retry next try time. */
605
606         if (!dbm_file)
607           dbm_file = dbfn_open(US"retry", O_RDWR, &dbblock, TRUE, TRUE);
608
609         if (!dbm_file)
610           {
611           DEBUG(D_deliver|D_retry|D_hints_lookup)
612             debug_printf("retry database not available for updating\n");
613           return;
614           }
615
616         /* If there are no deferred addresses, that is, if this message is
617         completing, and the retry item is for a message-specific SMTP error,
618         force it to be deleted, because there's no point in keeping data for
619         no-longer-existing messages. This situation can occur when a domain has
620         two hosts and a message-specific error occurs for the first of them,
621         but the address gets delivered to the second one. This optimization
622         doesn't succeed in cleaning out all the dead entries, but it helps. */
623
624         if (!*addr_defer  &&  rti->flags & rf_message)
625           rti->flags |= rf_delete;
626
627         /* Handle the case of a request to delete the retry info for this
628         destination. */
629
630         if (rti->flags & rf_delete)
631           {
632           (void)dbfn_delete(dbm_file, rti->key);
633           DEBUG(D_retry)
634             debug_printf("deleted retry information for %s\n", rti->key);
635           continue;
636           }
637
638         /* Count the number of non-delete retry items. This is so that we
639         can compare it to the count of timed_out ones, to check whether
640         all are timed out. */
641
642         update_count++;
643
644         /* Get the retry information for this destination and error code, if
645         any. If this item is for a remote host with ip address, then pass
646         the domain name as an alternative to search for. If no retry
647         information is found, we can't generate a retry time, so there is
648         no point updating the database. This retry item is timed out. */
649
650         if (!(retry = retry_find_config(rti->key + 2,
651              rti->flags & rf_host ? addr->domain : NULL,
652              rti->basic_errno, rti->more_errno)))
653           {
654           DEBUG(D_retry) debug_printf("No configured retry item for %s%s%s\n",
655             rti->key,
656             rti->flags & rf_host ? US" or " : US"",
657             rti->flags & rf_host ? addr->domain : US"");
658           if (addr == endaddr) timedout_count++;
659           continue;
660           }
661
662         DEBUG(D_retry)
663           if (rti->flags & rf_host)
664             debug_printf("retry for %s (%s) = %s %d %d\n", rti->key,
665               addr->domain, retry->pattern, retry->basic_errno,
666               retry->more_errno);
667           else
668             debug_printf("retry for %s = %s %d %d\n", rti->key, retry->pattern,
669               retry->basic_errno, retry->more_errno);
670
671         /* Set up the message for the database retry record. Because DBM
672         records have a maximum data length, we enforce a limit. There isn't
673         much point in keeping a huge message here, anyway. */
674
675         message = rti->basic_errno > 0
676           ? US strerror(rti->basic_errno)
677           : rti->message
678           ? US string_printing(rti->message)
679           : US"unknown error";
680         message_length = Ustrlen(message);
681         if (message_length > EXIM_DB_RLIMIT) message_length = EXIM_DB_RLIMIT;
682
683         /* Read a retry record from the database or construct a new one.
684         Ignore an old one if it is too old since it was last updated. */
685
686         retry_record = dbfn_read_with_length(dbm_file, rti->key,
687                                               &message_space);
688         if (  retry_record
689            && now - retry_record->time_stamp > retry_data_expire)
690           retry_record = NULL;
691
692         if (!retry_record)
693           {
694           retry_record = store_get(sizeof(dbdata_retry) + message_length,
695                                    message);
696           message_space = message_length;
697           retry_record->first_failed = now;
698           retry_record->last_try = now;
699           retry_record->next_try = now;
700           retry_record->expired = FALSE;
701           retry_record->text[0] = 0;      /* just in case */
702           }
703         else message_space -= sizeof(dbdata_retry);
704
705         /* Compute how long this destination has been failing */
706
707         failing_interval = now - retry_record->first_failed;
708         DEBUG(D_retry) debug_printf("failing_interval=%d message_age=%d\n",
709           failing_interval, message_age);
710
711         /* For a non-host error, if the message has been on the queue longer
712         than the recorded time of failure, use the message's age instead. This
713         can happen when some messages can be delivered and others cannot; a
714         successful delivery will reset the first_failed time, and this can lead
715         to a failing message being retried too often. */
716
717         if (!(rti->flags & rf_host) && message_age > failing_interval)
718           failing_interval = message_age;
719
720         /* Search for the current retry rule. The cutoff time of the
721         last rule is handled differently to the others. The rule continues
722         to operate for ever (the global maximum interval will eventually
723         limit the gaps) but its cutoff time determines when an individual
724         destination times out. If there are no retry rules, the destination
725         always times out, but we can't compute a retry time. */
726
727         final_rule = NULL;
728         for (rule = retry->rules; rule; rule = rule->next)
729           {
730           if (failing_interval <= rule->timeout) break;
731           final_rule = rule;
732           }
733
734         /* If there's an un-timed out rule, the destination has not
735         yet timed out, so the address as a whole has not timed out (but we are
736         interested in this only for the end address). Make sure the expired
737         flag is false (can be forced via fixdb from outside, but ensure it is
738         consistent with the rules whenever we go through here). */
739
740         if (rule)
741           retry_record->expired = FALSE;
742
743         /* Otherwise, set the retry timeout expired, and set the final rule
744         as the one from which to compute the next retry time. Subsequent
745         messages will fail immediately until the retry time is reached (unless
746         there are other, still active, retries). */
747
748         else
749           {
750           rule = final_rule;
751           retry_record->expired = TRUE;
752           if (addr == endaddr) timedout_count++;
753           }
754
755         /* There is a special case to consider when some messages get through
756         to a destination and others don't. This can happen locally when a
757         large message pushes a user over quota, and it can happen remotely
758         when a machine is on a dodgy Internet connection. The messages that
759         get through wipe the retry information, causing those that don't to
760         stay on the queue longer than the final retry time. In order to
761         avoid this, we check, using the time of arrival of the message, to
762         see if it has been on the queue for more than the final cutoff time,
763         and if so, cause this retry item to time out, and the retry time to
764         be set to "now" so that any subsequent messages in the same condition
765         also get tried. We search for the last rule onwards from the one that
766         is in use. If there are no retry rules for the item, rule will be null
767         and timedout_count will already have been updated.
768
769         This implements "timeout this rule if EITHER the host (or routing or
770         directing) has been failing for more than the maximum time, OR if the
771         message has been on the queue for more than the maximum time."
772
773         February 2006: It is possible that this code is no longer needed
774         following the change to the retry calculation to use the message age if
775         it is larger than the time since first failure. It may be that the
776         expired flag is always set when the other conditions are met. However,
777         this is a small bit of code, and it does no harm to leave it in place,
778         just in case. */
779
780         if (  received_time.tv_sec <= retry_record->first_failed
781            && addr == endaddr
782            && !retry_record->expired
783            && rule)
784           {
785           retry_rule *last_rule;
786           for (last_rule = rule; last_rule->next; last_rule = last_rule->next)
787             ;
788           if (now - received_time.tv_sec > last_rule->timeout)
789             {
790             DEBUG(D_retry) debug_printf("on queue longer than maximum retry\n");
791             timedout_count++;
792             rule = NULL;
793             }
794           }
795
796         /* Compute the next try time from the rule, subject to the global
797         maximum, and update the retry database. If rule == NULL it means
798         there were no rules at all (and the timeout will be set expired),
799         or we have a message that is older than the final timeout. In this
800         case set the next retry time to now, so that one delivery attempt
801         happens for subsequent messages. */
802
803         if (!rule)
804           next_try = now;
805         else
806           {
807           if (rule->rule == 'F')
808             next_try = now + rule->p1;
809           else  /* rule = 'G' or 'H' */
810             {
811             int last_predicted_gap =
812               retry_record->next_try - retry_record->last_try;
813             int last_actual_gap = now - retry_record->last_try;
814             int lastgap = (last_predicted_gap < last_actual_gap)?
815               last_predicted_gap : last_actual_gap;
816             int next_gap = (lastgap * rule->p2)/1000;
817             if (rule->rule == 'G')
818               next_try = now + ((lastgap < rule->p1)? rule->p1 : next_gap);
819             else  /* The 'H' rule */
820               {
821               next_try = now + rule->p1;
822               if (next_gap > rule->p1)
823                 next_try += random_number(next_gap - rule->p1)/2 +
824                   (next_gap - rule->p1)/2;
825               }
826             }
827           }
828
829         /* Impose a global retry max */
830
831         if (next_try - now > retry_interval_max)
832           next_try = now + retry_interval_max;
833
834         /* If the new message length is greater than the previous one, we have
835         to copy the record first.  If we're using an old one, the read used
836         tainted memory so we're ok to write into it. */
837
838         if (message_length > message_space)
839           {
840           dbdata_retry * newr =
841             store_get(sizeof(dbdata_retry) + message_length, message);
842           memcpy(newr, retry_record, sizeof(dbdata_retry));
843           retry_record = newr;
844           }
845
846         /* Set up the retry record; message_length may be less than the string
847         length for very long error strings. */
848
849         retry_record->last_try = now;
850         retry_record->next_try = next_try;
851         retry_record->basic_errno = rti->basic_errno;
852         retry_record->more_errno = rti->more_errno;
853         Ustrncpy(retry_record->text, message, message_length);
854         retry_record->text[message_length] = 0;
855
856         DEBUG(D_retry)
857           {
858           int letter = retry_record->more_errno & 255;
859           debug_printf("Writing retry data for %s\n", rti->key);
860           debug_printf("  first failed=%d last try=%d next try=%d expired=%d\n",
861             (int)retry_record->first_failed, (int)retry_record->last_try,
862             (int)retry_record->next_try, retry_record->expired);
863           debug_printf("  errno=%d more_errno=", retry_record->basic_errno);
864           if (letter == 'A' || letter == 'M')
865             debug_printf("%d,%c", (retry_record->more_errno >> 8) & 255,
866               letter);
867           else
868             debug_printf("%d", retry_record->more_errno);
869           debug_printf(" %s\n", retry_record->text);
870           }
871
872         (void)dbfn_write(dbm_file, rti->key, retry_record,
873           sizeof(dbdata_retry) + message_length);
874         }                            /* Loop for each retry item */
875
876       /* If all the non-delete retry items are timed out, the address is
877       timed out, provided that we didn't skip any hosts because their retry
878       time was not reached (or because of hosts_max_try). */
879
880       if (update_count > 0 && update_count == timedout_count)
881         if (!testflag(endaddr, af_retry_skipped))
882           {
883           DEBUG(D_retry) debug_printf("timed out: all retries expired\n");
884           timed_out = TRUE;
885           }
886         else
887           DEBUG(D_retry)
888             debug_printf("timed out but some hosts were skipped\n");
889       }     /* Loop for an address and its parents */
890
891     /* If this is a deferred address, and retry processing was requested by
892     means of one or more retry items, and they all timed out, move the address
893     to the failed queue, and restart this loop without updating paddr.
894
895     If there were several addresses batched in the same remote delivery, only
896     the original top one will have host retry items attached to it, but we want
897     to handle all the same. Each will have a pointer back to its "top" address,
898     and they will now precede the item with the retries because addresses are
899     inverted when added to these final queues. We have saved information about
900     them in passing (below) so they can all be cut out at once. */
901
902     if (i == 2)   /* Handling defers */
903       {
904       if (endaddr->retries && timed_out)
905         {
906         if (last_first == endaddr) paddr = saved_paddr;
907         addr = *paddr;
908         *paddr = endaddr->next;
909
910         endaddr->next = *addr_failed;
911         *addr_failed = addr;
912
913         for (;; addr = addr->next)
914           {
915           setflag(addr, af_retry_timedout);
916           addr->message = addr->message
917             ? string_sprintf("%s: retry timeout exceeded", addr->message)
918             : US"retry timeout exceeded";
919           addr->user_message = addr->user_message
920             ? string_sprintf("%s: retry timeout exceeded", addr->user_message)
921             : US"retry timeout exceeded";
922           log_write(0, LOG_MAIN, "** %s%s%s%s: retry timeout exceeded",
923             addr->address,
924             addr->parent ? US" <" : US"",
925             addr->parent ? addr->parent->address : US"",
926             addr->parent ? US">" : US"");
927
928           if (addr == endaddr) break;
929           }
930
931         continue;                       /* Restart from changed *paddr */
932         }
933
934       /* This address is to remain on the defer chain. If it has a "first"
935       pointer, save the pointer to it in case we want to fail the set of
936       addresses when we get to the first one. */
937
938       if (endaddr->first != last_first)
939         {
940         last_first = endaddr->first;
941         saved_paddr = paddr;
942         }
943       }
944
945     /* All cases (succeed, fail, defer left on queue) */
946
947     paddr = &(endaddr->next);         /* Advance to next address */
948     }                                 /* Loop for all addresses  */
949   }                                   /* Loop for succeed, fail, defer */
950
951 /* Close and unlock the database */
952
953 if (dbm_file) dbfn_close(dbm_file);
954
955 DEBUG(D_retry) debug_printf("end of retry processing\n");
956 }
957
958 /* End of retry.c */
959 /* vi: aw ai sw=2
960 */