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