Queue_Ramp in -bV output no longer experimental
[exim.git] / src / src / exim.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* Copyright (c) The Exim Maintainers 2020 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9
10 /* The main function: entry point, initialization, and high-level control.
11 Also a few functions that don't naturally fit elsewhere. */
12
13
14 #include "exim.h"
15
16 #if defined(__GLIBC__) && !defined(__UCLIBC__)
17 # include <gnu/libc-version.h>
18 #endif
19
20 #ifdef USE_GNUTLS
21 # include <gnutls/gnutls.h>
22 # if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
23 #  define DISABLE_OCSP
24 # endif
25 #endif
26
27 #ifndef _TIME_H
28 # include <time.h>
29 #endif
30
31 extern void init_lookup_list(void);
32
33
34
35 /*************************************************
36 *      Function interface to store functions     *
37 *************************************************/
38
39 /* We need some real functions to pass to the PCRE regular expression library
40 for store allocation via Exim's store manager. The normal calls are actually
41 macros that pass over location information to make tracing easier. These
42 functions just interface to the standard macro calls. A good compiler will
43 optimize out the tail recursion and so not make them too expensive. There
44 are two sets of functions; one for use when we want to retain the compiled
45 regular expression for a long time; the other for short-term use. */
46
47 static void *
48 function_store_get(PCRE2_SIZE size, void * tag)
49 {
50 /* For now, regard all RE results as potentially tainted.  We might need
51 more intelligence on this point. */
52 return store_get((int)size, TRUE);
53 }
54
55 static void
56 function_dummy_free(void * block, void * tag) {}
57
58 static void *
59 function_store_malloc(PCRE2_SIZE size, void * tag)
60 {
61 return store_malloc((int)size);
62 }
63
64 static void
65 function_store_free(void * block, void * tag)
66 {
67 store_free(block);
68 }
69
70
71
72
73 /*************************************************
74 *         Enums for cmdline interface            *
75 *************************************************/
76
77 enum commandline_info { CMDINFO_NONE=0,
78   CMDINFO_HELP, CMDINFO_SIEVE, CMDINFO_DSCP };
79
80
81
82
83 /*************************************************
84 *  Compile regular expression and panic on fail  *
85 *************************************************/
86
87 /* This function is called when failure to compile a regular expression leads
88 to a panic exit. In other cases, pcre_compile() is called directly. In many
89 cases where this function is used, the results of the compilation are to be
90 placed in long-lived store, so we temporarily reset the store management
91 functions that PCRE uses if the use_malloc flag is set.
92
93 Argument:
94   pattern     the pattern to compile
95   caseless    TRUE if caseless matching is required
96   use_malloc  TRUE if compile into malloc store
97
98 Returns:      pointer to the compiled pattern
99 */
100
101 const pcre2_code *
102 regex_must_compile(const uschar * pattern, BOOL caseless, BOOL use_malloc)
103 {
104 size_t offset;
105 int options = caseless ? PCRE_COPT|PCRE2_CASELESS : PCRE_COPT;
106 const pcre2_code * yield;
107 int err;
108 pcre2_general_context * gctx;
109 pcre2_compile_context * cctx;
110
111 if (use_malloc)
112   {
113   gctx = pcre2_general_context_create(function_store_malloc, function_store_free, NULL);
114   cctx = pcre2_compile_context_create(gctx);
115   }
116 else
117   cctx = pcre_cmp_ctx;
118
119 if (!(yield = pcre2_compile((PCRE2_SPTR)pattern, PCRE2_ZERO_TERMINATED, options,
120   &err, &offset, cctx)))
121   {
122   uschar errbuf[128];
123   pcre2_get_error_message(err, errbuf, sizeof(errbuf));
124   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "regular expression error: "
125     "%s at offset %ld while compiling %s", errbuf, (long)offset, pattern);
126   }
127
128 if (use_malloc)
129   {
130   pcre2_compile_context_free(cctx);
131   pcre2_general_context_free(gctx);
132   }
133 return yield;
134 }
135
136
137 static void
138 pcre_init(void)
139 {
140 pcre_gen_ctx = pcre2_general_context_create(function_store_malloc, function_store_free, NULL);
141 pcre_cmp_ctx = pcre2_compile_context_create(pcre_gen_ctx);
142 pcre_mtc_ctx = pcre2_match_context_create(pcre_gen_ctx);
143 }
144
145
146
147
148 /*************************************************
149 *   Execute regular expression and set strings   *
150 *************************************************/
151
152 /* This function runs a regular expression match, and sets up the pointers to
153 the matched substrings.  The matched strings are copied so the lifetime of
154 the subject is not a problem.
155
156 Arguments:
157   re          the compiled expression
158   subject     the subject string
159   options     additional PCRE options
160   setup       if < 0 do full setup
161               if >= 0 setup from setup+1 onwards,
162                 excluding the full matched string
163
164 Returns:      TRUE if matched, or FALSE
165 */
166
167 BOOL
168 regex_match_and_setup(const pcre2_code * re, const uschar * subject, int options, int setup)
169 {
170 pcre2_match_data * md = pcre2_match_data_create_from_pattern(re, pcre_gen_ctx);
171 int res = pcre2_match(re, (PCRE2_SPTR)subject, PCRE2_ZERO_TERMINATED, 0,
172                         PCRE_EOPT | options, md, pcre_mtc_ctx);
173 BOOL yield;
174
175 if ((yield = (res >= 0)))
176   {
177   res = pcre2_get_ovector_count(md);
178   expand_nmax = setup < 0 ? 0 : setup + 1;
179   for (int matchnum = setup < 0 ? 0 : 1; matchnum < res; matchnum++)
180     {
181     PCRE2_SIZE len;
182     pcre2_substring_get_bynumber(md, matchnum,
183       (PCRE2_UCHAR **)&expand_nstring[expand_nmax], &len);
184     expand_nlength[expand_nmax++] = (int)len;
185     }
186   expand_nmax--;
187   }
188 else if (res != PCRE2_ERROR_NOMATCH) DEBUG(D_any)
189   {
190   uschar errbuf[128];
191   pcre2_get_error_message(res, errbuf, sizeof(errbuf));
192   debug_printf_indent("pcre2: %s\n", errbuf);
193   }
194 pcre2_match_data_free(md);
195 return yield;
196 }
197
198
199 /* Check just for match with regex.  Uses the common memory-handling.
200
201 Arguments:
202         re      compiled regex
203         subject string to be checked
204         slen    length of subject; -1 for nul-terminated
205         rptr    pointer for matched string, copied, or NULL
206
207 Return: TRUE for a match.
208 */
209
210 BOOL
211 regex_match(const pcre2_code * re, const uschar * subject, int slen, uschar ** rptr)
212 {
213 pcre2_match_data * md = pcre2_match_data_create(1, pcre_gen_ctx);
214 int rc = pcre2_match(re, (PCRE2_SPTR)subject,
215                       slen >= 0 ? slen : PCRE2_ZERO_TERMINATED,
216                       0, PCRE_EOPT, md, pcre_mtc_ctx);
217 PCRE2_SIZE * ovec = pcre2_get_ovector_pointer(md);
218 if (rc < 0)
219   return FALSE;
220 if (rptr)
221   *rptr = string_copyn(subject + ovec[0], ovec[1] - ovec[0]);
222 return TRUE;
223 }
224
225
226
227 /*************************************************
228 *            Set up processing details           *
229 *************************************************/
230
231 /* Save a text string for dumping when SIGUSR1 is received.
232 Do checks for overruns.
233
234 Arguments: format and arguments, as for printf()
235 Returns:   nothing
236 */
237
238 void
239 set_process_info(const char *format, ...)
240 {
241 gstring gs = { .size = PROCESS_INFO_SIZE - 2, .ptr = 0, .s = process_info };
242 gstring * g;
243 int len;
244 va_list ap;
245
246 g = string_fmt_append(&gs, "%5d ", (int)getpid());
247 len = g->ptr;
248 va_start(ap, format);
249 if (!string_vformat(g, 0, format, ap))
250   {
251   gs.ptr = len;
252   g = string_cat(&gs, US"**** string overflowed buffer ****");
253   }
254 g = string_catn(g, US"\n", 1);
255 string_from_gstring(g);
256 process_info_len = g->ptr;
257 DEBUG(D_process_info) debug_printf("set_process_info: %s", process_info);
258 va_end(ap);
259 }
260
261 /***********************************************
262 *            Handler for SIGTERM               *
263 ***********************************************/
264
265 static void
266 term_handler(int sig)
267 {
268 exit(1);
269 }
270
271
272 /***********************************************
273 *            Handler for SIGSEGV               *
274 ***********************************************/
275
276 static void
277 segv_handler(int sig)
278 {
279 log_write(0, LOG_MAIN|LOG_PANIC, "SIGSEGV (maybe attempt to write to immutable memory)");
280 signal(SIGSEGV, SIG_DFL);
281 kill(getpid(), sig);
282 }
283
284
285 /*************************************************
286 *             Handler for SIGUSR1                *
287 *************************************************/
288
289 /* SIGUSR1 causes any exim process to write to the process log details of
290 what it is currently doing. It will only be used if the OS is capable of
291 setting up a handler that causes automatic restarting of any system call
292 that is in progress at the time.
293
294 This function takes care to be signal-safe.
295
296 Argument: the signal number (SIGUSR1)
297 Returns:  nothing
298 */
299
300 static void
301 usr1_handler(int sig)
302 {
303 int fd;
304
305 os_restarting_signal(sig, usr1_handler);
306
307 if (!process_log_path) return;
308 fd = log_open_as_exim(process_log_path);
309
310 /* If we are neither exim nor root, or if we failed to create the log file,
311 give up. There is not much useful we can do with errors, since we don't want
312 to disrupt whatever is going on outside the signal handler. */
313
314 if (fd < 0) return;
315
316 (void)write(fd, process_info, process_info_len);
317 (void)close(fd);
318 }
319
320
321
322 /*************************************************
323 *             Timeout handler                    *
324 *************************************************/
325
326 /* This handler is enabled most of the time that Exim is running. The handler
327 doesn't actually get used unless alarm() has been called to set a timer, to
328 place a time limit on a system call of some kind. When the handler is run, it
329 re-enables itself.
330
331 There are some other SIGALRM handlers that are used in special cases when more
332 than just a flag setting is required; for example, when reading a message's
333 input. These are normally set up in the code module that uses them, and the
334 SIGALRM handler is reset to this one afterwards.
335
336 Argument: the signal value (SIGALRM)
337 Returns:  nothing
338 */
339
340 void
341 sigalrm_handler(int sig)
342 {
343 sigalrm_seen = TRUE;
344 os_non_restarting_signal(SIGALRM, sigalrm_handler);
345 }
346
347
348
349 /*************************************************
350 *      Sleep for a fractional time interval      *
351 *************************************************/
352
353 /* This function is called by millisleep() and exim_wait_tick() to wait for a
354 period of time that may include a fraction of a second. The coding is somewhat
355 tedious. We do not expect setitimer() ever to fail, but if it does, the process
356 will wait for ever, so we panic in this instance. (There was a case of this
357 when a bug in a function that calls milliwait() caused it to pass invalid data.
358 That's when I added the check. :-)
359
360 We assume it to be not worth sleeping for under 50us; this value will
361 require revisiting as hardware advances.  This avoids the issue of
362 a zero-valued timer setting meaning "never fire".
363
364 Argument:  an itimerval structure containing the interval
365 Returns:   nothing
366 */
367
368 static void
369 milliwait(struct itimerval *itval)
370 {
371 sigset_t sigmask;
372 sigset_t old_sigmask;
373 int save_errno = errno;
374
375 if (itval->it_value.tv_usec < 50 && itval->it_value.tv_sec == 0)
376   return;
377 (void)sigemptyset(&sigmask);                           /* Empty mask */
378 (void)sigaddset(&sigmask, SIGALRM);                    /* Add SIGALRM */
379 (void)sigprocmask(SIG_BLOCK, &sigmask, &old_sigmask);  /* Block SIGALRM */
380 if (setitimer(ITIMER_REAL, itval, NULL) < 0)           /* Start timer */
381   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
382     "setitimer() failed: %s", strerror(errno));
383 (void)sigfillset(&sigmask);                            /* All signals */
384 (void)sigdelset(&sigmask, SIGALRM);                    /* Remove SIGALRM */
385 (void)sigsuspend(&sigmask);                            /* Until SIGALRM */
386 (void)sigprocmask(SIG_SETMASK, &old_sigmask, NULL);    /* Restore mask */
387 errno = save_errno;
388 sigalrm_seen = FALSE;
389 }
390
391
392
393
394 /*************************************************
395 *         Millisecond sleep function             *
396 *************************************************/
397
398 /* The basic sleep() function has a granularity of 1 second, which is too rough
399 in some cases - for example, when using an increasing delay to slow down
400 spammers.
401
402 Argument:    number of millseconds
403 Returns:     nothing
404 */
405
406 void
407 millisleep(int msec)
408 {
409 struct itimerval itval = {.it_interval = {.tv_sec = 0, .tv_usec = 0},
410                           .it_value = {.tv_sec = msec/1000,
411                                        .tv_usec = (msec % 1000) * 1000}};
412 milliwait(&itval);
413 }
414
415
416
417 /*************************************************
418 *         Compare microsecond times              *
419 *************************************************/
420
421 /*
422 Arguments:
423   tv1         the first time
424   tv2         the second time
425
426 Returns:      -1, 0, or +1
427 */
428
429 static int
430 exim_tvcmp(struct timeval *t1, struct timeval *t2)
431 {
432 if (t1->tv_sec > t2->tv_sec) return +1;
433 if (t1->tv_sec < t2->tv_sec) return -1;
434 if (t1->tv_usec > t2->tv_usec) return +1;
435 if (t1->tv_usec < t2->tv_usec) return -1;
436 return 0;
437 }
438
439
440
441
442 /*************************************************
443 *          Clock tick wait function              *
444 *************************************************/
445
446 #ifdef _POSIX_MONOTONIC_CLOCK
447 # ifdef CLOCK_BOOTTIME
448 #  define EXIM_CLOCKTYPE CLOCK_BOOTTIME
449 # else
450 #  define EXIM_CLOCKTYPE CLOCK_MONOTONIC
451 # endif
452
453 /* Amount EXIM_CLOCK is behind realtime, at startup. */
454 static struct timespec offset_ts;
455
456 static void
457 exim_clock_init(void)
458 {
459 struct timeval tv;
460 if (clock_gettime(EXIM_CLOCKTYPE, &offset_ts) != 0) return;
461 (void)gettimeofday(&tv, NULL);
462 offset_ts.tv_sec = tv.tv_sec - offset_ts.tv_sec;
463 offset_ts.tv_nsec = tv.tv_usec * 1000 - offset_ts.tv_nsec;
464 if (offset_ts.tv_nsec >= 0) return;
465 offset_ts.tv_sec--;
466 offset_ts.tv_nsec += 1000*1000*1000;
467 }
468 #endif
469
470
471 void
472 exim_gettime(struct timeval * tv)
473 {
474 #ifdef _POSIX_MONOTONIC_CLOCK
475 struct timespec now_ts;
476
477 if (clock_gettime(EXIM_CLOCKTYPE, &now_ts) == 0)
478   {
479   now_ts.tv_sec += offset_ts.tv_sec;
480   if ((now_ts.tv_nsec += offset_ts.tv_nsec) >= 1000*1000*1000)
481     {
482     now_ts.tv_sec++;
483     now_ts.tv_nsec -= 1000*1000*1000;
484     }
485   tv->tv_sec = now_ts.tv_sec;
486   tv->tv_usec = now_ts.tv_nsec / 1000;
487   }
488 else
489 #endif
490   (void)gettimeofday(tv, NULL);
491 }
492
493
494 /* Exim uses a time + a pid to generate a unique identifier in two places: its
495 message IDs, and in file names for maildir deliveries. Because some OS now
496 re-use pids within the same second, sub-second times are now being used.
497 However, for absolute certainty, we must ensure the clock has ticked before
498 allowing the relevant process to complete. At the time of implementation of
499 this code (February 2003), the speed of processors is such that the clock will
500 invariably have ticked already by the time a process has done its job. This
501 function prepares for the time when things are faster - and it also copes with
502 clocks that go backwards.
503
504 Arguments:
505   prev_tv      A timeval which was used to create uniqueness; its usec field
506                  has been rounded down to the value of the resolution.
507                  We want to be sure the current time is greater than this.
508                  On return, updated to current (rounded down).
509   resolution   The resolution that was used to divide the microseconds
510                  (1 for maildir, larger for message ids)
511
512 Returns:       nothing
513 */
514
515 void
516 exim_wait_tick(struct timeval * prev_tv, int resolution)
517 {
518 struct timeval now_tv;
519 long int now_true_usec;
520
521 exim_gettime(&now_tv);
522 now_true_usec = now_tv.tv_usec;
523 now_tv.tv_usec = (now_true_usec/resolution) * resolution;
524
525 while (exim_tvcmp(&now_tv, prev_tv) <= 0)
526   {
527   struct itimerval itval;
528   itval.it_interval.tv_sec = 0;
529   itval.it_interval.tv_usec = 0;
530   itval.it_value.tv_sec = prev_tv->tv_sec - now_tv.tv_sec;
531   itval.it_value.tv_usec = prev_tv->tv_usec + resolution - now_true_usec;
532
533   /* We know that, overall, "now" is less than or equal to "then". Therefore, a
534   negative value for the microseconds is possible only in the case when "now"
535   is more than a second less than "tgt". That means that itval.it_value.tv_sec
536   is greater than zero. The following correction is therefore safe. */
537
538   if (itval.it_value.tv_usec < 0)
539     {
540     itval.it_value.tv_usec += 1000000;
541     itval.it_value.tv_sec -= 1;
542     }
543
544   DEBUG(D_transport|D_receive)
545     {
546     if (!f.running_in_test_harness)
547       {
548       debug_printf("tick check: " TIME_T_FMT ".%06lu " TIME_T_FMT ".%06lu\n",
549         prev_tv->tv_sec, (long) prev_tv->tv_usec,
550         now_tv.tv_sec, (long) now_tv.tv_usec);
551       debug_printf("waiting " TIME_T_FMT ".%06lu sec\n",
552         itval.it_value.tv_sec, (long) itval.it_value.tv_usec);
553       }
554     }
555
556   milliwait(&itval);
557
558   /* Be prapared to go around if the kernel does not implement subtick
559   granularity (GNU Hurd) */
560
561   exim_gettime(&now_tv);
562   now_true_usec = now_tv.tv_usec;
563   now_tv.tv_usec = (now_true_usec/resolution) * resolution;
564   }
565 *prev_tv = now_tv;
566 }
567
568
569
570
571 /*************************************************
572 *   Call fopen() with umask 777 and adjust mode  *
573 *************************************************/
574
575 /* Exim runs with umask(0) so that files created with open() have the mode that
576 is specified in the open() call. However, there are some files, typically in
577 the spool directory, that are created with fopen(). They end up world-writeable
578 if no precautions are taken. Although the spool directory is not accessible to
579 the world, this is an untidiness. So this is a wrapper function for fopen()
580 that sorts out the mode of the created file.
581
582 Arguments:
583    filename       the file name
584    options        the fopen() options
585    mode           the required mode
586
587 Returns:          the fopened FILE or NULL
588 */
589
590 FILE *
591 modefopen(const uschar *filename, const char *options, mode_t mode)
592 {
593 mode_t saved_umask = umask(0777);
594 FILE *f = Ufopen(filename, options);
595 (void)umask(saved_umask);
596 if (f != NULL) (void)fchmod(fileno(f), mode);
597 return f;
598 }
599
600
601 /*************************************************
602 *   Ensure stdin, stdout, and stderr exist       *
603 *************************************************/
604
605 /* Some operating systems grumble if an exec() happens without a standard
606 input, output, and error (fds 0, 1, 2) being defined. The worry is that some
607 file will be opened and will use these fd values, and then some other bit of
608 code will assume, for example, that it can write error messages to stderr.
609 This function ensures that fds 0, 1, and 2 are open if they do not already
610 exist, by connecting them to /dev/null.
611
612 This function is also used to ensure that std{in,out,err} exist at all times,
613 so that if any library that Exim calls tries to use them, it doesn't crash.
614
615 Arguments:  None
616 Returns:    Nothing
617 */
618
619 void
620 exim_nullstd(void)
621 {
622 int devnull = -1;
623 struct stat statbuf;
624 for (int i = 0; i <= 2; i++)
625   {
626   if (fstat(i, &statbuf) < 0 && errno == EBADF)
627     {
628     if (devnull < 0) devnull = open("/dev/null", O_RDWR);
629     if (devnull < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s",
630       string_open_failed("/dev/null", NULL));
631     if (devnull != i) (void)dup2(devnull, i);
632     }
633   }
634 if (devnull > 2) (void)close(devnull);
635 }
636
637
638
639
640 /*************************************************
641 *   Close unwanted file descriptors for delivery *
642 *************************************************/
643
644 /* This function is called from a new process that has been forked to deliver
645 an incoming message, either directly, or using exec.
646
647 We want any smtp input streams to be closed in this new process. However, it
648 has been observed that using fclose() here causes trouble. When reading in -bS
649 input, duplicate copies of messages have been seen. The files will be sharing a
650 file pointer with the parent process, and it seems that fclose() (at least on
651 some systems - I saw this on Solaris 2.5.1) messes with that file pointer, at
652 least sometimes. Hence we go for closing the underlying file descriptors.
653
654 If TLS is active, we want to shut down the TLS library, but without molesting
655 the parent's SSL connection.
656
657 For delivery of a non-SMTP message, we want to close stdin and stdout (and
658 stderr unless debugging) because the calling process might have set them up as
659 pipes and be waiting for them to close before it waits for the submission
660 process to terminate. If they aren't closed, they hold up the calling process
661 until the initial delivery process finishes, which is not what we want.
662
663 Exception: We do want it for synchronous delivery!
664
665 And notwithstanding all the above, if D_resolver is set, implying resolver
666 debugging, leave stdout open, because that's where the resolver writes its
667 debugging output.
668
669 When we close stderr (which implies we've also closed stdout), we also get rid
670 of any controlling terminal.
671
672 Arguments:   None
673 Returns:     Nothing
674 */
675
676 static void
677 close_unwanted(void)
678 {
679 if (smtp_input)
680   {
681 #ifndef DISABLE_TLS
682   tls_close(NULL, TLS_NO_SHUTDOWN);      /* Shut down the TLS library */
683 #endif
684   (void)close(fileno(smtp_in));
685   (void)close(fileno(smtp_out));
686   smtp_in = NULL;
687   }
688 else
689   {
690   (void)close(0);                                          /* stdin */
691   if ((debug_selector & D_resolver) == 0) (void)close(1);  /* stdout */
692   if (debug_selector == 0)                                 /* stderr */
693     {
694     if (!f.synchronous_delivery)
695       {
696       (void)close(2);
697       log_stderr = NULL;
698       }
699     (void)setsid();
700     }
701   }
702 }
703
704
705
706
707 /*************************************************
708 *          Set uid and gid                       *
709 *************************************************/
710
711 /* This function sets a new uid and gid permanently, optionally calling
712 initgroups() to set auxiliary groups. There are some special cases when running
713 Exim in unprivileged modes. In these situations the effective uid will not be
714 root; if we already have the right effective uid/gid, and don't need to
715 initialize any groups, leave things as they are.
716
717 Arguments:
718   uid        the uid
719   gid        the gid
720   igflag     TRUE if initgroups() wanted
721   msg        text to use in debugging output and failure log
722
723 Returns:     nothing; bombs out on failure
724 */
725
726 void
727 exim_setugid(uid_t uid, gid_t gid, BOOL igflag, uschar *msg)
728 {
729 uid_t euid = geteuid();
730 gid_t egid = getegid();
731
732 if (euid == root_uid || euid != uid || egid != gid || igflag)
733   {
734   /* At least one OS returns +1 for initgroups failure, so just check for
735   non-zero. */
736
737   if (igflag)
738     {
739     struct passwd *pw = getpwuid(uid);
740     if (!pw)
741       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "cannot run initgroups(): "
742         "no passwd entry for uid=%ld", (long int)uid);
743
744     if (initgroups(pw->pw_name, gid) != 0)
745       log_write(0,LOG_MAIN|LOG_PANIC_DIE,"initgroups failed for uid=%ld: %s",
746         (long int)uid, strerror(errno));
747     }
748
749   if (setgid(gid) < 0 || setuid(uid) < 0)
750     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "unable to set gid=%ld or uid=%ld "
751       "(euid=%ld): %s", (long int)gid, (long int)uid, (long int)euid, msg);
752   }
753
754 /* Debugging output included uid/gid and all groups */
755
756 DEBUG(D_uid)
757   {
758   int group_count, save_errno;
759   gid_t group_list[EXIM_GROUPLIST_SIZE];
760   debug_printf("changed uid/gid: %s\n  uid=%ld gid=%ld pid=%ld\n", msg,
761     (long int)geteuid(), (long int)getegid(), (long int)getpid());
762   group_count = getgroups(nelem(group_list), group_list);
763   save_errno = errno;
764   debug_printf("  auxiliary group list:");
765   if (group_count > 0)
766     for (int i = 0; i < group_count; i++) debug_printf(" %d", (int)group_list[i]);
767   else if (group_count < 0)
768     debug_printf(" <error: %s>", strerror(save_errno));
769   else debug_printf(" <none>");
770   debug_printf("\n");
771   }
772 }
773
774
775
776
777 /*************************************************
778 *               Exit point                       *
779 *************************************************/
780
781 /* Exim exits via this function so that it always clears up any open
782 databases.
783
784 Arguments:
785   rc         return code
786
787 Returns:     does not return
788 */
789
790 void
791 exim_exit(int rc)
792 {
793 search_tidyup();
794 store_exit();
795 DEBUG(D_any)
796   debug_printf(">>>>>>>>>>>>>>>> Exim pid=%d (%s) terminating with rc=%d "
797     ">>>>>>>>>>>>>>>>\n",
798     (int)getpid(), process_purpose, rc);
799 exit(rc);
800 }
801
802
803 void
804 exim_underbar_exit(int rc)
805 {
806 store_exit();
807 DEBUG(D_any)
808   debug_printf(">>>>>>>>>>>>>>>> Exim pid=%d (%s) terminating with rc=%d "
809     ">>>>>>>>>>>>>>>>\n",
810     (int)getpid(), process_purpose, rc);
811 _exit(rc);
812 }
813
814
815
816 /* Print error string, then die */
817 static void
818 exim_fail(const char * fmt, ...)
819 {
820 va_list ap;
821 va_start(ap, fmt);
822 vfprintf(stderr, fmt, ap);
823 exit(EXIT_FAILURE);
824 }
825
826 /* fail if a length is too long */
827 static inline void
828 exim_len_fail_toolong(int itemlen, int maxlen, const char *description)
829 {
830 if (itemlen <= maxlen)
831   return;
832 fprintf(stderr, "exim: length limit exceeded (%d > %d) for: %s\n",
833         itemlen, maxlen, description);
834 exit(EXIT_FAILURE);
835 }
836
837 /* only pass through the string item back to the caller if it's short enough */
838 static inline const uschar *
839 exim_str_fail_toolong(const uschar *item, int maxlen, const char *description)
840 {
841 exim_len_fail_toolong(Ustrlen(item), maxlen, description);
842 return item;
843 }
844
845 /* exim_chown_failure() called from exim_chown()/exim_fchown() on failure
846 of chown()/fchown().  See src/functions.h for more explanation */
847 int
848 exim_chown_failure(int fd, const uschar *name, uid_t owner, gid_t group)
849 {
850 int saved_errno = errno;  /* from the preceeding chown call */
851 #if 1
852 log_write(0, LOG_MAIN|LOG_PANIC,
853   __FILE__ ":%d: chown(%s, %d:%d) failed (%s)."
854   " Please contact the authors and refer to https://bugs.exim.org/show_bug.cgi?id=2391",
855   __LINE__, name?name:US"<unknown>", owner, group, strerror(errno));
856 #else
857 /* I leave this here, commented, in case the "bug"(?) comes up again.
858    It is not an Exim bug, but we can provide a workaround.
859    See Bug 2391
860    HS 2019-04-18 */
861
862 struct stat buf;
863
864 if (0 == (fd < 0 ? stat(name, &buf) : fstat(fd, &buf)))
865 {
866   if (buf.st_uid == owner && buf.st_gid == group) return 0;
867   log_write(0, LOG_MAIN|LOG_PANIC, "Wrong ownership on %s", name);
868 }
869 else log_write(0, LOG_MAIN|LOG_PANIC, "Stat failed on %s: %s", name, strerror(errno));
870
871 #endif
872 errno = saved_errno;
873 return -1;
874 }
875
876
877 /*************************************************
878 *         Extract port from host address         *
879 *************************************************/
880
881 /* Called to extract the port from the values given to -oMa and -oMi.
882 It also checks the syntax of the address, and terminates it before the
883 port data when a port is extracted.
884
885 Argument:
886   address   the address, with possible port on the end
887
888 Returns:    the port, or zero if there isn't one
889             bombs out on a syntax error
890 */
891
892 static int
893 check_port(uschar *address)
894 {
895 int port = host_address_extract_port(address);
896 if (string_is_ip_address(address, NULL) == 0)
897   exim_fail("exim abandoned: \"%s\" is not an IP address\n", address);
898 return port;
899 }
900
901
902
903 /*************************************************
904 *              Test/verify an address            *
905 *************************************************/
906
907 /* This function is called by the -bv and -bt code. It extracts a working
908 address from a full RFC 822 address. This isn't really necessary per se, but it
909 has the effect of collapsing source routes.
910
911 Arguments:
912   s            the address string
913   flags        flag bits for verify_address()
914   exit_value   to be set for failures
915
916 Returns:       nothing
917 */
918
919 static void
920 test_address(uschar *s, int flags, int *exit_value)
921 {
922 int start, end, domain;
923 uschar *parse_error = NULL;
924 uschar *address = parse_extract_address(s, &parse_error, &start, &end, &domain,
925   FALSE);
926 if (!address)
927   {
928   fprintf(stdout, "syntax error: %s\n", parse_error);
929   *exit_value = 2;
930   }
931 else
932   {
933   int rc = verify_address(deliver_make_addr(address,TRUE), stdout, flags, -1,
934     -1, -1, NULL, NULL, NULL);
935   if (rc == FAIL) *exit_value = 2;
936     else if (rc == DEFER && *exit_value == 0) *exit_value = 1;
937   }
938 }
939
940
941
942 /*************************************************
943 *          Show supported features               *
944 *************************************************/
945
946 static void
947 show_db_version(FILE * f)
948 {
949 #ifdef DB_VERSION_STRING
950 DEBUG(D_any)
951   {
952   fprintf(f, "Library version: BDB: Compile: %s\n", DB_VERSION_STRING);
953   fprintf(f, "                      Runtime: %s\n",
954     db_version(NULL, NULL, NULL));
955   }
956 else
957   fprintf(f, "Berkeley DB: %s\n", DB_VERSION_STRING);
958
959 #elif defined(BTREEVERSION) && defined(HASHVERSION)
960   #ifdef USE_DB
961   fprintf(f, "Probably Berkeley DB version 1.8x (native mode)\n");
962   #else
963   fprintf(f, "Probably Berkeley DB version 1.8x (compatibility mode)\n");
964   #endif
965
966 #elif defined(_DBM_RDONLY) || defined(dbm_dirfno)
967 fprintf(f, "Probably ndbm\n");
968 #elif defined(USE_TDB)
969 fprintf(f, "Using tdb\n");
970 #else
971   #ifdef USE_GDBM
972   fprintf(f, "Probably GDBM (native mode)\n");
973   #else
974   fprintf(f, "Probably GDBM (compatibility mode)\n");
975   #endif
976 #endif
977 }
978
979
980 /* This function is called for -bV/--version and for -d to output the optional
981 features of the current Exim binary.
982
983 Arguments:  a FILE for printing
984 Returns:    nothing
985 */
986
987 static void
988 show_whats_supported(FILE * fp)
989 {
990 rmark reset_point = store_mark();
991 gstring * g;
992 DEBUG(D_any) {} else show_db_version(fp);
993
994 g = string_cat(NULL, US"Support for:");
995 #ifdef SUPPORT_CRYPTEQ
996   g = string_cat(g, US" crypteq");
997 #endif
998 #if HAVE_ICONV
999   g = string_cat(g, US" iconv()");
1000 #endif
1001 #if HAVE_IPV6
1002   g = string_cat(g, US" IPv6");
1003 #endif
1004 #ifdef HAVE_SETCLASSRESOURCES
1005   g = string_cat(g, US" use_setclassresources");
1006 #endif
1007 #ifdef SUPPORT_PAM
1008   g = string_cat(g, US" PAM");
1009 #endif
1010 #ifdef EXIM_PERL
1011   g = string_cat(g, US" Perl");
1012 #endif
1013 #ifdef EXPAND_DLFUNC
1014   g = string_cat(g, US" Expand_dlfunc");
1015 #endif
1016 #ifdef USE_TCP_WRAPPERS
1017   g = string_cat(g, US" TCPwrappers");
1018 #endif
1019 #ifdef USE_GNUTLS
1020   g = string_cat(g, US" GnuTLS");
1021 #endif
1022 #ifdef USE_OPENSSL
1023   g = string_cat(g, US" OpenSSL");
1024 #endif
1025 #ifndef DISABLE_TLS_RESUME
1026   g = string_cat(g, US" TLS_resume");
1027 #endif
1028 #ifdef SUPPORT_TRANSLATE_IP_ADDRESS
1029   g = string_cat(g, US" translate_ip_address");
1030 #endif
1031 #ifdef SUPPORT_MOVE_FROZEN_MESSAGES
1032   g = string_cat(g, US" move_frozen_messages");
1033 #endif
1034 #ifdef WITH_CONTENT_SCAN
1035   g = string_cat(g, US" Content_Scanning");
1036 #endif
1037 #ifdef SUPPORT_DANE
1038   g = string_cat(g, US" DANE");
1039 #endif
1040 #ifndef DISABLE_DKIM
1041   g = string_cat(g, US" DKIM");
1042 #endif
1043 #ifdef SUPPORT_DMARC
1044   g = string_cat(g, US" DMARC");
1045 #endif
1046 #ifndef DISABLE_DNSSEC
1047   g = string_cat(g, US" DNSSEC");
1048 #endif
1049 #ifndef DISABLE_EVENT
1050   g = string_cat(g, US" Event");
1051 #endif
1052 #ifdef SUPPORT_I18N
1053   g = string_cat(g, US" I18N");
1054 #endif
1055 #ifndef DISABLE_OCSP
1056   g = string_cat(g, US" OCSP");
1057 #endif
1058 #ifndef DISABLE_PIPE_CONNECT
1059   g = string_cat(g, US" PIPECONNECT");
1060 #endif
1061 #ifndef DISABLE_PRDR
1062   g = string_cat(g, US" PRDR");
1063 #endif
1064 #ifdef SUPPORT_PROXY
1065   g = string_cat(g, US" PROXY");
1066 #endif
1067 #ifndef DISABLE_QUEUE_RAMP
1068   g = string_cat(g, US" Queue_Ramp");
1069 #endif
1070 #ifdef SUPPORT_SOCKS
1071   g = string_cat(g, US" SOCKS");
1072 #endif
1073 #ifdef SUPPORT_SPF
1074   g = string_cat(g, US" SPF");
1075 #endif
1076 #if defined(SUPPORT_SRS)
1077   g = string_cat(g, US" SRS");
1078 #endif
1079 #ifdef TCP_FASTOPEN
1080   tcp_init();
1081   if (f.tcp_fastopen_ok) g = string_cat(g, US" TCP_Fast_Open");
1082 #endif
1083 #ifdef EXPERIMENTAL_ARC
1084   g = string_cat(g, US" Experimental_ARC");
1085 #endif
1086 #ifdef EXPERIMENTAL_BRIGHTMAIL
1087   g = string_cat(g, US" Experimental_Brightmail");
1088 #endif
1089 #ifdef EXPERIMENTAL_DCC
1090   g = string_cat(g, US" Experimental_DCC");
1091 #endif
1092 #ifdef EXPERIMENTAL_DSN_INFO
1093   g = string_cat(g, US" Experimental_DSN_info");
1094 #endif
1095 #ifdef EXPERIMENTAL_ESMTP_LIMITS
1096   g = string_cat(g, US" Experimental_ESMTP_Limits");
1097 #endif
1098 #ifdef EXPERIMENTAL_QUEUEFILE
1099   g = string_cat(g, US" Experimental_QUEUEFILE");
1100 #endif
1101 #if defined(EXPERIMENTAL_SRS_ALT)
1102   g = string_cat(g, US" Experimental_SRS");
1103 #endif
1104 g = string_cat(g, US"\n");
1105
1106 g = string_cat(g, US"Lookups (built-in):");
1107 #if defined(LOOKUP_LSEARCH) && LOOKUP_LSEARCH!=2
1108   g = string_cat(g, US" lsearch wildlsearch nwildlsearch iplsearch");
1109 #endif
1110 #if defined(LOOKUP_CDB) && LOOKUP_CDB!=2
1111   g = string_cat(g, US" cdb");
1112 #endif
1113 #if defined(LOOKUP_DBM) && LOOKUP_DBM!=2
1114   g = string_cat(g, US" dbm dbmjz dbmnz");
1115 #endif
1116 #if defined(LOOKUP_DNSDB) && LOOKUP_DNSDB!=2
1117   g = string_cat(g, US" dnsdb");
1118 #endif
1119 #if defined(LOOKUP_DSEARCH) && LOOKUP_DSEARCH!=2
1120   g = string_cat(g, US" dsearch");
1121 #endif
1122 #if defined(LOOKUP_IBASE) && LOOKUP_IBASE!=2
1123   g = string_cat(g, US" ibase");
1124 #endif
1125 #if defined(LOOKUP_JSON) && LOOKUP_JSON!=2
1126   g = string_cat(g, US" json");
1127 #endif
1128 #if defined(LOOKUP_LDAP) && LOOKUP_LDAP!=2
1129   g = string_cat(g, US" ldap ldapdn ldapm");
1130 #endif
1131 #ifdef LOOKUP_LMDB
1132   g = string_cat(g, US" lmdb");
1133 #endif
1134 #if defined(LOOKUP_MYSQL) && LOOKUP_MYSQL!=2
1135   g = string_cat(g, US" mysql");
1136 #endif
1137 #if defined(LOOKUP_NIS) && LOOKUP_NIS!=2
1138   g = string_cat(g, US" nis nis0");
1139 #endif
1140 #if defined(LOOKUP_NISPLUS) && LOOKUP_NISPLUS!=2
1141   g = string_cat(g, US" nisplus");
1142 #endif
1143 #if defined(LOOKUP_ORACLE) && LOOKUP_ORACLE!=2
1144   g = string_cat(g, US" oracle");
1145 #endif
1146 #if defined(LOOKUP_PASSWD) && LOOKUP_PASSWD!=2
1147   g = string_cat(g, US" passwd");
1148 #endif
1149 #if defined(LOOKUP_PGSQL) && LOOKUP_PGSQL!=2
1150   g = string_cat(g, US" pgsql");
1151 #endif
1152 #if defined(LOOKUP_REDIS) && LOOKUP_REDIS!=2
1153   g = string_cat(g, US" redis");
1154 #endif
1155 #if defined(LOOKUP_SQLITE) && LOOKUP_SQLITE!=2
1156   g = string_cat(g, US" sqlite");
1157 #endif
1158 #if defined(LOOKUP_TESTDB) && LOOKUP_TESTDB!=2
1159   g = string_cat(g, US" testdb");
1160 #endif
1161 #if defined(LOOKUP_WHOSON) && LOOKUP_WHOSON!=2
1162   g = string_cat(g, US" whoson");
1163 #endif
1164 g = string_cat(g, US"\n");
1165
1166 g = auth_show_supported(g);
1167 g = route_show_supported(g);
1168 g = transport_show_supported(g);
1169
1170 #ifdef WITH_CONTENT_SCAN
1171 g = malware_show_supported(g);
1172 #endif
1173
1174 if (fixed_never_users[0] > 0)
1175   {
1176   int i;
1177   g = string_cat(g, US"Fixed never_users: ");
1178   for (i = 1; i <= (int)fixed_never_users[0] - 1; i++)
1179     string_fmt_append(g, "%u:", (unsigned)fixed_never_users[i]);
1180   g = string_fmt_append(g, "%u\n", (unsigned)fixed_never_users[i]);
1181   }
1182
1183 g = string_fmt_append(g, "Configure owner: %d:%d\n", config_uid, config_gid);
1184 fputs(CS string_from_gstring(g), fp);
1185
1186 fprintf(fp, "Size of off_t: " SIZE_T_FMT "\n", sizeof(off_t));
1187
1188 /* Everything else is details which are only worth reporting when debugging.
1189 Perhaps the tls_version_report should move into this too. */
1190 DEBUG(D_any) do {
1191
1192 /* clang defines __GNUC__ (at least, for me) so test for it first */
1193 #if defined(__clang__)
1194   fprintf(fp, "Compiler: CLang [%s]\n", __clang_version__);
1195 #elif defined(__GNUC__)
1196   fprintf(fp, "Compiler: GCC [%s]\n",
1197 # ifdef __VERSION__
1198       __VERSION__
1199 # else
1200       "? unknown version ?"
1201 # endif
1202       );
1203 #else
1204   fprintf(fp, "Compiler: <unknown>\n");
1205 #endif
1206
1207 #if defined(__GLIBC__) && !defined(__UCLIBC__)
1208   fprintf(fp, "Library version: Glibc: Compile: %d.%d\n",
1209                 __GLIBC__, __GLIBC_MINOR__);
1210   if (__GLIBC_PREREQ(2, 1))
1211     fprintf(fp, "                        Runtime: %s\n",
1212                 gnu_get_libc_version());
1213 #endif
1214
1215 show_db_version(fp);
1216
1217 #ifndef DISABLE_TLS
1218   tls_version_report(fp);
1219 #endif
1220 #ifdef SUPPORT_I18N
1221   utf8_version_report(fp);
1222 #endif
1223 #ifdef SUPPORT_DMARC
1224   dmarc_version_report(fp);
1225 #endif
1226 #ifdef SUPPORT_SPF
1227   spf_lib_version_report(fp);
1228 #endif
1229
1230   for (auth_info * authi = auths_available; *authi->driver_name != '\0'; ++authi)
1231     if (authi->version_report)
1232       (*authi->version_report)(fp);
1233
1234   /* PCRE_PRERELEASE is either defined and empty or a bare sequence of
1235   characters; unless it's an ancient version of PCRE in which case it
1236   is not defined. */
1237 #ifndef PCRE_PRERELEASE
1238 # define PCRE_PRERELEASE
1239 #endif
1240 #define QUOTE(X) #X
1241 #define EXPAND_AND_QUOTE(X) QUOTE(X)
1242   {
1243   uschar buf[24];
1244   pcre2_config(PCRE2_CONFIG_VERSION, buf);
1245   fprintf(fp, "Library version: PCRE2: Compile: %d.%d%s\n"
1246               "                        Runtime: %s\n",
1247           PCRE2_MAJOR, PCRE2_MINOR,
1248           EXPAND_AND_QUOTE(PCRE2_PRERELEASE) "",
1249           buf);
1250   }
1251 #undef QUOTE
1252 #undef EXPAND_AND_QUOTE
1253
1254   init_lookup_list();
1255   for (int i = 0; i < lookup_list_count; i++)
1256     if (lookup_list[i]->version_report)
1257       lookup_list[i]->version_report(fp);
1258
1259 #ifdef WHITELIST_D_MACROS
1260   fprintf(fp, "WHITELIST_D_MACROS: \"%s\"\n", WHITELIST_D_MACROS);
1261 #else
1262   fprintf(fp, "WHITELIST_D_MACROS unset\n");
1263 #endif
1264 #ifdef TRUSTED_CONFIG_LIST
1265   fprintf(fp, "TRUSTED_CONFIG_LIST: \"%s\"\n", TRUSTED_CONFIG_LIST);
1266 #else
1267   fprintf(fp, "TRUSTED_CONFIG_LIST unset\n");
1268 #endif
1269
1270 } while (0);
1271 store_reset(reset_point);
1272 }
1273
1274
1275 /*************************************************
1276 *     Show auxiliary information about Exim      *
1277 *************************************************/
1278
1279 static void
1280 show_exim_information(enum commandline_info request, FILE *stream)
1281 {
1282 switch(request)
1283   {
1284   case CMDINFO_NONE:
1285     fprintf(stream, "Oops, something went wrong.\n");
1286     return;
1287   case CMDINFO_HELP:
1288     fprintf(stream,
1289 "The -bI: flag takes a string indicating which information to provide.\n"
1290 "If the string is not recognised, you'll get this help (on stderr).\n"
1291 "\n"
1292 "  exim -bI:help    this information\n"
1293 "  exim -bI:dscp    list of known dscp value keywords\n"
1294 "  exim -bI:sieve   list of supported sieve extensions\n"
1295 );
1296     return;
1297   case CMDINFO_SIEVE:
1298     for (const uschar ** pp = exim_sieve_extension_list; *pp; ++pp)
1299       fprintf(stream, "%s\n", *pp);
1300     return;
1301   case CMDINFO_DSCP:
1302     dscp_list_to_stream(stream);
1303     return;
1304   }
1305 }
1306
1307
1308 /*************************************************
1309 *               Quote a local part               *
1310 *************************************************/
1311
1312 /* This function is used when a sender address or a From: or Sender: header
1313 line is being created from the caller's login, or from an authenticated_id. It
1314 applies appropriate quoting rules for a local part.
1315
1316 Argument:    the local part
1317 Returns:     the local part, quoted if necessary
1318 */
1319
1320 uschar *
1321 local_part_quote(uschar *lpart)
1322 {
1323 BOOL needs_quote = FALSE;
1324 gstring * g;
1325
1326 for (uschar * t = lpart; !needs_quote && *t != 0; t++)
1327   {
1328   needs_quote = !isalnum(*t) && strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL &&
1329     (*t != '.' || t == lpart || t[1] == 0);
1330   }
1331
1332 if (!needs_quote) return lpart;
1333
1334 g = string_catn(NULL, US"\"", 1);
1335
1336 for (;;)
1337   {
1338   uschar *nq = US Ustrpbrk(lpart, "\\\"");
1339   if (nq == NULL)
1340     {
1341     g = string_cat(g, lpart);
1342     break;
1343     }
1344   g = string_catn(g, lpart, nq - lpart);
1345   g = string_catn(g, US"\\", 1);
1346   g = string_catn(g, nq, 1);
1347   lpart = nq + 1;
1348   }
1349
1350 g = string_catn(g, US"\"", 1);
1351 return string_from_gstring(g);
1352 }
1353
1354
1355
1356 #ifdef USE_READLINE
1357 /*************************************************
1358 *         Load readline() functions              *
1359 *************************************************/
1360
1361 /* This function is called from testing executions that read data from stdin,
1362 but only when running as the calling user. Currently, only -be does this. The
1363 function loads the readline() function library and passes back the functions.
1364 On some systems, it needs the curses library, so load that too, but try without
1365 it if loading fails. All this functionality has to be requested at build time.
1366
1367 Arguments:
1368   fn_readline_ptr   pointer to where to put the readline pointer
1369   fn_addhist_ptr    pointer to where to put the addhistory function
1370
1371 Returns:            the dlopen handle or NULL on failure
1372 */
1373
1374 static void *
1375 set_readline(char * (**fn_readline_ptr)(const char *),
1376              void   (**fn_addhist_ptr)(const char *))
1377 {
1378 void *dlhandle;
1379 void *dlhandle_curses = dlopen("libcurses." DYNLIB_FN_EXT, RTLD_GLOBAL|RTLD_LAZY);
1380
1381 dlhandle = dlopen("libreadline." DYNLIB_FN_EXT, RTLD_GLOBAL|RTLD_NOW);
1382 if (dlhandle_curses) dlclose(dlhandle_curses);
1383
1384 if (dlhandle)
1385   {
1386   /* Checked manual pages; at least in GNU Readline 6.1, the prototypes are:
1387    *   char * readline (const char *prompt);
1388    *   void add_history (const char *string);
1389    */
1390   *fn_readline_ptr = (char *(*)(const char*))dlsym(dlhandle, "readline");
1391   *fn_addhist_ptr = (void(*)(const char*))dlsym(dlhandle, "add_history");
1392   }
1393 else
1394   DEBUG(D_any) debug_printf("failed to load readline: %s\n", dlerror());
1395
1396 return dlhandle;
1397 }
1398 #endif
1399
1400
1401
1402 /*************************************************
1403 *    Get a line from stdin for testing things    *
1404 *************************************************/
1405
1406 /* This function is called when running tests that can take a number of lines
1407 of input (for example, -be and -bt). It handles continuations and trailing
1408 spaces. And prompting and a blank line output on eof. If readline() is in use,
1409 the arguments are non-NULL and provide the relevant functions.
1410
1411 Arguments:
1412   fn_readline   readline function or NULL
1413   fn_addhist    addhist function or NULL
1414
1415 Returns:        pointer to dynamic memory, or NULL at end of file
1416 */
1417
1418 static uschar *
1419 get_stdinput(char *(*fn_readline)(const char *), void(*fn_addhist)(const char *))
1420 {
1421 gstring * g = NULL;
1422
1423 if (!fn_readline) { printf("> "); fflush(stdout); }
1424
1425 for (int i = 0;; i++)
1426   {
1427   uschar buffer[1024];
1428   uschar *p, *ss;
1429
1430   #ifdef USE_READLINE
1431   char *readline_line = NULL;
1432   if (fn_readline)
1433     {
1434     if (!(readline_line = fn_readline((i > 0)? "":"> "))) break;
1435     if (*readline_line != 0 && fn_addhist) fn_addhist(readline_line);
1436     p = US readline_line;
1437     }
1438   else
1439   #endif
1440
1441   /* readline() not in use */
1442
1443     {
1444     if (Ufgets(buffer, sizeof(buffer), stdin) == NULL) break;
1445     p = buffer;
1446     }
1447
1448   /* Handle the line */
1449
1450   ss = p + (int)Ustrlen(p);
1451   while (ss > p && isspace(ss[-1])) ss--;
1452
1453   if (i > 0)
1454     while (p < ss && isspace(*p)) p++;   /* leading space after cont */
1455
1456   g = string_catn(g, p, ss - p);
1457
1458   #ifdef USE_READLINE
1459   if (fn_readline) free(readline_line);
1460   #endif
1461
1462   /* g can only be NULL if ss==p */
1463   if (ss == p || g->s[g->ptr-1] != '\\')
1464     break;
1465
1466   --g->ptr;
1467   (void) string_from_gstring(g);
1468   }
1469
1470 if (!g) printf("\n");
1471 return string_from_gstring(g);
1472 }
1473
1474
1475
1476 /*************************************************
1477 *    Output usage information for the program    *
1478 *************************************************/
1479
1480 /* This function is called when there are no recipients
1481    or a specific --help argument was added.
1482
1483 Arguments:
1484   progname      information on what name we were called by
1485
1486 Returns:        DOES NOT RETURN
1487 */
1488
1489 static void
1490 exim_usage(uschar *progname)
1491 {
1492
1493 /* Handle specific program invocation variants */
1494 if (Ustrcmp(progname, US"-mailq") == 0)
1495   exim_fail(
1496     "mailq - list the contents of the mail queue\n\n"
1497     "For a list of options, see the Exim documentation.\n");
1498
1499 /* Generic usage - we output this whatever happens */
1500 exim_fail(
1501   "Exim is a Mail Transfer Agent. It is normally called by Mail User Agents,\n"
1502   "not directly from a shell command line. Options and/or arguments control\n"
1503   "what it does when called. For a list of options, see the Exim documentation.\n");
1504 }
1505
1506
1507
1508 /*************************************************
1509 *    Validate that the macros given are okay     *
1510 *************************************************/
1511
1512 /* Typically, Exim will drop privileges if macros are supplied.  In some
1513 cases, we want to not do so.
1514
1515 Arguments:    opt_D_used - true if the commandline had a "-D" option
1516 Returns:      true if trusted, false otherwise
1517 */
1518
1519 static BOOL
1520 macros_trusted(BOOL opt_D_used)
1521 {
1522 #ifdef WHITELIST_D_MACROS
1523 uschar *whitelisted, *end, *p, **whites;
1524 int white_count, i, n;
1525 size_t len;
1526 BOOL prev_char_item, found;
1527 #endif
1528
1529 if (!opt_D_used)
1530   return TRUE;
1531 #ifndef WHITELIST_D_MACROS
1532 return FALSE;
1533 #else
1534
1535 /* We only trust -D overrides for some invoking users:
1536 root, the exim run-time user, the optional config owner user.
1537 I don't know why config-owner would be needed, but since they can own the
1538 config files anyway, there's no security risk to letting them override -D. */
1539 if ( ! ((real_uid == root_uid)
1540      || (real_uid == exim_uid)
1541 #ifdef CONFIGURE_OWNER
1542      || (real_uid == config_uid)
1543 #endif
1544    ))
1545   {
1546   debug_printf("macros_trusted rejecting macros for uid %d\n", (int) real_uid);
1547   return FALSE;
1548   }
1549
1550 /* Get a list of macros which are whitelisted */
1551 whitelisted = string_copy_perm(US WHITELIST_D_MACROS, FALSE);
1552 prev_char_item = FALSE;
1553 white_count = 0;
1554 for (p = whitelisted; *p != '\0'; ++p)
1555   {
1556   if (*p == ':' || isspace(*p))
1557     {
1558     *p = '\0';
1559     if (prev_char_item)
1560       ++white_count;
1561     prev_char_item = FALSE;
1562     continue;
1563     }
1564   if (!prev_char_item)
1565     prev_char_item = TRUE;
1566   }
1567 end = p;
1568 if (prev_char_item)
1569   ++white_count;
1570 if (!white_count)
1571   return FALSE;
1572 whites = store_malloc(sizeof(uschar *) * (white_count+1));
1573 for (p = whitelisted, i = 0; (p != end) && (i < white_count); ++p)
1574   {
1575   if (*p != '\0')
1576     {
1577     whites[i++] = p;
1578     if (i == white_count)
1579       break;
1580     while (*p != '\0' && p < end)
1581       ++p;
1582     }
1583   }
1584 whites[i] = NULL;
1585
1586 /* The list of commandline macros should be very short.
1587 Accept the N*M complexity. */
1588 for (macro_item * m = macros_user; m; m = m->next) if (m->command_line)
1589   {
1590   found = FALSE;
1591   for (uschar ** w = whites; *w; ++w)
1592     if (Ustrcmp(*w, m->name) == 0)
1593       {
1594       found = TRUE;
1595       break;
1596       }
1597   if (!found)
1598     return FALSE;
1599   if (!m->replacement)
1600     continue;
1601   if ((len = m->replen) == 0)
1602     continue;
1603   if (!regex_match(regex_whitelisted_macro, m->replacement, len, NULL))
1604     return FALSE;
1605   }
1606 DEBUG(D_any) debug_printf("macros_trusted overridden to true by whitelisting\n");
1607 return TRUE;
1608 #endif
1609 }
1610
1611
1612 /*************************************************
1613 *          Expansion testing                     *
1614 *************************************************/
1615
1616 /* Expand and print one item, doing macro-processing.
1617
1618 Arguments:
1619   item          line for expansion
1620 */
1621
1622 static void
1623 expansion_test_line(const uschar * line)
1624 {
1625 int len;
1626 BOOL dummy_macexp;
1627 uschar * s;
1628
1629 Ustrncpy(big_buffer, line, big_buffer_size);
1630 big_buffer[big_buffer_size-1] = '\0';
1631 len = Ustrlen(big_buffer);
1632
1633 (void) macros_expand(0, &len, &dummy_macexp);
1634
1635 if (isupper(big_buffer[0]))
1636   {
1637   if (macro_read_assignment(big_buffer))
1638     printf("Defined macro '%s'\n", mlast->name);
1639   }
1640 else
1641   if ((s = expand_string(big_buffer))) printf("%s\n", CS s);
1642   else printf("Failed: %s\n", expand_string_message);
1643 }
1644
1645
1646
1647 /*************************************************
1648 *          Entry point and high-level code       *
1649 *************************************************/
1650
1651 /* Entry point for the Exim mailer. Analyse the arguments and arrange to take
1652 the appropriate action. All the necessary functions are present in the one
1653 binary. I originally thought one should split it up, but it turns out that so
1654 much of the apparatus is needed in each chunk that one might as well just have
1655 it all available all the time, which then makes the coding easier as well.
1656
1657 Arguments:
1658   argc      count of entries in argv
1659   argv      argument strings, with argv[0] being the program name
1660
1661 Returns:    EXIT_SUCCESS if terminated successfully
1662             EXIT_FAILURE otherwise, except when a message has been sent
1663               to the sender, and -oee was given
1664 */
1665
1666 int
1667 main(int argc, char **cargv)
1668 {
1669 uschar **argv = USS cargv;
1670 int  arg_receive_timeout = -1;
1671 int  arg_smtp_receive_timeout = -1;
1672 int  arg_error_handling = error_handling;
1673 int  filter_sfd = -1;
1674 int  filter_ufd = -1;
1675 int  group_count;
1676 int  i, rv;
1677 int  list_queue_option = 0;
1678 int  msg_action = 0;
1679 int  msg_action_arg = -1;
1680 int  namelen = (argv[0] == NULL)? 0 : Ustrlen(argv[0]);
1681 int  queue_only_reason = 0;
1682 #ifdef EXIM_PERL
1683 int  perl_start_option = 0;
1684 #endif
1685 int  recipients_arg = argc;
1686 int  sender_address_domain = 0;
1687 int  test_retry_arg = -1;
1688 int  test_rewrite_arg = -1;
1689 gid_t original_egid;
1690 BOOL arg_queue_only = FALSE;
1691 BOOL bi_option = FALSE;
1692 BOOL checking = FALSE;
1693 BOOL count_queue = FALSE;
1694 BOOL expansion_test = FALSE;
1695 BOOL extract_recipients = FALSE;
1696 BOOL flag_G = FALSE;
1697 BOOL flag_n = FALSE;
1698 BOOL forced_delivery = FALSE;
1699 BOOL f_end_dot = FALSE;
1700 BOOL deliver_give_up = FALSE;
1701 BOOL list_queue = FALSE;
1702 BOOL list_options = FALSE;
1703 BOOL list_config = FALSE;
1704 BOOL local_queue_only;
1705 BOOL one_msg_action = FALSE;
1706 BOOL opt_D_used = FALSE;
1707 BOOL queue_only_set = FALSE;
1708 BOOL receiving_message = TRUE;
1709 BOOL sender_ident_set = FALSE;
1710 BOOL session_local_queue_only;
1711 BOOL unprivileged;
1712 BOOL removed_privilege = FALSE;
1713 BOOL usage_wanted = FALSE;
1714 BOOL verify_address_mode = FALSE;
1715 BOOL verify_as_sender = FALSE;
1716 BOOL rcpt_verify_quota = FALSE;
1717 BOOL version_printed = FALSE;
1718 uschar *alias_arg = NULL;
1719 uschar *called_as = US"";
1720 uschar *cmdline_syslog_name = NULL;
1721 uschar *start_queue_run_id = NULL;
1722 uschar *stop_queue_run_id = NULL;
1723 uschar *expansion_test_message = NULL;
1724 const uschar *ftest_domain = NULL;
1725 const uschar *ftest_localpart = NULL;
1726 const uschar *ftest_prefix = NULL;
1727 const uschar *ftest_suffix = NULL;
1728 uschar *log_oneline = NULL;
1729 uschar *malware_test_file = NULL;
1730 uschar *real_sender_address;
1731 uschar *originator_home = US"/";
1732 size_t sz;
1733
1734 struct passwd *pw;
1735 struct stat statbuf;
1736 pid_t passed_qr_pid = (pid_t)0;
1737 int passed_qr_pipe = -1;
1738 gid_t group_list[EXIM_GROUPLIST_SIZE];
1739
1740 /* For the -bI: flag */
1741 enum commandline_info info_flag = CMDINFO_NONE;
1742 BOOL info_stdout = FALSE;
1743
1744 /* Possible options for -R and -S */
1745
1746 static uschar *rsopts[] = { US"f", US"ff", US"r", US"rf", US"rff" };
1747
1748 /* Need to define this in case we need to change the environment in order
1749 to get rid of a bogus time zone. We have to make it char rather than uschar
1750 because some OS define it in /usr/include/unistd.h. */
1751
1752 extern char **environ;
1753
1754 #ifdef MEASURE_TIMING
1755 (void)gettimeofday(&timestamp_startup, NULL);
1756 #endif
1757
1758 store_init();   /* Initialise the memory allocation susbsystem */
1759 pcre_init();    /* Set up memory handling for pcre */
1760
1761 /* If the Exim user and/or group and/or the configuration file owner/group were
1762 defined by ref:name at build time, we must now find the actual uid/gid values.
1763 This is a feature to make the lives of binary distributors easier. */
1764
1765 #ifdef EXIM_USERNAME
1766 if (route_finduser(US EXIM_USERNAME, &pw, &exim_uid))
1767   {
1768   if (exim_uid == 0)
1769     exim_fail("exim: refusing to run with uid 0 for \"%s\"\n", EXIM_USERNAME);
1770
1771   /* If ref:name uses a number as the name, route_finduser() returns
1772   TRUE with exim_uid set and pw coerced to NULL. */
1773   if (pw)
1774     exim_gid = pw->pw_gid;
1775 #ifndef EXIM_GROUPNAME
1776   else
1777     exim_fail(
1778         "exim: ref:name should specify a usercode, not a group.\n"
1779         "exim: can't let you get away with it unless you also specify a group.\n");
1780 #endif
1781   }
1782 else
1783   exim_fail("exim: failed to find uid for user name \"%s\"\n", EXIM_USERNAME);
1784 #endif
1785
1786 #ifdef EXIM_GROUPNAME
1787 if (!route_findgroup(US EXIM_GROUPNAME, &exim_gid))
1788   exim_fail("exim: failed to find gid for group name \"%s\"\n", EXIM_GROUPNAME);
1789 #endif
1790
1791 #ifdef CONFIGURE_OWNERNAME
1792 if (!route_finduser(US CONFIGURE_OWNERNAME, NULL, &config_uid))
1793   exim_fail("exim: failed to find uid for user name \"%s\"\n",
1794     CONFIGURE_OWNERNAME);
1795 #endif
1796
1797 /* We default the system_filter_user to be the Exim run-time user, as a
1798 sane non-root value. */
1799 system_filter_uid = exim_uid;
1800
1801 #ifdef CONFIGURE_GROUPNAME
1802 if (!route_findgroup(US CONFIGURE_GROUPNAME, &config_gid))
1803   exim_fail("exim: failed to find gid for group name \"%s\"\n",
1804     CONFIGURE_GROUPNAME);
1805 #endif
1806
1807 /* In the Cygwin environment, some initialization used to need doing.
1808 It was fudged in by means of this macro; now no longer but we'll leave
1809 it in case of others. */
1810
1811 #ifdef OS_INIT
1812 OS_INIT
1813 #endif
1814
1815 /* Check a field which is patched when we are running Exim within its
1816 testing harness; do a fast initial check, and then the whole thing. */
1817
1818 f.running_in_test_harness =
1819   *running_status == '<' && Ustrcmp(running_status, "<<<testing>>>") == 0;
1820 if (f.running_in_test_harness)
1821   debug_store = TRUE;
1822
1823 /* Protect against abusive argv[0] */
1824 exim_str_fail_toolong(argv[0], PATH_MAX, "argv[0]");
1825
1826 /* The C standard says that the equivalent of setlocale(LC_ALL, "C") is obeyed
1827 at the start of a program; however, it seems that some environments do not
1828 follow this. A "strange" locale can affect the formatting of timestamps, so we
1829 make quite sure. */
1830
1831 setlocale(LC_ALL, "C");
1832
1833 /* Get the offset between CLOCK_MONOTONIC/CLOCK_BOOTTIME and wallclock */
1834
1835 #ifdef _POSIX_MONOTONIC_CLOCK
1836 exim_clock_init();
1837 #endif
1838
1839 /* Set up the default handler for timing using alarm(). */
1840
1841 os_non_restarting_signal(SIGALRM, sigalrm_handler);
1842
1843 /* Ensure we have a buffer for constructing log entries. Use malloc directly,
1844 because store_malloc writes a log entry on failure. */
1845
1846 if (!(log_buffer = US malloc(LOG_BUFFER_SIZE)))
1847   exim_fail("exim: failed to get store for log buffer\n");
1848
1849 /* Initialize the default log options. */
1850
1851 bits_set(log_selector, log_selector_size, log_default);
1852
1853 /* Set log_stderr to stderr, provided that stderr exists. This gets reset to
1854 NULL when the daemon is run and the file is closed. We have to use this
1855 indirection, because some systems don't allow writing to the variable "stderr".
1856 */
1857
1858 if (fstat(fileno(stderr), &statbuf) >= 0) log_stderr = stderr;
1859
1860 /* Ensure there is a big buffer for temporary use in several places. It is put
1861 in malloc store so that it can be freed for enlargement if necessary. */
1862
1863 big_buffer = store_malloc(big_buffer_size);
1864
1865 /* Set up the handler for the data request signal, and set the initial
1866 descriptive text. */
1867
1868 process_info = store_get(PROCESS_INFO_SIZE, TRUE);      /* tainted */
1869 set_process_info("initializing");
1870 os_restarting_signal(SIGUSR1, usr1_handler);            /* exiwhat */
1871 signal(SIGSEGV, segv_handler);                          /* log faults */
1872
1873 /* If running in a dockerized environment, the TERM signal is only
1874 delegated to the PID 1 if we request it by setting an signal handler */
1875 if (getpid() == 1) signal(SIGTERM, term_handler);
1876
1877 /* SIGHUP is used to get the daemon to reconfigure. It gets set as appropriate
1878 in the daemon code. For the rest of Exim's uses, we ignore it. */
1879
1880 signal(SIGHUP, SIG_IGN);
1881
1882 /* We don't want to die on pipe errors as the code is written to handle
1883 the write error instead. */
1884
1885 signal(SIGPIPE, SIG_IGN);
1886
1887 /* Under some circumstance on some OS, Exim can get called with SIGCHLD
1888 set to SIG_IGN. This causes subprocesses that complete before the parent
1889 process waits for them not to hang around, so when Exim calls wait(), nothing
1890 is there. The wait() code has been made robust against this, but let's ensure
1891 that SIGCHLD is set to SIG_DFL, because it's tidier to wait and get a process
1892 ending status. We use sigaction rather than plain signal() on those OS where
1893 SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a
1894 problem on AIX with this.) */
1895
1896 #ifdef SA_NOCLDWAIT
1897   {
1898   struct sigaction act;
1899   act.sa_handler = SIG_DFL;
1900   sigemptyset(&(act.sa_mask));
1901   act.sa_flags = 0;
1902   sigaction(SIGCHLD, &act, NULL);
1903   }
1904 #else
1905 signal(SIGCHLD, SIG_DFL);
1906 #endif
1907
1908 /* Save the arguments for use if we re-exec exim as a daemon after receiving
1909 SIGHUP. */
1910
1911 sighup_argv = argv;
1912
1913 /* Set up the version number. Set up the leading 'E' for the external form of
1914 message ids, set the pointer to the internal form, and initialize it to
1915 indicate no message being processed. */
1916
1917 version_init();
1918 message_id_option[0] = '-';
1919 message_id_external = message_id_option + 1;
1920 message_id_external[0] = 'E';
1921 message_id = message_id_external + 1;
1922 message_id[0] = 0;
1923
1924 /* Set the umask to zero so that any files Exim creates using open() are
1925 created with the modes that it specifies. NOTE: Files created with fopen() have
1926 a problem, which was not recognized till rather late (February 2006). With this
1927 umask, such files will be world writeable. (They are all content scanning files
1928 in the spool directory, which isn't world-accessible, so this is not a
1929 disaster, but it's untidy.) I don't want to change this overall setting,
1930 however, because it will interact badly with the open() calls. Instead, there's
1931 now a function called modefopen() that fiddles with the umask while calling
1932 fopen(). */
1933
1934 (void)umask(0);
1935
1936 /* Precompile the regular expression for matching a message id. Keep this in
1937 step with the code that generates ids in the accept.c module. We need to do
1938 this here, because the -M options check their arguments for syntactic validity
1939 using mac_ismsgid, which uses this. */
1940
1941 regex_ismsgid =
1942   regex_must_compile(US"^(?:[^\\W_]{6}-){2}[^\\W_]{2}$", FALSE, TRUE);
1943
1944 /* Precompile the regular expression that is used for matching an SMTP error
1945 code, possibly extended, at the start of an error message. Note that the
1946 terminating whitespace character is included. */
1947
1948 regex_smtp_code =
1949   regex_must_compile(US"^\\d\\d\\d\\s(?:\\d\\.\\d\\d?\\d?\\.\\d\\d?\\d?\\s)?",
1950     FALSE, TRUE);
1951
1952 #ifdef WHITELIST_D_MACROS
1953 /* Precompile the regular expression used to filter the content of macros
1954 given to -D for permissibility. */
1955
1956 regex_whitelisted_macro =
1957   regex_must_compile(US"^[A-Za-z0-9_/.-]*$", FALSE, TRUE);
1958 #endif
1959
1960 for (i = 0; i < REGEX_VARS; i++) regex_vars[i] = NULL;
1961
1962 /* If the program is called as "mailq" treat it as equivalent to "exim -bp";
1963 this seems to be a generally accepted convention, since one finds symbolic
1964 links called "mailq" in standard OS configurations. */
1965
1966 if ((namelen == 5 && Ustrcmp(argv[0], "mailq") == 0) ||
1967     (namelen  > 5 && Ustrncmp(argv[0] + namelen - 6, "/mailq", 6) == 0))
1968   {
1969   list_queue = TRUE;
1970   receiving_message = FALSE;
1971   called_as = US"-mailq";
1972   }
1973
1974 /* If the program is called as "rmail" treat it as equivalent to
1975 "exim -i -oee", thus allowing UUCP messages to be input using non-SMTP mode,
1976 i.e. preventing a single dot on a line from terminating the message, and
1977 returning with zero return code, even in cases of error (provided an error
1978 message has been sent). */
1979
1980 if ((namelen == 5 && Ustrcmp(argv[0], "rmail") == 0) ||
1981     (namelen  > 5 && Ustrncmp(argv[0] + namelen - 6, "/rmail", 6) == 0))
1982   {
1983   f.dot_ends = FALSE;
1984   called_as = US"-rmail";
1985   errors_sender_rc = EXIT_SUCCESS;
1986   }
1987
1988 /* If the program is called as "rsmtp" treat it as equivalent to "exim -bS";
1989 this is a smail convention. */
1990
1991 if ((namelen == 5 && Ustrcmp(argv[0], "rsmtp") == 0) ||
1992     (namelen  > 5 && Ustrncmp(argv[0] + namelen - 6, "/rsmtp", 6) == 0))
1993   {
1994   smtp_input = smtp_batched_input = TRUE;
1995   called_as = US"-rsmtp";
1996   }
1997
1998 /* If the program is called as "runq" treat it as equivalent to "exim -q";
1999 this is a smail convention. */
2000
2001 if ((namelen == 4 && Ustrcmp(argv[0], "runq") == 0) ||
2002     (namelen  > 4 && Ustrncmp(argv[0] + namelen - 5, "/runq", 5) == 0))
2003   {
2004   queue_interval = 0;
2005   receiving_message = FALSE;
2006   called_as = US"-runq";
2007   }
2008
2009 /* If the program is called as "newaliases" treat it as equivalent to
2010 "exim -bi"; this is a sendmail convention. */
2011
2012 if ((namelen == 10 && Ustrcmp(argv[0], "newaliases") == 0) ||
2013     (namelen  > 10 && Ustrncmp(argv[0] + namelen - 11, "/newaliases", 11) == 0))
2014   {
2015   bi_option = TRUE;
2016   receiving_message = FALSE;
2017   called_as = US"-newaliases";
2018   }
2019
2020 /* Save the original effective uid for a couple of uses later. It should
2021 normally be root, but in some esoteric environments it may not be. */
2022
2023 original_euid = geteuid();
2024 original_egid = getegid();
2025
2026 /* Get the real uid and gid. If the caller is root, force the effective uid/gid
2027 to be the same as the real ones. This makes a difference only if Exim is setuid
2028 (or setgid) to something other than root, which could be the case in some
2029 special configurations. */
2030
2031 real_uid = getuid();
2032 real_gid = getgid();
2033
2034 if (real_uid == root_uid)
2035   {
2036   if ((rv = setgid(real_gid)))
2037     exim_fail("exim: setgid(%ld) failed: %s\n",
2038         (long int)real_gid, strerror(errno));
2039   if ((rv = setuid(real_uid)))
2040     exim_fail("exim: setuid(%ld) failed: %s\n",
2041         (long int)real_uid, strerror(errno));
2042   }
2043
2044 /* If neither the original real uid nor the original euid was root, Exim is
2045 running in an unprivileged state. */
2046
2047 unprivileged = (real_uid != root_uid && original_euid != root_uid);
2048
2049 /* For most of the args-parsing we need to use permanent pool memory */
2050  {
2051  int old_pool = store_pool;
2052  store_pool = POOL_PERM;
2053
2054 /* Scan the program's arguments. Some can be dealt with right away; others are
2055 simply recorded for checking and handling afterwards. Do a high-level switch
2056 on the second character (the one after '-'), to save some effort. */
2057
2058  for (i = 1; i < argc; i++)
2059   {
2060   BOOL badarg = FALSE;
2061   uschar * arg = argv[i];
2062   uschar * argrest;
2063   int switchchar;
2064
2065   /* An argument not starting with '-' is the start of a recipients list;
2066   break out of the options-scanning loop. */
2067
2068   if (arg[0] != '-')
2069     {
2070     recipients_arg = i;
2071     break;
2072     }
2073
2074   /* An option consisting of -- terminates the options */
2075
2076   if (Ustrcmp(arg, "--") == 0)
2077     {
2078     recipients_arg = i + 1;
2079     break;
2080     }
2081
2082   /* Handle flagged options */
2083
2084   switchchar = arg[1];
2085   argrest = arg+2;
2086
2087   /* Make all -ex options synonymous with -oex arguments, since that
2088   is assumed by various callers. Also make -qR options synonymous with -R
2089   options, as that seems to be required as well. Allow for -qqR too, and
2090   the same for -S options. */
2091
2092   if (Ustrncmp(arg+1, "oe", 2) == 0 ||
2093       Ustrncmp(arg+1, "qR", 2) == 0 ||
2094       Ustrncmp(arg+1, "qS", 2) == 0)
2095     {
2096     switchchar = arg[2];
2097     argrest++;
2098     }
2099   else if (Ustrncmp(arg+1, "qqR", 3) == 0 || Ustrncmp(arg+1, "qqS", 3) == 0)
2100     {
2101     switchchar = arg[3];
2102     argrest += 2;
2103     f.queue_2stage = TRUE;
2104     }
2105
2106   /* Make -r synonymous with -f, since it is a documented alias */
2107
2108   else if (arg[1] == 'r') switchchar = 'f';
2109
2110   /* Make -ov synonymous with -v */
2111
2112   else if (Ustrcmp(arg, "-ov") == 0)
2113     {
2114     switchchar = 'v';
2115     argrest++;
2116     }
2117
2118   /* deal with --option_aliases */
2119   else if (switchchar == '-')
2120     {
2121     if (Ustrcmp(argrest, "help") == 0)
2122       {
2123       usage_wanted = TRUE;
2124       break;
2125       }
2126     else if (Ustrcmp(argrest, "version") == 0)
2127       {
2128       switchchar = 'b';
2129       argrest = US"V";
2130       }
2131     }
2132
2133   /* High-level switch on active initial letter */
2134
2135   switch(switchchar)
2136     {
2137
2138     /* sendmail uses -Ac and -Am to control which .cf file is used;
2139     we ignore them. */
2140     case 'A':
2141     if (!*argrest) { badarg = TRUE; break; }
2142     else
2143       {
2144       BOOL ignore = FALSE;
2145       switch (*argrest)
2146         {
2147         case 'c':
2148         case 'm':
2149           if (*(argrest + 1) == '\0')
2150             ignore = TRUE;
2151           break;
2152         }
2153       if (!ignore) badarg = TRUE;
2154       }
2155     break;
2156
2157     /* -Btype is a sendmail option for 7bit/8bit setting. Exim is 8-bit clean
2158     so has no need of it. */
2159
2160     case 'B':
2161     if (!*argrest) i++;       /* Skip over the type */
2162     break;
2163
2164
2165     case 'b':
2166       {
2167       receiving_message = FALSE;    /* Reset TRUE for -bm, -bS, -bs below */
2168
2169       switch (*argrest++)
2170         {
2171         /* -bd:  Run in daemon mode, awaiting SMTP connections.
2172            -bdf: Ditto, but in the foreground.
2173         */
2174         case 'd':
2175           f.daemon_listen = TRUE;
2176           if (*argrest == 'f') f.background_daemon = FALSE;
2177           else if (*argrest) badarg = TRUE;
2178           break;
2179
2180         /* -be:  Run in expansion test mode
2181            -bem: Ditto, but read a message from a file first
2182         */
2183         case 'e':
2184           expansion_test = checking = TRUE;
2185           if (*argrest == 'm')
2186             {
2187             if (++i >= argc) { badarg = TRUE; break; }
2188             expansion_test_message = argv[i];
2189             argrest++;
2190             }
2191           if (*argrest) badarg = TRUE;
2192           break;
2193
2194         /* -bF:  Run system filter test */
2195         case 'F':
2196           filter_test |= checking = FTEST_SYSTEM;
2197           if (*argrest) badarg = TRUE;
2198           else if (++i < argc) filter_test_sfile = argv[i];
2199           else exim_fail("exim: file name expected after %s\n", argv[i-1]);
2200           break;
2201
2202         /* -bf:  Run user filter test
2203            -bfd: Set domain for filter testing
2204            -bfl: Set local part for filter testing
2205            -bfp: Set prefix for filter testing
2206            -bfs: Set suffix for filter testing
2207         */
2208         case 'f':
2209           if (!*argrest)
2210             {
2211             filter_test |= checking = FTEST_USER;
2212             if (++i < argc) filter_test_ufile = argv[i];
2213             else exim_fail("exim: file name expected after %s\n", argv[i-1]);
2214             }
2215           else
2216             {
2217             if (++i >= argc)
2218               exim_fail("exim: string expected after %s\n", arg);
2219             if (Ustrcmp(argrest, "d") == 0) ftest_domain = exim_str_fail_toolong(argv[i], EXIM_DOMAINNAME_MAX, "-bfd");
2220             else if (Ustrcmp(argrest, "l") == 0) ftest_localpart = exim_str_fail_toolong(argv[i], EXIM_LOCALPART_MAX, "-bfl");
2221             else if (Ustrcmp(argrest, "p") == 0) ftest_prefix = exim_str_fail_toolong(argv[i], EXIM_LOCALPART_MAX, "-bfp");
2222             else if (Ustrcmp(argrest, "s") == 0) ftest_suffix = exim_str_fail_toolong(argv[i], EXIM_LOCALPART_MAX, "-bfs");
2223             else badarg = TRUE;
2224             }
2225           break;
2226
2227         /* -bh: Host checking - an IP address must follow. */
2228         case 'h':
2229           if (!*argrest || Ustrcmp(argrest, "c") == 0)
2230             {
2231             if (++i >= argc) { badarg = TRUE; break; }
2232             sender_host_address = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_IPADDR_MAX, "-bh"), TRUE);
2233             host_checking = checking = f.log_testing_mode = TRUE;
2234             f.host_checking_callout = *argrest == 'c';
2235             message_logs = FALSE;
2236             }
2237           else badarg = TRUE;
2238           break;
2239
2240         /* -bi: This option is used by sendmail to initialize *the* alias file,
2241         though it has the -oA option to specify a different file. Exim has no
2242         concept of *the* alias file, but since Sun's YP make script calls
2243         sendmail this way, some support must be provided. */
2244         case 'i':
2245           if (!*argrest) bi_option = TRUE;
2246           else badarg = TRUE;
2247           break;
2248
2249         /* -bI: provide information, of the type to follow after a colon.
2250         This is an Exim flag. */
2251         case 'I':
2252           if (Ustrlen(argrest) >= 1 && *argrest == ':')
2253             {
2254             uschar *p = argrest+1;
2255             info_flag = CMDINFO_HELP;
2256             if (Ustrlen(p))
2257               if (strcmpic(p, CUS"sieve") == 0)
2258                 {
2259                 info_flag = CMDINFO_SIEVE;
2260                 info_stdout = TRUE;
2261                 }
2262               else if (strcmpic(p, CUS"dscp") == 0)
2263                 {
2264                 info_flag = CMDINFO_DSCP;
2265                 info_stdout = TRUE;
2266                 }
2267               else if (strcmpic(p, CUS"help") == 0)
2268                 info_stdout = TRUE;
2269             }
2270           else badarg = TRUE;
2271           break;
2272
2273         /* -bm: Accept and deliver message - the default option. Reinstate
2274         receiving_message, which got turned off for all -b options.
2275            -bmalware: test the filename given for malware */
2276         case 'm':
2277           if (!*argrest) receiving_message = TRUE;
2278           else if (Ustrcmp(argrest, "alware") == 0)
2279             {
2280             if (++i >= argc) { badarg = TRUE; break; }
2281             checking = TRUE;
2282             malware_test_file = argv[i];
2283             }
2284           else badarg = TRUE;
2285           break;
2286
2287         /* -bnq: For locally originating messages, do not qualify unqualified
2288         addresses. In the envelope, this causes errors; in header lines they
2289         just get left. */
2290         case 'n':
2291           if (Ustrcmp(argrest, "q") == 0)
2292             {
2293             f.allow_unqualified_sender = FALSE;
2294             f.allow_unqualified_recipient = FALSE;
2295             }
2296           else badarg = TRUE;
2297           break;
2298
2299         /* -bpxx: List the contents of the mail queue, in various forms. If
2300         the option is -bpc, just a queue count is needed. Otherwise, if the
2301         first letter after p is r, then order is random. */
2302         case 'p':
2303           if (*argrest == 'c')
2304             {
2305             count_queue = TRUE;
2306             if (*++argrest) badarg = TRUE;
2307             break;
2308             }
2309
2310           if (*argrest == 'r')
2311             {
2312             list_queue_option = 8;
2313             argrest++;
2314             }
2315           else list_queue_option = 0;
2316
2317           list_queue = TRUE;
2318
2319           /* -bp: List the contents of the mail queue, top-level only */
2320
2321           if (!*argrest) {}
2322
2323           /* -bpu: List the contents of the mail queue, top-level undelivered */
2324
2325           else if (Ustrcmp(argrest, "u") == 0) list_queue_option += 1;
2326
2327           /* -bpa: List the contents of the mail queue, including all delivered */
2328
2329           else if (Ustrcmp(argrest, "a") == 0) list_queue_option += 2;
2330
2331           /* Unknown after -bp[r] */
2332
2333           else badarg = TRUE;
2334           break;
2335
2336
2337         /* -bP: List the configuration variables given as the address list.
2338         Force -v, so configuration errors get displayed. */
2339         case 'P':
2340
2341           /* -bP config: we need to setup here, because later,
2342           when list_options is checked, the config is read already */
2343           if (*argrest)
2344             badarg = TRUE;
2345           else if (argv[i+1] && Ustrcmp(argv[i+1], "config") == 0)
2346             {
2347             list_config = TRUE;
2348             readconf_save_config(version_string);
2349             }
2350           else
2351             {
2352             list_options = TRUE;
2353             debug_selector |= D_v;
2354             debug_file = stderr;
2355             }
2356           break;
2357
2358         /* -brt: Test retry configuration lookup */
2359         case 'r':
2360           if (Ustrcmp(argrest, "t") == 0)
2361             {
2362             checking = TRUE;
2363             test_retry_arg = i + 1;
2364             goto END_ARG;
2365             }
2366
2367           /* -brw: Test rewrite configuration */
2368
2369           else if (Ustrcmp(argrest, "w") == 0)
2370             {
2371             checking = TRUE;
2372             test_rewrite_arg = i + 1;
2373             goto END_ARG;
2374             }
2375           else badarg = TRUE;
2376           break;
2377
2378         /* -bS: Read SMTP commands on standard input, but produce no replies -
2379         all errors are reported by sending messages. */
2380         case 'S':
2381           if (!*argrest)
2382             smtp_input = smtp_batched_input = receiving_message = TRUE;
2383           else badarg = TRUE;
2384           break;
2385
2386         /* -bs: Read SMTP commands on standard input and produce SMTP replies
2387         on standard output. */
2388         case 's':
2389           if (!*argrest) smtp_input = receiving_message = TRUE;
2390           else badarg = TRUE;
2391           break;
2392
2393         /* -bt: address testing mode */
2394         case 't':
2395           if (!*argrest)
2396             f.address_test_mode = checking = f.log_testing_mode = TRUE;
2397           else badarg = TRUE;
2398           break;
2399
2400         /* -bv: verify addresses */
2401         case 'v':
2402           if (!*argrest)
2403             verify_address_mode = checking = f.log_testing_mode = TRUE;
2404
2405         /* -bvs: verify sender addresses */
2406
2407           else if (Ustrcmp(argrest, "s") == 0)
2408             {
2409             verify_address_mode = checking = f.log_testing_mode = TRUE;
2410             verify_as_sender = TRUE;
2411             }
2412           else badarg = TRUE;
2413           break;
2414
2415         /* -bV: Print version string and support details */
2416         case 'V':
2417           if (!*argrest)
2418             {
2419             printf("Exim version %s #%s built %s\n", version_string,
2420               version_cnumber, version_date);
2421             printf("%s\n", CS version_copyright);
2422             version_printed = TRUE;
2423             show_whats_supported(stdout);
2424             f.log_testing_mode = TRUE;
2425             }
2426           else badarg = TRUE;
2427           break;
2428
2429         /* -bw: inetd wait mode, accept a listening socket as stdin */
2430         case 'w':
2431           f.inetd_wait_mode = TRUE;
2432           f.background_daemon = FALSE;
2433           f.daemon_listen = TRUE;
2434           if (*argrest)
2435             if ((inetd_wait_timeout = readconf_readtime(argrest, 0, FALSE)) <= 0)
2436               exim_fail("exim: bad time value %s: abandoned\n", argv[i]);
2437           break;
2438
2439         default:
2440           badarg = TRUE;
2441           break;
2442         }
2443       break;
2444       }
2445
2446
2447     /* -C: change configuration file list; ignore if it isn't really
2448     a change! Enforce a prefix check if required. */
2449
2450     case 'C':
2451     if (!*argrest)
2452       if (++i < argc) argrest = argv[i]; else { badarg = TRUE; break; }
2453     if (Ustrcmp(config_main_filelist, argrest) != 0)
2454       {
2455       #ifdef ALT_CONFIG_PREFIX
2456       int sep = 0;
2457       int len = Ustrlen(ALT_CONFIG_PREFIX);
2458       const uschar *list = argrest;
2459       uschar *filename;
2460       /* The argv is untainted, so big_buffer (also untainted) is ok to use */
2461       while((filename = string_nextinlist(&list, &sep, big_buffer,
2462              big_buffer_size)))
2463         if (  (  Ustrlen(filename) < len
2464               || Ustrncmp(filename, ALT_CONFIG_PREFIX, len) != 0
2465               || Ustrstr(filename, "/../") != NULL
2466               )
2467            && (Ustrcmp(filename, "/dev/null") != 0 || real_uid != root_uid)
2468            )
2469           exim_fail("-C Permission denied\n");
2470       #endif
2471       if (real_uid != root_uid)
2472         {
2473         #ifdef TRUSTED_CONFIG_LIST
2474
2475         if (real_uid != exim_uid
2476             #ifdef CONFIGURE_OWNER
2477             && real_uid != config_uid
2478             #endif
2479             )
2480           f.trusted_config = FALSE;
2481         else
2482           {
2483           FILE *trust_list = Ufopen(TRUSTED_CONFIG_LIST, "rb");
2484           if (trust_list)
2485             {
2486             struct stat statbuf;
2487
2488             if (fstat(fileno(trust_list), &statbuf) != 0 ||
2489                 (statbuf.st_uid != root_uid        /* owner not root */
2490                  #ifdef CONFIGURE_OWNER
2491                  && statbuf.st_uid != config_uid   /* owner not the special one */
2492                  #endif
2493                    ) ||                            /* or */
2494                 (statbuf.st_gid != root_gid        /* group not root */
2495                  #ifdef CONFIGURE_GROUP
2496                  && statbuf.st_gid != config_gid   /* group not the special one */
2497                  #endif
2498                  && (statbuf.st_mode & 020) != 0   /* group writeable */
2499                    ) ||                            /* or */
2500                 (statbuf.st_mode & 2) != 0)        /* world writeable */
2501               {
2502               f.trusted_config = FALSE;
2503               fclose(trust_list);
2504               }
2505             else
2506               {
2507               /* Well, the trust list at least is up to scratch... */
2508               rmark reset_point;
2509               uschar *trusted_configs[32];
2510               int nr_configs = 0;
2511               int i = 0;
2512               int old_pool = store_pool;
2513               store_pool = POOL_MAIN;
2514
2515               reset_point = store_mark();
2516               while (Ufgets(big_buffer, big_buffer_size, trust_list))
2517                 {
2518                 uschar *start = big_buffer, *nl;
2519                 while (*start && isspace(*start))
2520                 start++;
2521                 if (*start != '/')
2522                   continue;
2523                 nl = Ustrchr(start, '\n');
2524                 if (nl)
2525                   *nl = 0;
2526                 trusted_configs[nr_configs++] = string_copy(start);
2527                 if (nr_configs == nelem(trusted_configs))
2528                   break;
2529                 }
2530               fclose(trust_list);
2531
2532               if (nr_configs)
2533                 {
2534                 int sep = 0;
2535                 const uschar *list = argrest;
2536                 uschar *filename;
2537                 while (f.trusted_config && (filename = string_nextinlist(&list,
2538                         &sep, big_buffer, big_buffer_size)))
2539                   {
2540                   for (i=0; i < nr_configs; i++)
2541                     if (Ustrcmp(filename, trusted_configs[i]) == 0)
2542                       break;
2543                   if (i == nr_configs)
2544                     {
2545                     f.trusted_config = FALSE;
2546                     break;
2547                     }
2548                   }
2549                 }
2550               else      /* No valid prefixes found in trust_list file. */
2551                 f.trusted_config = FALSE;
2552               store_reset(reset_point);
2553               store_pool = old_pool;
2554               }
2555             }
2556           else          /* Could not open trust_list file. */
2557             f.trusted_config = FALSE;
2558           }
2559       #else
2560         /* Not root; don't trust config */
2561         f.trusted_config = FALSE;
2562       #endif
2563         }
2564
2565       config_main_filelist = argrest;
2566       f.config_changed = TRUE;
2567       }
2568     break;
2569
2570
2571     /* -D: set up a macro definition */
2572
2573     case 'D':
2574 #ifdef DISABLE_D_OPTION
2575       exim_fail("exim: -D is not available in this Exim binary\n");
2576 #else
2577       {
2578       int ptr = 0;
2579       macro_item *m;
2580       uschar name[24];
2581       uschar *s = argrest;
2582
2583       opt_D_used = TRUE;
2584       while (isspace(*s)) s++;
2585
2586       if (*s < 'A' || *s > 'Z')
2587         exim_fail("exim: macro name set by -D must start with "
2588           "an upper case letter\n");
2589
2590       while (isalnum(*s) || *s == '_')
2591         {
2592         if (ptr < sizeof(name)-1) name[ptr++] = *s;
2593         s++;
2594         }
2595       name[ptr] = 0;
2596       if (ptr == 0) { badarg = TRUE; break; }
2597       while (isspace(*s)) s++;
2598       if (*s != 0)
2599         {
2600         if (*s++ != '=') { badarg = TRUE; break; }
2601         while (isspace(*s)) s++;
2602         }
2603
2604       for (m = macros_user; m; m = m->next)
2605         if (Ustrcmp(m->name, name) == 0)
2606           exim_fail("exim: duplicated -D in command line\n");
2607
2608       m = macro_create(name, s, TRUE);
2609
2610       if (clmacro_count >= MAX_CLMACROS)
2611         exim_fail("exim: too many -D options on command line\n");
2612       clmacros[clmacro_count++] =
2613         string_sprintf("-D%s=%s", m->name, m->replacement);
2614       }
2615     #endif
2616     break;
2617
2618     /* -d: Set debug level (see also -v below) or set the drop_cr option.
2619     The latter is now a no-op, retained for compatibility only. If -dd is used,
2620     debugging subprocesses of the daemon is disabled. */
2621
2622     case 'd':
2623     if (Ustrcmp(argrest, "ropcr") == 0)
2624       {
2625       /* drop_cr = TRUE; */
2626       }
2627
2628     /* Use an intermediate variable so that we don't set debugging while
2629     decoding the debugging bits. */
2630
2631     else
2632       {
2633       unsigned int selector = D_default;
2634       debug_selector = 0;
2635       debug_file = NULL;
2636       if (*argrest == 'd')
2637         {
2638         f.debug_daemon = TRUE;
2639         argrest++;
2640         }
2641       if (*argrest)
2642         decode_bits(&selector, 1, debug_notall, argrest,
2643           debug_options, debug_options_count, US"debug", 0);
2644       debug_selector = selector;
2645       }
2646     break;
2647
2648
2649     /* -E: This is a local error message. This option is not intended for
2650     external use at all, but is not restricted to trusted callers because it
2651     does no harm (just suppresses certain error messages) and if Exim is run
2652     not setuid root it won't always be trusted when it generates error
2653     messages using this option. If there is a message id following -E, point
2654     message_reference at it, for logging. */
2655
2656     case 'E':
2657     f.local_error_message = TRUE;
2658     if (mac_ismsgid(argrest)) message_reference = argrest;
2659     break;
2660
2661
2662     /* -ex: The vacation program calls sendmail with the undocumented "-eq"
2663     option, so it looks as if historically the -oex options are also callable
2664     without the leading -o. So we have to accept them. Before the switch,
2665     anything starting -oe has been converted to -e. Exim does not support all
2666     of the sendmail error options. */
2667
2668     case 'e':
2669     if (Ustrcmp(argrest, "e") == 0)
2670       {
2671       arg_error_handling = ERRORS_SENDER;
2672       errors_sender_rc = EXIT_SUCCESS;
2673       }
2674     else if (Ustrcmp(argrest, "m") == 0) arg_error_handling = ERRORS_SENDER;
2675     else if (Ustrcmp(argrest, "p") == 0) arg_error_handling = ERRORS_STDERR;
2676     else if (Ustrcmp(argrest, "q") == 0) arg_error_handling = ERRORS_STDERR;
2677     else if (Ustrcmp(argrest, "w") == 0) arg_error_handling = ERRORS_SENDER;
2678     else badarg = TRUE;
2679     break;
2680
2681
2682     /* -F: Set sender's full name, used instead of the gecos entry from
2683     the password file. Since users can usually alter their gecos entries,
2684     there's no security involved in using this instead. The data can follow
2685     the -F or be in the next argument. */
2686
2687     case 'F':
2688     if (!*argrest)
2689       if (++i < argc) argrest = argv[i]; else { badarg = TRUE; break; }
2690     originator_name = string_copy_taint(exim_str_fail_toolong(argrest, EXIM_HUMANNAME_MAX, "-F"), TRUE);
2691     f.sender_name_forced = TRUE;
2692     break;
2693
2694
2695     /* -f: Set sender's address - this value is only actually used if Exim is
2696     run by a trusted user, or if untrusted_set_sender is set and matches the
2697     address, except that the null address can always be set by any user. The
2698     test for this happens later, when the value given here is ignored when not
2699     permitted. For an untrusted user, the actual sender is still put in Sender:
2700     if it doesn't match the From: header (unless no_local_from_check is set).
2701     The data can follow the -f or be in the next argument. The -r switch is an
2702     obsolete form of -f but since there appear to be programs out there that
2703     use anything that sendmail has ever supported, better accept it - the
2704     synonymizing is done before the switch above.
2705
2706     At this stage, we must allow domain literal addresses, because we don't
2707     know what the setting of allow_domain_literals is yet. Ditto for trailing
2708     dots and strip_trailing_dot. */
2709
2710     case 'f':
2711       {
2712       int dummy_start, dummy_end;
2713       uschar *errmess;
2714       if (!*argrest)
2715         if (i+1 < argc) argrest = argv[++i]; else { badarg = TRUE; break; }
2716       (void) exim_str_fail_toolong(argrest, EXIM_DISPLAYMAIL_MAX, "-f");
2717       if (!*argrest)
2718         *(sender_address = store_get(1, FALSE)) = '\0';  /* Ensure writeable memory */
2719       else
2720         {
2721         uschar * temp = argrest + Ustrlen(argrest) - 1;
2722         while (temp >= argrest && isspace(*temp)) temp--;
2723         if (temp >= argrest && *temp == '.') f_end_dot = TRUE;
2724         allow_domain_literals = TRUE;
2725         strip_trailing_dot = TRUE;
2726 #ifdef SUPPORT_I18N
2727         allow_utf8_domains = TRUE;
2728 #endif
2729         if (!(sender_address = parse_extract_address(argrest, &errmess,
2730                   &dummy_start, &dummy_end, &sender_address_domain, TRUE)))
2731           exim_fail("exim: bad -f address \"%s\": %s\n", argrest, errmess);
2732
2733         sender_address = string_copy_taint(sender_address, TRUE);
2734 #ifdef SUPPORT_I18N
2735         message_smtputf8 =  string_is_utf8(sender_address);
2736         allow_utf8_domains = FALSE;
2737 #endif
2738         allow_domain_literals = FALSE;
2739         strip_trailing_dot = FALSE;
2740         }
2741       f.sender_address_forced = TRUE;
2742       }
2743     break;
2744
2745     /* -G: sendmail invocation to specify that it's a gateway submission and
2746     sendmail may complain about problems instead of fixing them.
2747     We make it equivalent to an ACL "control = suppress_local_fixups" and do
2748     not at this time complain about problems. */
2749
2750     case 'G':
2751     flag_G = TRUE;
2752     break;
2753
2754     /* -h: Set the hop count for an incoming message. Exim does not currently
2755     support this; it always computes it by counting the Received: headers.
2756     To put it in will require a change to the spool header file format. */
2757
2758     case 'h':
2759     if (!*argrest)
2760       if (++i < argc) argrest = argv[i]; else { badarg = TRUE; break; }
2761     if (!isdigit(*argrest)) badarg = TRUE;
2762     break;
2763
2764
2765     /* -i: Set flag so dot doesn't end non-SMTP input (same as -oi, seems
2766     not to be documented for sendmail but mailx (at least) uses it) */
2767
2768     case 'i':
2769     if (!*argrest) f.dot_ends = FALSE; else badarg = TRUE;
2770     break;
2771
2772
2773     /* -L: set the identifier used for syslog; equivalent to setting
2774     syslog_processname in the config file, but needs to be an admin option. */
2775
2776     case 'L':
2777     if (!*argrest)
2778       if (++i < argc) argrest = argv[i]; else { badarg = TRUE; break; }
2779     if ((sz = Ustrlen(argrest)) > 32)
2780       exim_fail("exim: the -L syslog name is too long: \"%s\"\n", argrest);
2781     if (sz < 1)
2782       exim_fail("exim: the -L syslog name is too short\n");
2783     cmdline_syslog_name = string_copy_taint(argrest, TRUE);
2784     break;
2785
2786     case 'M':
2787     receiving_message = FALSE;
2788
2789     /* -MC:  continue delivery of another message via an existing open
2790     file descriptor. This option is used for an internal call by the
2791     smtp transport when there is a pending message waiting to go to an
2792     address to which it has got a connection. Five subsequent arguments are
2793     required: transport name, host name, IP address, sequence number, and
2794     message_id. Transports may decline to create new processes if the sequence
2795     number gets too big. The channel is stdin. This (-MC) must be the last
2796     argument. There's a subsequent check that the real-uid is privileged.
2797
2798     If we are running in the test harness. delay for a bit, to let the process
2799     that set this one up complete. This makes for repeatability of the logging,
2800     etc. output. */
2801
2802     if (Ustrcmp(argrest, "C") == 0)
2803       {
2804       union sockaddr_46 interface_sock;
2805       EXIM_SOCKLEN_T size = sizeof(interface_sock);
2806
2807       if (argc != i + 6)
2808         exim_fail("exim: too many or too few arguments after -MC\n");
2809
2810       if (msg_action_arg >= 0)
2811         exim_fail("exim: incompatible arguments\n");
2812
2813       continue_transport = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_DRIVERNAME_MAX, "-C internal transport"), TRUE);
2814       continue_hostname = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_HOSTNAME_MAX, "-C internal hostname"), TRUE);
2815       continue_host_address = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_IPADDR_MAX, "-C internal hostaddr"), TRUE);
2816       continue_sequence = Uatoi(argv[++i]);
2817       msg_action = MSG_DELIVER;
2818       msg_action_arg = ++i;
2819       forced_delivery = TRUE;
2820       queue_run_pid = passed_qr_pid;
2821       queue_run_pipe = passed_qr_pipe;
2822
2823       if (!mac_ismsgid(argv[i]))
2824         exim_fail("exim: malformed message id %s after -MC option\n",
2825           argv[i]);
2826
2827       /* Set up $sending_ip_address and $sending_port, unless proxied */
2828
2829       if (!continue_proxy_cipher)
2830         if (getsockname(fileno(stdin), (struct sockaddr *)(&interface_sock),
2831             &size) == 0)
2832           sending_ip_address = host_ntoa(-1, &interface_sock, NULL,
2833             &sending_port);
2834         else
2835           exim_fail("exim: getsockname() failed after -MC option: %s\n",
2836             strerror(errno));
2837
2838       testharness_pause_ms(500);
2839       break;
2840       }
2841
2842     else if (*argrest == 'C' && argrest[1] && !argrest[2])
2843       {
2844       switch(argrest[1])
2845         {
2846     /* -MCA: set the smtp_authenticated flag; this is useful only when it
2847     precedes -MC (see above). The flag indicates that the host to which
2848     Exim is connected has accepted an AUTH sequence. */
2849
2850         case 'A': f.smtp_authenticated = TRUE; break;
2851
2852     /* -MCD: set the smtp_use_dsn flag; this indicates that the host
2853        that exim is connected to supports the esmtp extension DSN */
2854
2855         case 'D': smtp_peer_options |= OPTION_DSN; break;
2856
2857     /* -MCd: for debug, set a process-purpose string */
2858
2859         case 'd': if (++i < argc)
2860                     process_purpose = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_DRIVERNAME_MAX, "-MCd"), TRUE);
2861                   else badarg = TRUE;
2862                   break;
2863
2864     /* -MCG: set the queue name, to a non-default value. Arguably, anything
2865        from the commandline should be tainted - but we will need an untainted
2866        value for the spoolfile when doing a -odi delivery process. */
2867
2868         case 'G': if (++i < argc) queue_name = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_DRIVERNAME_MAX, "-MCG"), FALSE);
2869                   else badarg = TRUE;
2870                   break;
2871
2872     /* -MCK: the peer offered CHUNKING.  Must precede -MC */
2873
2874         case 'K': smtp_peer_options |= OPTION_CHUNKING; break;
2875
2876 #ifdef EXPERIMENTAL_ESMTP_LIMITS
2877     /* -MCL: peer used LIMITS RCPTMAX and/or RCPTDOMAINMAX */
2878         case 'L': if (++i < argc) continue_limit_mail = Uatoi(argv[i]);
2879                   else badarg = TRUE;
2880                   if (++i < argc) continue_limit_rcpt = Uatoi(argv[i]);
2881                   else badarg = TRUE;
2882                   if (++i < argc) continue_limit_rcptdom = Uatoi(argv[i]);
2883                   else badarg = TRUE;
2884                   break;
2885 #endif
2886
2887     /* -MCP: set the smtp_use_pipelining flag; this is useful only when
2888     it preceded -MC (see above) */
2889
2890         case 'P': smtp_peer_options |= OPTION_PIPE; break;
2891
2892 #ifdef SUPPORT_SOCKS
2893     /* -MCp: Socks proxy in use; nearside IP, port, external IP, port */
2894         case 'p': proxy_session = TRUE;
2895                   if (++i < argc)
2896                     {
2897                     proxy_local_address = string_copy_taint(argv[i], TRUE);
2898                     if (++i < argc)
2899                       {
2900                       proxy_local_port = Uatoi(argv[i]);
2901                       if (++i < argc)
2902                         {
2903                         proxy_external_address = string_copy_taint(argv[i], TRUE);
2904                         if (++i < argc)
2905                           {
2906                           proxy_external_port = Uatoi(argv[i]);
2907                           break;
2908                     } } } }
2909                   badarg = TRUE;
2910                   break;
2911 #endif
2912     /* -MCQ: pass on the pid of the queue-running process that started
2913     this chain of deliveries and the fd of its synchronizing pipe; this
2914     is useful only when it precedes -MC (see above) */
2915
2916         case 'Q': if (++i < argc) passed_qr_pid = (pid_t)(Uatol(argv[i]));
2917                   else badarg = TRUE;
2918                   if (++i < argc) passed_qr_pipe = (int)(Uatol(argv[i]));
2919                   else badarg = TRUE;
2920                   break;
2921
2922     /* -MCq: do a quota check on the given recipient for the given size
2923     of message.  Separate from -MC. */
2924         case 'q': rcpt_verify_quota = TRUE;
2925                   if (++i < argc) message_size = Uatoi(argv[i]);
2926                   else badarg = TRUE;
2927                   break;
2928
2929     /* -MCS: set the smtp_use_size flag; this is useful only when it
2930     precedes -MC (see above) */
2931
2932         case 'S': smtp_peer_options |= OPTION_SIZE; break;
2933
2934 #ifndef DISABLE_TLS
2935     /* -MCs: used with -MCt; SNI was sent */
2936     /* -MCr: ditto, DANE */
2937
2938         case 'r':
2939         case 's': if (++i < argc)
2940                     {
2941                     continue_proxy_sni = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_HOSTNAME_MAX, "-MCr/-MCs"), TRUE);
2942                     if (argrest[1] == 'r') continue_proxy_dane = TRUE;
2943                     }
2944                   else badarg = TRUE;
2945                   break;
2946
2947     /* -MCt: similar to -MCT below but the connection is still open
2948     via a proxy process which handles the TLS context and coding.
2949     Require three arguments for the proxied local address and port,
2950     and the TLS cipher. */
2951
2952         case 't': if (++i < argc)
2953                     sending_ip_address = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_IPADDR_MAX, "-MCt IP"), TRUE);
2954                   else badarg = TRUE;
2955                   if (++i < argc)
2956                     sending_port = (int)(Uatol(argv[i]));
2957                   else badarg = TRUE;
2958                   if (++i < argc)
2959                     continue_proxy_cipher = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_CIPHERNAME_MAX, "-MCt cipher"), TRUE);
2960                   else badarg = TRUE;
2961                   /*FALLTHROUGH*/
2962
2963     /* -MCT: set the tls_offered flag; this is useful only when it
2964     precedes -MC (see above). The flag indicates that the host to which
2965     Exim is connected has offered TLS support. */
2966
2967         case 'T': smtp_peer_options |= OPTION_TLS; break;
2968 #endif
2969
2970         default:  badarg = TRUE; break;
2971         }
2972       break;
2973       }
2974
2975     /* -M[x]: various operations on the following list of message ids:
2976        -M    deliver the messages, ignoring next retry times and thawing
2977        -Mc   deliver the messages, checking next retry times, no thawing
2978        -Mf   freeze the messages
2979        -Mg   give up on the messages
2980        -Mt   thaw the messages
2981        -Mrm  remove the messages
2982     In the above cases, this must be the last option. There are also the
2983     following options which are followed by a single message id, and which
2984     act on that message. Some of them use the "recipient" addresses as well.
2985        -Mar  add recipient(s)
2986        -MG   move to a different queue
2987        -Mmad mark all recipients delivered
2988        -Mmd  mark recipients(s) delivered
2989        -Mes  edit sender
2990        -Mset load a message for use with -be
2991        -Mvb  show body
2992        -Mvc  show copy (of whole message, in RFC 2822 format)
2993        -Mvh  show header
2994        -Mvl  show log
2995     */
2996
2997     else if (!*argrest)
2998       {
2999       msg_action = MSG_DELIVER;
3000       forced_delivery = f.deliver_force_thaw = TRUE;
3001       }
3002     else if (Ustrcmp(argrest, "ar") == 0)
3003       {
3004       msg_action = MSG_ADD_RECIPIENT;
3005       one_msg_action = TRUE;
3006       }
3007     else if (Ustrcmp(argrest, "c") == 0)  msg_action = MSG_DELIVER;
3008     else if (Ustrcmp(argrest, "es") == 0)
3009       {
3010       msg_action = MSG_EDIT_SENDER;
3011       one_msg_action = TRUE;
3012       }
3013     else if (Ustrcmp(argrest, "f") == 0)  msg_action = MSG_FREEZE;
3014     else if (Ustrcmp(argrest, "g") == 0)
3015       {
3016       msg_action = MSG_DELIVER;
3017       deliver_give_up = TRUE;
3018       }
3019    else if (Ustrcmp(argrest, "G") == 0)
3020       {
3021       msg_action = MSG_SETQUEUE;
3022       queue_name_dest = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_DRIVERNAME_MAX, "-MG"), TRUE);
3023       }
3024     else if (Ustrcmp(argrest, "mad") == 0)
3025       {
3026       msg_action = MSG_MARK_ALL_DELIVERED;
3027       }
3028     else if (Ustrcmp(argrest, "md") == 0)
3029       {
3030       msg_action = MSG_MARK_DELIVERED;
3031       one_msg_action = TRUE;
3032       }
3033     else if (Ustrcmp(argrest, "rm") == 0) msg_action = MSG_REMOVE;
3034     else if (Ustrcmp(argrest, "set") == 0)
3035       {
3036       msg_action = MSG_LOAD;
3037       one_msg_action = TRUE;
3038       }
3039     else if (Ustrcmp(argrest, "t") == 0)  msg_action = MSG_THAW;
3040     else if (Ustrcmp(argrest, "vb") == 0)
3041       {
3042       msg_action = MSG_SHOW_BODY;
3043       one_msg_action = TRUE;
3044       }
3045     else if (Ustrcmp(argrest, "vc") == 0)
3046       {
3047       msg_action = MSG_SHOW_COPY;
3048       one_msg_action = TRUE;
3049       }
3050     else if (Ustrcmp(argrest, "vh") == 0)
3051       {
3052       msg_action = MSG_SHOW_HEADER;
3053       one_msg_action = TRUE;
3054       }
3055     else if (Ustrcmp(argrest, "vl") == 0)
3056       {
3057       msg_action = MSG_SHOW_LOG;
3058       one_msg_action = TRUE;
3059       }
3060     else { badarg = TRUE; break; }
3061
3062     /* All the -Mxx options require at least one message id. */
3063
3064     msg_action_arg = i + 1;
3065     if (msg_action_arg >= argc)
3066       exim_fail("exim: no message ids given after %s option\n", arg);
3067
3068     /* Some require only message ids to follow */
3069
3070     if (!one_msg_action)
3071       {
3072       for (int j = msg_action_arg; j < argc; j++) if (!mac_ismsgid(argv[j]))
3073         exim_fail("exim: malformed message id %s after %s option\n",
3074           argv[j], arg);
3075       goto END_ARG;   /* Remaining args are ids */
3076       }
3077
3078     /* Others require only one message id, possibly followed by addresses,
3079     which will be handled as normal arguments. */
3080
3081     else
3082       {
3083       if (!mac_ismsgid(argv[msg_action_arg]))
3084         exim_fail("exim: malformed message id %s after %s option\n",
3085           argv[msg_action_arg], arg);
3086       i++;
3087       }
3088     break;
3089
3090
3091     /* Some programs seem to call the -om option without the leading o;
3092     for sendmail it askes for "me too". Exim always does this. */
3093
3094     case 'm':
3095     if (*argrest) badarg = TRUE;
3096     break;
3097
3098
3099     /* -N: don't do delivery - a debugging option that stops transports doing
3100     their thing. It implies debugging at the D_v level. */
3101
3102     case 'N':
3103     if (!*argrest)
3104       {
3105       f.dont_deliver = TRUE;
3106       debug_selector |= D_v;
3107       debug_file = stderr;
3108       }
3109     else badarg = TRUE;
3110     break;
3111
3112
3113     /* -n: This means "don't alias" in sendmail, apparently.
3114     For normal invocations, it has no effect.
3115     It may affect some other options. */
3116
3117     case 'n':
3118     flag_n = TRUE;
3119     break;
3120
3121     /* -O: Just ignore it. In sendmail, apparently -O option=value means set
3122     option to the specified value. This form uses long names. We need to handle
3123     -O option=value and -Ooption=value. */
3124
3125     case 'O':
3126     if (!*argrest)
3127       if (++i >= argc)
3128         exim_fail("exim: string expected after -O\n");
3129     break;
3130
3131     case 'o':
3132     switch (*argrest++)
3133       {
3134       /* -oA: Set an argument for the bi command (sendmail's "alternate alias
3135       file" option). */
3136       case 'A':
3137         if (!*(alias_arg = argrest))
3138           if (i+1 < argc) alias_arg = argv[++i];
3139           else exim_fail("exim: string expected after -oA\n");
3140         break;
3141
3142       /* -oB: Set a connection message max value for remote deliveries */
3143       case 'B':
3144         {
3145         uschar * p = argrest;
3146         if (!*p)
3147           if (i+1 < argc && isdigit((argv[i+1][0])))
3148             p = argv[++i];
3149           else
3150             {
3151             connection_max_messages = 1;
3152             p = NULL;
3153             }
3154
3155         if (p)
3156           {
3157           if (!isdigit(*p))
3158             exim_fail("exim: number expected after -oB\n");
3159           connection_max_messages = Uatoi(p);
3160           }
3161         }
3162         break;
3163
3164       /* -odb: background delivery */
3165
3166       case 'd':
3167         if (Ustrcmp(argrest, "b") == 0)
3168           {
3169           f.synchronous_delivery = FALSE;
3170           arg_queue_only = FALSE;
3171           queue_only_set = TRUE;
3172           }
3173
3174       /* -odd: testsuite-only: add no inter-process delays */
3175
3176         else if (Ustrcmp(argrest, "d") == 0)
3177           f.testsuite_delays = FALSE;
3178
3179       /* -odf: foreground delivery (smail-compatible option); same effect as
3180          -odi: interactive (synchronous) delivery (sendmail-compatible option)
3181       */
3182
3183         else if (Ustrcmp(argrest, "f") == 0 || Ustrcmp(argrest, "i") == 0)
3184           {
3185           f.synchronous_delivery = TRUE;
3186           arg_queue_only = FALSE;
3187           queue_only_set = TRUE;
3188           }
3189
3190       /* -odq: queue only */
3191
3192         else if (Ustrcmp(argrest, "q") == 0)
3193           {
3194           f.synchronous_delivery = FALSE;
3195           arg_queue_only = TRUE;
3196           queue_only_set = TRUE;
3197           }
3198
3199       /* -odqs: queue SMTP only - do local deliveries and remote routing,
3200       but no remote delivery */
3201
3202         else if (Ustrcmp(argrest, "qs") == 0)
3203           {
3204           f.queue_smtp = TRUE;
3205           arg_queue_only = FALSE;
3206           queue_only_set = TRUE;
3207           }
3208         else badarg = TRUE;
3209         break;
3210
3211       /* -oex: Sendmail error flags. As these are also accepted without the
3212       leading -o prefix, for compatibility with vacation and other callers,
3213       they are handled with -e above. */
3214
3215       /* -oi:     Set flag so dot doesn't end non-SMTP input (same as -i)
3216          -oitrue: Another sendmail syntax for the same */
3217
3218       case 'i':
3219         if (!*argrest || Ustrcmp(argrest, "true") == 0)
3220           f.dot_ends = FALSE;
3221         else badarg = TRUE;
3222         break;
3223
3224     /* -oM*: Set various characteristics for an incoming message; actually
3225     acted on for trusted callers only. */
3226
3227       case 'M':
3228         {
3229         if (i+1 >= argc)
3230           exim_fail("exim: data expected after -oM%s\n", argrest);
3231
3232         /* -oMa: Set sender host address */
3233
3234         if (Ustrcmp(argrest, "a") == 0)
3235           sender_host_address = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_IPADDR_MAX, "-oMa"), TRUE);
3236
3237         /* -oMaa: Set authenticator name */
3238
3239         else if (Ustrcmp(argrest, "aa") == 0)
3240           sender_host_authenticated = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_DRIVERNAME_MAX, "-oMaa"), TRUE);
3241
3242         /* -oMas: setting authenticated sender */
3243
3244         else if (Ustrcmp(argrest, "as") == 0)
3245           authenticated_sender = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_EMAILADDR_MAX, "-oMas"), TRUE);
3246
3247         /* -oMai: setting authenticated id */
3248
3249         else if (Ustrcmp(argrest, "ai") == 0)
3250           authenticated_id = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_EMAILADDR_MAX, "-oMas"), TRUE);
3251
3252         /* -oMi: Set incoming interface address */
3253
3254         else if (Ustrcmp(argrest, "i") == 0)
3255           interface_address = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_IPADDR_MAX, "-oMi"), TRUE);
3256
3257         /* -oMm: Message reference */
3258
3259         else if (Ustrcmp(argrest, "m") == 0)
3260           {
3261           if (!mac_ismsgid(argv[i+1]))
3262               exim_fail("-oMm must be a valid message ID\n");
3263           if (!f.trusted_config)
3264               exim_fail("-oMm must be called by a trusted user/config\n");
3265             message_reference = argv[++i];
3266           }
3267
3268         /* -oMr: Received protocol */
3269
3270         else if (Ustrcmp(argrest, "r") == 0)
3271
3272           if (received_protocol)
3273             exim_fail("received_protocol is set already\n");
3274           else
3275             received_protocol = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_DRIVERNAME_MAX, "-oMr"), TRUE);
3276
3277         /* -oMs: Set sender host name */
3278
3279         else if (Ustrcmp(argrest, "s") == 0)
3280           sender_host_name = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_HOSTNAME_MAX, "-oMs"), TRUE);
3281
3282         /* -oMt: Set sender ident */
3283
3284         else if (Ustrcmp(argrest, "t") == 0)
3285           {
3286           sender_ident_set = TRUE;
3287           sender_ident = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_IDENTUSER_MAX, "-oMt"), TRUE);
3288           }
3289
3290         /* Else a bad argument */
3291
3292         else
3293           badarg = TRUE;
3294         }
3295         break;
3296
3297       /* -om: Me-too flag for aliases. Exim always does this. Some programs
3298       seem to call this as -m (undocumented), so that is also accepted (see
3299       above). */
3300       /* -oo: An ancient flag for old-style addresses which still seems to
3301       crop up in some calls (see in SCO). */
3302
3303       case 'm':
3304       case 'o':
3305         if (*argrest) badarg = TRUE;
3306         break;
3307
3308       /* -oP <name>: set pid file path for daemon
3309          -oPX:       delete pid file of daemon */
3310
3311       case 'P':
3312         if (!f.running_in_test_harness && real_uid != root_uid && real_uid != exim_uid)
3313           exim_fail("exim: only uid=%d or uid=%d can use -oP and -oPX "
3314                     "(uid=%d euid=%d | %d)\n",
3315                     root_uid, exim_uid, getuid(), geteuid(), real_uid);
3316         if (!*argrest) override_pid_file_path = argv[++i];
3317         else if (Ustrcmp(argrest, "X") == 0) delete_pid_file();
3318         else badarg = TRUE;
3319         break;
3320
3321
3322       /* -or <n>: set timeout for non-SMTP acceptance
3323          -os <n>: set timeout for SMTP acceptance */
3324
3325       case 'r':
3326       case 's':
3327         {
3328         int * tp = argrest[-1] == 'r'
3329           ? &arg_receive_timeout : &arg_smtp_receive_timeout;
3330         if (*argrest)
3331           *tp = readconf_readtime(argrest, 0, FALSE);
3332         else if (i+1 < argc)
3333           *tp = readconf_readtime(argv[++i], 0, FALSE);
3334
3335         if (*tp < 0)
3336           exim_fail("exim: bad time value %s: abandoned\n", argv[i]);
3337         }
3338         break;
3339
3340       /* -oX <list>: Override local_interfaces and/or default daemon ports */
3341       /* Limits: Is there a real limit we want here?  1024 is very arbitrary. */
3342
3343       case 'X':
3344         if (*argrest) badarg = TRUE;
3345         else override_local_interfaces = string_copy_taint(exim_str_fail_toolong(argv[++i], 1024, "-oX"), TRUE);
3346         break;
3347
3348       /* -oY: Override creation of daemon notifier socket */
3349
3350       case 'Y':
3351         if (*argrest) badarg = TRUE;
3352         else notifier_socket = NULL;
3353         break;
3354
3355       /* Unknown -o argument */
3356
3357       default:
3358         badarg = TRUE;
3359       }
3360     break;
3361
3362
3363     /* -ps: force Perl startup; -pd force delayed Perl startup */
3364
3365     case 'p':
3366     #ifdef EXIM_PERL
3367     if (*argrest == 's' && argrest[1] == 0)
3368       {
3369       perl_start_option = 1;
3370       break;
3371       }
3372     if (*argrest == 'd' && argrest[1] == 0)
3373       {
3374       perl_start_option = -1;
3375       break;
3376       }
3377     #endif
3378
3379     /* -panythingelse is taken as the Sendmail-compatible argument -prval:sval,
3380     which sets the host protocol and host name */
3381
3382     if (!*argrest)
3383       if (i+1 < argc) argrest = argv[++i]; else { badarg = TRUE; break; }
3384
3385     if (*argrest)
3386       {
3387       uschar * hn = Ustrchr(argrest, ':');
3388
3389       if (received_protocol)
3390         exim_fail("received_protocol is set already\n");
3391
3392       if (!hn)
3393         received_protocol = string_copy_taint(exim_str_fail_toolong(argrest, EXIM_DRIVERNAME_MAX, "-p<protocol>"), TRUE);
3394       else
3395         {
3396         (void) exim_str_fail_toolong(argrest, (EXIM_DRIVERNAME_MAX+1+EXIM_HOSTNAME_MAX), "-p<protocol>:<host>");
3397         received_protocol = string_copyn_taint(argrest, hn - argrest, TRUE);
3398         sender_host_name = string_copy_taint(hn + 1, TRUE);
3399         }
3400       }
3401     break;
3402
3403
3404     case 'q':
3405     receiving_message = FALSE;
3406     if (queue_interval >= 0)
3407       exim_fail("exim: -q specified more than once\n");
3408
3409     /* -qq...: Do queue runs in a 2-stage manner */
3410
3411     if (*argrest == 'q')
3412       {
3413       f.queue_2stage = TRUE;
3414       argrest++;
3415       }
3416
3417     /* -qi...: Do only first (initial) deliveries */
3418
3419     if (*argrest == 'i')
3420       {
3421       f.queue_run_first_delivery = TRUE;
3422       argrest++;
3423       }
3424
3425     /* -qf...: Run the queue, forcing deliveries
3426        -qff..: Ditto, forcing thawing as well */
3427
3428     if (*argrest == 'f')
3429       {
3430       f.queue_run_force = TRUE;
3431       if (*++argrest == 'f')
3432         {
3433         f.deliver_force_thaw = TRUE;
3434         argrest++;
3435         }
3436       }
3437
3438     /* -q[f][f]l...: Run the queue only on local deliveries */
3439
3440     if (*argrest == 'l')
3441       {
3442       f.queue_run_local = TRUE;
3443       argrest++;
3444       }
3445
3446     /* -q[f][f][l][G<name>]... Work on the named queue */
3447
3448     if (*argrest == 'G')
3449       {
3450       int i;
3451       for (argrest++, i = 0; argrest[i] && argrest[i] != '/'; ) i++;
3452       exim_len_fail_toolong(i, EXIM_DRIVERNAME_MAX, "-q*G<name>");
3453       queue_name = string_copyn(argrest, i);
3454       argrest += i;
3455       if (*argrest == '/') argrest++;
3456       }
3457
3458     /* -q[f][f][l][G<name>]: Run the queue, optionally forced, optionally local
3459     only, optionally named, optionally starting from a given message id. */
3460
3461     if (!(list_queue || count_queue))
3462       if (  !*argrest
3463          && (i + 1 >= argc || argv[i+1][0] == '-' || mac_ismsgid(argv[i+1])))
3464         {
3465         queue_interval = 0;
3466         if (i+1 < argc && mac_ismsgid(argv[i+1]))
3467           start_queue_run_id = string_copy_taint(argv[++i], TRUE);
3468         if (i+1 < argc && mac_ismsgid(argv[i+1]))
3469           stop_queue_run_id = string_copy_taint(argv[++i], TRUE);
3470         }
3471
3472     /* -q[f][f][l][G<name>/]<n>: Run the queue at regular intervals, optionally
3473     forced, optionally local only, optionally named. */
3474
3475       else if ((queue_interval = readconf_readtime(*argrest ? argrest : argv[++i],
3476                                                   0, FALSE)) <= 0)
3477         exim_fail("exim: bad time value %s: abandoned\n", argv[i]);
3478     break;
3479
3480
3481     case 'R':   /* Synonymous with -qR... */
3482       {
3483       const uschar *tainted_selectstr;
3484
3485       receiving_message = FALSE;
3486
3487     /* -Rf:   As -R (below) but force all deliveries,
3488        -Rff:  Ditto, but also thaw all frozen messages,
3489        -Rr:   String is regex
3490        -Rrf:  Regex and force
3491        -Rrff: Regex and force and thaw
3492
3493     in all cases provided there are no further characters in this
3494     argument. */
3495
3496       if (*argrest)
3497         for (int i = 0; i < nelem(rsopts); i++)
3498           if (Ustrcmp(argrest, rsopts[i]) == 0)
3499             {
3500             if (i != 2) f.queue_run_force = TRUE;
3501             if (i >= 2) f.deliver_selectstring_regex = TRUE;
3502             if (i == 1 || i == 4) f.deliver_force_thaw = TRUE;
3503             argrest += Ustrlen(rsopts[i]);
3504             }
3505
3506     /* -R: Set string to match in addresses for forced queue run to
3507     pick out particular messages. */
3508
3509       /* Avoid attacks from people providing very long strings, and do so before
3510       we make copies. */
3511       if (*argrest)
3512         tainted_selectstr = argrest;
3513       else if (i+1 < argc)
3514         tainted_selectstr = argv[++i];
3515       else
3516         exim_fail("exim: string expected after -R\n");
3517       deliver_selectstring = string_copy_taint(exim_str_fail_toolong(tainted_selectstr, EXIM_EMAILADDR_MAX, "-R"), TRUE);
3518       }
3519     break;
3520
3521     /* -r: an obsolete synonym for -f (see above) */
3522
3523
3524     /* -S: Like -R but works on sender. */
3525
3526     case 'S':   /* Synonymous with -qS... */
3527       {
3528       const uschar *tainted_selectstr;
3529
3530       receiving_message = FALSE;
3531
3532     /* -Sf:   As -S (below) but force all deliveries,
3533        -Sff:  Ditto, but also thaw all frozen messages,
3534        -Sr:   String is regex
3535        -Srf:  Regex and force
3536        -Srff: Regex and force and thaw
3537
3538     in all cases provided there are no further characters in this
3539     argument. */
3540
3541       if (*argrest)
3542         for (int i = 0; i < nelem(rsopts); i++)
3543           if (Ustrcmp(argrest, rsopts[i]) == 0)
3544             {
3545             if (i != 2) f.queue_run_force = TRUE;
3546             if (i >= 2) f.deliver_selectstring_sender_regex = TRUE;
3547             if (i == 1 || i == 4) f.deliver_force_thaw = TRUE;
3548             argrest += Ustrlen(rsopts[i]);
3549             }
3550
3551     /* -S: Set string to match in addresses for forced queue run to
3552     pick out particular messages. */
3553
3554       if (*argrest)
3555         tainted_selectstr = argrest;
3556       else if (i+1 < argc)
3557         tainted_selectstr = argv[++i];
3558       else
3559         exim_fail("exim: string expected after -S\n");
3560       deliver_selectstring_sender = string_copy_taint(exim_str_fail_toolong(tainted_selectstr, EXIM_EMAILADDR_MAX, "-S"), TRUE);
3561       }
3562     break;
3563
3564     /* -Tqt is an option that is exclusively for use by the testing suite.
3565     It is not recognized in other circumstances. It allows for the setting up
3566     of explicit "queue times" so that various warning/retry things can be
3567     tested. Otherwise variability of clock ticks etc. cause problems. */
3568
3569     case 'T':
3570     if (f.running_in_test_harness && Ustrcmp(argrest, "qt") == 0)
3571       fudged_queue_times = string_copy_taint(argv[++i], TRUE);
3572     else badarg = TRUE;
3573     break;
3574
3575
3576     /* -t: Set flag to extract recipients from body of message. */
3577
3578     case 't':
3579     if (!*argrest) extract_recipients = TRUE;
3580
3581     /* -ti: Set flag to extract recipients from body of message, and also
3582     specify that dot does not end the message. */
3583
3584     else if (Ustrcmp(argrest, "i") == 0)
3585       {
3586       extract_recipients = TRUE;
3587       f.dot_ends = FALSE;
3588       }
3589
3590     /* -tls-on-connect: don't wait for STARTTLS (for old clients) */
3591
3592     #ifndef DISABLE_TLS
3593     else if (Ustrcmp(argrest, "ls-on-connect") == 0) tls_in.on_connect = TRUE;
3594     #endif
3595
3596     else badarg = TRUE;
3597     break;
3598
3599
3600     /* -U: This means "initial user submission" in sendmail, apparently. The
3601     doc claims that in future sendmail may refuse syntactically invalid
3602     messages instead of fixing them. For the moment, we just ignore it. */
3603
3604     case 'U':
3605     break;
3606
3607
3608     /* -v: verify things - this is a very low-level debugging */
3609
3610     case 'v':
3611     if (!*argrest)
3612       {
3613       debug_selector |= D_v;
3614       debug_file = stderr;
3615       }
3616     else badarg = TRUE;
3617     break;
3618
3619
3620     /* -x: AIX uses this to indicate some fancy 8-bit character stuff:
3621
3622       The -x flag tells the sendmail command that mail from a local
3623       mail program has National Language Support (NLS) extended characters
3624       in the body of the mail item. The sendmail command can send mail with
3625       extended NLS characters across networks that normally corrupts these
3626       8-bit characters.
3627
3628     As Exim is 8-bit clean, it just ignores this flag. */
3629
3630     case 'x':
3631     if (*argrest) badarg = TRUE;
3632     break;
3633
3634     /* -X: in sendmail: takes one parameter, logfile, and sends debugging
3635     logs to that file.  We swallow the parameter and otherwise ignore it. */
3636
3637     case 'X':
3638     if (!*argrest)
3639       if (++i >= argc)
3640         exim_fail("exim: string expected after -X\n");
3641     break;
3642
3643     /* -z: a line of text to log */
3644
3645     case 'z':
3646     if (!*argrest)
3647       if (++i < argc)
3648         log_oneline = string_copy_taint(exim_str_fail_toolong(argv[i], 2048, "-z logtext"), TRUE);
3649       else
3650         exim_fail("exim: file name expected after %s\n", argv[i-1]);
3651     break;
3652
3653     /* All other initial characters are errors */
3654
3655     default:
3656     badarg = TRUE;
3657     break;
3658     }         /* End of high-level switch statement */
3659
3660   /* Failed to recognize the option, or syntax error */
3661
3662   if (badarg)
3663     exim_fail("exim abandoned: unknown, malformed, or incomplete "
3664       "option %s\n", arg);
3665   }
3666
3667
3668 /* If -R or -S have been specified without -q, assume a single queue run. */
3669
3670  if (  (deliver_selectstring || deliver_selectstring_sender)
3671     && queue_interval < 0)
3672   queue_interval = 0;
3673
3674
3675 END_ARG:
3676  store_pool = old_pool;
3677  }
3678
3679 /* If usage_wanted is set we call the usage function - which never returns */
3680 if (usage_wanted) exim_usage(called_as);
3681
3682 /* Arguments have been processed. Check for incompatibilities. */
3683 if (  (  (smtp_input || extract_recipients || recipients_arg < argc)
3684       && (  f.daemon_listen || queue_interval >= 0 || bi_option
3685          || test_retry_arg >= 0 || test_rewrite_arg >= 0
3686          || filter_test != FTEST_NONE
3687          || msg_action_arg > 0 && !one_msg_action
3688       )  )
3689    || (  msg_action_arg > 0
3690       && (  f.daemon_listen || queue_interval > 0 || list_options
3691          || checking && msg_action != MSG_LOAD
3692          || bi_option || test_retry_arg >= 0 || test_rewrite_arg >= 0
3693       )  )
3694    || (  (f.daemon_listen || queue_interval > 0)
3695       && (  sender_address || list_options || list_queue || checking
3696          || bi_option
3697       )  )
3698    || f.daemon_listen && queue_interval == 0
3699    || f.inetd_wait_mode && queue_interval >= 0
3700    || (  list_options
3701       && (  checking || smtp_input || extract_recipients
3702          || filter_test != FTEST_NONE || bi_option
3703       )  )
3704    || (  verify_address_mode
3705       && (  f.address_test_mode || smtp_input || extract_recipients
3706          || filter_test != FTEST_NONE || bi_option
3707       )  )
3708    || (  f.address_test_mode
3709       && (  smtp_input || extract_recipients || filter_test != FTEST_NONE
3710          || bi_option
3711       )  )
3712    || (  smtp_input
3713       && (sender_address || filter_test != FTEST_NONE || extract_recipients)
3714       )
3715    || deliver_selectstring && queue_interval < 0
3716    || msg_action == MSG_LOAD && (!expansion_test || expansion_test_message)
3717    )
3718   exim_fail("exim: incompatible command-line options or arguments\n");
3719
3720 /* If debugging is set up, set the file and the file descriptor to pass on to
3721 child processes. It should, of course, be 2 for stderr. Also, force the daemon
3722 to run in the foreground. */
3723
3724 if (debug_selector != 0)
3725   {
3726   debug_file = stderr;
3727   debug_fd = fileno(debug_file);
3728   f.background_daemon = FALSE;
3729   testharness_pause_ms(100);   /* lets caller finish */
3730   if (debug_selector != D_v)    /* -v only doesn't show this */
3731     {
3732     debug_printf("Exim version %s uid=%ld gid=%ld pid=%d D=%x\n",
3733       version_string, (long int)real_uid, (long int)real_gid, (int)getpid(),
3734       debug_selector);
3735     if (!version_printed)
3736       show_whats_supported(stderr);
3737     }
3738   }
3739
3740 /* When started with root privilege, ensure that the limits on the number of
3741 open files and the number of processes (where that is accessible) are
3742 sufficiently large, or are unset, in case Exim has been called from an
3743 environment where the limits are screwed down. Not all OS have the ability to
3744 change some of these limits. */
3745
3746 if (unprivileged)
3747   {
3748   DEBUG(D_any) debug_print_ids(US"Exim has no root privilege:");
3749   }
3750 else
3751   {
3752   struct rlimit rlp;
3753
3754 #ifdef RLIMIT_NOFILE
3755   if (getrlimit(RLIMIT_NOFILE, &rlp) < 0)
3756     {
3757     log_write(0, LOG_MAIN|LOG_PANIC, "getrlimit(RLIMIT_NOFILE) failed: %s",
3758       strerror(errno));
3759     rlp.rlim_cur = rlp.rlim_max = 0;
3760     }
3761
3762   /* I originally chose 1000 as a nice big number that was unlikely to
3763   be exceeded. It turns out that some older OS have a fixed upper limit of
3764   256. */
3765
3766   if (rlp.rlim_cur < 1000)
3767     {
3768     rlp.rlim_cur = rlp.rlim_max = 1000;
3769     if (setrlimit(RLIMIT_NOFILE, &rlp) < 0)
3770       {
3771       rlp.rlim_cur = rlp.rlim_max = 256;
3772       if (setrlimit(RLIMIT_NOFILE, &rlp) < 0)
3773         log_write(0, LOG_MAIN|LOG_PANIC, "setrlimit(RLIMIT_NOFILE) failed: %s",
3774           strerror(errno));
3775       }
3776     }
3777 #endif
3778
3779 #ifdef RLIMIT_NPROC
3780   if (getrlimit(RLIMIT_NPROC, &rlp) < 0)
3781     {
3782     log_write(0, LOG_MAIN|LOG_PANIC, "getrlimit(RLIMIT_NPROC) failed: %s",
3783       strerror(errno));
3784     rlp.rlim_cur = rlp.rlim_max = 0;
3785     }
3786
3787 # ifdef RLIM_INFINITY
3788   if (rlp.rlim_cur != RLIM_INFINITY && rlp.rlim_cur < 1000)
3789     {
3790     rlp.rlim_cur = rlp.rlim_max = RLIM_INFINITY;
3791 # else
3792   if (rlp.rlim_cur < 1000)
3793     {
3794     rlp.rlim_cur = rlp.rlim_max = 1000;
3795 # endif
3796     if (setrlimit(RLIMIT_NPROC, &rlp) < 0)
3797       log_write(0, LOG_MAIN|LOG_PANIC, "setrlimit(RLIMIT_NPROC) failed: %s",
3798         strerror(errno));
3799     }
3800 #endif
3801   }
3802
3803 /* Exim is normally entered as root (but some special configurations are
3804 possible that don't do this). However, it always spins off sub-processes that
3805 set their uid and gid as required for local delivery. We don't want to pass on
3806 any extra groups that root may belong to, so we want to get rid of them all at
3807 this point.
3808
3809 We need to obey setgroups() at this stage, before possibly giving up root
3810 privilege for a changed configuration file, but later on we might need to
3811 check on the additional groups for the admin user privilege - can't do that
3812 till after reading the config, which might specify the exim gid. Therefore,
3813 save the group list here first. */
3814
3815 if ((group_count = getgroups(nelem(group_list), group_list)) < 0)
3816   exim_fail("exim: getgroups() failed: %s\n", strerror(errno));
3817
3818 /* There is a fundamental difference in some BSD systems in the matter of
3819 groups. FreeBSD and BSDI are known to be different; NetBSD and OpenBSD are
3820 known not to be different. On the "different" systems there is a single group
3821 list, and the first entry in it is the current group. On all other versions of
3822 Unix there is a supplementary group list, which is in *addition* to the current
3823 group. Consequently, to get rid of all extraneous groups on a "standard" system
3824 you pass over 0 groups to setgroups(), while on a "different" system you pass
3825 over a single group - the current group, which is always the first group in the
3826 list. Calling setgroups() with zero groups on a "different" system results in
3827 an error return. The following code should cope with both types of system.
3828
3829  Unfortunately, recent MacOS, which should be a FreeBSD, "helpfully" succeeds
3830  the "setgroups() with zero groups" - and changes the egid.
3831  Thanks to that we had to stash the original_egid above, for use below
3832  in the call to exim_setugid().
3833
3834 However, if this process isn't running as root, setgroups() can't be used
3835 since you have to be root to run it, even if throwing away groups.
3836 Except, sigh, for Hurd - where you can.
3837 Not being root here happens only in some unusual configurations. */
3838
3839 if (  !unprivileged
3840 #ifndef OS_SETGROUPS_ZERO_DROPS_ALL
3841    && setgroups(0, NULL) != 0
3842 #endif
3843    && setgroups(1, group_list) != 0)
3844   exim_fail("exim: setgroups() failed: %s\n", strerror(errno));
3845
3846 /* If the configuration file name has been altered by an argument on the
3847 command line (either a new file name or a macro definition) and the caller is
3848 not root, or if this is a filter testing run, remove any setuid privilege the
3849 program has and run as the underlying user.
3850
3851 The exim user is locked out of this, which severely restricts the use of -C
3852 for some purposes.
3853
3854 Otherwise, set the real ids to the effective values (should be root unless run
3855 from inetd, which it can either be root or the exim uid, if one is configured).
3856
3857 There is a private mechanism for bypassing some of this, in order to make it
3858 possible to test lots of configurations automatically, without having either to
3859 recompile each time, or to patch in an actual configuration file name and other
3860 values (such as the path name). If running in the test harness, pretend that
3861 configuration file changes and macro definitions haven't happened. */
3862
3863 if ((                                            /* EITHER */
3864     (!f.trusted_config ||                          /* Config changed, or */
3865      !macros_trusted(opt_D_used)) &&             /*  impermissible macros and */
3866     real_uid != root_uid &&                      /* Not root, and */
3867     !f.running_in_test_harness                     /* Not fudged */
3868     ) ||                                         /*   OR   */
3869     expansion_test                               /* expansion testing */
3870     ||                                           /*   OR   */
3871     filter_test != FTEST_NONE)                   /* Filter testing */
3872   {
3873   setgroups(group_count, group_list);
3874   exim_setugid(real_uid, real_gid, FALSE,
3875     US"-C, -D, -be or -bf forces real uid");
3876   removed_privilege = TRUE;
3877
3878   /* In the normal case when Exim is called like this, stderr is available
3879   and should be used for any logging information because attempts to write
3880   to the log will usually fail. To arrange this, we unset really_exim. However,
3881   if no stderr is available there is no point - we might as well have a go
3882   at the log (if it fails, syslog will be written).
3883
3884   Note that if the invoker is Exim, the logs remain available. Messing with
3885   this causes unlogged successful deliveries.  */
3886
3887   if (log_stderr && real_uid != exim_uid)
3888     f.really_exim = FALSE;
3889   }
3890
3891 /* Privilege is to be retained for the moment. It may be dropped later,
3892 depending on the job that this Exim process has been asked to do. For now, set
3893 the real uid to the effective so that subsequent re-execs of Exim are done by a
3894 privileged user. */
3895
3896 else
3897   exim_setugid(geteuid(), original_egid, FALSE, US"forcing real = effective");
3898
3899 /* If testing a filter, open the file(s) now, before wasting time doing other
3900 setups and reading the message. */
3901
3902 if (filter_test & FTEST_SYSTEM)
3903   if ((filter_sfd = Uopen(filter_test_sfile, O_RDONLY, 0)) < 0)
3904     exim_fail("exim: failed to open %s: %s\n", filter_test_sfile,
3905       strerror(errno));
3906
3907 if (filter_test & FTEST_USER)
3908   if ((filter_ufd = Uopen(filter_test_ufile, O_RDONLY, 0)) < 0)
3909     exim_fail("exim: failed to open %s: %s\n", filter_test_ufile,
3910       strerror(errno));
3911
3912 /* Initialise lookup_list
3913 If debugging, already called above via version reporting.
3914 In either case, we initialise the list of available lookups while running
3915 as root.  All dynamically modules are loaded from a directory which is
3916 hard-coded into the binary and is code which, if not a module, would be
3917 part of Exim already.  Ability to modify the content of the directory
3918 is equivalent to the ability to modify a setuid binary!
3919
3920 This needs to happen before we read the main configuration. */
3921 init_lookup_list();
3922
3923 /*XXX this excrescence could move to the testsuite standard config setup file */
3924 #ifdef SUPPORT_I18N
3925 if (f.running_in_test_harness) smtputf8_advertise_hosts = NULL;
3926 #endif
3927
3928 /* Read the main runtime configuration data; this gives up if there
3929 is a failure. It leaves the configuration file open so that the subsequent
3930 configuration data for delivery can be read if needed.
3931
3932 NOTE: immediately after opening the configuration file we change the working
3933 directory to "/"! Later we change to $spool_directory. We do it there, because
3934 during readconf_main() some expansion takes place already. */
3935
3936 /* Store the initial cwd before we change directories.  Can be NULL if the
3937 dir has already been unlinked. */
3938 initial_cwd = os_getcwd(NULL, 0);
3939 if (!initial_cwd && errno)
3940   exim_fail("exim: getting initial cwd failed: %s\n", strerror(errno));
3941
3942 if (initial_cwd && (strlen(CCS initial_cwd) >= BIG_BUFFER_SIZE))
3943   exim_fail("exim: initial cwd is far too long (%d)\n", Ustrlen(CCS initial_cwd));
3944
3945 /* checking:
3946     -be[m] expansion test        -
3947     -b[fF] filter test           new
3948     -bh[c] host test             -
3949     -bmalware malware_test_file  new
3950     -brt   retry test            new
3951     -brw   rewrite test          new
3952     -bt    address test          -
3953     -bv[s] address verify        -
3954    list_options:
3955     -bP <option> (except -bP config, which sets list_config)
3956
3957 If any of these options is set, we suppress warnings about configuration
3958 issues (currently about tls_advertise_hosts and keep_environment not being
3959 defined) */
3960
3961   {
3962   int old_pool = store_pool;
3963 #ifdef MEASURE_TIMING
3964   struct timeval t0, diff;
3965   (void)gettimeofday(&t0, NULL);
3966 #endif
3967
3968   store_pool = POOL_CONFIG;
3969   readconf_main(checking || list_options);
3970   store_pool = old_pool;
3971
3972 #ifdef MEASURE_TIMING
3973   report_time_since(&t0, US"readconf_main (delta)");
3974 #endif
3975   }
3976
3977 /* Now in directory "/" */
3978
3979 if (cleanup_environment() == FALSE)
3980   log_write(0, LOG_PANIC_DIE, "Can't cleanup environment");
3981
3982
3983 /* If an action on specific messages is requested, or if a daemon or queue
3984 runner is being started, we need to know if Exim was called by an admin user.
3985 This is the case if the real user is root or exim, or if the real group is
3986 exim, or if one of the supplementary groups is exim or a group listed in
3987 admin_groups. We don't fail all message actions immediately if not admin_user,
3988 since some actions can be performed by non-admin users. Instead, set admin_user
3989 for later interrogation. */
3990
3991 if (real_uid == root_uid || real_uid == exim_uid || real_gid == exim_gid)
3992   f.admin_user = TRUE;
3993 else
3994   for (int i = 0; i < group_count && !f.admin_user; i++)
3995     if (group_list[i] == exim_gid)
3996       f.admin_user = TRUE;
3997     else if (admin_groups)
3998       for (int j = 1; j <= (int)admin_groups[0] && !f.admin_user; j++)
3999         if (admin_groups[j] == group_list[i])
4000           f.admin_user = TRUE;
4001
4002 /* Another group of privileged users are the trusted users. These are root,
4003 exim, and any caller matching trusted_users or trusted_groups. Trusted callers
4004 are permitted to specify sender_addresses with -f on the command line, and
4005 other message parameters as well. */
4006
4007 if (real_uid == root_uid || real_uid == exim_uid)
4008   f.trusted_caller = TRUE;
4009 else
4010   {
4011   if (trusted_users)
4012     for (int i = 1; i <= (int)trusted_users[0] && !f.trusted_caller; i++)
4013       if (trusted_users[i] == real_uid)
4014         f.trusted_caller = TRUE;
4015
4016   if (trusted_groups)
4017     for (int i = 1; i <= (int)trusted_groups[0] && !f.trusted_caller; i++)
4018       if (trusted_groups[i] == real_gid)
4019         f.trusted_caller = TRUE;
4020       else for (int j = 0; j < group_count && !f.trusted_caller; j++)
4021         if (trusted_groups[i] == group_list[j])
4022           f.trusted_caller = TRUE;
4023   }
4024
4025 /* At this point, we know if the user is privileged and some command-line
4026 options become possibly impermissible, depending upon the configuration file. */
4027
4028 if (checking && commandline_checks_require_admin && !f.admin_user)
4029   exim_fail("exim: those command-line flags are set to require admin\n");
4030
4031 /* Handle the decoding of logging options. */
4032
4033 decode_bits(log_selector, log_selector_size, log_notall,
4034   log_selector_string, log_options, log_options_count, US"log", 0);
4035
4036 DEBUG(D_any)
4037   {
4038   debug_printf("configuration file is %s\n", config_main_filename);
4039   debug_printf("log selectors =");
4040   for (int i = 0; i < log_selector_size; i++)
4041     debug_printf(" %08x", log_selector[i]);
4042   debug_printf("\n");
4043   }
4044
4045 /* If domain literals are not allowed, check the sender address that was
4046 supplied with -f. Ditto for a stripped trailing dot. */
4047
4048 if (sender_address)
4049   {
4050   if (sender_address[sender_address_domain] == '[' && !allow_domain_literals)
4051     exim_fail("exim: bad -f address \"%s\": domain literals not "
4052       "allowed\n", sender_address);
4053   if (f_end_dot && !strip_trailing_dot)
4054     exim_fail("exim: bad -f address \"%s.\": domain is malformed "
4055       "(trailing dot not allowed)\n", sender_address);
4056   }
4057
4058 /* See if an admin user overrode our logging. */
4059
4060 if (cmdline_syslog_name)
4061   if (f.admin_user)
4062     {
4063     syslog_processname = cmdline_syslog_name;
4064     log_file_path = string_copy(CUS"syslog");
4065     }
4066   else
4067     /* not a panic, non-privileged users should not be able to spam paniclog */
4068     exim_fail(
4069         "exim: you lack sufficient privilege to specify syslog process name\n");
4070
4071 /* Paranoia check of maximum lengths of certain strings. There is a check
4072 on the length of the log file path in log.c, which will come into effect
4073 if there are any calls to write the log earlier than this. However, if we
4074 get this far but the string is very long, it is better to stop now than to
4075 carry on and (e.g.) receive a message and then have to collapse. The call to
4076 log_write() from here will cause the ultimate panic collapse if the complete
4077 file name exceeds the buffer length. */
4078
4079 if (Ustrlen(log_file_path) > 200)
4080   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
4081     "log_file_path is longer than 200 chars: aborting");
4082
4083 if (Ustrlen(pid_file_path) > 200)
4084   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
4085     "pid_file_path is longer than 200 chars: aborting");
4086
4087 if (Ustrlen(spool_directory) > 200)
4088   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
4089     "spool_directory is longer than 200 chars: aborting");
4090
4091 /* Length check on the process name given to syslog for its TAG field,
4092 which is only permitted to be 32 characters or less. See RFC 3164. */
4093
4094 if (Ustrlen(syslog_processname) > 32)
4095   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
4096     "syslog_processname is longer than 32 chars: aborting");
4097
4098 if (log_oneline)
4099   if (f.admin_user)
4100     {
4101     log_write(0, LOG_MAIN, "%s", log_oneline);
4102     return EXIT_SUCCESS;
4103     }
4104   else
4105     return EXIT_FAILURE;
4106
4107 /* In some operating systems, the environment variable TMPDIR controls where
4108 temporary files are created; Exim doesn't use these (apart from when delivering
4109 to MBX mailboxes), but called libraries such as DBM libraries may require them.
4110 If TMPDIR is found in the environment, reset it to the value defined in the
4111 EXIM_TMPDIR macro, if this macro is defined.  For backward compatibility this
4112 macro may be called TMPDIR in old "Local/Makefile"s. It's converted to
4113 EXIM_TMPDIR by the build scripts.
4114 */
4115
4116 #ifdef EXIM_TMPDIR
4117   if (environ) for (uschar ** p = USS environ; *p; p++)
4118     if (Ustrncmp(*p, "TMPDIR=", 7) == 0 && Ustrcmp(*p+7, EXIM_TMPDIR) != 0)
4119       {
4120       uschar * newp = store_malloc(Ustrlen(EXIM_TMPDIR) + 8);
4121       sprintf(CS newp, "TMPDIR=%s", EXIM_TMPDIR);
4122       *p = newp;
4123       DEBUG(D_any) debug_printf("reset TMPDIR=%s in environment\n", EXIM_TMPDIR);
4124       }
4125 #endif
4126
4127 /* Timezone handling. If timezone_string is "utc", set a flag to cause all
4128 timestamps to be in UTC (gmtime() is used instead of localtime()). Otherwise,
4129 we may need to get rid of a bogus timezone setting. This can arise when Exim is
4130 called by a user who has set the TZ variable. This then affects the timestamps
4131 in log files and in Received: headers, and any created Date: header lines. The
4132 required timezone is settable in the configuration file, so nothing can be done
4133 about this earlier - but hopefully nothing will normally be logged earlier than
4134 this. We have to make a new environment if TZ is wrong, but don't bother if
4135 timestamps_utc is set, because then all times are in UTC anyway. */
4136
4137 if (timezone_string && strcmpic(timezone_string, US"UTC") == 0)
4138   f.timestamps_utc = TRUE;
4139 else
4140   {
4141   uschar *envtz = US getenv("TZ");
4142   if (envtz
4143       ? !timezone_string || Ustrcmp(timezone_string, envtz) != 0
4144       : timezone_string != NULL
4145      )
4146     {
4147     uschar **p = USS environ;
4148     uschar **new;
4149     uschar **newp;
4150     int count = 0;
4151     if (environ) while (*p++) count++;
4152     if (!envtz) count++;
4153     newp = new = store_malloc(sizeof(uschar *) * (count + 1));
4154     if (environ) for (p = USS environ; *p; p++)
4155       if (Ustrncmp(*p, "TZ=", 3) != 0) *newp++ = *p;
4156     if (timezone_string)
4157       {
4158       *newp = store_malloc(Ustrlen(timezone_string) + 4);
4159       sprintf(CS *newp++, "TZ=%s", timezone_string);
4160       }
4161     *newp = NULL;
4162     environ = CSS new;
4163     tzset();
4164     DEBUG(D_any) debug_printf("Reset TZ to %s: time is %s\n", timezone_string,
4165       tod_stamp(tod_log));
4166     }
4167   }
4168
4169 /* Handle the case when we have removed the setuid privilege because of -C or
4170 -D. This means that the caller of Exim was not root.
4171
4172 There is a problem if we were running as the Exim user. The sysadmin may
4173 expect this case to retain privilege because "the binary was called by the
4174 Exim user", but it hasn't, because either the -D option set macros, or the
4175 -C option set a non-trusted configuration file. There are two possibilities:
4176
4177   (1) If deliver_drop_privilege is set, Exim is not going to re-exec in order
4178       to do message deliveries. Thus, the fact that it is running as a
4179       non-privileged user is plausible, and might be wanted in some special
4180       configurations. However, really_exim will have been set false when
4181       privilege was dropped, to stop Exim trying to write to its normal log
4182       files. Therefore, re-enable normal log processing, assuming the sysadmin
4183       has set up the log directory correctly.
4184
4185   (2) If deliver_drop_privilege is not set, the configuration won't work as
4186       apparently intended, and so we log a panic message. In order to retain
4187       root for -C or -D, the caller must either be root or be invoking a
4188       trusted configuration file (when deliver_drop_privilege is false). */
4189
4190 if (  removed_privilege
4191    && (!f.trusted_config || opt_D_used)
4192    && real_uid == exim_uid)
4193   if (deliver_drop_privilege)
4194     f.really_exim = TRUE; /* let logging work normally */
4195   else
4196     log_write(0, LOG_MAIN|LOG_PANIC,
4197       "exim user lost privilege for using %s option",
4198       f.trusted_config? "-D" : "-C");
4199
4200 /* Start up Perl interpreter if Perl support is configured and there is a
4201 perl_startup option, and the configuration or the command line specifies
4202 initializing starting. Note that the global variables are actually called
4203 opt_perl_xxx to avoid clashing with perl's namespace (perl_*). */
4204
4205 #ifdef EXIM_PERL
4206 if (perl_start_option != 0)
4207   opt_perl_at_start = (perl_start_option > 0);
4208 if (opt_perl_at_start && opt_perl_startup != NULL)
4209   {
4210   uschar *errstr;
4211   DEBUG(D_any) debug_printf("Starting Perl interpreter\n");
4212   if ((errstr = init_perl(opt_perl_startup)))
4213     exim_fail("exim: error in perl_startup code: %s\n", errstr);
4214   opt_perl_started = TRUE;
4215   }
4216 #endif /* EXIM_PERL */
4217
4218 /* Log the arguments of the call if the configuration file said so. This is
4219 a debugging feature for finding out what arguments certain MUAs actually use.
4220 Don't attempt it if logging is disabled, or if listing variables or if
4221 verifying/testing addresses or expansions. */
4222
4223 if (  (debug_selector & D_any  ||  LOGGING(arguments))
4224    && f.really_exim && !list_options && !checking)
4225   {
4226   uschar *p = big_buffer;
4227   Ustrcpy(p, US"cwd= (failed)");
4228
4229   if (!initial_cwd)
4230     p += 13;
4231   else
4232     {
4233     p += 4;
4234     snprintf(CS p, big_buffer_size - (p - big_buffer), "%s", CCS initial_cwd);
4235     p += Ustrlen(CCS p);
4236     }
4237
4238   (void)string_format(p, big_buffer_size - (p - big_buffer), " %d args:", argc);
4239   while (*p) p++;
4240   for (int i = 0; i < argc; i++)
4241     {
4242     int len = Ustrlen(argv[i]);
4243     const uschar *printing;
4244     uschar *quote;
4245     if (p + len + 8 >= big_buffer + big_buffer_size)
4246       {
4247       Ustrcpy(p, US" ...");
4248       log_write(0, LOG_MAIN, "%s", big_buffer);
4249       Ustrcpy(big_buffer, US"...");
4250       p = big_buffer + 3;
4251       }
4252     printing = string_printing(argv[i]);
4253     if (!*printing) quote = US"\"";
4254     else
4255       {
4256       const uschar *pp = printing;
4257       quote = US"";
4258       while (*pp) if (isspace(*pp++)) { quote = US"\""; break; }
4259       }
4260     p += sprintf(CS p, " %s%.*s%s", quote, (int)(big_buffer_size -
4261       (p - big_buffer) - 4), printing, quote);
4262     }
4263
4264   if (LOGGING(arguments))
4265     log_write(0, LOG_MAIN, "%s", big_buffer);
4266   else
4267     debug_printf("%s\n", big_buffer);
4268   }
4269
4270 /* Set the working directory to be the top-level spool directory. We don't rely
4271 on this in the code, which always uses fully qualified names, but it's useful
4272 for core dumps etc. Don't complain if it fails - the spool directory might not
4273 be generally accessible and calls with the -C option (and others) have lost
4274 privilege by now. Before the chdir, we try to ensure that the directory exists.
4275 */
4276
4277 if (Uchdir(spool_directory) != 0)
4278   {
4279   (void) directory_make(spool_directory, US"", SPOOL_DIRECTORY_MODE, FALSE);
4280   (void) Uchdir(spool_directory);
4281   }
4282
4283 /* Handle calls with the -bi option. This is a sendmail option to rebuild *the*
4284 alias file. Exim doesn't have such a concept, but this call is screwed into
4285 Sun's YP makefiles. Handle this by calling a configured script, as the real
4286 user who called Exim. The -oA option can be used to pass an argument to the
4287 script. */
4288
4289 if (bi_option)
4290   {
4291   (void) fclose(config_file);
4292   if (bi_command && *bi_command)
4293     {
4294     int i = 0;
4295     uschar *argv[3];
4296     argv[i++] = bi_command;
4297     if (alias_arg) argv[i++] = alias_arg;
4298     argv[i++] = NULL;
4299
4300     setgroups(group_count, group_list);
4301     exim_setugid(real_uid, real_gid, FALSE, US"running bi_command");
4302
4303     DEBUG(D_exec) debug_printf("exec '%.256s' %s%.256s%s\n", argv[0],
4304       argv[1] ? "'" : "", argv[1] ? argv[1] : US"", argv[1] ? "'" : "");
4305
4306     execv(CS argv[0], (char *const *)argv);
4307     exim_fail("exim: exec '%s' failed: %s\n", argv[0], strerror(errno));
4308     }
4309   else
4310     {
4311     DEBUG(D_any) debug_printf("-bi used but bi_command not set; exiting\n");
4312     exit(EXIT_SUCCESS);
4313     }
4314   }
4315
4316 /* We moved the admin/trusted check to be immediately after reading the
4317 configuration file.  We leave these prints here to ensure that syslog setup,
4318 logfile setup, and so on has already happened. */
4319
4320 if (f.trusted_caller) DEBUG(D_any) debug_printf("trusted user\n");
4321 if (f.admin_user) DEBUG(D_any) debug_printf("admin user\n");
4322
4323 /* Only an admin user may start the daemon or force a queue run in the default
4324 configuration, but the queue run restriction can be relaxed. Only an admin
4325 user may request that a message be returned to its sender forthwith. Only an
4326 admin user may specify a debug level greater than D_v (because it might show
4327 passwords, etc. in lookup queries). Only an admin user may request a queue
4328 count. Only an admin user can use the test interface to scan for email
4329 (because Exim will be in the spool dir and able to look at mails). */
4330
4331 if (!f.admin_user)
4332   {
4333   BOOL debugset = (debug_selector & ~D_v) != 0;
4334   if (  deliver_give_up || f.daemon_listen || malware_test_file
4335      || count_queue && queue_list_requires_admin
4336      || list_queue && queue_list_requires_admin
4337      || queue_interval >= 0 && prod_requires_admin
4338      || queue_name_dest && prod_requires_admin
4339      || debugset && !f.running_in_test_harness
4340      )
4341     exim_fail("exim:%s permission denied\n", debugset ? " debugging" : "");
4342   }
4343
4344 /* If the real user is not root or the exim uid, the argument for passing
4345 in an open TCP/IP connection for another message is not permitted, nor is
4346 running with the -N option for any delivery action, unless this call to exim is
4347 one that supplied an input message, or we are using a patched exim for
4348 regression testing. */
4349
4350 if (  real_uid != root_uid && real_uid != exim_uid
4351    && (  continue_hostname
4352       || (  f.dont_deliver
4353          && (queue_interval >= 0 || f.daemon_listen || msg_action_arg > 0)
4354       )  )
4355    && !f.running_in_test_harness
4356    )
4357   exim_fail("exim: Permission denied\n");
4358
4359 /* If the caller is not trusted, certain arguments are ignored when running for
4360 real, but are permitted when checking things (-be, -bv, -bt, -bh, -bf, -bF).
4361 Note that authority for performing certain actions on messages is tested in the
4362 queue_action() function. */
4363
4364 if (!f.trusted_caller && !checking)
4365   {
4366   sender_host_name = sender_host_address = interface_address =
4367     sender_ident = received_protocol = NULL;
4368   sender_host_port = interface_port = 0;
4369   sender_host_authenticated = authenticated_sender = authenticated_id = NULL;
4370   }
4371
4372 /* If a sender host address is set, extract the optional port number off the
4373 end of it and check its syntax. Do the same thing for the interface address.
4374 Exim exits if the syntax is bad. */
4375
4376 else
4377   {
4378   if (sender_host_address)
4379     sender_host_port = check_port(sender_host_address);
4380   if (interface_address)
4381     interface_port = check_port(interface_address);
4382   }
4383
4384 /* If the caller is trusted, then they can use -G to suppress_local_fixups. */
4385 if (flag_G)
4386   {
4387   if (f.trusted_caller)
4388     {
4389     f.suppress_local_fixups = f.suppress_local_fixups_default = TRUE;
4390     DEBUG(D_acl) debug_printf("suppress_local_fixups forced on by -G\n");
4391     }
4392   else
4393     exim_fail("exim: permission denied (-G requires a trusted user)\n");
4394   }
4395
4396 /* If an SMTP message is being received check to see if the standard input is a
4397 TCP/IP socket. If it is, we assume that Exim was called from inetd if the
4398 caller is root or the Exim user, or if the port is a privileged one. Otherwise,
4399 barf. */
4400
4401 if (smtp_input)
4402   {
4403   union sockaddr_46 inetd_sock;
4404   EXIM_SOCKLEN_T size = sizeof(inetd_sock);
4405   if (getpeername(0, (struct sockaddr *)(&inetd_sock), &size) == 0)
4406     {
4407     int family = ((struct sockaddr *)(&inetd_sock))->sa_family;
4408     if (family == AF_INET || family == AF_INET6)
4409       {
4410       union sockaddr_46 interface_sock;
4411       size = sizeof(interface_sock);
4412
4413       if (getsockname(0, (struct sockaddr *)(&interface_sock), &size) == 0)
4414         interface_address = host_ntoa(-1, &interface_sock, NULL,
4415           &interface_port);
4416
4417       if (host_is_tls_on_connect_port(interface_port)) tls_in.on_connect = TRUE;
4418
4419       if (real_uid == root_uid || real_uid == exim_uid || interface_port < 1024)
4420         {
4421         f.is_inetd = TRUE;
4422         sender_host_address = host_ntoa(-1, (struct sockaddr *)(&inetd_sock),
4423           NULL, &sender_host_port);
4424         if (mua_wrapper) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Input from "
4425           "inetd is not supported when mua_wrapper is set");
4426         }
4427       else
4428         exim_fail(
4429           "exim: Permission denied (unprivileged user, unprivileged port)\n");
4430       }
4431     }
4432   }
4433
4434 /* If the load average is going to be needed while receiving a message, get it
4435 now for those OS that require the first call to os_getloadavg() to be done as
4436 root. There will be further calls later for each message received. */
4437
4438 #ifdef LOAD_AVG_NEEDS_ROOT
4439 if (  receiving_message
4440    && (queue_only_load >= 0 || (f.is_inetd && smtp_load_reserve >= 0)))
4441   load_average = OS_GETLOADAVG();
4442 #endif
4443
4444 /* The queue_only configuration option can be overridden by -odx on the command
4445 line, except that if queue_only_override is false, queue_only cannot be unset
4446 from the command line. */
4447
4448 if (queue_only_set && (queue_only_override || arg_queue_only))
4449   queue_only = arg_queue_only;
4450
4451 /* The receive_timeout and smtp_receive_timeout options can be overridden by
4452 -or and -os. */
4453
4454 if (arg_receive_timeout >= 0) receive_timeout = arg_receive_timeout;
4455 if (arg_smtp_receive_timeout >= 0)
4456   smtp_receive_timeout = arg_smtp_receive_timeout;
4457
4458 /* If Exim was started with root privilege, unless we have already removed the
4459 root privilege above as a result of -C, -D, -be, -bf or -bF, remove it now
4460 except when starting the daemon or doing some kind of delivery or address
4461 testing (-bt). These are the only cases when root need to be retained. We run
4462 as exim for -bv and -bh. However, if deliver_drop_privilege is set, root is
4463 retained only for starting the daemon. We always do the initgroups() in this
4464 situation (controlled by the TRUE below), in order to be as close as possible
4465 to the state Exim usually runs in. */
4466
4467 if (  !unprivileged                             /* originally had root AND */
4468    && !removed_privilege                        /* still got root AND      */
4469    && !f.daemon_listen                          /* not starting the daemon */
4470    && queue_interval <= 0                       /* (either kind of daemon) */
4471    && (                                         /*    AND EITHER           */
4472          deliver_drop_privilege                 /* requested unprivileged  */
4473       || (                                      /*       OR                */
4474             queue_interval < 0                  /* not running the queue   */
4475          && (  msg_action_arg < 0               /*       and               */
4476             || msg_action != MSG_DELIVER        /* not delivering          */
4477             )                                   /*       and               */
4478          && (!checking || !f.address_test_mode) /* not address checking    */
4479          && !rcpt_verify_quota                  /* and not quota checking  */
4480    )  )  )
4481   exim_setugid(exim_uid, exim_gid, TRUE, US"privilege not needed");
4482
4483 /* When we are retaining a privileged uid, we still change to the exim gid. */
4484
4485 else
4486   {
4487   int rv;
4488   DEBUG(D_any) debug_printf("dropping to exim gid; retaining priv uid\n");
4489   rv = setgid(exim_gid);
4490   /* Impact of failure is that some stuff might end up with an incorrect group.
4491   We track this for failures from root, since any attempt to change privilege
4492   by root should succeed and failures should be examined.  For non-root,
4493   there's no security risk.  For me, it's { exim -bV } on a just-built binary,
4494   no need to complain then. */
4495   if (rv == -1)
4496     if (!(unprivileged || removed_privilege))
4497       exim_fail("exim: changing group failed: %s\n", strerror(errno));
4498     else
4499       {
4500       DEBUG(D_any) debug_printf("changing group to %ld failed: %s\n",
4501           (long int)exim_gid, strerror(errno));
4502       }
4503   }
4504
4505 /* Handle a request to scan a file for malware */
4506 if (malware_test_file)
4507   {
4508 #ifdef WITH_CONTENT_SCAN
4509   int result;
4510   set_process_info("scanning file for malware");
4511   if ((result = malware_in_file(malware_test_file)) == FAIL)
4512     {
4513     printf("No malware found.\n");
4514     exit(EXIT_SUCCESS);
4515     }
4516   if (result != OK)
4517     {
4518     printf("Malware lookup returned non-okay/fail: %d\n", result);
4519     exit(EXIT_FAILURE);
4520     }
4521   if (malware_name)
4522     printf("Malware found: %s\n", malware_name);
4523   else
4524     printf("Malware scan detected malware of unknown name.\n");
4525 #else
4526   printf("Malware scanning not enabled at compile time.\n");
4527 #endif
4528   exit(EXIT_FAILURE);
4529   }
4530
4531 /* Handle a request to list the delivery queue */
4532
4533 if (list_queue)
4534   {
4535   set_process_info("listing the queue");
4536   queue_list(list_queue_option, argv + recipients_arg, argc - recipients_arg);
4537   exit(EXIT_SUCCESS);
4538   }
4539
4540 /* Handle a request to count the delivery queue */
4541
4542 if (count_queue)
4543   {
4544   set_process_info("counting the queue");
4545   fprintf(stdout, "%u\n", queue_count());
4546   exit(EXIT_SUCCESS);
4547   }
4548
4549 /* Handle actions on specific messages, except for the force delivery and
4550 message load actions, which are done below. Some actions take a whole list of
4551 message ids, which are known to continue up to the end of the arguments. Others
4552 take a single message id and then operate on the recipients list. */
4553
4554 if (msg_action_arg > 0 && msg_action != MSG_DELIVER && msg_action != MSG_LOAD)
4555   {
4556   int yield = EXIT_SUCCESS;
4557   set_process_info("acting on specified messages");
4558
4559   /* ACL definitions may be needed when removing a message (-Mrm) because
4560   event_action gets expanded */
4561
4562   if (msg_action == MSG_REMOVE)
4563     {
4564     int old_pool = store_pool;
4565     store_pool = POOL_CONFIG;
4566     readconf_rest();
4567     store_pool = old_pool;
4568     store_writeprotect(POOL_CONFIG);
4569     }
4570
4571   if (!one_msg_action)
4572     {
4573     for (i = msg_action_arg; i < argc; i++)
4574       if (!queue_action(argv[i], msg_action, NULL, 0, 0))
4575         yield = EXIT_FAILURE;
4576     switch (msg_action)
4577       {
4578       case MSG_REMOVE: case MSG_FREEZE: case MSG_THAW: break;
4579       default: printf("\n"); break;
4580       }
4581     }
4582
4583   else if (!queue_action(argv[msg_action_arg], msg_action, argv, argc,
4584     recipients_arg)) yield = EXIT_FAILURE;
4585   exit(yield);
4586   }
4587
4588 /* We used to set up here to skip reading the ACL section, on
4589  (msg_action_arg > 0 || (queue_interval == 0 && !f.daemon_listen)
4590 Now, since the intro of the ${acl } expansion, ACL definitions may be
4591 needed in transports so we lost the optimisation. */
4592
4593   {
4594   int old_pool = store_pool;
4595 #ifdef MEASURE_TIMING
4596   struct timeval t0, diff;
4597   (void)gettimeofday(&t0, NULL);
4598 #endif
4599
4600   store_pool = POOL_CONFIG;
4601   readconf_rest();
4602   store_pool = old_pool;
4603   store_writeprotect(POOL_CONFIG);
4604
4605 #ifdef MEASURE_TIMING
4606   report_time_since(&t0, US"readconf_rest (delta)");
4607 #endif
4608   }
4609
4610 /* Handle a request to check quota */
4611 if (rcpt_verify_quota)
4612   if (real_uid != root_uid && real_uid != exim_uid)
4613     exim_fail("exim: Permission denied\n");
4614   else if (recipients_arg >= argc)
4615     exim_fail("exim: missing recipient for quota check\n");
4616   else
4617     {
4618     verify_quota(argv[recipients_arg]);
4619     exim_exit(EXIT_SUCCESS);
4620     }
4621
4622 /* Handle the -brt option. This is for checking out retry configurations.
4623 The next three arguments are a domain name or a complete address, and
4624 optionally two error numbers. All it does is to call the function that
4625 scans the retry configuration data. */
4626
4627 if (test_retry_arg >= 0)
4628   {
4629   retry_config *yield;
4630   int basic_errno = 0;
4631   int more_errno = 0;
4632   const uschar *s1, *s2;
4633
4634   if (test_retry_arg >= argc)
4635     {
4636     printf("-brt needs a domain or address argument\n");
4637     exim_exit(EXIT_FAILURE);
4638     }
4639   s1 = exim_str_fail_toolong(argv[test_retry_arg++], EXIM_EMAILADDR_MAX, "-brt");
4640   s2 = NULL;
4641
4642   /* If the first argument contains no @ and no . it might be a local user
4643   or it might be a single-component name. Treat as a domain. */
4644
4645   if (Ustrchr(s1, '@') == NULL && Ustrchr(s1, '.') == NULL)
4646     {
4647     printf("Warning: \"%s\" contains no '@' and no '.' characters. It is "
4648       "being \ntreated as a one-component domain, not as a local part.\n\n",
4649       s1);
4650     }
4651
4652   /* There may be an optional second domain arg. */
4653
4654   if (test_retry_arg < argc && Ustrchr(argv[test_retry_arg], '.') != NULL)
4655     s2 = exim_str_fail_toolong(argv[test_retry_arg++], EXIM_DOMAINNAME_MAX, "-brt 2nd");
4656
4657   /* The final arg is an error name */
4658
4659   if (test_retry_arg < argc)
4660     {
4661     const uschar *ss = exim_str_fail_toolong(argv[test_retry_arg], EXIM_DRIVERNAME_MAX, "-brt 3rd");
4662     uschar *error =
4663       readconf_retry_error(ss, ss + Ustrlen(ss), &basic_errno, &more_errno);
4664     if (error != NULL)
4665       {
4666       printf("%s\n", CS error);
4667       return EXIT_FAILURE;
4668       }
4669
4670     /* For the {MAIL,RCPT,DATA}_4xx errors, a value of 255 means "any", and a
4671     code > 100 as an error is for matching codes to the decade. Turn them into
4672     a real error code, off the decade. */
4673
4674     if (basic_errno == ERRNO_MAIL4XX ||
4675         basic_errno == ERRNO_RCPT4XX ||
4676         basic_errno == ERRNO_DATA4XX)
4677       {
4678       int code = (more_errno >> 8) & 255;
4679       if (code == 255)
4680         more_errno = (more_errno & 0xffff00ff) | (21 << 8);
4681       else if (code > 100)
4682         more_errno = (more_errno & 0xffff00ff) | ((code - 96) << 8);
4683       }
4684     }
4685
4686   if (!(yield = retry_find_config(s1, s2, basic_errno, more_errno)))
4687     printf("No retry information found\n");
4688   else
4689     {
4690     more_errno = yield->more_errno;
4691     printf("Retry rule: %s  ", yield->pattern);
4692
4693     if (yield->basic_errno == ERRNO_EXIMQUOTA)
4694       {
4695       printf("quota%s%s  ",
4696         (more_errno > 0)? "_" : "",
4697         (more_errno > 0)? readconf_printtime(more_errno) : US"");
4698       }
4699     else if (yield->basic_errno == ECONNREFUSED)
4700       {
4701       printf("refused%s%s  ",
4702         (more_errno > 0)? "_" : "",
4703         (more_errno == 'M')? "MX" :
4704         (more_errno == 'A')? "A" : "");
4705       }
4706     else if (yield->basic_errno == ETIMEDOUT)
4707       {
4708       printf("timeout");
4709       if ((more_errno & RTEF_CTOUT) != 0) printf("_connect");
4710       more_errno &= 255;
4711       if (more_errno != 0) printf("_%s",
4712         (more_errno == 'M')? "MX" : "A");
4713       printf("  ");
4714       }
4715     else if (yield->basic_errno == ERRNO_AUTHFAIL)
4716       printf("auth_failed  ");
4717     else printf("*  ");
4718
4719     for (retry_rule * r = yield->rules; r; r = r->next)
4720       {
4721       printf("%c,%s", r->rule, readconf_printtime(r->timeout)); /* Do not */
4722       printf(",%s", readconf_printtime(r->p1));                 /* amalgamate */
4723       if (r->rule == 'G')
4724         {
4725         int x = r->p2;
4726         int f = x % 1000;
4727         int d = 100;
4728         printf(",%d.", x/1000);
4729         do
4730           {
4731           printf("%d", f/d);
4732           f %= d;
4733           d /= 10;
4734           }
4735         while (f != 0);
4736         }
4737       printf("; ");
4738       }
4739
4740     printf("\n");
4741     }
4742   exim_exit(EXIT_SUCCESS);
4743   }
4744
4745 /* Handle a request to list one or more configuration options */
4746 /* If -n was set, we suppress some information */
4747
4748 if (list_options)
4749   {
4750   BOOL fail = FALSE;
4751   set_process_info("listing variables");
4752   if (recipients_arg >= argc)
4753     fail = !readconf_print(US"all", NULL, flag_n);
4754   else for (i = recipients_arg; i < argc; i++)
4755     {
4756     if (i < argc - 1 &&
4757         (Ustrcmp(argv[i], "router") == 0 ||
4758          Ustrcmp(argv[i], "transport") == 0 ||
4759          Ustrcmp(argv[i], "authenticator") == 0 ||
4760          Ustrcmp(argv[i], "macro") == 0 ||
4761          Ustrcmp(argv[i], "environment") == 0))
4762       {
4763       fail |= !readconf_print(exim_str_fail_toolong(argv[i+1], EXIM_DRIVERNAME_MAX, "-bP name"), argv[i], flag_n);
4764       i++;
4765       }
4766     else
4767       fail = !readconf_print(exim_str_fail_toolong(argv[i], EXIM_DRIVERNAME_MAX, "-bP item"), NULL, flag_n);
4768     }
4769   exim_exit(fail ? EXIT_FAILURE : EXIT_SUCCESS);
4770   }
4771
4772 if (list_config)
4773   {
4774   set_process_info("listing config");
4775   exim_exit(readconf_print(US"config", NULL, flag_n)
4776                 ? EXIT_SUCCESS : EXIT_FAILURE);
4777   }
4778
4779
4780 /* Initialise subsystems as required. */
4781
4782 tcp_init();
4783
4784 /* Handle a request to deliver one or more messages that are already on the
4785 queue. Values of msg_action other than MSG_DELIVER and MSG_LOAD are dealt with
4786 above. MSG_LOAD is handled with -be (which is the only time it applies) below.
4787
4788 Delivery of specific messages is typically used for a small number when
4789 prodding by hand (when the option forced_delivery will be set) or when
4790 re-execing to regain root privilege. Each message delivery must happen in a
4791 separate process, so we fork a process for each one, and run them sequentially
4792 so that debugging output doesn't get intertwined, and to avoid spawning too
4793 many processes if a long list is given. However, don't fork for the last one;
4794 this saves a process in the common case when Exim is called to deliver just one
4795 message. */
4796
4797 if (msg_action_arg > 0 && msg_action != MSG_LOAD)
4798   {
4799   if (prod_requires_admin && !f.admin_user)
4800     {
4801     fprintf(stderr, "exim: Permission denied\n");
4802     exim_exit(EXIT_FAILURE);
4803     }
4804   set_process_info("delivering specified messages");
4805   if (deliver_give_up) forced_delivery = f.deliver_force_thaw = TRUE;
4806   for (i = msg_action_arg; i < argc; i++)
4807     {
4808     int status;
4809     pid_t pid;
4810     /*XXX This use of argv[i] for msg_id should really be tainted, but doing
4811     that runs into a later copy into the untainted global message_id[] */
4812     /*XXX Do we need a length limit check here? */
4813     if (i == argc - 1)
4814       (void)deliver_message(argv[i], forced_delivery, deliver_give_up);
4815     else if ((pid = exim_fork(US"cmdline-delivery")) == 0)
4816       {
4817       (void)deliver_message(argv[i], forced_delivery, deliver_give_up);
4818       exim_underbar_exit(EXIT_SUCCESS);
4819       }
4820     else if (pid < 0)
4821       {
4822       fprintf(stderr, "failed to fork delivery process for %s: %s\n", argv[i],
4823         strerror(errno));
4824       exim_exit(EXIT_FAILURE);
4825       }
4826     else wait(&status);
4827     }
4828   exim_exit(EXIT_SUCCESS);
4829   }
4830
4831
4832 /* If only a single queue run is requested, without SMTP listening, we can just
4833 turn into a queue runner, with an optional starting message id. */
4834
4835 if (queue_interval == 0 && !f.daemon_listen)
4836   {
4837   DEBUG(D_queue_run) debug_printf("Single queue run%s%s%s%s\n",
4838     start_queue_run_id ? US" starting at " : US"",
4839     start_queue_run_id ? start_queue_run_id: US"",
4840     stop_queue_run_id ?  US" stopping at " : US"",
4841     stop_queue_run_id ?  stop_queue_run_id : US"");
4842   if (*queue_name)
4843     set_process_info("running the '%s' queue (single queue run)", queue_name);
4844   else
4845     set_process_info("running the queue (single queue run)");
4846   queue_run(start_queue_run_id, stop_queue_run_id, FALSE);
4847   exim_exit(EXIT_SUCCESS);
4848   }
4849
4850
4851 /* Find the login name of the real user running this process. This is always
4852 needed when receiving a message, because it is written into the spool file. It
4853 may also be used to construct a from: or a sender: header, and in this case we
4854 need the user's full name as well, so save a copy of it, checked for RFC822
4855 syntax and munged if necessary, if it hasn't previously been set by the -F
4856 argument. We may try to get the passwd entry more than once, in case NIS or
4857 other delays are in evidence. Save the home directory for use in filter testing
4858 (only). */
4859
4860 for (i = 0;;)
4861   {
4862   if ((pw = getpwuid(real_uid)) != NULL)
4863     {
4864     originator_login = string_copy(US pw->pw_name);
4865     originator_home = string_copy(US pw->pw_dir);
4866
4867     /* If user name has not been set by -F, set it from the passwd entry
4868     unless -f has been used to set the sender address by a trusted user. */
4869
4870     if (!originator_name)
4871       {
4872       if (!sender_address || (!f.trusted_caller && filter_test == FTEST_NONE))
4873         {
4874         uschar *name = US pw->pw_gecos;
4875         uschar *amp = Ustrchr(name, '&');
4876         uschar buffer[256];
4877
4878         /* Most Unix specify that a '&' character in the gecos field is
4879         replaced by a copy of the login name, and some even specify that
4880         the first character should be upper cased, so that's what we do. */
4881
4882         if (amp)
4883           {
4884           int loffset;
4885           string_format(buffer, sizeof(buffer), "%.*s%n%s%s",
4886             (int)(amp - name), name, &loffset, originator_login, amp + 1);
4887           buffer[loffset] = toupper(buffer[loffset]);
4888           name = buffer;
4889           }
4890
4891         /* If a pattern for matching the gecos field was supplied, apply
4892         it and then expand the name string. */
4893
4894         if (gecos_pattern && gecos_name)
4895           {
4896           const pcre2_code *re;
4897           re = regex_must_compile(gecos_pattern, FALSE, TRUE); /* Use malloc */
4898
4899           if (regex_match_and_setup(re, name, 0, -1))
4900             {
4901             uschar *new_name = expand_string(gecos_name);
4902             expand_nmax = -1;
4903             if (new_name)
4904               {
4905               DEBUG(D_receive) debug_printf("user name \"%s\" extracted from "
4906                 "gecos field \"%s\"\n", new_name, name);
4907               name = new_name;
4908               }
4909             else DEBUG(D_receive) debug_printf("failed to expand gecos_name string "
4910               "\"%s\": %s\n", gecos_name, expand_string_message);
4911             }
4912           else DEBUG(D_receive) debug_printf("gecos_pattern \"%s\" did not match "
4913             "gecos field \"%s\"\n", gecos_pattern, name);
4914           store_free((void *)re);
4915           }
4916         originator_name = string_copy(name);
4917         }
4918
4919       /* A trusted caller has used -f but not -F */
4920
4921       else originator_name = US"";
4922       }
4923
4924     /* Break the retry loop */
4925
4926     break;
4927     }
4928
4929   if (++i > finduser_retries) break;
4930   sleep(1);
4931   }
4932
4933 /* If we cannot get a user login, log the incident and give up, unless the
4934 configuration specifies something to use. When running in the test harness,
4935 any setting of unknown_login overrides the actual name. */
4936
4937 if (!originator_login || f.running_in_test_harness)
4938   {
4939   if (unknown_login)
4940     {
4941     originator_login = expand_string(unknown_login);
4942     if (!originator_name && unknown_username)
4943       originator_name = expand_string(unknown_username);
4944     if (!originator_name) originator_name = US"";
4945     }
4946   if (!originator_login)
4947     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to get user name for uid %d",
4948       (int)real_uid);
4949   }
4950
4951 /* Ensure that the user name is in a suitable form for use as a "phrase" in an
4952 RFC822 address.*/
4953
4954 originator_name = US parse_fix_phrase(originator_name, Ustrlen(originator_name));
4955
4956 /* If a message is created by this call of Exim, the uid/gid of its originator
4957 are those of the caller. These values are overridden if an existing message is
4958 read in from the spool. */
4959
4960 originator_uid = real_uid;
4961 originator_gid = real_gid;
4962
4963 DEBUG(D_receive) debug_printf("originator: uid=%d gid=%d login=%s name=%s\n",
4964   (int)originator_uid, (int)originator_gid, originator_login, originator_name);
4965
4966 /* Run in daemon and/or queue-running mode. The function daemon_go() never
4967 returns. We leave this till here so that the originator_ fields are available
4968 for incoming messages via the daemon. The daemon cannot be run in mua_wrapper
4969 mode. */
4970
4971 if (f.daemon_listen || f.inetd_wait_mode || queue_interval > 0)
4972   {
4973   if (mua_wrapper)
4974     {
4975     fprintf(stderr, "Daemon cannot be run when mua_wrapper is set\n");
4976     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Daemon cannot be run when "
4977       "mua_wrapper is set");
4978     }
4979
4980 # ifndef DISABLE_TLS
4981   /* This also checks that the library linkage is working and we can call
4982   routines in it, so call even if tls_require_ciphers is unset */
4983     {
4984 # ifdef MEASURE_TIMING
4985     struct timeval t0, diff;
4986     (void)gettimeofday(&t0, NULL);
4987 # endif
4988     if (!tls_dropprivs_validate_require_cipher(FALSE))
4989       exit(1);
4990 # ifdef MEASURE_TIMING
4991     report_time_since(&t0, US"validate_ciphers (delta)");
4992 # endif
4993     }
4994 #endif
4995
4996   daemon_go();
4997   }
4998
4999 /* If the sender ident has not been set (by a trusted caller) set it to
5000 the caller. This will get overwritten below for an inetd call. If a trusted
5001 caller has set it empty, unset it. */
5002
5003 if (!sender_ident) sender_ident = originator_login;
5004 else if (!*sender_ident) sender_ident = NULL;
5005
5006 /* Handle the -brw option, which is for checking out rewriting rules. Cause log
5007 writes (on errors) to go to stderr instead. Can't do this earlier, as want the
5008 originator_* variables set. */
5009
5010 if (test_rewrite_arg >= 0)
5011   {
5012   f.really_exim = FALSE;
5013   if (test_rewrite_arg >= argc)
5014     {
5015     printf("-brw needs an address argument\n");
5016     exim_exit(EXIT_FAILURE);
5017     }
5018   rewrite_test(exim_str_fail_toolong(argv[test_rewrite_arg], EXIM_EMAILADDR_MAX, "-brw"));
5019   exim_exit(EXIT_SUCCESS);
5020   }
5021
5022 /* A locally-supplied message is considered to be coming from a local user
5023 unless a trusted caller supplies a sender address with -f, or is passing in the
5024 message via SMTP (inetd invocation or otherwise). */
5025
5026 if (  !sender_address && !smtp_input
5027    || !f.trusted_caller && filter_test == FTEST_NONE)
5028   {
5029   f.sender_local = TRUE;
5030
5031   /* A trusted caller can supply authenticated_sender and authenticated_id
5032   via -oMas and -oMai and if so, they will already be set. Otherwise, force
5033   defaults except when host checking. */
5034
5035   if (!authenticated_sender && !host_checking)
5036     authenticated_sender = string_sprintf("%s@%s", originator_login,
5037       qualify_domain_sender);
5038   if (!authenticated_id && !host_checking)
5039     authenticated_id = originator_login;
5040   }
5041
5042 /* Trusted callers are always permitted to specify the sender address.
5043 Untrusted callers may specify it if it matches untrusted_set_sender, or if what
5044 is specified is the empty address. However, if a trusted caller does not
5045 specify a sender address for SMTP input, we leave sender_address unset. This
5046 causes the MAIL commands to be honoured. */
5047
5048 if (  !smtp_input && !sender_address
5049    || !receive_check_set_sender(sender_address))
5050   {
5051   /* Either the caller is not permitted to set a general sender, or this is
5052   non-SMTP input and the trusted caller has not set a sender. If there is no
5053   sender, or if a sender other than <> is set, override with the originator's
5054   login (which will get qualified below), except when checking things. */
5055
5056   if (  !sender_address                  /* No sender_address set */
5057      ||                                  /*         OR            */
5058        (sender_address[0] != 0 &&        /* Non-empty sender address, AND */
5059        !checking))                       /* Not running tests, including filter tests */
5060     {
5061     sender_address = originator_login;
5062     f.sender_address_forced = FALSE;
5063     sender_address_domain = 0;
5064     }
5065   }
5066
5067 /* Remember whether an untrusted caller set the sender address */
5068
5069 f.sender_set_untrusted = sender_address != originator_login && !f.trusted_caller;
5070
5071 /* Ensure that the sender address is fully qualified unless it is the empty
5072 address, which indicates an error message, or doesn't exist (root caller, smtp
5073 interface, no -f argument). */
5074
5075 if (sender_address && *sender_address && sender_address_domain == 0)
5076   sender_address = string_sprintf("%s@%s", local_part_quote(sender_address),
5077     qualify_domain_sender);
5078
5079 DEBUG(D_receive) debug_printf("sender address = %s\n", sender_address);
5080
5081 /* Handle a request to verify a list of addresses, or test them for delivery.
5082 This must follow the setting of the sender address, since routers can be
5083 predicated upon the sender. If no arguments are given, read addresses from
5084 stdin. Set debug_level to at least D_v to get full output for address testing.
5085 */
5086
5087 if (verify_address_mode || f.address_test_mode)
5088   {
5089   int exit_value = 0;
5090   int flags = vopt_qualify;
5091
5092   if (verify_address_mode)
5093     {
5094     if (!verify_as_sender) flags |= vopt_is_recipient;
5095     DEBUG(D_verify) debug_print_ids(US"Verifying:");
5096     }
5097
5098   else
5099     {
5100     flags |= vopt_is_recipient;
5101     debug_selector |= D_v;
5102     debug_file = stderr;
5103     debug_fd = fileno(debug_file);
5104     DEBUG(D_verify) debug_print_ids(US"Address testing:");
5105     }
5106
5107   if (recipients_arg < argc)
5108     while (recipients_arg < argc)
5109       {
5110       /* Supplied addresses are tainted since they come from a user */
5111       uschar * s = string_copy_taint(exim_str_fail_toolong(argv[recipients_arg++], EXIM_DISPLAYMAIL_MAX, "address verification"), TRUE);
5112       while (*s)
5113         {
5114         BOOL finished = FALSE;
5115         uschar *ss = parse_find_address_end(s, FALSE);
5116         if (*ss == ',') *ss = 0; else finished = TRUE;
5117         test_address(s, flags, &exit_value);
5118         s = ss;
5119         if (!finished)
5120           while (*++s == ',' || isspace(*s)) ;
5121         }
5122       }
5123
5124   else for (;;)
5125     {
5126     uschar * s = get_stdinput(NULL, NULL);
5127     if (!s) break;
5128     test_address(string_copy_taint(exim_str_fail_toolong(s, EXIM_DISPLAYMAIL_MAX, "address verification (stdin)"), TRUE), flags, &exit_value);
5129     }
5130
5131   route_tidyup();
5132   exim_exit(exit_value);
5133   }
5134
5135 /* Handle expansion checking. Either expand items on the command line, or read
5136 from stdin if there aren't any. If -Mset was specified, load the message so
5137 that its variables can be used, but restrict this facility to admin users.
5138 Otherwise, if -bem was used, read a message from stdin. */
5139
5140 if (expansion_test)
5141   {
5142   dns_init(FALSE, FALSE, FALSE);
5143   if (msg_action_arg > 0 && msg_action == MSG_LOAD)
5144     {
5145     uschar * spoolname;
5146     if (!f.admin_user)
5147       exim_fail("exim: permission denied\n");
5148     message_id = US exim_str_fail_toolong(argv[msg_action_arg], MESSAGE_ID_LENGTH, "message-id");
5149     /* Checking the length of the ID is sufficient to validate it.
5150     Get an untainted version so file opens can be done. */
5151     message_id = string_copy_taint(message_id, FALSE);
5152
5153     spoolname = string_sprintf("%s-H", message_id);
5154     if ((deliver_datafile = spool_open_datafile(message_id)) < 0)
5155       printf ("Failed to load message datafile %s\n", message_id);
5156     if (spool_read_header(spoolname, TRUE, FALSE) != spool_read_OK)
5157       printf ("Failed to load message %s\n", message_id);
5158     }
5159
5160   /* Read a test message from a file. We fudge it up to be on stdin, saving
5161   stdin itself for later reading of expansion strings. */
5162
5163   else if (expansion_test_message)
5164     {
5165     int save_stdin = dup(0);
5166     int fd = Uopen(expansion_test_message, O_RDONLY, 0);
5167     if (fd < 0)
5168       exim_fail("exim: failed to open %s: %s\n", expansion_test_message,
5169         strerror(errno));
5170     (void) dup2(fd, 0);
5171     filter_test = FTEST_USER;      /* Fudge to make it look like filter test */
5172     message_ended = END_NOTENDED;
5173     read_message_body(receive_msg(extract_recipients));
5174     message_linecount += body_linecount;
5175     (void)dup2(save_stdin, 0);
5176     (void)close(save_stdin);
5177     clearerr(stdin);               /* Required by Darwin */
5178     }
5179
5180   /* Only admin users may see config-file macros this way */
5181
5182   if (!f.admin_user) macros_user = macros = mlast = NULL;
5183
5184   /* Allow $recipients for this testing */
5185
5186   f.enable_dollar_recipients = TRUE;
5187
5188   /* Expand command line items */
5189
5190   if (recipients_arg < argc)
5191     while (recipients_arg < argc)
5192       expansion_test_line(exim_str_fail_toolong(argv[recipients_arg++], EXIM_EMAILADDR_MAX, "recipient"));
5193
5194   /* Read stdin */
5195
5196   else
5197     {
5198     char *(*fn_readline)(const char *) = NULL;
5199     void (*fn_addhist)(const char *) = NULL;
5200     uschar * s;
5201
5202 #ifdef USE_READLINE
5203     void *dlhandle = set_readline(&fn_readline, &fn_addhist);
5204 #endif
5205
5206     while (s = get_stdinput(fn_readline, fn_addhist))
5207       expansion_test_line(s);
5208
5209 #ifdef USE_READLINE
5210     if (dlhandle) dlclose(dlhandle);
5211 #endif
5212     }
5213
5214   /* The data file will be open after -Mset */
5215
5216   if (deliver_datafile >= 0)
5217     {
5218     (void)close(deliver_datafile);
5219     deliver_datafile = -1;
5220     }
5221
5222   exim_exit(EXIT_SUCCESS);
5223   }
5224
5225
5226 /* The active host name is normally the primary host name, but it can be varied
5227 for hosts that want to play several parts at once. We need to ensure that it is
5228 set for host checking, and for receiving messages. */
5229
5230 smtp_active_hostname = primary_hostname;
5231 if (raw_active_hostname != NULL)
5232   {
5233   uschar *nah = expand_string(raw_active_hostname);
5234   if (nah == NULL)
5235     {
5236     if (!f.expand_string_forcedfail)
5237       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand \"%s\" "
5238         "(smtp_active_hostname): %s", raw_active_hostname,
5239         expand_string_message);
5240     }
5241   else if (nah[0] != 0) smtp_active_hostname = nah;
5242   }
5243
5244 /* Handle host checking: this facility mocks up an incoming SMTP call from a
5245 given IP address so that the blocking and relay configuration can be tested.
5246 Unless a sender_ident was set by -oMt, we discard it (the default is the
5247 caller's login name). An RFC 1413 call is made only if we are running in the
5248 test harness and an incoming interface and both ports are specified, because
5249 there is no TCP/IP call to find the ident for. */
5250
5251 if (host_checking)
5252   {
5253   int x[4];
5254   int size;
5255
5256   if (!sender_ident_set)
5257     {
5258     sender_ident = NULL;
5259     if (f.running_in_test_harness && sender_host_port
5260        && interface_address && interface_port)
5261       verify_get_ident(1223);           /* note hardwired port number */
5262     }
5263
5264   /* In case the given address is a non-canonical IPv6 address, canonicalize
5265   it. The code works for both IPv4 and IPv6, as it happens. */
5266
5267   size = host_aton(sender_host_address, x);
5268   sender_host_address = store_get(48, FALSE);  /* large enough for full IPv6 */
5269   (void)host_nmtoa(size, x, -1, sender_host_address, ':');
5270
5271   /* Now set up for testing */
5272
5273   host_build_sender_fullhost();
5274   smtp_input = TRUE;
5275   smtp_in = stdin;
5276   smtp_out = stdout;
5277   f.sender_local = FALSE;
5278   f.sender_host_notsocket = TRUE;
5279   debug_file = stderr;
5280   debug_fd = fileno(debug_file);
5281   fprintf(stdout, "\n**** SMTP testing session as if from host %s\n"
5282     "**** but without any ident (RFC 1413) callback.\n"
5283     "**** This is not for real!\n\n",
5284       sender_host_address);
5285
5286   memset(sender_host_cache, 0, sizeof(sender_host_cache));
5287   if (verify_check_host(&hosts_connection_nolog) == OK)
5288     BIT_CLEAR(log_selector, log_selector_size, Li_smtp_connection);
5289   log_write(L_smtp_connection, LOG_MAIN, "%s", smtp_get_connection_info());
5290
5291   /* NOTE: We do *not* call smtp_log_no_mail() if smtp_start_session() fails,
5292   because a log line has already been written for all its failure exists
5293   (usually "connection refused: <reason>") and writing another one is
5294   unnecessary clutter. */
5295
5296   if (smtp_start_session())
5297     {
5298     rmark reset_point;
5299     for (; (reset_point = store_mark()); store_reset(reset_point))
5300       {
5301       if (smtp_setup_msg() <= 0) break;
5302       if (!receive_msg(FALSE)) break;
5303
5304       return_path = sender_address = NULL;
5305       dnslist_domain = dnslist_matched = NULL;
5306 #ifndef DISABLE_DKIM
5307       dkim_cur_signer = NULL;
5308 #endif
5309       acl_var_m = NULL;
5310       deliver_localpart_orig = NULL;
5311       deliver_domain_orig = NULL;
5312       callout_address = sending_ip_address = NULL;
5313       deliver_localpart_data = deliver_domain_data =
5314       recipient_data = sender_data = NULL;
5315       sender_rate = sender_rate_limit = sender_rate_period = NULL;
5316       }
5317     smtp_log_no_mail();
5318     }
5319   exim_exit(EXIT_SUCCESS);
5320   }
5321
5322
5323 /* Arrange for message reception if recipients or SMTP were specified;
5324 otherwise complain unless a version print (-bV) happened or this is a filter
5325 verification test or info dump.
5326 In the former case, show the configuration file name. */
5327
5328 if (recipients_arg >= argc && !extract_recipients && !smtp_input)
5329   {
5330   if (version_printed)
5331     {
5332     if (Ustrchr(config_main_filelist, ':'))
5333       printf("Configuration file search path is %s\n", config_main_filelist);
5334     printf("Configuration file is %s\n", config_main_filename);
5335     return EXIT_SUCCESS;
5336     }
5337
5338   if (info_flag != CMDINFO_NONE)
5339     {
5340     show_exim_information(info_flag, info_stdout ? stdout : stderr);
5341     return info_stdout ? EXIT_SUCCESS : EXIT_FAILURE;
5342     }
5343
5344   if (filter_test == FTEST_NONE)
5345     exim_usage(called_as);
5346   }
5347
5348
5349 /* If mua_wrapper is set, Exim is being used to turn an MUA that submits on the
5350 standard input into an MUA that submits to a smarthost over TCP/IP. We know
5351 that we are not called from inetd, because that is rejected above. The
5352 following configuration settings are forced here:
5353
5354   (1) Synchronous delivery (-odi)
5355   (2) Errors to stderr (-oep == -oeq)
5356   (3) No parallel remote delivery
5357   (4) Unprivileged delivery
5358
5359 We don't force overall queueing options because there are several of them;
5360 instead, queueing is avoided below when mua_wrapper is set. However, we do need
5361 to override any SMTP queueing. */
5362
5363 if (mua_wrapper)
5364   {
5365   f.synchronous_delivery = TRUE;
5366   arg_error_handling = ERRORS_STDERR;
5367   remote_max_parallel = 1;
5368   deliver_drop_privilege = TRUE;
5369   f.queue_smtp = FALSE;
5370   queue_smtp_domains = NULL;
5371 #ifdef SUPPORT_I18N
5372   message_utf8_downconvert = -1;        /* convert-if-needed */
5373 #endif
5374   }
5375
5376
5377 /* Prepare to accept one or more new messages on the standard input. When a
5378 message has been read, its id is returned in message_id[]. If doing immediate
5379 delivery, we fork a delivery process for each received message, except for the
5380 last one, where we can save a process switch.
5381
5382 It is only in non-smtp mode that error_handling is allowed to be changed from
5383 its default of ERRORS_SENDER by argument. (Idle thought: are any of the
5384 sendmail error modes other than -oem ever actually used? Later: yes.) */
5385
5386 if (!smtp_input) error_handling = arg_error_handling;
5387
5388 /* If this is an inetd call, ensure that stderr is closed to prevent panic
5389 logging being sent down the socket and make an identd call to get the
5390 sender_ident. */
5391
5392 else if (f.is_inetd)
5393   {
5394   (void)fclose(stderr);
5395   exim_nullstd();                       /* Re-open to /dev/null */
5396   verify_get_ident(IDENT_PORT);
5397   host_build_sender_fullhost();
5398   set_process_info("handling incoming connection from %s via inetd",
5399     sender_fullhost);
5400   }
5401
5402 /* If the sender host address has been set, build sender_fullhost if it hasn't
5403 already been done (which it will have been for inetd). This caters for the
5404 case when it is forced by -oMa. However, we must flag that it isn't a socket,
5405 so that the test for IP options is skipped for -bs input. */
5406
5407 if (sender_host_address && !sender_fullhost)
5408   {
5409   host_build_sender_fullhost();
5410   set_process_info("handling incoming connection from %s via -oMa",
5411     sender_fullhost);
5412   f.sender_host_notsocket = TRUE;
5413   }
5414
5415 /* Otherwise, set the sender host as unknown except for inetd calls. This
5416 prevents host checking in the case of -bs not from inetd and also for -bS. */
5417
5418 else if (!f.is_inetd) f.sender_host_unknown = TRUE;
5419
5420 /* If stdout does not exist, then dup stdin to stdout. This can happen
5421 if exim is started from inetd. In this case fd 0 will be set to the socket,
5422 but fd 1 will not be set. This also happens for passed SMTP channels. */
5423
5424 if (fstat(1, &statbuf) < 0) (void)dup2(0, 1);
5425
5426 /* Set up the incoming protocol name and the state of the program. Root is
5427 allowed to force received protocol via the -oMr option above. If we have come
5428 via inetd, the process info has already been set up. We don't set
5429 received_protocol here for smtp input, as it varies according to
5430 batch/HELO/EHLO/AUTH/TLS. */
5431
5432 if (smtp_input)
5433   {
5434   if (!f.is_inetd) set_process_info("accepting a local %sSMTP message from <%s>",
5435     smtp_batched_input? "batched " : "",
5436     sender_address ? sender_address : originator_login);
5437   }
5438 else
5439   {
5440   int old_pool = store_pool;
5441   store_pool = POOL_PERM;
5442   if (!received_protocol)
5443     received_protocol = string_sprintf("local%s", called_as);
5444   store_pool = old_pool;
5445   set_process_info("accepting a local non-SMTP message from <%s>",
5446     sender_address);
5447   }
5448
5449 /* Initialize the session_local_queue-only flag (this will be ignored if
5450 mua_wrapper is set) */
5451
5452 queue_check_only();
5453 session_local_queue_only = queue_only;
5454
5455 /* For non-SMTP and for batched SMTP input, check that there is enough space on
5456 the spool if so configured. On failure, we must not attempt to send an error
5457 message! (For interactive SMTP, the check happens at MAIL FROM and an SMTP
5458 error code is given.) */
5459
5460 if ((!smtp_input || smtp_batched_input) && !receive_check_fs(0))
5461   exim_fail("exim: insufficient disk space\n");
5462
5463 /* If this is smtp input of any kind, real or batched, handle the start of the
5464 SMTP session.
5465
5466 NOTE: We do *not* call smtp_log_no_mail() if smtp_start_session() fails,
5467 because a log line has already been written for all its failure exists
5468 (usually "connection refused: <reason>") and writing another one is
5469 unnecessary clutter. */
5470
5471 if (smtp_input)
5472   {
5473   smtp_in = stdin;
5474   smtp_out = stdout;
5475   memset(sender_host_cache, 0, sizeof(sender_host_cache));
5476   if (verify_check_host(&hosts_connection_nolog) == OK)
5477     BIT_CLEAR(log_selector, log_selector_size, Li_smtp_connection);
5478   log_write(L_smtp_connection, LOG_MAIN, "%s", smtp_get_connection_info());
5479   if (!smtp_start_session())
5480     {
5481     mac_smtp_fflush();
5482     exim_exit(EXIT_SUCCESS);
5483     }
5484   }
5485
5486 /* Otherwise, set up the input size limit here and set no stdin stdio buffer
5487 (we handle buferring so as to have visibility of fill level). */
5488
5489 else
5490   {
5491   thismessage_size_limit = expand_string_integer(message_size_limit, TRUE);
5492   if (expand_string_message)
5493     if (thismessage_size_limit == -1)
5494       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand "
5495         "message_size_limit: %s", expand_string_message);
5496     else
5497       log_write(0, LOG_MAIN|LOG_PANIC_DIE, "invalid value for "
5498         "message_size_limit: %s", expand_string_message);
5499
5500   setvbuf(stdin, NULL, _IONBF, 0);
5501   }
5502
5503 /* Loop for several messages when reading SMTP input. If we fork any child
5504 processes, we don't want to wait for them unless synchronous delivery is
5505 requested, so set SIGCHLD to SIG_IGN in that case. This is not necessarily the
5506 same as SIG_DFL, despite the fact that documentation often lists the default as
5507 "ignore". This is a confusing area. This is what I know:
5508
5509 At least on some systems (e.g. Solaris), just setting SIG_IGN causes child
5510 processes that complete simply to go away without ever becoming defunct. You
5511 can't then wait for them - but we don't want to wait for them in the
5512 non-synchronous delivery case. However, this behaviour of SIG_IGN doesn't
5513 happen for all OS (e.g. *BSD is different).
5514
5515 But that's not the end of the story. Some (many? all?) systems have the
5516 SA_NOCLDWAIT option for sigaction(). This requests the behaviour that Solaris
5517 has by default, so it seems that the difference is merely one of default
5518 (compare restarting vs non-restarting signals).
5519
5520 To cover all cases, Exim sets SIG_IGN with SA_NOCLDWAIT here if it can. If not,
5521 it just sets SIG_IGN. To be on the safe side it also calls waitpid() at the end
5522 of the loop below. Paranoia rules.
5523
5524 February 2003: That's *still* not the end of the story. There are now versions
5525 of Linux (where SIG_IGN does work) that are picky. If, having set SIG_IGN, a
5526 process then calls waitpid(), a grumble is written to the system log, because
5527 this is logically inconsistent. In other words, it doesn't like the paranoia.
5528 As a consequence of this, the waitpid() below is now excluded if we are sure
5529 that SIG_IGN works. */
5530
5531 if (!f.synchronous_delivery)
5532   {
5533 #ifdef SA_NOCLDWAIT
5534   struct sigaction act;
5535   act.sa_handler = SIG_IGN;
5536   sigemptyset(&(act.sa_mask));
5537   act.sa_flags = SA_NOCLDWAIT;
5538   sigaction(SIGCHLD, &act, NULL);
5539 #else
5540   signal(SIGCHLD, SIG_IGN);
5541 #endif
5542   }
5543
5544 /* Save the current store pool point, for resetting at the start of
5545 each message, and save the real sender address, if any. */
5546
5547 real_sender_address = sender_address;
5548
5549 /* Loop to receive messages; receive_msg() returns TRUE if there are more
5550 messages to be read (SMTP input), or FALSE otherwise (not SMTP, or SMTP channel
5551 collapsed). */
5552
5553 for (BOOL more = TRUE; more; )
5554   {
5555   rmark reset_point = store_mark();
5556   message_id[0] = 0;
5557
5558   /* Handle the SMTP case; call smtp_setup_mst() to deal with the initial SMTP
5559   input and build the recipients list, before calling receive_msg() to read the
5560   message proper. Whatever sender address is given in the SMTP transaction is
5561   often ignored for local senders - we use the actual sender, which is normally
5562   either the underlying user running this process or a -f argument provided by
5563   a trusted caller. It is saved in real_sender_address. The test for whether to
5564   accept the SMTP sender is encapsulated in receive_check_set_sender(). */
5565
5566   if (smtp_input)
5567     {
5568     int rc;
5569     if ((rc = smtp_setup_msg()) > 0)
5570       {
5571       if (real_sender_address != NULL &&
5572           !receive_check_set_sender(sender_address))
5573         {
5574         sender_address = raw_sender = real_sender_address;
5575         sender_address_unrewritten = NULL;
5576         }
5577
5578       /* For batched SMTP, we have to run the acl_not_smtp_start ACL, since it
5579       isn't really SMTP, so no other ACL will run until the acl_not_smtp one at
5580       the very end. The result of the ACL is ignored (as for other non-SMTP
5581       messages). It is run for its potential side effects. */
5582
5583       if (smtp_batched_input && acl_not_smtp_start != NULL)
5584         {
5585         uschar *user_msg, *log_msg;
5586         f.enable_dollar_recipients = TRUE;
5587         (void)acl_check(ACL_WHERE_NOTSMTP_START, NULL, acl_not_smtp_start,
5588           &user_msg, &log_msg);
5589         f.enable_dollar_recipients = FALSE;
5590         }
5591
5592       /* Now get the data for the message */
5593
5594       more = receive_msg(extract_recipients);
5595       if (!message_id[0])
5596         {
5597         cancel_cutthrough_connection(TRUE, US"receive dropped");
5598         if (more) goto MORELOOP;
5599         smtp_log_no_mail();               /* Log no mail if configured */
5600         exim_exit(EXIT_FAILURE);
5601         }
5602       }
5603     else
5604       {
5605       cancel_cutthrough_connection(TRUE, US"message setup dropped");
5606       smtp_log_no_mail();               /* Log no mail if configured */
5607       exim_exit(rc ? EXIT_FAILURE : EXIT_SUCCESS);
5608       }
5609     }
5610
5611   /* In the non-SMTP case, we have all the information from the command
5612   line, but must process it in case it is in the more general RFC822
5613   format, and in any case, to detect syntax errors. Also, it appears that
5614   the use of comma-separated lists as single arguments is common, so we
5615   had better support them. */
5616
5617   else
5618     {
5619     int rcount = 0;
5620     int count = argc - recipients_arg;
5621     uschar **list = argv + recipients_arg;
5622
5623     /* These options cannot be changed dynamically for non-SMTP messages */
5624
5625     f.active_local_sender_retain = local_sender_retain;
5626     f.active_local_from_check = local_from_check;
5627
5628     /* Save before any rewriting */
5629
5630     raw_sender = string_copy(sender_address);
5631
5632     /* Loop for each argument (supplied by user hence tainted) */
5633
5634     for (int i = 0; i < count; i++)
5635       {
5636       int start, end, domain;
5637       uschar * errmess;
5638       /* There can be multiple addresses, so EXIM_DISPLAYMAIL_MAX (tuned for 1) is too short.
5639        * We'll still want to cap it to something, just in case. */
5640       uschar * s = string_copy_taint(exim_str_fail_toolong(list[i], BIG_BUFFER_SIZE, "address argument"), TRUE);
5641
5642       /* Loop for each comma-separated address */
5643
5644       while (*s != 0)
5645         {
5646         BOOL finished = FALSE;
5647         uschar *recipient;
5648         uschar *ss = parse_find_address_end(s, FALSE);
5649
5650         if (*ss == ',') *ss = 0; else finished = TRUE;
5651
5652         /* Check max recipients - if -t was used, these aren't recipients */
5653
5654         if (recipients_max > 0 && ++rcount > recipients_max &&
5655             !extract_recipients)
5656           if (error_handling == ERRORS_STDERR)
5657             {
5658             fprintf(stderr, "exim: too many recipients\n");
5659             exim_exit(EXIT_FAILURE);
5660             }
5661           else
5662             return
5663               moan_to_sender(ERRMESS_TOOMANYRECIP, NULL, NULL, stdin, TRUE)?
5664                 errors_sender_rc : EXIT_FAILURE;
5665
5666 #ifdef SUPPORT_I18N
5667         {
5668         BOOL b = allow_utf8_domains;
5669         allow_utf8_domains = TRUE;
5670 #endif
5671         recipient =
5672           parse_extract_address(s, &errmess, &start, &end, &domain, FALSE);
5673
5674 #ifdef SUPPORT_I18N
5675         if (recipient)
5676           if (string_is_utf8(recipient)) message_smtputf8 = TRUE;
5677           else allow_utf8_domains = b;
5678         }
5679 #else
5680         ;
5681 #endif
5682         if (domain == 0 && !f.allow_unqualified_recipient)
5683           {
5684           recipient = NULL;
5685           errmess = US"unqualified recipient address not allowed";
5686           }
5687
5688         if (!recipient)
5689           if (error_handling == ERRORS_STDERR)
5690             {
5691             fprintf(stderr, "exim: bad recipient address \"%s\": %s\n",
5692               string_printing(list[i]), errmess);
5693             exim_exit(EXIT_FAILURE);
5694             }
5695           else
5696             {
5697             error_block eblock;
5698             eblock.next = NULL;
5699             eblock.text1 = string_printing(list[i]);
5700             eblock.text2 = errmess;
5701             return
5702               moan_to_sender(ERRMESS_BADARGADDRESS, &eblock, NULL, stdin, TRUE)?
5703                 errors_sender_rc : EXIT_FAILURE;
5704             }
5705
5706         receive_add_recipient(string_copy_taint(recipient, TRUE), -1);
5707         s = ss;
5708         if (!finished)
5709           while (*(++s) != 0 && (*s == ',' || isspace(*s)));
5710         }
5711       }
5712
5713     /* Show the recipients when debugging */
5714
5715     DEBUG(D_receive)
5716       {
5717       if (sender_address) debug_printf("Sender: %s\n", sender_address);
5718       if (recipients_list)
5719         {
5720         debug_printf("Recipients:\n");
5721         for (int i = 0; i < recipients_count; i++)
5722           debug_printf("  %s\n", recipients_list[i].address);
5723         }
5724       }
5725
5726     /* Run the acl_not_smtp_start ACL if required. The result of the ACL is
5727     ignored; rejecting here would just add complication, and it can just as
5728     well be done later. Allow $recipients to be visible in the ACL. */
5729
5730     if (acl_not_smtp_start)
5731       {
5732       uschar *user_msg, *log_msg;
5733       f.enable_dollar_recipients = TRUE;
5734       (void)acl_check(ACL_WHERE_NOTSMTP_START, NULL, acl_not_smtp_start,
5735         &user_msg, &log_msg);
5736       f.enable_dollar_recipients = FALSE;
5737       }
5738
5739     /* Pause for a while waiting for input.  If none received in that time,
5740     close the logfile, if we had one open; then if we wait for a long-running
5741     datasource (months, in one use-case) log rotation will not leave us holding
5742     the file copy. */
5743
5744     if (!receive_timeout)
5745       {
5746       struct timeval t = { .tv_sec = 30*60, .tv_usec = 0 };     /* 30 minutes */
5747       fd_set r;
5748
5749       FD_ZERO(&r); FD_SET(0, &r);
5750       if (select(1, &r, NULL, NULL, &t) == 0) mainlog_close();
5751       }
5752
5753     /* Read the data for the message. If filter_test is not FTEST_NONE, this
5754     will just read the headers for the message, and not write anything onto the
5755     spool. */
5756
5757     message_ended = END_NOTENDED;
5758     more = receive_msg(extract_recipients);
5759
5760     /* more is always FALSE here (not SMTP message) when reading a message
5761     for real; when reading the headers of a message for filter testing,
5762     it is TRUE if the headers were terminated by '.' and FALSE otherwise. */
5763
5764     if (!message_id[0]) exim_exit(EXIT_FAILURE);
5765     }  /* Non-SMTP message reception */
5766
5767   /* If this is a filter testing run, there are headers in store, but
5768   no message on the spool. Run the filtering code in testing mode, setting
5769   the domain to the qualify domain and the local part to the current user,
5770   unless they have been set by options. The prefix and suffix are left unset
5771   unless specified. The the return path is set to to the sender unless it has
5772   already been set from a return-path header in the message. */
5773
5774   if (filter_test != FTEST_NONE)
5775     {
5776     deliver_domain = ftest_domain ? ftest_domain : qualify_domain_recipient;
5777     deliver_domain_orig = deliver_domain;
5778     deliver_localpart = ftest_localpart ? US ftest_localpart : originator_login;
5779     deliver_localpart_orig = deliver_localpart;
5780     deliver_localpart_prefix = US ftest_prefix;
5781     deliver_localpart_suffix = US ftest_suffix;
5782     deliver_home = originator_home;
5783
5784     if (!return_path)
5785       {
5786       printf("Return-path copied from sender\n");
5787       return_path = string_copy(sender_address);
5788       }
5789     else
5790       printf("Return-path = %s\n", (return_path[0] == 0)? US"<>" : return_path);
5791     printf("Sender      = %s\n", (sender_address[0] == 0)? US"<>" : sender_address);
5792
5793     receive_add_recipient(
5794       string_sprintf("%s%s%s@%s",
5795         ftest_prefix ? ftest_prefix : US"",
5796         deliver_localpart,
5797         ftest_suffix ? ftest_suffix : US"",
5798         deliver_domain), -1);
5799
5800     printf("Recipient   = %s\n", recipients_list[0].address);
5801     if (ftest_prefix) printf("Prefix    = %s\n", ftest_prefix);
5802     if (ftest_suffix) printf("Suffix    = %s\n", ftest_suffix);
5803
5804     if (chdir("/"))   /* Get away from wherever the user is running this from */
5805       {
5806       DEBUG(D_receive) debug_printf("chdir(\"/\") failed\n");
5807       exim_exit(EXIT_FAILURE);
5808       }
5809
5810     /* Now we run either a system filter test, or a user filter test, or both.
5811     In the latter case, headers added by the system filter will persist and be
5812     available to the user filter. We need to copy the filter variables
5813     explicitly. */
5814
5815     if (filter_test & FTEST_SYSTEM)
5816       if (!filter_runtest(filter_sfd, filter_test_sfile, TRUE, more))
5817         exim_exit(EXIT_FAILURE);
5818
5819     memcpy(filter_sn, filter_n, sizeof(filter_sn));
5820
5821     if (filter_test & FTEST_USER)
5822       if (!filter_runtest(filter_ufd, filter_test_ufile, FALSE, more))
5823         exim_exit(EXIT_FAILURE);
5824
5825     exim_exit(EXIT_SUCCESS);
5826     }
5827
5828   /* Else act on the result of message reception. We should not get here unless
5829   message_id[0] is non-zero. If queue_only is set, session_local_queue_only
5830   will be TRUE. If it is not, check on the number of messages received in this
5831   connection. */
5832
5833   if (  !session_local_queue_only
5834      && smtp_accept_queue_per_connection > 0
5835      && receive_messagecount > smtp_accept_queue_per_connection)
5836     {
5837     session_local_queue_only = TRUE;
5838     queue_only_reason = 2;
5839     }
5840
5841   /* Initialize local_queue_only from session_local_queue_only. If it is false,
5842   and queue_only_load is set, check that the load average is below it. If it is
5843   not, set local_queue_only TRUE. If queue_only_load_latch is true (the
5844   default), we put the whole session into queue_only mode. It then remains this
5845   way for any subsequent messages on the same SMTP connection. This is a
5846   deliberate choice; even though the load average may fall, it doesn't seem
5847   right to deliver later messages on the same call when not delivering earlier
5848   ones. However, there are odd cases where this is not wanted, so this can be
5849   changed by setting queue_only_load_latch false. */
5850
5851   if (!(local_queue_only = session_local_queue_only) && queue_only_load >= 0)
5852     if ((local_queue_only = (load_average = OS_GETLOADAVG()) > queue_only_load))
5853       {
5854       queue_only_reason = 3;
5855       if (queue_only_load_latch) session_local_queue_only = TRUE;
5856       }
5857
5858   /* If running as an MUA wrapper, all queueing options and freezing options
5859   are ignored. */
5860
5861   if (mua_wrapper)
5862     local_queue_only = f.queue_only_policy = f.deliver_freeze = FALSE;
5863
5864   /* Log the queueing here, when it will get a message id attached, but
5865   not if queue_only is set (case 0). Case 1 doesn't happen here (too many
5866   connections). */
5867
5868   if (local_queue_only)
5869     {
5870     cancel_cutthrough_connection(TRUE, US"no delivery; queueing");
5871     switch(queue_only_reason)
5872       {
5873       case 2:
5874         log_write(L_delay_delivery,
5875                 LOG_MAIN, "no immediate delivery: more than %d messages "
5876           "received in one connection", smtp_accept_queue_per_connection);
5877         break;
5878
5879       case 3:
5880         log_write(L_delay_delivery,
5881                 LOG_MAIN, "no immediate delivery: load average %.2f",
5882                 (double)load_average/1000.0);
5883       break;
5884       }
5885     }
5886
5887   else if (f.queue_only_policy || f.deliver_freeze)
5888     cancel_cutthrough_connection(TRUE, US"no delivery; queueing");
5889
5890   /* Else do the delivery unless the ACL or local_scan() called for queue only
5891   or froze the message. Always deliver in a separate process. A fork failure is
5892   not a disaster, as the delivery will eventually happen on a subsequent queue
5893   run. The search cache must be tidied before the fork, as the parent will
5894   do it before exiting. The child will trigger a lookup failure and
5895   thereby defer the delivery if it tries to use (for example) a cached ldap
5896   connection that the parent has called unbind on. */
5897
5898   else
5899     {
5900     pid_t pid;
5901     search_tidyup();
5902
5903     if ((pid = exim_fork(US"local-accept-delivery")) == 0)
5904       {
5905       int rc;
5906       close_unwanted();      /* Close unwanted file descriptors and TLS */
5907       exim_nullstd();        /* Ensure std{in,out,err} exist */
5908
5909       /* Re-exec Exim if we need to regain privilege (note: in mua_wrapper
5910       mode, deliver_drop_privilege is forced TRUE). */
5911
5912       if (geteuid() != root_uid && !deliver_drop_privilege && !unprivileged)
5913         {
5914         delivery_re_exec(CEE_EXEC_EXIT);
5915         /* Control does not return here. */
5916         }
5917
5918       /* No need to re-exec */
5919
5920       rc = deliver_message(message_id, FALSE, FALSE);
5921       search_tidyup();
5922       exim_underbar_exit(!mua_wrapper || rc == DELIVER_MUA_SUCCEEDED
5923         ? EXIT_SUCCESS : EXIT_FAILURE);
5924       }
5925
5926     if (pid < 0)
5927       {
5928       cancel_cutthrough_connection(TRUE, US"delivery fork failed");
5929       log_write(0, LOG_MAIN|LOG_PANIC, "failed to fork automatic delivery "
5930         "process: %s", strerror(errno));
5931       }
5932     else
5933       {
5934       release_cutthrough_connection(US"msg passed for delivery");
5935
5936       /* In the parent, wait if synchronous delivery is required. This will
5937       always be the case in MUA wrapper mode. */
5938
5939       if (f.synchronous_delivery)
5940         {
5941         int status;
5942         while (wait(&status) != pid);
5943         if ((status & 0x00ff) != 0)
5944           log_write(0, LOG_MAIN|LOG_PANIC,
5945             "process %d crashed with signal %d while delivering %s",
5946             (int)pid, status & 0x00ff, message_id);
5947         if (mua_wrapper && (status & 0xffff) != 0) exim_exit(EXIT_FAILURE);
5948         }
5949       }
5950     }
5951
5952   /* The loop will repeat if more is TRUE. If we do not know know that the OS
5953   automatically reaps children (see comments above the loop), clear away any
5954   finished subprocesses here, in case there are lots of messages coming in
5955   from the same source. */
5956
5957 #ifndef SIG_IGN_WORKS
5958   while (waitpid(-1, NULL, WNOHANG) > 0);
5959 #endif
5960
5961 MORELOOP:
5962   return_path = sender_address = NULL;
5963   authenticated_sender = NULL;
5964   deliver_localpart_orig = NULL;
5965   deliver_domain_orig = NULL;
5966   deliver_host = deliver_host_address = NULL;
5967   dnslist_domain = dnslist_matched = NULL;
5968 #ifdef WITH_CONTENT_SCAN
5969   malware_name = NULL;
5970 #endif
5971   callout_address = NULL;
5972   sending_ip_address = NULL;
5973   deliver_localpart_data = deliver_domain_data =
5974   recipient_data = sender_data = NULL;
5975   acl_var_m = NULL;
5976   for(int i = 0; i < REGEX_VARS; i++) regex_vars[i] = NULL;
5977
5978   store_reset(reset_point);
5979   }
5980
5981 exim_exit(EXIT_SUCCESS);   /* Never returns */
5982 return 0;                  /* To stop compiler warning */
5983 }
5984
5985
5986 /* End of exim.c */