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