Events: avoid evaluating intermediates for unneeded events
[exim.git] / src / src / queue.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* Functions that operate on the input queue. */
9
10
11 #include "exim.h"
12
13
14
15 /* Routines with knowledge of spool layout */
16
17 #ifndef COMPILE_UTILITY
18 static void
19 spool_pname_buf(uschar * buf, int len)
20 {
21 snprintf(CS buf, len, "%s/%s/input", spool_directory, queue_name);
22 }
23
24 uschar *
25 spool_dname(const uschar * purpose, uschar * subdir)
26 {
27 return string_sprintf("%s/%s/%s/%s",
28         spool_directory, queue_name, purpose, subdir);
29 }
30 #endif
31
32 uschar *
33 spool_sname(const uschar * purpose, uschar * subdir)
34 {
35 return string_sprintf("%s%s%s%s%s",
36                     queue_name, *queue_name ? "/" : "",
37                     purpose,
38                     *subdir ? "/" : "", subdir);
39 }
40
41 uschar *
42 spool_fname(const uschar * purpose, const uschar * subdir, const uschar * fname,
43         const uschar * suffix)
44 {
45 return string_sprintf("%s/%s/%s/%s/%s%s",
46         spool_directory, queue_name, purpose, subdir, fname, suffix);
47 }
48
49
50
51
52 #ifndef COMPILE_UTILITY
53
54 /* The number of nodes to use for the bottom-up merge sort when a list of queue
55 items is to be ordered. The code for this sort was contributed as a patch by
56 Michael Haardt. */
57
58 #define LOG2_MAXNODES 32
59
60
61
62 /*************************************************
63 *  Helper sort function for queue_get_spool_list *
64 *************************************************/
65
66 /* This function is used when sorting the queue list in the function
67 queue_get_spool_list() below.
68
69 Arguments:
70   a            points to an ordered list of queue_filename items
71   b            points to another ordered list
72
73 Returns:       a pointer to a merged ordered list
74 */
75
76 static queue_filename *
77 merge_queue_lists(queue_filename *a, queue_filename *b)
78 {
79 queue_filename *first = NULL;
80 queue_filename **append = &first;
81
82 while (a && b)
83   {
84   int d;
85   if ((d = Ustrncmp(a->text, b->text, 6)) == 0)
86     d = Ustrcmp(a->text + 14, b->text + 14);
87   if (d < 0)
88     {
89     *append = a;
90     append= &a->next;
91     a = a->next;
92     }
93   else
94     {
95     *append = b;
96     append= &b->next;
97     b = b->next;
98     }
99   }
100
101 *append = a ? a : b;
102 return first;
103 }
104
105
106
107
108
109 /*************************************************
110 *             Get list of spool files            *
111 *************************************************/
112
113 /* Scan the spool directory and return a list of the relevant file names
114 therein. Single-character sub-directories are handled as follows:
115
116   If the first argument is > 0, a sub-directory is scanned; the letter is
117   taken from the nth entry in subdirs.
118
119   If the first argument is 0, sub-directories are not scanned. However, a
120   list of them is returned.
121
122   If the first argument is < 0, sub-directories are scanned for messages,
123   and a single, unified list is created. The returned data blocks contain the
124   identifying character of the subdirectory, if any. The subdirs vector is
125   still required as an argument.
126
127 If the randomize argument is TRUE, messages are returned in "randomized" order.
128 Actually, the order is anything but random, but the algorithm is cheap, and the
129 point is simply to ensure that the same order doesn't occur every time, in case
130 a particular message is causing a remote MTA to barf - we would like to try
131 other messages to that MTA first.
132
133 If the randomize argument is FALSE, sort the list according to the file name.
134 This should give the order in which the messages arrived. It is normally used
135 only for presentation to humans, in which case the (possibly expensive) sort
136 that it does is not part of the normal operational code. However, if
137 queue_run_in_order is set, sorting has to take place for queue runs as well.
138 When randomize is FALSE, the first argument is normally -1, so all messages are
139 included.
140
141 Arguments:
142   subdiroffset   sub-directory character offset, or 0 or -1 (see above)
143   subdirs        vector to store list of subdirchars
144   subcount       pointer to int in which to store count of subdirs
145   randomize      TRUE if the order of the list is to be unpredictable
146
147 Returns:         pointer to a chain of queue name items
148 */
149
150 static queue_filename *
151 queue_get_spool_list(int subdiroffset, uschar *subdirs, int *subcount,
152   BOOL randomize)
153 {
154 int i;
155 int flags = 0;
156 int resetflags = -1;
157 int subptr;
158 queue_filename *yield = NULL;
159 queue_filename *last = NULL;
160 struct dirent *ent;
161 DIR *dd;
162 uschar buffer[256];
163 queue_filename *root[LOG2_MAXNODES];
164
165 /* When randomizing, the file names are added to the start or end of the list
166 according to the bits of the flags variable. Get a collection of bits from the
167 current time. Use the bottom 16 and just keep re-using them if necessary. When
168 not randomizing, initialize the sublists for the bottom-up merge sort. */
169
170 if (randomize)
171   resetflags = time(NULL) & 0xFFFF;
172 else
173    for (i = 0; i < LOG2_MAXNODES; i++)
174      root[i] = NULL;
175
176 /* If processing the full queue, or just the top-level, start at the base
177 directory, and initialize the first subdirectory name (as none). Otherwise,
178 start at the sub-directory offset. */
179
180 if (subdiroffset <= 0)
181   {
182   i = 0;
183   subdirs[0] = 0;
184   *subcount = 0;
185   }
186 else
187   i = subdiroffset;
188
189 /* Set up prototype for the directory name. */
190
191 spool_pname_buf(buffer, sizeof(buffer));
192 buffer[sizeof(buffer) - 3] = 0;
193 subptr = Ustrlen(buffer);
194 buffer[subptr+2] = 0;               /* terminator for lengthened name */
195
196 /* This loop runs at least once, for the main or given directory, and then as
197 many times as necessary to scan any subdirectories encountered in the main
198 directory, if they are to be scanned at this time. */
199
200 for (; i <= *subcount; i++)
201   {
202   int count = 0;
203   int subdirchar = subdirs[i];      /* 0 for main directory */
204
205   if (subdirchar != 0)
206     {
207     buffer[subptr] = '/';
208     buffer[subptr+1] = subdirchar;
209     }
210
211   DEBUG(D_queue_run) debug_printf("looking in %s\n", buffer);
212   if (!(dd = opendir(CS buffer)))
213     continue;
214
215   /* Now scan the directory. */
216
217   while ((ent = readdir(dd)))
218     {
219     uschar *name = US ent->d_name;
220     int len = Ustrlen(name);
221
222     /* Count entries */
223
224     count++;
225
226     /* If we find a single alphameric sub-directory in the base directory,
227     add it to the list for subsequent scans. */
228
229     if (i == 0 && len == 1 && isalnum(*name))
230       {
231       *subcount = *subcount + 1;
232       subdirs[*subcount] = *name;
233       continue;
234       }
235
236     /* Otherwise, if it is a header spool file, add it to the list */
237
238     if (len == SPOOL_NAME_LENGTH &&
239         Ustrcmp(name + SPOOL_NAME_LENGTH - 2, "-H") == 0)
240       {
241       queue_filename *next =
242         store_get(sizeof(queue_filename) + Ustrlen(name));
243       Ustrcpy(next->text, name);
244       next->dir_uschar = subdirchar;
245
246       /* Handle the creation of a randomized list. The first item becomes both
247       the top and bottom of the list. Subsequent items are inserted either at
248       the top or the bottom, randomly. This is, I argue, faster than doing a
249       sort by allocating a random number to each item, and it also saves having
250       to store the number with each item. */
251
252       if (randomize)
253         if (!yield)
254           {
255           next->next = NULL;
256           yield = last = next;
257           }
258         else
259           {
260           if (flags == 0)
261             flags = resetflags;
262           if ((flags & 1) == 0)
263             {
264             next->next = yield;
265             yield = next;
266             }
267           else
268             {
269             next->next = NULL;
270             last->next = next;
271             last = next;
272             }
273           flags = flags >> 1;
274           }
275
276       /* Otherwise do a bottom-up merge sort based on the name. */
277
278       else
279         {
280         next->next = NULL;
281         for (int j = 0; j < LOG2_MAXNODES; j++)
282           if (root[j])
283             {
284             next = merge_queue_lists(next, root[j]);
285             root[j] = j == LOG2_MAXNODES - 1 ? next : NULL;
286             }
287           else
288             {
289             root[j] = next;
290             break;
291             }
292         }
293       }
294     }
295
296   /* Finished with this directory */
297
298   closedir(dd);
299
300   /* If we have just scanned a sub-directory, and it was empty (count == 2
301   implies just "." and ".." entries), and Exim is no longer configured to
302   use sub-directories, attempt to get rid of it. At the same time, try to
303   get rid of any corresponding msglog subdirectory. These are just cosmetic
304   tidying actions, so just ignore failures. If we are scanning just a single
305   sub-directory, break the loop. */
306
307   if (i != 0)
308     {
309     if (!split_spool_directory && count <= 2)
310       {
311       uschar subdir[2];
312
313       rmdir(CS buffer);
314       subdir[0] = subdirchar; subdir[1] = 0;
315       rmdir(CS spool_dname(US"msglog", subdir));
316       }
317     if (subdiroffset > 0) break;    /* Single sub-directory */
318     }
319
320   /* If we have just scanned the base directory, and subdiroffset is 0,
321   we do not want to continue scanning the sub-directories. */
322
323   else if (subdiroffset == 0)
324     break;
325   }    /* Loop for multiple subdirectories */
326
327 /* When using a bottom-up merge sort, do the final merging of the sublists.
328 Then pass back the final list of file items. */
329
330 if (!randomize)
331   for (i = 0; i < LOG2_MAXNODES; ++i)
332     yield = merge_queue_lists(yield, root[i]);
333
334 return yield;
335 }
336
337
338
339
340 /*************************************************
341 *              Perform a queue run               *
342 *************************************************/
343
344 /* The arguments give the messages to start and stop at; NULL means start at
345 the beginning or stop at the end. If the given start message doesn't exist, we
346 start at the next lexically greater one, and likewise we stop at the after the
347 previous lexically lesser one if the given stop message doesn't exist. Because
348 a queue run can take some time, stat each file before forking, in case it has
349 been delivered in the meantime by some other means.
350
351 The global variables queue_run_force and queue_run_local may be set to cause
352 forced deliveries or local-only deliveries, respectively.
353
354 If deliver_selectstring[_sender] is not NULL, skip messages whose recipients do
355 not contain the string. As this option is typically used when a machine comes
356 back online, we want to ensure that at least one delivery attempt takes place,
357 so force the first one. The selecting string can optionally be a regex, or
358 refer to the sender instead of recipients.
359
360 If queue_2stage is set, the queue is scanned twice. The first time, queue_smtp
361 is set so that routing is done for all messages. Thus in the second run those
362 that are routed to the same host should go down the same SMTP connection.
363
364 Arguments:
365   start_id   message id to start at, or NULL for all
366   stop_id    message id to end at, or NULL for all
367   recurse    TRUE if recursing for 2-stage run
368
369 Returns:     nothing
370 */
371
372 void
373 queue_run(uschar *start_id, uschar *stop_id, BOOL recurse)
374 {
375 BOOL force_delivery = f.queue_run_force || deliver_selectstring != NULL ||
376   deliver_selectstring_sender != NULL;
377 const pcre *selectstring_regex = NULL;
378 const pcre *selectstring_regex_sender = NULL;
379 uschar *log_detail = NULL;
380 int subcount = 0;
381 uschar subdirs[64];
382
383 /* Cancel any specific queue domains. Turn off the flag that causes SMTP
384 deliveries not to happen, unless doing a 2-stage queue run, when the SMTP flag
385 gets set. Save the queue_runner's pid and the flag that indicates any
386 deliveries run directly from this process. Deliveries that are run by handing
387 on TCP/IP channels have queue_run_pid set, but not queue_running. */
388
389 queue_domains = NULL;
390 queue_smtp_domains = NULL;
391 f.queue_smtp = f.queue_2stage;
392
393 queue_run_pid = getpid();
394 f.queue_running = TRUE;
395
396 /* Log the true start of a queue run, and fancy options */
397
398 if (!recurse)
399   {
400   uschar extras[8];
401   uschar *p = extras;
402
403   if (f.queue_2stage) *p++ = 'q';
404   if (f.queue_run_first_delivery) *p++ = 'i';
405   if (f.queue_run_force) *p++ = 'f';
406   if (f.deliver_force_thaw) *p++ = 'f';
407   if (f.queue_run_local) *p++ = 'l';
408   *p = 0;
409
410   p = big_buffer;
411   p += sprintf(CS p, "pid=%d", (int)queue_run_pid);
412
413   if (extras[0] != 0)
414     p += sprintf(CS p, " -q%s", extras);
415
416   if (deliver_selectstring)
417     p += sprintf(CS p, " -R%s %s", f.deliver_selectstring_regex? "r" : "",
418       deliver_selectstring);
419
420   if (deliver_selectstring_sender)
421     p += sprintf(CS p, " -S%s %s", f.deliver_selectstring_sender_regex? "r" : "",
422       deliver_selectstring_sender);
423
424   log_detail = string_copy(big_buffer);
425   if (*queue_name)
426     log_write(L_queue_run, LOG_MAIN, "Start '%s' queue run: %s",
427       queue_name, log_detail);
428   else
429     log_write(L_queue_run, LOG_MAIN, "Start queue run: %s", log_detail);
430   }
431
432 /* If deliver_selectstring is a regex, compile it. */
433
434 if (deliver_selectstring && f.deliver_selectstring_regex)
435   selectstring_regex = regex_must_compile(deliver_selectstring, TRUE, FALSE);
436
437 if (deliver_selectstring_sender && f.deliver_selectstring_sender_regex)
438   selectstring_regex_sender =
439     regex_must_compile(deliver_selectstring_sender, TRUE, FALSE);
440
441 /* If the spool is split into subdirectories, we want to process it one
442 directory at a time, so as to spread out the directory scanning and the
443 delivering when there are lots of messages involved, except when
444 queue_run_in_order is set.
445
446 In the random order case, this loop runs once for the main directory (handling
447 any messages therein), and then repeats for any subdirectories that were found.
448 When the first argument of queue_get_spool_list() is 0, it scans the top
449 directory, fills in subdirs, and sets subcount. The order of the directories is
450 then randomized after the first time through, before they are scanned in
451 subsequent iterations.
452
453 When the first argument of queue_get_spool_list() is -1 (for queue_run_in_
454 order), it scans all directories and makes a single message list. */
455
456 for (int i = queue_run_in_order ? -1 : 0;
457      i <= (queue_run_in_order ? -1 : subcount);
458      i++)
459   {
460   void *reset_point1 = store_get(0);
461
462   DEBUG(D_queue_run)
463     {
464     if (i == 0)
465       debug_printf("queue running main directory\n");
466     else if (i == -1)
467       debug_printf("queue running combined directories\n");
468     else
469       debug_printf("queue running subdirectory '%c'\n", subdirs[i]);
470     }
471
472   for (queue_filename * fq = queue_get_spool_list(i, subdirs, &subcount,
473                                                !queue_run_in_order);
474        fq; fq = fq->next)
475     {
476     pid_t pid;
477     int status;
478     int pfd[2];
479     struct stat statbuf;
480     uschar buffer[256];
481
482     /* Unless deliveries are forced, if deliver_queue_load_max is non-negative,
483     check that the load average is low enough to permit deliveries. */
484
485     if (!f.queue_run_force && deliver_queue_load_max >= 0)
486       if ((load_average = os_getloadavg()) > deliver_queue_load_max)
487         {
488         log_write(L_queue_run, LOG_MAIN, "Abandon queue run: %s (load %.2f, max %.2f)",
489           log_detail,
490           (double)load_average/1000.0,
491           (double)deliver_queue_load_max/1000.0);
492         i = subcount;                 /* Don't process other directories */
493         break;
494         }
495       else
496         DEBUG(D_load) debug_printf("load average = %.2f max = %.2f\n",
497           (double)load_average/1000.0,
498           (double)deliver_queue_load_max/1000.0);
499
500     /* Skip this message unless it's within the ID limits */
501
502     if (stop_id && Ustrncmp(fq->text, stop_id, MESSAGE_ID_LENGTH) > 0)
503       continue;
504     if (start_id && Ustrncmp(fq->text, start_id, MESSAGE_ID_LENGTH) < 0)
505       continue;
506
507     /* Check that the message still exists */
508
509     message_subdir[0] = fq->dir_uschar;
510     if (Ustat(spool_fname(US"input", message_subdir, fq->text, US""), &statbuf) < 0)
511       continue;
512
513     /* There are some tests that require the reading of the header file. Ensure
514     the store used is scavenged afterwards so that this process doesn't keep
515     growing its store. We have to read the header file again when actually
516     delivering, but it's cheaper than forking a delivery process for each
517     message when many are not going to be delivered. */
518
519     if (deliver_selectstring || deliver_selectstring_sender ||
520         f.queue_run_first_delivery)
521       {
522       BOOL wanted = TRUE;
523       BOOL orig_dont_deliver = f.dont_deliver;
524       void *reset_point2 = store_get(0);
525
526       /* Restore the original setting of dont_deliver after reading the header,
527       so that a setting for a particular message doesn't force it for any that
528       follow. If the message is chosen for delivery, the header is read again
529       in the deliver_message() function, in a subprocess. */
530
531       if (spool_read_header(fq->text, FALSE, TRUE) != spool_read_OK) continue;
532       f.dont_deliver = orig_dont_deliver;
533
534       /* Now decide if we want to deliver this message. As we have read the
535       header file, we might as well do the freeze test now, and save forking
536       another process. */
537
538       if (f.deliver_freeze && !f.deliver_force_thaw)
539         {
540         log_write(L_skip_delivery, LOG_MAIN, "Message is frozen");
541         wanted = FALSE;
542         }
543
544       /* Check first_delivery in the case when there are no message logs. */
545
546       else if (f.queue_run_first_delivery && !f.deliver_firsttime)
547         {
548         DEBUG(D_queue_run) debug_printf("%s: not first delivery\n", fq->text);
549         wanted = FALSE;
550         }
551
552       /* Check for a matching address if deliver_selectstring[_sender] is set.
553       If so, we do a fully delivery - don't want to omit other addresses since
554       their routing might trigger re-writing etc. */
555
556       /* Sender matching */
557
558       else if (  deliver_selectstring_sender
559               && !(f.deliver_selectstring_sender_regex
560                   ? (pcre_exec(selectstring_regex_sender, NULL,
561                       CS sender_address, Ustrlen(sender_address), 0, PCRE_EOPT,
562                       NULL, 0) >= 0)
563                   : (strstric(sender_address, deliver_selectstring_sender, FALSE)
564                       != NULL)
565               )   )
566         {
567         DEBUG(D_queue_run) debug_printf("%s: sender address did not match %s\n",
568           fq->text, deliver_selectstring_sender);
569         wanted = FALSE;
570         }
571
572       /* Recipient matching */
573
574       else if (deliver_selectstring)
575         {
576         int i;
577         for (i = 0; i < recipients_count; i++)
578           {
579           uschar *address = recipients_list[i].address;
580           if (  (f.deliver_selectstring_regex
581                 ? (pcre_exec(selectstring_regex, NULL, CS address,
582                      Ustrlen(address), 0, PCRE_EOPT, NULL, 0) >= 0)
583                 : (strstric(address, deliver_selectstring, FALSE) != NULL)
584                 )
585              && tree_search(tree_nonrecipients, address) == NULL
586              )
587             break;
588           }
589
590         if (i >= recipients_count)
591           {
592           DEBUG(D_queue_run)
593             debug_printf("%s: no recipient address matched %s\n",
594               fq->text, deliver_selectstring);
595           wanted = FALSE;
596           }
597         }
598
599       /* Recover store used when reading the header */
600
601       spool_clear_header_globals();
602       store_reset(reset_point2);
603       if (!wanted) continue;      /* With next message */
604       }
605
606     /* OK, got a message we want to deliver. Create a pipe which will
607     serve as a means of detecting when all the processes created by the
608     delivery process are finished. This is relevant when the delivery
609     process passes one or more SMTP channels on to its own children. The
610     pipe gets passed down; by reading on it here we detect when the last
611     descendent dies by the unblocking of the read. It's a pity that for
612     most of the time the pipe isn't used, but creating a pipe should be
613     pretty cheap. */
614
615     if (pipe(pfd) < 0)
616       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to create pipe in queue "
617         "runner process %d: %s", queue_run_pid, strerror(errno));
618     queue_run_pipe = pfd[pipe_write];  /* To ensure it gets passed on. */
619
620     /* Make sure it isn't stdin. This seems unlikely, but just to be on the
621     safe side... */
622
623     if (queue_run_pipe == 0)
624       {
625       queue_run_pipe = dup(queue_run_pipe);
626       (void)close(0);
627       }
628
629     /* Before forking to deliver the message, ensure any open and cached
630     lookup files or databases are closed. Otherwise, closing in the subprocess
631     can make the next subprocess have problems. There won't often be anything
632     open here, but it is possible (e.g. if spool_directory is an expanded
633     string). A single call before this loop would probably suffice, but just in
634     case expansions get inserted at some point, I've taken the heavy-handed
635     approach. When nothing is open, the call should be cheap. */
636
637     search_tidyup();
638
639     /* Now deliver the message; get the id by cutting the -H off the file
640     name. The return of the process is zero if a delivery was attempted. */
641
642     set_process_info("running queue: %s", fq->text);
643     fq->text[SPOOL_NAME_LENGTH-2] = 0;
644     if ((pid = fork()) == 0)
645       {
646       int rc;
647       if (f.running_in_test_harness) millisleep(100);
648       (void)close(pfd[pipe_read]);
649       rc = deliver_message(fq->text, force_delivery, FALSE);
650       _exit(rc == DELIVER_NOT_ATTEMPTED);
651       }
652     if (pid < 0)
653       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "fork of delivery process from "
654         "queue runner %d failed\n", queue_run_pid);
655
656     /* Close the writing end of the synchronizing pipe in this process,
657     then wait for the first level process to terminate. */
658
659     (void)close(pfd[pipe_write]);
660     set_process_info("running queue: waiting for %s (%d)", fq->text, pid);
661     while (wait(&status) != pid);
662
663     /* A zero return means a delivery was attempted; turn off the force flag
664     for any subsequent calls unless queue_force is set. */
665
666     if ((status & 0xffff) == 0) force_delivery = f.queue_run_force;
667
668     /* If the process crashed, tell somebody */
669
670     else if ((status & 0x00ff) != 0)
671       log_write(0, LOG_MAIN|LOG_PANIC,
672         "queue run: process %d crashed with signal %d while delivering %s",
673         (int)pid, status & 0x00ff, fq->text);
674
675     /* Before continuing, wait till the pipe gets closed at the far end. This
676     tells us that any children created by the delivery to re-use any SMTP
677     channels have all finished. Since no process actually writes to the pipe,
678     the mere fact that read() unblocks is enough. */
679
680     set_process_info("running queue: waiting for children of %d", pid);
681     if ((status = read(pfd[pipe_read], buffer, sizeof(buffer))) != 0)
682       log_write(0, LOG_MAIN|LOG_PANIC, "queue run: %s on pipe",
683                 status > 0 ? "unexpected data" : "error");
684     (void)close(pfd[pipe_read]);
685     set_process_info("running queue");
686
687     /* If we are in the test harness, and this is not the first of a 2-stage
688     queue run, update fudged queue times. */
689
690     if (f.running_in_test_harness && !f.queue_2stage)
691       {
692       uschar *fqtnext = Ustrchr(fudged_queue_times, '/');
693       if (fqtnext != NULL) fudged_queue_times = fqtnext + 1;
694       }
695     }                                  /* End loop for list of messages */
696
697   tree_nonrecipients = NULL;
698   store_reset(reset_point1);           /* Scavenge list of messages */
699
700   /* If this was the first time through for random order processing, and
701   sub-directories have been found, randomize their order if necessary. */
702
703   if (i == 0 && subcount > 1 && !queue_run_in_order)
704     for (int j = 1; j <= subcount; j++)
705       {
706       int r;
707       if ((r = random_number(100)) >= 50)
708         {
709         int k = (r % subcount) + 1;
710         int x = subdirs[j];
711         subdirs[j] = subdirs[k];
712         subdirs[k] = x;
713         }
714       }
715   }                                    /* End loop for multiple directories */
716
717 /* If queue_2stage is true, we do it all again, with the 2stage flag
718 turned off. */
719
720 if (f.queue_2stage)
721   {
722   f.queue_2stage = FALSE;
723   queue_run(start_id, stop_id, TRUE);
724   }
725
726 /* At top level, log the end of the run. */
727
728 if (!recurse)
729   if (*queue_name)
730     log_write(L_queue_run, LOG_MAIN, "End '%s' queue run: %s",
731       queue_name, log_detail);
732   else
733     log_write(L_queue_run, LOG_MAIN, "End queue run: %s", log_detail);
734 }
735
736
737
738
739 /************************************************
740 *         Count messages on the queue           *
741 ************************************************/
742
743 /* Called as a result of -bpc
744
745 Arguments:  none
746 Returns:    nothing
747 */
748
749 void
750 queue_count(void)
751 {
752 int subcount;
753 int count = 0;
754 uschar subdirs[64];
755
756 for (queue_filename *f = queue_get_spool_list(
757                                 -1,             /* entire queue */
758                                 subdirs,        /* for holding sub list */
759                                 &subcount,      /* for subcount */
760                                 FALSE);         /* not random */
761     f; f = f->next) count++;
762 fprintf(stdout, "%d\n", count);
763 }
764
765
766
767 /************************************************
768 *          List extra deliveries                *
769 ************************************************/
770
771 /* This is called from queue_list below to print out all addresses that
772 have received a message but which were not primary addresses. That is, all
773 the addresses in the tree of non-recipients that are not primary addresses.
774 The tree has been scanned and the data field filled in for those that are
775 primary addresses.
776
777 Argument:    points to the tree node
778 Returns:     nothing
779 */
780
781 static void
782 queue_list_extras(tree_node *p)
783 {
784 if (p->left) queue_list_extras(p->left);
785 if (!p->data.val) printf("       +D %s\n", p->name);
786 if (p->right) queue_list_extras(p->right);
787 }
788
789
790
791 /************************************************
792 *          List messages on the queue           *
793 ************************************************/
794
795 /* Or a given list of messages. In the "all" case, we get a list of file names
796 as quickly as possible, then scan each one for information to output. If any
797 disappear while we are processing, just leave them out, but give an error if an
798 explicit list was given. This function is a top-level function that is obeyed
799 as a result of the -bp argument. As there may be a lot of messages on the
800 queue, we must tidy up the store after reading the headers for each one.
801
802 Arguments:
803    option     0 => list top-level recipients, with "D" for those delivered
804               1 => list only undelivered top-level recipients
805               2 => as 0, plus any generated delivered recipients
806               If 8 is added to any of these values, the queue is listed in
807                 random order.
808    list       => first of any message ids to list
809    count      count of message ids; 0 => all
810
811 Returns:      nothing
812 */
813
814 void
815 queue_list(int option, uschar **list, int count)
816 {
817 int subcount;
818 int now = (int)time(NULL);
819 void *reset_point;
820 queue_filename * qf = NULL;
821 uschar subdirs[64];
822
823 /* If given a list of messages, build a chain containing their ids. */
824
825 if (count > 0)
826   {
827   queue_filename *last = NULL;
828   for (int i = 0; i < count; i++)
829     {
830     queue_filename *next =
831       store_get(sizeof(queue_filename) + Ustrlen(list[i]) + 2);
832     sprintf(CS next->text, "%s-H", list[i]);
833     next->dir_uschar = '*';
834     next->next = NULL;
835     if (i == 0) qf = next; else last->next = next;
836     last = next;
837     }
838   }
839
840 /* Otherwise get a list of the entire queue, in order if necessary. */
841
842 else
843   qf = queue_get_spool_list(
844           -1,             /* entire queue */
845           subdirs,        /* for holding sub list */
846           &subcount,      /* for subcount */
847           option >= 8);   /* randomize if required */
848
849 if (option >= 8) option -= 8;
850
851 /* Now scan the chain and print information, resetting store used
852 each time. */
853
854 for (reset_point = store_get(0);
855     qf;
856     spool_clear_header_globals(), store_reset(reset_point), qf = qf->next
857     )
858   {
859   int rc, save_errno;
860   int size = 0;
861   BOOL env_read;
862
863   message_size = 0;
864   message_subdir[0] = qf->dir_uschar;
865   rc = spool_read_header(qf->text, FALSE, count <= 0);
866   if (rc == spool_read_notopen && errno == ENOENT && count <= 0)
867     continue;
868   save_errno = errno;
869
870   env_read = (rc == spool_read_OK || rc == spool_read_hdrerror);
871
872   if (env_read)
873     {
874     int i, ptr;
875     FILE *jread;
876     struct stat statbuf;
877     uschar * fname = spool_fname(US"input", message_subdir, qf->text, US"");
878
879     ptr = Ustrlen(fname)-1;
880     fname[ptr] = 'D';
881
882     /* Add the data size to the header size; don't count the file name
883     at the start of the data file, but add one for the notional blank line
884     that precedes the data. */
885
886     if (Ustat(fname, &statbuf) == 0)
887       size = message_size + statbuf.st_size - SPOOL_DATA_START_OFFSET + 1;
888     i = (now - received_time.tv_sec)/60;  /* minutes on queue */
889     if (i > 90)
890       {
891       i = (i + 30)/60;
892       if (i > 72) printf("%2dd ", (i + 12)/24); else printf("%2dh ", i);
893       }
894     else printf("%2dm ", i);
895
896     /* Collect delivered addresses from any J file */
897
898     fname[ptr] = 'J';
899     if ((jread = Ufopen(fname, "rb")))
900       {
901       while (Ufgets(big_buffer, big_buffer_size, jread) != NULL)
902         {
903         int n = Ustrlen(big_buffer);
904         big_buffer[n-1] = 0;
905         tree_add_nonrecipient(big_buffer);
906         }
907       (void)fclose(jread);
908       }
909     }
910
911   fprintf(stdout, "%s ", string_format_size(size, big_buffer));
912   for (int i = 0; i < 16; i++) fputc(qf->text[i], stdout);
913
914   if (env_read && sender_address)
915     {
916     printf(" <%s>", sender_address);
917     if (f.sender_set_untrusted) printf(" (%s)", originator_login);
918     }
919
920   if (rc != spool_read_OK)
921     {
922     printf("\n    ");
923     if (save_errno == ERRNO_SPOOLFORMAT)
924       {
925       struct stat statbuf;
926       uschar * fname = spool_fname(US"input", message_subdir, qf->text, US"");
927
928       if (Ustat(fname, &statbuf) == 0)
929         printf("*** spool format error: size=" OFF_T_FMT " ***",
930           statbuf.st_size);
931       else printf("*** spool format error ***");
932       }
933     else printf("*** spool read error: %s ***", strerror(save_errno));
934     if (rc != spool_read_hdrerror)
935       {
936       printf("\n\n");
937       continue;
938       }
939     }
940
941   if (f.deliver_freeze) printf(" *** frozen ***");
942
943   printf("\n");
944
945   if (recipients_list)
946     {
947     for (int i = 0; i < recipients_count; i++)
948       {
949       tree_node *delivered =
950         tree_search(tree_nonrecipients, recipients_list[i].address);
951       if (!delivered || option != 1)
952         printf("        %s %s\n",
953           delivered ? "D" : " ", recipients_list[i].address);
954       if (delivered) delivered->data.val = TRUE;
955       }
956     if (option == 2 && tree_nonrecipients)
957       queue_list_extras(tree_nonrecipients);
958     printf("\n");
959     }
960   }
961 }
962
963
964
965 /*************************************************
966 *             Act on a specific message          *
967 *************************************************/
968
969 /* Actions that require a list of addresses make use of argv/argc/
970 recipients_arg. Other actions do not. This function does its own
971 authority checking.
972
973 Arguments:
974   id              id of the message to work on
975   action          which action is required (MSG_xxx)
976   argv            the original argv for Exim
977   argc            the original argc for Exim
978   recipients_arg  offset to the list of recipients in argv
979
980 Returns:          FALSE if there was any problem
981 */
982
983 BOOL
984 queue_action(uschar *id, int action, uschar **argv, int argc, int recipients_arg)
985 {
986 BOOL yield = TRUE;
987 BOOL removed = FALSE;
988 struct passwd *pw;
989 uschar *doing = NULL;
990 uschar *username;
991 uschar *errmsg;
992 uschar spoolname[32];
993
994 /* Set the global message_id variable, used when re-writing spool files. This
995 also causes message ids to be added to log messages. */
996
997 Ustrcpy(message_id, id);
998
999 /* The "actions" that just list the files do not require any locking to be
1000 done. Only admin users may read the spool files. */
1001
1002 if (action >= MSG_SHOW_BODY)
1003   {
1004   int fd, rc;
1005   uschar *subdirectory, *suffix;
1006
1007   if (!f.admin_user)
1008     {
1009     printf("Permission denied\n");
1010     return FALSE;
1011     }
1012
1013   if (recipients_arg < argc)
1014     {
1015     printf("*** Only one message can be listed at once\n");
1016     return FALSE;
1017     }
1018
1019   if (action == MSG_SHOW_BODY)
1020     {
1021     subdirectory = US"input";
1022     suffix = US"-D";
1023     }
1024   else if (action == MSG_SHOW_HEADER)
1025     {
1026     subdirectory = US"input";
1027     suffix = US"-H";
1028     }
1029   else
1030     {
1031     subdirectory = US"msglog";
1032     suffix = US"";
1033     }
1034
1035   for (int i = 0; i < 2; i++)
1036     {
1037     message_subdir[0] = split_spool_directory == (i == 0) ? id[5] : 0;
1038     if ((fd = Uopen(spool_fname(subdirectory, message_subdir, id, suffix),
1039                     O_RDONLY, 0)) >= 0)
1040       break;
1041     if (i == 0)
1042       continue;
1043
1044     printf("Failed to open %s file for %s%s: %s\n", subdirectory, id, suffix,
1045       strerror(errno));
1046     if (action == MSG_SHOW_LOG && !message_logs)
1047       printf("(No message logs are being created because the message_logs "
1048         "option is false.)\n");
1049     return FALSE;
1050     }
1051
1052   while((rc = read(fd, big_buffer, big_buffer_size)) > 0)
1053     rc = write(fileno(stdout), big_buffer, rc);
1054
1055   (void)close(fd);
1056   return TRUE;
1057   }
1058
1059 /* For actions that actually act, open and lock the data file to ensure that no
1060 other process is working on this message. If the file does not exist, continue
1061 only if the action is remove and the user is an admin user, to allow for
1062 tidying up broken states. */
1063
1064 if ((deliver_datafile = spool_open_datafile(id)) < 0)
1065   if (errno == ENOENT)
1066     {
1067     yield = FALSE;
1068     printf("Spool data file for %s does not exist\n", id);
1069     if (action != MSG_REMOVE || !f.admin_user) return FALSE;
1070     printf("Continuing, to ensure all files removed\n");
1071     }
1072   else
1073     {
1074     if (errno == 0) printf("Message %s is locked\n", id);
1075       else printf("Couldn't open spool file for %s: %s\n", id,
1076         strerror(errno));
1077     return FALSE;
1078     }
1079
1080 /* Read the spool header file for the message. Again, continue after an
1081 error only in the case of deleting by an administrator. Setting the third
1082 argument false causes it to look both in the main spool directory and in
1083 the appropriate subdirectory, and set message_subdir according to where it
1084 found the message. */
1085
1086 sprintf(CS spoolname, "%s-H", id);
1087 if (spool_read_header(spoolname, TRUE, FALSE) != spool_read_OK)
1088   {
1089   yield = FALSE;
1090   if (errno != ERRNO_SPOOLFORMAT)
1091     printf("Spool read error for %s: %s\n", spoolname, strerror(errno));
1092   else
1093     printf("Spool format error for %s\n", spoolname);
1094   if (action != MSG_REMOVE || !f.admin_user)
1095     {
1096     (void)close(deliver_datafile);
1097     deliver_datafile = -1;
1098     return FALSE;
1099     }
1100   printf("Continuing to ensure all files removed\n");
1101   }
1102
1103 /* Check that the user running this process is entitled to operate on this
1104 message. Only admin users may freeze/thaw, add/cancel recipients, or otherwise
1105 mess about, but the original sender is permitted to remove a message. That's
1106 why we leave this check until after the headers are read. */
1107
1108 if (!f.admin_user && (action != MSG_REMOVE || real_uid != originator_uid))
1109   {
1110   printf("Permission denied\n");
1111   (void)close(deliver_datafile);
1112   deliver_datafile = -1;
1113   return FALSE;
1114   }
1115
1116 /* Set up the user name for logging. */
1117
1118 pw = getpwuid(real_uid);
1119 username = (pw != NULL)?
1120   US pw->pw_name : string_sprintf("uid %ld", (long int)real_uid);
1121
1122 /* Take the necessary action. */
1123
1124 if (action != MSG_SHOW_COPY) printf("Message %s ", id);
1125
1126 switch(action)
1127   {
1128   case MSG_SHOW_COPY:
1129     {
1130     transport_ctx tctx = {{0}};
1131     deliver_in_buffer = store_malloc(DELIVER_IN_BUFFER_SIZE);
1132     deliver_out_buffer = store_malloc(DELIVER_OUT_BUFFER_SIZE);
1133     tctx.u.fd = 1;
1134     (void) transport_write_message(&tctx, 0);
1135     break;
1136     }
1137
1138
1139   case MSG_FREEZE:
1140   if (f.deliver_freeze)
1141     {
1142     yield = FALSE;
1143     printf("is already frozen\n");
1144     }
1145   else
1146     {
1147     f.deliver_freeze = TRUE;
1148     f.deliver_manual_thaw = FALSE;
1149     deliver_frozen_at = time(NULL);
1150     if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0)
1151       {
1152       printf("is now frozen\n");
1153       log_write(0, LOG_MAIN, "frozen by %s", username);
1154       }
1155     else
1156       {
1157       yield = FALSE;
1158       printf("could not be frozen: %s\n", errmsg);
1159       }
1160     }
1161   break;
1162
1163
1164   case MSG_THAW:
1165   if (!f.deliver_freeze)
1166     {
1167     yield = FALSE;
1168     printf("is not frozen\n");
1169     }
1170   else
1171     {
1172     f.deliver_freeze = FALSE;
1173     f.deliver_manual_thaw = TRUE;
1174     if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0)
1175       {
1176       printf("is no longer frozen\n");
1177       log_write(0, LOG_MAIN, "unfrozen by %s", username);
1178       }
1179     else
1180       {
1181       yield = FALSE;
1182       printf("could not be unfrozen: %s\n", errmsg);
1183       }
1184     }
1185   break;
1186
1187
1188   /* We must ensure all files are removed from both the input directory
1189   and the appropriate subdirectory, to clean up cases when there are odd
1190   files left lying around in odd places. In the normal case message_subdir
1191   will have been set correctly by spool_read_header, but as this is a rare
1192   operation, just run everything twice. */
1193
1194   case MSG_REMOVE:
1195     {
1196     uschar suffix[3];
1197
1198     suffix[0] = '-';
1199     suffix[2] = 0;
1200     message_subdir[0] = id[5];
1201
1202     for (int j = 0; j < 2; message_subdir[0] = 0, j++)
1203       {
1204       uschar * fname = spool_fname(US"msglog", message_subdir, id, US"");
1205
1206       DEBUG(D_any) debug_printf(" removing %s", fname);
1207       if (Uunlink(fname) < 0)
1208         {
1209         if (errno != ENOENT)
1210           {
1211           yield = FALSE;
1212           printf("Error while removing %s: %s\n", fname, strerror(errno));
1213           }
1214         else DEBUG(D_any) debug_printf(" (no file)\n");
1215         }
1216       else
1217         {
1218         removed = TRUE;
1219         DEBUG(D_any) debug_printf(" (ok)\n");
1220         }
1221
1222       for (int i = 0; i < 3; i++)
1223         {
1224         uschar * fname;
1225
1226         suffix[1] = (US"DHJ")[i];
1227         fname = spool_fname(US"input", message_subdir, id, suffix);
1228
1229         DEBUG(D_any) debug_printf(" removing %s", fname);
1230         if (Uunlink(fname) < 0)
1231           {
1232           if (errno != ENOENT)
1233             {
1234             yield = FALSE;
1235             printf("Error while removing %s: %s\n", fname, strerror(errno));
1236             }
1237           else DEBUG(D_any) debug_printf(" (no file)\n");
1238           }
1239         else
1240           {
1241           removed = TRUE;
1242           DEBUG(D_any) debug_printf(" (done)\n");
1243           }
1244         }
1245       }
1246
1247     /* In the common case, the datafile is open (and locked), so give the
1248     obvious message. Otherwise be more specific. */
1249
1250     if (deliver_datafile >= 0) printf("has been removed\n");
1251       else printf("has been removed or did not exist\n");
1252     if (removed)
1253       {
1254 #ifndef DISABLE_EVENT
1255       if (event_action) for (int i = 0; i < recipients_count; i++)
1256         {
1257         tree_node *delivered =
1258           tree_search(tree_nonrecipients, recipients_list[i].address);
1259         if (!delivered)
1260           {
1261           uschar * save_local = deliver_localpart;
1262           const uschar * save_domain = deliver_domain;
1263           uschar * addr = recipients_list[i].address, * errmsg = NULL;
1264           int start, end, dom;
1265
1266           if (!parse_extract_address(addr, &errmsg, &start, &end, &dom, TRUE))
1267             log_write(0, LOG_MAIN|LOG_PANIC,
1268               "failed to parse address '%.100s'\n: %s", addr, errmsg);
1269           else
1270             {
1271             deliver_localpart =
1272               string_copyn(addr+start, dom ? (dom-1) - start : end - start);
1273             deliver_domain = dom
1274               ? CUS string_copyn(addr+dom, end - dom) : CUS"";
1275
1276             event_raise(event_action, US"msg:fail:internal",
1277               string_sprintf("message removed by %s", username));
1278
1279             deliver_localpart = save_local;
1280             deliver_domain = save_domain;
1281             }
1282           }
1283         }
1284       (void) event_raise(event_action, US"msg:complete", NULL);
1285 #endif
1286       log_write(0, LOG_MAIN, "removed by %s", username);
1287       log_write(0, LOG_MAIN, "Completed");
1288       }
1289     break;
1290     }
1291
1292
1293   case MSG_MARK_ALL_DELIVERED:
1294   for (int i = 0; i < recipients_count; i++)
1295     tree_add_nonrecipient(recipients_list[i].address);
1296
1297   if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0)
1298     {
1299     printf("has been modified\n");
1300     for (int i = 0; i < recipients_count; i++)
1301       log_write(0, LOG_MAIN, "address <%s> marked delivered by %s",
1302         recipients_list[i].address, username);
1303     }
1304   else
1305     {
1306     yield = FALSE;
1307     printf("- could not mark all delivered: %s\n", errmsg);
1308     }
1309   break;
1310
1311
1312   case MSG_EDIT_SENDER:
1313   if (recipients_arg < argc - 1)
1314     {
1315     yield = FALSE;
1316     printf("- only one sender address can be specified\n");
1317     break;
1318     }
1319   doing = US"editing sender";
1320   /* Fall through */
1321
1322   case MSG_ADD_RECIPIENT:
1323   if (doing == NULL) doing = US"adding recipient";
1324   /* Fall through */
1325
1326   case MSG_MARK_DELIVERED:
1327   if (doing == NULL) doing = US"marking as delivered";
1328
1329   /* Common code for EDIT_SENDER, ADD_RECIPIENT, & MARK_DELIVERED */
1330
1331   if (recipients_arg >= argc)
1332     {
1333     yield = FALSE;
1334     printf("- error while %s: no address given\n", doing);
1335     break;
1336     }
1337
1338   for (; recipients_arg < argc; recipients_arg++)
1339     {
1340     int start, end, domain;
1341     uschar *errmess;
1342     uschar *recipient =
1343       parse_extract_address(argv[recipients_arg], &errmess, &start, &end,
1344         &domain, (action == MSG_EDIT_SENDER));
1345
1346     if (recipient == NULL)
1347       {
1348       yield = FALSE;
1349       printf("- error while %s:\n  bad address %s: %s\n",
1350         doing, argv[recipients_arg], errmess);
1351       }
1352     else if (recipient[0] != 0 && domain == 0)
1353       {
1354       yield = FALSE;
1355       printf("- error while %s:\n  bad address %s: "
1356         "domain missing\n", doing, argv[recipients_arg]);
1357       }
1358     else
1359       {
1360       if (action == MSG_ADD_RECIPIENT)
1361         {
1362 #ifdef SUPPORT_I18N
1363         if (string_is_utf8(recipient)) allow_utf8_domains = message_smtputf8 = TRUE;
1364 #endif
1365         receive_add_recipient(recipient, -1);
1366         log_write(0, LOG_MAIN, "recipient <%s> added by %s",
1367           recipient, username);
1368         }
1369       else if (action == MSG_MARK_DELIVERED)
1370         {
1371         int i;
1372         for (i = 0; i < recipients_count; i++)
1373           if (Ustrcmp(recipients_list[i].address, recipient) == 0) break;
1374         if (i >= recipients_count)
1375           {
1376           printf("- error while %s:\n  %s is not a recipient:"
1377             " message not updated\n", doing, recipient);
1378           yield = FALSE;
1379           }
1380         else
1381           {
1382           tree_add_nonrecipient(recipients_list[i].address);
1383           log_write(0, LOG_MAIN, "address <%s> marked delivered by %s",
1384             recipient, username);
1385           }
1386         }
1387       else  /* MSG_EDIT_SENDER */
1388         {
1389 #ifdef SUPPORT_I18N
1390         if (string_is_utf8(recipient)) allow_utf8_domains = message_smtputf8 = TRUE;
1391 #endif
1392         sender_address = recipient;
1393         log_write(0, LOG_MAIN, "sender address changed to <%s> by %s",
1394           recipient, username);
1395         }
1396       }
1397     }
1398
1399   if (yield)
1400     if (spool_write_header(id, SW_MODIFYING, &errmsg) >= 0)
1401       printf("has been modified\n");
1402     else
1403       {
1404       yield = FALSE;
1405       printf("- while %s: %s\n", doing, errmsg);
1406       }
1407
1408   break;
1409   }
1410
1411 /* Closing the datafile releases the lock and permits other processes
1412 to operate on the message (if it still exists). */
1413
1414 if (deliver_datafile >= 0)
1415   {
1416   (void)close(deliver_datafile);
1417   deliver_datafile = -1;
1418   }
1419 return yield;
1420 }
1421
1422
1423
1424 /*************************************************
1425 *       Check the queue_only_file condition      *
1426 *************************************************/
1427
1428 /* The queue_only_file option forces certain kinds of queueing if a given file
1429 exists.
1430
1431 Arguments:  none
1432 Returns:    nothing
1433 */
1434
1435 void
1436 queue_check_only(void)
1437 {
1438 int sep = 0;
1439 struct stat statbuf;
1440 const uschar *s;
1441 uschar *ss;
1442 uschar buffer[1024];
1443
1444 if (queue_only_file == NULL) return;
1445
1446 s = queue_only_file;
1447 while ((ss = string_nextinlist(&s, &sep, buffer, sizeof(buffer))) != NULL)
1448   {
1449   if (Ustrncmp(ss, "smtp", 4) == 0)
1450     {
1451     ss += 4;
1452     if (Ustat(ss, &statbuf) == 0)
1453       {
1454       f.queue_smtp = TRUE;
1455       DEBUG(D_receive) debug_printf("queue_smtp set because %s exists\n", ss);
1456       }
1457     }
1458   else
1459     {
1460     if (Ustat(ss, &statbuf) == 0)
1461       {
1462       queue_only = TRUE;
1463       DEBUG(D_receive) debug_printf("queue_only set because %s exists\n", ss);
1464       }
1465     }
1466   }
1467 }
1468
1469 #endif /*!COMPILE_UTILITY*/
1470
1471 /* End of queue.c */