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