1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* Copyright (c) The Exim Maintainers 2020 */
7 /* See the file NOTICE for conditions of use and distribution. */
10 /* The main function: entry point, initialization, and high-level control.
11 Also a few functions that don't naturally fit elsewhere. */
16 #if defined(__GLIBC__) && !defined(__UCLIBC__)
17 # include <gnu/libc-version.h>
21 # include <gnutls/gnutls.h>
22 # if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
31 extern void init_lookup_list(void);
35 /*************************************************
36 * Function interface to store functions *
37 *************************************************/
39 /* We need some real functions to pass to the PCRE regular expression library
40 for store allocation via Exim's store manager. The normal calls are actually
41 macros that pass over location information to make tracing easier. These
42 functions just interface to the standard macro calls. A good compiler will
43 optimize out the tail recursion and so not make them too expensive. There
44 are two sets of functions; one for use when we want to retain the compiled
45 regular expression for a long time; the other for short-term use. */
48 function_store_get(PCRE2_SIZE size, void * tag)
50 /* For now, regard all RE results as potentially tainted. We might need
51 more intelligence on this point. */
52 return store_get((int)size, TRUE);
56 function_dummy_free(void * block, void * tag) {}
59 function_store_malloc(PCRE2_SIZE size, void * tag)
61 return store_malloc((int)size);
65 function_store_free(void * block, void * tag)
73 /*************************************************
74 * Enums for cmdline interface *
75 *************************************************/
77 enum commandline_info { CMDINFO_NONE=0,
78 CMDINFO_HELP, CMDINFO_SIEVE, CMDINFO_DSCP };
83 /*************************************************
84 * Compile regular expression and panic on fail *
85 *************************************************/
87 /* This function is called when failure to compile a regular expression leads
88 to a panic exit. In other cases, pcre_compile() is called directly. In many
89 cases where this function is used, the results of the compilation are to be
90 placed in long-lived store, so we temporarily reset the store management
91 functions that PCRE uses if the use_malloc flag is set.
94 pattern the pattern to compile
95 caseless TRUE if caseless matching is required
96 use_malloc TRUE if compile into malloc store
98 Returns: pointer to the compiled pattern
102 regex_must_compile(const uschar * pattern, BOOL caseless, BOOL use_malloc)
105 int options = caseless ? PCRE_COPT|PCRE2_CASELESS : PCRE_COPT;
106 const pcre2_code * yield;
108 pcre2_general_context * gctx;
109 pcre2_compile_context * cctx;
113 gctx = pcre2_general_context_create(function_store_malloc, function_store_free, NULL);
114 cctx = pcre2_compile_context_create(gctx);
119 if (!(yield = pcre2_compile((PCRE2_SPTR)pattern, PCRE2_ZERO_TERMINATED, options,
120 &err, &offset, cctx)))
123 pcre2_get_error_message(err, errbuf, sizeof(errbuf));
124 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "regular expression error: "
125 "%s at offset %ld while compiling %s", errbuf, (long)offset, pattern);
130 pcre2_compile_context_free(cctx);
131 pcre2_general_context_free(gctx);
140 pcre_gen_ctx = pcre2_general_context_create(function_store_malloc, function_store_free, NULL);
141 pcre_cmp_ctx = pcre2_compile_context_create(pcre_gen_ctx);
142 pcre_mtc_ctx = pcre2_match_context_create(pcre_gen_ctx);
148 /*************************************************
149 * Execute regular expression and set strings *
150 *************************************************/
152 /* This function runs a regular expression match, and sets up the pointers to
153 the matched substrings. The matched strings are copied so the lifetime of
154 the subject is not a problem.
157 re the compiled expression
158 subject the subject string
159 options additional PCRE options
160 setup if < 0 do full setup
161 if >= 0 setup from setup+1 onwards,
162 excluding the full matched string
164 Returns: TRUE if matched, or FALSE
168 regex_match_and_setup(const pcre2_code * re, const uschar * subject, int options, int setup)
170 pcre2_match_data * md = pcre2_match_data_create_from_pattern(re, pcre_gen_ctx);
171 int res = pcre2_match(re, (PCRE2_SPTR)subject, PCRE2_ZERO_TERMINATED, 0,
172 PCRE_EOPT | options, md, pcre_mtc_ctx);
175 if ((yield = (res >= 0)))
177 res = pcre2_get_ovector_count(md);
178 expand_nmax = setup < 0 ? 0 : setup + 1;
179 for (int matchnum = setup < 0 ? 0 : 1; matchnum < res; matchnum++)
182 pcre2_substring_get_bynumber(md, matchnum,
183 (PCRE2_UCHAR **)&expand_nstring[expand_nmax], &len);
184 expand_nlength[expand_nmax++] = (int)len;
188 else if (res != PCRE2_ERROR_NOMATCH) DEBUG(D_any)
191 pcre2_get_error_message(res, errbuf, sizeof(errbuf));
192 debug_printf_indent("pcre2: %s\n", errbuf);
194 pcre2_match_data_free(md);
199 /* Check just for match with regex. Uses the common memory-handling.
203 subject string to be checked
204 slen length of subject; -1 for nul-terminated
205 rptr pointer for matched string, copied, or NULL
207 Return: TRUE for a match.
211 regex_match(const pcre2_code * re, const uschar * subject, int slen, uschar ** rptr)
213 pcre2_match_data * md = pcre2_match_data_create(1, pcre_gen_ctx);
214 int rc = pcre2_match(re, (PCRE2_SPTR)subject,
215 slen >= 0 ? slen : PCRE2_ZERO_TERMINATED,
216 0, PCRE_EOPT, md, pcre_mtc_ctx);
217 PCRE2_SIZE * ovec = pcre2_get_ovector_pointer(md);
221 *rptr = string_copyn(subject + ovec[0], ovec[1] - ovec[0]);
227 /*************************************************
228 * Set up processing details *
229 *************************************************/
231 /* Save a text string for dumping when SIGUSR1 is received.
232 Do checks for overruns.
234 Arguments: format and arguments, as for printf()
239 set_process_info(const char *format, ...)
241 gstring gs = { .size = PROCESS_INFO_SIZE - 2, .ptr = 0, .s = process_info };
246 g = string_fmt_append(&gs, "%5d ", (int)getpid());
248 va_start(ap, format);
249 if (!string_vformat(g, 0, format, ap))
252 g = string_cat(&gs, US"**** string overflowed buffer ****");
254 g = string_catn(g, US"\n", 1);
255 string_from_gstring(g);
256 process_info_len = g->ptr;
257 DEBUG(D_process_info) debug_printf("set_process_info: %s", process_info);
261 /***********************************************
262 * Handler for SIGTERM *
263 ***********************************************/
266 term_handler(int sig)
272 /***********************************************
273 * Handler for SIGSEGV *
274 ***********************************************/
277 segv_handler(int sig)
279 log_write(0, LOG_MAIN|LOG_PANIC, "SIGSEGV (maybe attempt to write to immutable memory)");
280 signal(SIGSEGV, SIG_DFL);
285 /*************************************************
286 * Handler for SIGUSR1 *
287 *************************************************/
289 /* SIGUSR1 causes any exim process to write to the process log details of
290 what it is currently doing. It will only be used if the OS is capable of
291 setting up a handler that causes automatic restarting of any system call
292 that is in progress at the time.
294 This function takes care to be signal-safe.
296 Argument: the signal number (SIGUSR1)
301 usr1_handler(int sig)
305 os_restarting_signal(sig, usr1_handler);
307 if (!process_log_path) return;
308 fd = log_open_as_exim(process_log_path);
310 /* If we are neither exim nor root, or if we failed to create the log file,
311 give up. There is not much useful we can do with errors, since we don't want
312 to disrupt whatever is going on outside the signal handler. */
316 (void)write(fd, process_info, process_info_len);
322 /*************************************************
324 *************************************************/
326 /* This handler is enabled most of the time that Exim is running. The handler
327 doesn't actually get used unless alarm() has been called to set a timer, to
328 place a time limit on a system call of some kind. When the handler is run, it
331 There are some other SIGALRM handlers that are used in special cases when more
332 than just a flag setting is required; for example, when reading a message's
333 input. These are normally set up in the code module that uses them, and the
334 SIGALRM handler is reset to this one afterwards.
336 Argument: the signal value (SIGALRM)
341 sigalrm_handler(int sig)
344 os_non_restarting_signal(SIGALRM, sigalrm_handler);
349 /*************************************************
350 * Sleep for a fractional time interval *
351 *************************************************/
353 /* This function is called by millisleep() and exim_wait_tick() to wait for a
354 period of time that may include a fraction of a second. The coding is somewhat
355 tedious. We do not expect setitimer() ever to fail, but if it does, the process
356 will wait for ever, so we panic in this instance. (There was a case of this
357 when a bug in a function that calls milliwait() caused it to pass invalid data.
358 That's when I added the check. :-)
360 We assume it to be not worth sleeping for under 50us; this value will
361 require revisiting as hardware advances. This avoids the issue of
362 a zero-valued timer setting meaning "never fire".
364 Argument: an itimerval structure containing the interval
369 milliwait(struct itimerval *itval)
372 sigset_t old_sigmask;
373 int save_errno = errno;
375 if (itval->it_value.tv_usec < 50 && itval->it_value.tv_sec == 0)
377 (void)sigemptyset(&sigmask); /* Empty mask */
378 (void)sigaddset(&sigmask, SIGALRM); /* Add SIGALRM */
379 (void)sigprocmask(SIG_BLOCK, &sigmask, &old_sigmask); /* Block SIGALRM */
380 if (setitimer(ITIMER_REAL, itval, NULL) < 0) /* Start timer */
381 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
382 "setitimer() failed: %s", strerror(errno));
383 (void)sigfillset(&sigmask); /* All signals */
384 (void)sigdelset(&sigmask, SIGALRM); /* Remove SIGALRM */
385 (void)sigsuspend(&sigmask); /* Until SIGALRM */
386 (void)sigprocmask(SIG_SETMASK, &old_sigmask, NULL); /* Restore mask */
388 sigalrm_seen = FALSE;
394 /*************************************************
395 * Millisecond sleep function *
396 *************************************************/
398 /* The basic sleep() function has a granularity of 1 second, which is too rough
399 in some cases - for example, when using an increasing delay to slow down
402 Argument: number of millseconds
409 struct itimerval itval = {.it_interval = {.tv_sec = 0, .tv_usec = 0},
410 .it_value = {.tv_sec = msec/1000,
411 .tv_usec = (msec % 1000) * 1000}};
417 /*************************************************
418 * Compare microsecond times *
419 *************************************************/
426 Returns: -1, 0, or +1
430 exim_tvcmp(struct timeval *t1, struct timeval *t2)
432 if (t1->tv_sec > t2->tv_sec) return +1;
433 if (t1->tv_sec < t2->tv_sec) return -1;
434 if (t1->tv_usec > t2->tv_usec) return +1;
435 if (t1->tv_usec < t2->tv_usec) return -1;
442 /*************************************************
443 * Clock tick wait function *
444 *************************************************/
446 #ifdef _POSIX_MONOTONIC_CLOCK
447 # ifdef CLOCK_BOOTTIME
448 # define EXIM_CLOCKTYPE CLOCK_BOOTTIME
450 # define EXIM_CLOCKTYPE CLOCK_MONOTONIC
453 /* Amount EXIM_CLOCK is behind realtime, at startup. */
454 static struct timespec offset_ts;
457 exim_clock_init(void)
460 if (clock_gettime(EXIM_CLOCKTYPE, &offset_ts) != 0) return;
461 (void)gettimeofday(&tv, NULL);
462 offset_ts.tv_sec = tv.tv_sec - offset_ts.tv_sec;
463 offset_ts.tv_nsec = tv.tv_usec * 1000 - offset_ts.tv_nsec;
464 if (offset_ts.tv_nsec >= 0) return;
466 offset_ts.tv_nsec += 1000*1000*1000;
472 exim_gettime(struct timeval * tv)
474 #ifdef _POSIX_MONOTONIC_CLOCK
475 struct timespec now_ts;
477 if (clock_gettime(EXIM_CLOCKTYPE, &now_ts) == 0)
479 now_ts.tv_sec += offset_ts.tv_sec;
480 if ((now_ts.tv_nsec += offset_ts.tv_nsec) >= 1000*1000*1000)
483 now_ts.tv_nsec -= 1000*1000*1000;
485 tv->tv_sec = now_ts.tv_sec;
486 tv->tv_usec = now_ts.tv_nsec / 1000;
490 (void)gettimeofday(tv, NULL);
494 /* Exim uses a time + a pid to generate a unique identifier in two places: its
495 message IDs, and in file names for maildir deliveries. Because some OS now
496 re-use pids within the same second, sub-second times are now being used.
497 However, for absolute certainty, we must ensure the clock has ticked before
498 allowing the relevant process to complete. At the time of implementation of
499 this code (February 2003), the speed of processors is such that the clock will
500 invariably have ticked already by the time a process has done its job. This
501 function prepares for the time when things are faster - and it also copes with
502 clocks that go backwards.
505 prev_tv A timeval which was used to create uniqueness; its usec field
506 has been rounded down to the value of the resolution.
507 We want to be sure the current time is greater than this.
508 On return, updated to current (rounded down).
509 resolution The resolution that was used to divide the microseconds
510 (1 for maildir, larger for message ids)
516 exim_wait_tick(struct timeval * prev_tv, int resolution)
518 struct timeval now_tv;
519 long int now_true_usec;
521 exim_gettime(&now_tv);
522 now_true_usec = now_tv.tv_usec;
523 now_tv.tv_usec = (now_true_usec/resolution) * resolution;
525 while (exim_tvcmp(&now_tv, prev_tv) <= 0)
527 struct itimerval itval;
528 itval.it_interval.tv_sec = 0;
529 itval.it_interval.tv_usec = 0;
530 itval.it_value.tv_sec = prev_tv->tv_sec - now_tv.tv_sec;
531 itval.it_value.tv_usec = prev_tv->tv_usec + resolution - now_true_usec;
533 /* We know that, overall, "now" is less than or equal to "then". Therefore, a
534 negative value for the microseconds is possible only in the case when "now"
535 is more than a second less than "tgt". That means that itval.it_value.tv_sec
536 is greater than zero. The following correction is therefore safe. */
538 if (itval.it_value.tv_usec < 0)
540 itval.it_value.tv_usec += 1000000;
541 itval.it_value.tv_sec -= 1;
544 DEBUG(D_transport|D_receive)
546 if (!f.running_in_test_harness)
548 debug_printf("tick check: " TIME_T_FMT ".%06lu " TIME_T_FMT ".%06lu\n",
549 prev_tv->tv_sec, (long) prev_tv->tv_usec,
550 now_tv.tv_sec, (long) now_tv.tv_usec);
551 debug_printf("waiting " TIME_T_FMT ".%06lu sec\n",
552 itval.it_value.tv_sec, (long) itval.it_value.tv_usec);
558 /* Be prapared to go around if the kernel does not implement subtick
559 granularity (GNU Hurd) */
561 exim_gettime(&now_tv);
562 now_true_usec = now_tv.tv_usec;
563 now_tv.tv_usec = (now_true_usec/resolution) * resolution;
571 /*************************************************
572 * Call fopen() with umask 777 and adjust mode *
573 *************************************************/
575 /* Exim runs with umask(0) so that files created with open() have the mode that
576 is specified in the open() call. However, there are some files, typically in
577 the spool directory, that are created with fopen(). They end up world-writeable
578 if no precautions are taken. Although the spool directory is not accessible to
579 the world, this is an untidiness. So this is a wrapper function for fopen()
580 that sorts out the mode of the created file.
583 filename the file name
584 options the fopen() options
585 mode the required mode
587 Returns: the fopened FILE or NULL
591 modefopen(const uschar *filename, const char *options, mode_t mode)
593 mode_t saved_umask = umask(0777);
594 FILE *f = Ufopen(filename, options);
595 (void)umask(saved_umask);
596 if (f != NULL) (void)fchmod(fileno(f), mode);
601 /*************************************************
602 * Ensure stdin, stdout, and stderr exist *
603 *************************************************/
605 /* Some operating systems grumble if an exec() happens without a standard
606 input, output, and error (fds 0, 1, 2) being defined. The worry is that some
607 file will be opened and will use these fd values, and then some other bit of
608 code will assume, for example, that it can write error messages to stderr.
609 This function ensures that fds 0, 1, and 2 are open if they do not already
610 exist, by connecting them to /dev/null.
612 This function is also used to ensure that std{in,out,err} exist at all times,
613 so that if any library that Exim calls tries to use them, it doesn't crash.
624 for (int i = 0; i <= 2; i++)
626 if (fstat(i, &statbuf) < 0 && errno == EBADF)
628 if (devnull < 0) devnull = open("/dev/null", O_RDWR);
629 if (devnull < 0) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s",
630 string_open_failed("/dev/null", NULL));
631 if (devnull != i) (void)dup2(devnull, i);
634 if (devnull > 2) (void)close(devnull);
640 /*************************************************
641 * Close unwanted file descriptors for delivery *
642 *************************************************/
644 /* This function is called from a new process that has been forked to deliver
645 an incoming message, either directly, or using exec.
647 We want any smtp input streams to be closed in this new process. However, it
648 has been observed that using fclose() here causes trouble. When reading in -bS
649 input, duplicate copies of messages have been seen. The files will be sharing a
650 file pointer with the parent process, and it seems that fclose() (at least on
651 some systems - I saw this on Solaris 2.5.1) messes with that file pointer, at
652 least sometimes. Hence we go for closing the underlying file descriptors.
654 If TLS is active, we want to shut down the TLS library, but without molesting
655 the parent's SSL connection.
657 For delivery of a non-SMTP message, we want to close stdin and stdout (and
658 stderr unless debugging) because the calling process might have set them up as
659 pipes and be waiting for them to close before it waits for the submission
660 process to terminate. If they aren't closed, they hold up the calling process
661 until the initial delivery process finishes, which is not what we want.
663 Exception: We do want it for synchronous delivery!
665 And notwithstanding all the above, if D_resolver is set, implying resolver
666 debugging, leave stdout open, because that's where the resolver writes its
669 When we close stderr (which implies we've also closed stdout), we also get rid
670 of any controlling terminal.
682 tls_close(NULL, TLS_NO_SHUTDOWN); /* Shut down the TLS library */
684 (void)close(fileno(smtp_in));
685 (void)close(fileno(smtp_out));
690 (void)close(0); /* stdin */
691 if ((debug_selector & D_resolver) == 0) (void)close(1); /* stdout */
692 if (debug_selector == 0) /* stderr */
694 if (!f.synchronous_delivery)
707 /*************************************************
709 *************************************************/
711 /* This function sets a new uid and gid permanently, optionally calling
712 initgroups() to set auxiliary groups. There are some special cases when running
713 Exim in unprivileged modes. In these situations the effective uid will not be
714 root; if we already have the right effective uid/gid, and don't need to
715 initialize any groups, leave things as they are.
720 igflag TRUE if initgroups() wanted
721 msg text to use in debugging output and failure log
723 Returns: nothing; bombs out on failure
727 exim_setugid(uid_t uid, gid_t gid, BOOL igflag, uschar *msg)
729 uid_t euid = geteuid();
730 gid_t egid = getegid();
732 if (euid == root_uid || euid != uid || egid != gid || igflag)
734 /* At least one OS returns +1 for initgroups failure, so just check for
739 struct passwd *pw = getpwuid(uid);
741 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "cannot run initgroups(): "
742 "no passwd entry for uid=%ld", (long int)uid);
744 if (initgroups(pw->pw_name, gid) != 0)
745 log_write(0,LOG_MAIN|LOG_PANIC_DIE,"initgroups failed for uid=%ld: %s",
746 (long int)uid, strerror(errno));
749 if (setgid(gid) < 0 || setuid(uid) < 0)
750 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "unable to set gid=%ld or uid=%ld "
751 "(euid=%ld): %s", (long int)gid, (long int)uid, (long int)euid, msg);
754 /* Debugging output included uid/gid and all groups */
758 int group_count, save_errno;
759 gid_t group_list[EXIM_GROUPLIST_SIZE];
760 debug_printf("changed uid/gid: %s\n uid=%ld gid=%ld pid=%ld\n", msg,
761 (long int)geteuid(), (long int)getegid(), (long int)getpid());
762 group_count = getgroups(nelem(group_list), group_list);
764 debug_printf(" auxiliary group list:");
766 for (int i = 0; i < group_count; i++) debug_printf(" %d", (int)group_list[i]);
767 else if (group_count < 0)
768 debug_printf(" <error: %s>", strerror(save_errno));
769 else debug_printf(" <none>");
777 /*************************************************
779 *************************************************/
781 /* Exim exits via this function so that it always clears up any open
787 Returns: does not return
796 debug_printf(">>>>>>>>>>>>>>>> Exim pid=%d (%s) terminating with rc=%d "
797 ">>>>>>>>>>>>>>>>\n",
798 (int)getpid(), process_purpose, rc);
804 exim_underbar_exit(int rc)
808 debug_printf(">>>>>>>>>>>>>>>> Exim pid=%d (%s) terminating with rc=%d "
809 ">>>>>>>>>>>>>>>>\n",
810 (int)getpid(), process_purpose, rc);
816 /* Print error string, then die */
818 exim_fail(const char * fmt, ...)
822 vfprintf(stderr, fmt, ap);
826 /* fail if a length is too long */
828 exim_len_fail_toolong(int itemlen, int maxlen, const char *description)
830 if (itemlen <= maxlen)
832 fprintf(stderr, "exim: length limit exceeded (%d > %d) for: %s\n",
833 itemlen, maxlen, description);
837 /* only pass through the string item back to the caller if it's short enough */
838 static inline const uschar *
839 exim_str_fail_toolong(const uschar *item, int maxlen, const char *description)
841 exim_len_fail_toolong(Ustrlen(item), maxlen, description);
845 /* exim_chown_failure() called from exim_chown()/exim_fchown() on failure
846 of chown()/fchown(). See src/functions.h for more explanation */
848 exim_chown_failure(int fd, const uschar *name, uid_t owner, gid_t group)
850 int saved_errno = errno; /* from the preceeding chown call */
852 log_write(0, LOG_MAIN|LOG_PANIC,
853 __FILE__ ":%d: chown(%s, %d:%d) failed (%s)."
854 " Please contact the authors and refer to https://bugs.exim.org/show_bug.cgi?id=2391",
855 __LINE__, name?name:US"<unknown>", owner, group, strerror(errno));
857 /* I leave this here, commented, in case the "bug"(?) comes up again.
858 It is not an Exim bug, but we can provide a workaround.
864 if (0 == (fd < 0 ? stat(name, &buf) : fstat(fd, &buf)))
866 if (buf.st_uid == owner && buf.st_gid == group) return 0;
867 log_write(0, LOG_MAIN|LOG_PANIC, "Wrong ownership on %s", name);
869 else log_write(0, LOG_MAIN|LOG_PANIC, "Stat failed on %s: %s", name, strerror(errno));
877 /*************************************************
878 * Extract port from host address *
879 *************************************************/
881 /* Called to extract the port from the values given to -oMa and -oMi.
882 It also checks the syntax of the address, and terminates it before the
883 port data when a port is extracted.
886 address the address, with possible port on the end
888 Returns: the port, or zero if there isn't one
889 bombs out on a syntax error
893 check_port(uschar *address)
895 int port = host_address_extract_port(address);
896 if (string_is_ip_address(address, NULL) == 0)
897 exim_fail("exim abandoned: \"%s\" is not an IP address\n", address);
903 /*************************************************
904 * Test/verify an address *
905 *************************************************/
907 /* This function is called by the -bv and -bt code. It extracts a working
908 address from a full RFC 822 address. This isn't really necessary per se, but it
909 has the effect of collapsing source routes.
913 flags flag bits for verify_address()
914 exit_value to be set for failures
920 test_address(uschar *s, int flags, int *exit_value)
922 int start, end, domain;
923 uschar *parse_error = NULL;
924 uschar *address = parse_extract_address(s, &parse_error, &start, &end, &domain,
928 fprintf(stdout, "syntax error: %s\n", parse_error);
933 int rc = verify_address(deliver_make_addr(address,TRUE), stdout, flags, -1,
934 -1, -1, NULL, NULL, NULL);
935 if (rc == FAIL) *exit_value = 2;
936 else if (rc == DEFER && *exit_value == 0) *exit_value = 1;
942 /*************************************************
943 * Show supported features *
944 *************************************************/
947 show_db_version(FILE * f)
949 #ifdef DB_VERSION_STRING
952 fprintf(f, "Library version: BDB: Compile: %s\n", DB_VERSION_STRING);
953 fprintf(f, " Runtime: %s\n",
954 db_version(NULL, NULL, NULL));
957 fprintf(f, "Berkeley DB: %s\n", DB_VERSION_STRING);
959 #elif defined(BTREEVERSION) && defined(HASHVERSION)
961 fprintf(f, "Probably Berkeley DB version 1.8x (native mode)\n");
963 fprintf(f, "Probably Berkeley DB version 1.8x (compatibility mode)\n");
966 #elif defined(_DBM_RDONLY) || defined(dbm_dirfno)
967 fprintf(f, "Probably ndbm\n");
968 #elif defined(USE_TDB)
969 fprintf(f, "Using tdb\n");
972 fprintf(f, "Probably GDBM (native mode)\n");
974 fprintf(f, "Probably GDBM (compatibility mode)\n");
980 /* This function is called for -bV/--version and for -d to output the optional
981 features of the current Exim binary.
983 Arguments: a FILE for printing
988 show_whats_supported(FILE * fp)
990 rmark reset_point = store_mark();
992 DEBUG(D_any) {} else show_db_version(fp);
994 g = string_cat(NULL, US"Support for:");
995 #ifdef SUPPORT_CRYPTEQ
996 g = string_cat(g, US" crypteq");
999 g = string_cat(g, US" iconv()");
1002 g = string_cat(g, US" IPv6");
1004 #ifdef HAVE_SETCLASSRESOURCES
1005 g = string_cat(g, US" use_setclassresources");
1008 g = string_cat(g, US" PAM");
1011 g = string_cat(g, US" Perl");
1013 #ifdef EXPAND_DLFUNC
1014 g = string_cat(g, US" Expand_dlfunc");
1016 #ifdef USE_TCP_WRAPPERS
1017 g = string_cat(g, US" TCPwrappers");
1020 g = string_cat(g, US" GnuTLS");
1023 g = string_cat(g, US" OpenSSL");
1025 #ifndef DISABLE_TLS_RESUME
1026 g = string_cat(g, US" TLS_resume");
1028 #ifdef SUPPORT_TRANSLATE_IP_ADDRESS
1029 g = string_cat(g, US" translate_ip_address");
1031 #ifdef SUPPORT_MOVE_FROZEN_MESSAGES
1032 g = string_cat(g, US" move_frozen_messages");
1034 #ifdef WITH_CONTENT_SCAN
1035 g = string_cat(g, US" Content_Scanning");
1038 g = string_cat(g, US" DANE");
1040 #ifndef DISABLE_DKIM
1041 g = string_cat(g, US" DKIM");
1043 #ifdef SUPPORT_DMARC
1044 g = string_cat(g, US" DMARC");
1046 #ifndef DISABLE_DNSSEC
1047 g = string_cat(g, US" DNSSEC");
1049 #ifndef DISABLE_EVENT
1050 g = string_cat(g, US" Event");
1053 g = string_cat(g, US" I18N");
1055 #ifndef DISABLE_OCSP
1056 g = string_cat(g, US" OCSP");
1058 #ifndef DISABLE_PIPE_CONNECT
1059 g = string_cat(g, US" PIPE_CONNECT");
1061 #ifndef DISABLE_PRDR
1062 g = string_cat(g, US" PRDR");
1064 #ifdef SUPPORT_PROXY
1065 g = string_cat(g, US" PROXY");
1067 #ifndef DISABLE_QUEUE_RAMP
1068 g = string_cat(g, US" Experimental_Queue_Ramp");
1070 #ifdef SUPPORT_SOCKS
1071 g = string_cat(g, US" SOCKS");
1074 g = string_cat(g, US" SPF");
1076 #if defined(SUPPORT_SRS)
1077 g = string_cat(g, US" SRS");
1081 if (f.tcp_fastopen_ok) g = string_cat(g, US" TCP_Fast_Open");
1083 #ifdef EXPERIMENTAL_ARC
1084 g = string_cat(g, US" Experimental_ARC");
1086 #ifdef EXPERIMENTAL_BRIGHTMAIL
1087 g = string_cat(g, US" Experimental_Brightmail");
1089 #ifdef EXPERIMENTAL_DCC
1090 g = string_cat(g, US" Experimental_DCC");
1092 #ifdef EXPERIMENTAL_DSN_INFO
1093 g = string_cat(g, US" Experimental_DSN_info");
1095 #ifdef EXPERIMENTAL_ESMTP_LIMITS
1096 g = string_cat(g, US" Experimental_ESMTP_Limits");
1098 #ifdef EXPERIMENTAL_QUEUEFILE
1099 g = string_cat(g, US" Experimental_QUEUEFILE");
1101 #if defined(EXPERIMENTAL_SRS_ALT)
1102 g = string_cat(g, US" Experimental_SRS");
1104 g = string_cat(g, US"\n");
1106 g = string_cat(g, US"Lookups (built-in):");
1107 #if defined(LOOKUP_LSEARCH) && LOOKUP_LSEARCH!=2
1108 g = string_cat(g, US" lsearch wildlsearch nwildlsearch iplsearch");
1110 #if defined(LOOKUP_CDB) && LOOKUP_CDB!=2
1111 g = string_cat(g, US" cdb");
1113 #if defined(LOOKUP_DBM) && LOOKUP_DBM!=2
1114 g = string_cat(g, US" dbm dbmjz dbmnz");
1116 #if defined(LOOKUP_DNSDB) && LOOKUP_DNSDB!=2
1117 g = string_cat(g, US" dnsdb");
1119 #if defined(LOOKUP_DSEARCH) && LOOKUP_DSEARCH!=2
1120 g = string_cat(g, US" dsearch");
1122 #if defined(LOOKUP_IBASE) && LOOKUP_IBASE!=2
1123 g = string_cat(g, US" ibase");
1125 #if defined(LOOKUP_JSON) && LOOKUP_JSON!=2
1126 g = string_cat(g, US" json");
1128 #if defined(LOOKUP_LDAP) && LOOKUP_LDAP!=2
1129 g = string_cat(g, US" ldap ldapdn ldapm");
1132 g = string_cat(g, US" lmdb");
1134 #if defined(LOOKUP_MYSQL) && LOOKUP_MYSQL!=2
1135 g = string_cat(g, US" mysql");
1137 #if defined(LOOKUP_NIS) && LOOKUP_NIS!=2
1138 g = string_cat(g, US" nis nis0");
1140 #if defined(LOOKUP_NISPLUS) && LOOKUP_NISPLUS!=2
1141 g = string_cat(g, US" nisplus");
1143 #if defined(LOOKUP_ORACLE) && LOOKUP_ORACLE!=2
1144 g = string_cat(g, US" oracle");
1146 #if defined(LOOKUP_PASSWD) && LOOKUP_PASSWD!=2
1147 g = string_cat(g, US" passwd");
1149 #if defined(LOOKUP_PGSQL) && LOOKUP_PGSQL!=2
1150 g = string_cat(g, US" pgsql");
1152 #if defined(LOOKUP_REDIS) && LOOKUP_REDIS!=2
1153 g = string_cat(g, US" redis");
1155 #if defined(LOOKUP_SQLITE) && LOOKUP_SQLITE!=2
1156 g = string_cat(g, US" sqlite");
1158 #if defined(LOOKUP_TESTDB) && LOOKUP_TESTDB!=2
1159 g = string_cat(g, US" testdb");
1161 #if defined(LOOKUP_WHOSON) && LOOKUP_WHOSON!=2
1162 g = string_cat(g, US" whoson");
1164 g = string_cat(g, US"\n");
1166 g = auth_show_supported(g);
1167 g = route_show_supported(g);
1168 g = transport_show_supported(g);
1170 #ifdef WITH_CONTENT_SCAN
1171 g = malware_show_supported(g);
1174 if (fixed_never_users[0] > 0)
1177 g = string_cat(g, US"Fixed never_users: ");
1178 for (i = 1; i <= (int)fixed_never_users[0] - 1; i++)
1179 string_fmt_append(g, "%u:", (unsigned)fixed_never_users[i]);
1180 g = string_fmt_append(g, "%u\n", (unsigned)fixed_never_users[i]);
1183 g = string_fmt_append(g, "Configure owner: %d:%d\n", config_uid, config_gid);
1184 fputs(CS string_from_gstring(g), fp);
1186 fprintf(fp, "Size of off_t: " SIZE_T_FMT "\n", sizeof(off_t));
1188 /* Everything else is details which are only worth reporting when debugging.
1189 Perhaps the tls_version_report should move into this too. */
1192 /* clang defines __GNUC__ (at least, for me) so test for it first */
1193 #if defined(__clang__)
1194 fprintf(fp, "Compiler: CLang [%s]\n", __clang_version__);
1195 #elif defined(__GNUC__)
1196 fprintf(fp, "Compiler: GCC [%s]\n",
1200 "? unknown version ?"
1204 fprintf(fp, "Compiler: <unknown>\n");
1207 #if defined(__GLIBC__) && !defined(__UCLIBC__)
1208 fprintf(fp, "Library version: Glibc: Compile: %d.%d\n",
1209 __GLIBC__, __GLIBC_MINOR__);
1210 if (__GLIBC_PREREQ(2, 1))
1211 fprintf(fp, " Runtime: %s\n",
1212 gnu_get_libc_version());
1215 show_db_version(fp);
1218 tls_version_report(fp);
1221 utf8_version_report(fp);
1223 #ifdef SUPPORT_DMARC
1224 dmarc_version_report(fp);
1227 spf_lib_version_report(fp);
1230 for (auth_info * authi = auths_available; *authi->driver_name != '\0'; ++authi)
1231 if (authi->version_report)
1232 (*authi->version_report)(fp);
1234 /* PCRE_PRERELEASE is either defined and empty or a bare sequence of
1235 characters; unless it's an ancient version of PCRE in which case it
1237 #ifndef PCRE_PRERELEASE
1238 # define PCRE_PRERELEASE
1241 #define EXPAND_AND_QUOTE(X) QUOTE(X)
1244 pcre2_config(PCRE2_CONFIG_VERSION, buf);
1245 fprintf(fp, "Library version: PCRE2: Compile: %d.%d%s\n"
1247 PCRE2_MAJOR, PCRE2_MINOR,
1248 EXPAND_AND_QUOTE(PCRE2_PRERELEASE) "",
1252 #undef EXPAND_AND_QUOTE
1255 for (int i = 0; i < lookup_list_count; i++)
1256 if (lookup_list[i]->version_report)
1257 lookup_list[i]->version_report(fp);
1259 #ifdef WHITELIST_D_MACROS
1260 fprintf(fp, "WHITELIST_D_MACROS: \"%s\"\n", WHITELIST_D_MACROS);
1262 fprintf(fp, "WHITELIST_D_MACROS unset\n");
1264 #ifdef TRUSTED_CONFIG_LIST
1265 fprintf(fp, "TRUSTED_CONFIG_LIST: \"%s\"\n", TRUSTED_CONFIG_LIST);
1267 fprintf(fp, "TRUSTED_CONFIG_LIST unset\n");
1271 store_reset(reset_point);
1275 /*************************************************
1276 * Show auxiliary information about Exim *
1277 *************************************************/
1280 show_exim_information(enum commandline_info request, FILE *stream)
1285 fprintf(stream, "Oops, something went wrong.\n");
1289 "The -bI: flag takes a string indicating which information to provide.\n"
1290 "If the string is not recognised, you'll get this help (on stderr).\n"
1292 " exim -bI:help this information\n"
1293 " exim -bI:dscp list of known dscp value keywords\n"
1294 " exim -bI:sieve list of supported sieve extensions\n"
1298 for (const uschar ** pp = exim_sieve_extension_list; *pp; ++pp)
1299 fprintf(stream, "%s\n", *pp);
1302 dscp_list_to_stream(stream);
1308 /*************************************************
1309 * Quote a local part *
1310 *************************************************/
1312 /* This function is used when a sender address or a From: or Sender: header
1313 line is being created from the caller's login, or from an authenticated_id. It
1314 applies appropriate quoting rules for a local part.
1316 Argument: the local part
1317 Returns: the local part, quoted if necessary
1321 local_part_quote(uschar *lpart)
1323 BOOL needs_quote = FALSE;
1326 for (uschar * t = lpart; !needs_quote && *t != 0; t++)
1328 needs_quote = !isalnum(*t) && strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL &&
1329 (*t != '.' || t == lpart || t[1] == 0);
1332 if (!needs_quote) return lpart;
1334 g = string_catn(NULL, US"\"", 1);
1338 uschar *nq = US Ustrpbrk(lpart, "\\\"");
1341 g = string_cat(g, lpart);
1344 g = string_catn(g, lpart, nq - lpart);
1345 g = string_catn(g, US"\\", 1);
1346 g = string_catn(g, nq, 1);
1350 g = string_catn(g, US"\"", 1);
1351 return string_from_gstring(g);
1357 /*************************************************
1358 * Load readline() functions *
1359 *************************************************/
1361 /* This function is called from testing executions that read data from stdin,
1362 but only when running as the calling user. Currently, only -be does this. The
1363 function loads the readline() function library and passes back the functions.
1364 On some systems, it needs the curses library, so load that too, but try without
1365 it if loading fails. All this functionality has to be requested at build time.
1368 fn_readline_ptr pointer to where to put the readline pointer
1369 fn_addhist_ptr pointer to where to put the addhistory function
1371 Returns: the dlopen handle or NULL on failure
1375 set_readline(char * (**fn_readline_ptr)(const char *),
1376 void (**fn_addhist_ptr)(const char *))
1379 void *dlhandle_curses = dlopen("libcurses." DYNLIB_FN_EXT, RTLD_GLOBAL|RTLD_LAZY);
1381 dlhandle = dlopen("libreadline." DYNLIB_FN_EXT, RTLD_GLOBAL|RTLD_NOW);
1382 if (dlhandle_curses) dlclose(dlhandle_curses);
1386 /* Checked manual pages; at least in GNU Readline 6.1, the prototypes are:
1387 * char * readline (const char *prompt);
1388 * void add_history (const char *string);
1390 *fn_readline_ptr = (char *(*)(const char*))dlsym(dlhandle, "readline");
1391 *fn_addhist_ptr = (void(*)(const char*))dlsym(dlhandle, "add_history");
1394 DEBUG(D_any) debug_printf("failed to load readline: %s\n", dlerror());
1402 /*************************************************
1403 * Get a line from stdin for testing things *
1404 *************************************************/
1406 /* This function is called when running tests that can take a number of lines
1407 of input (for example, -be and -bt). It handles continuations and trailing
1408 spaces. And prompting and a blank line output on eof. If readline() is in use,
1409 the arguments are non-NULL and provide the relevant functions.
1412 fn_readline readline function or NULL
1413 fn_addhist addhist function or NULL
1415 Returns: pointer to dynamic memory, or NULL at end of file
1419 get_stdinput(char *(*fn_readline)(const char *), void(*fn_addhist)(const char *))
1423 if (!fn_readline) { printf("> "); fflush(stdout); }
1425 for (int i = 0;; i++)
1427 uschar buffer[1024];
1431 char *readline_line = NULL;
1434 if (!(readline_line = fn_readline((i > 0)? "":"> "))) break;
1435 if (*readline_line != 0 && fn_addhist) fn_addhist(readline_line);
1436 p = US readline_line;
1441 /* readline() not in use */
1444 if (Ufgets(buffer, sizeof(buffer), stdin) == NULL) break;
1448 /* Handle the line */
1450 ss = p + (int)Ustrlen(p);
1451 while (ss > p && isspace(ss[-1])) ss--;
1454 while (p < ss && isspace(*p)) p++; /* leading space after cont */
1456 g = string_catn(g, p, ss - p);
1459 if (fn_readline) free(readline_line);
1462 /* g can only be NULL if ss==p */
1463 if (ss == p || g->s[g->ptr-1] != '\\')
1467 (void) string_from_gstring(g);
1470 if (!g) printf("\n");
1471 return string_from_gstring(g);
1476 /*************************************************
1477 * Output usage information for the program *
1478 *************************************************/
1480 /* This function is called when there are no recipients
1481 or a specific --help argument was added.
1484 progname information on what name we were called by
1486 Returns: DOES NOT RETURN
1490 exim_usage(uschar *progname)
1493 /* Handle specific program invocation variants */
1494 if (Ustrcmp(progname, US"-mailq") == 0)
1496 "mailq - list the contents of the mail queue\n\n"
1497 "For a list of options, see the Exim documentation.\n");
1499 /* Generic usage - we output this whatever happens */
1501 "Exim is a Mail Transfer Agent. It is normally called by Mail User Agents,\n"
1502 "not directly from a shell command line. Options and/or arguments control\n"
1503 "what it does when called. For a list of options, see the Exim documentation.\n");
1508 /*************************************************
1509 * Validate that the macros given are okay *
1510 *************************************************/
1512 /* Typically, Exim will drop privileges if macros are supplied. In some
1513 cases, we want to not do so.
1515 Arguments: opt_D_used - true if the commandline had a "-D" option
1516 Returns: true if trusted, false otherwise
1520 macros_trusted(BOOL opt_D_used)
1522 #ifdef WHITELIST_D_MACROS
1523 uschar *whitelisted, *end, *p, **whites;
1524 int white_count, i, n;
1526 BOOL prev_char_item, found;
1531 #ifndef WHITELIST_D_MACROS
1535 /* We only trust -D overrides for some invoking users:
1536 root, the exim run-time user, the optional config owner user.
1537 I don't know why config-owner would be needed, but since they can own the
1538 config files anyway, there's no security risk to letting them override -D. */
1539 if ( ! ((real_uid == root_uid)
1540 || (real_uid == exim_uid)
1541 #ifdef CONFIGURE_OWNER
1542 || (real_uid == config_uid)
1546 debug_printf("macros_trusted rejecting macros for uid %d\n", (int) real_uid);
1550 /* Get a list of macros which are whitelisted */
1551 whitelisted = string_copy_perm(US WHITELIST_D_MACROS, FALSE);
1552 prev_char_item = FALSE;
1554 for (p = whitelisted; *p != '\0'; ++p)
1556 if (*p == ':' || isspace(*p))
1561 prev_char_item = FALSE;
1564 if (!prev_char_item)
1565 prev_char_item = TRUE;
1572 whites = store_malloc(sizeof(uschar *) * (white_count+1));
1573 for (p = whitelisted, i = 0; (p != end) && (i < white_count); ++p)
1578 if (i == white_count)
1580 while (*p != '\0' && p < end)
1586 /* The list of commandline macros should be very short.
1587 Accept the N*M complexity. */
1588 for (macro_item * m = macros_user; m; m = m->next) if (m->command_line)
1591 for (uschar ** w = whites; *w; ++w)
1592 if (Ustrcmp(*w, m->name) == 0)
1599 if (!m->replacement)
1601 if ((len = m->replen) == 0)
1603 if (!regex_match(regex_whitelisted_macro, m->replacement, len, NULL))
1606 DEBUG(D_any) debug_printf("macros_trusted overridden to true by whitelisting\n");
1612 /*************************************************
1613 * Expansion testing *
1614 *************************************************/
1616 /* Expand and print one item, doing macro-processing.
1619 item line for expansion
1623 expansion_test_line(const uschar * line)
1629 Ustrncpy(big_buffer, line, big_buffer_size);
1630 big_buffer[big_buffer_size-1] = '\0';
1631 len = Ustrlen(big_buffer);
1633 (void) macros_expand(0, &len, &dummy_macexp);
1635 if (isupper(big_buffer[0]))
1637 if (macro_read_assignment(big_buffer))
1638 printf("Defined macro '%s'\n", mlast->name);
1641 if ((s = expand_string(big_buffer))) printf("%s\n", CS s);
1642 else printf("Failed: %s\n", expand_string_message);
1647 /*************************************************
1648 * Entry point and high-level code *
1649 *************************************************/
1651 /* Entry point for the Exim mailer. Analyse the arguments and arrange to take
1652 the appropriate action. All the necessary functions are present in the one
1653 binary. I originally thought one should split it up, but it turns out that so
1654 much of the apparatus is needed in each chunk that one might as well just have
1655 it all available all the time, which then makes the coding easier as well.
1658 argc count of entries in argv
1659 argv argument strings, with argv[0] being the program name
1661 Returns: EXIT_SUCCESS if terminated successfully
1662 EXIT_FAILURE otherwise, except when a message has been sent
1663 to the sender, and -oee was given
1667 main(int argc, char **cargv)
1669 uschar **argv = USS cargv;
1670 int arg_receive_timeout = -1;
1671 int arg_smtp_receive_timeout = -1;
1672 int arg_error_handling = error_handling;
1673 int filter_sfd = -1;
1674 int filter_ufd = -1;
1677 int list_queue_option = 0;
1679 int msg_action_arg = -1;
1680 int namelen = (argv[0] == NULL)? 0 : Ustrlen(argv[0]);
1681 int queue_only_reason = 0;
1683 int perl_start_option = 0;
1685 int recipients_arg = argc;
1686 int sender_address_domain = 0;
1687 int test_retry_arg = -1;
1688 int test_rewrite_arg = -1;
1689 gid_t original_egid;
1690 BOOL arg_queue_only = FALSE;
1691 BOOL bi_option = FALSE;
1692 BOOL checking = FALSE;
1693 BOOL count_queue = FALSE;
1694 BOOL expansion_test = FALSE;
1695 BOOL extract_recipients = FALSE;
1696 BOOL flag_G = FALSE;
1697 BOOL flag_n = FALSE;
1698 BOOL forced_delivery = FALSE;
1699 BOOL f_end_dot = FALSE;
1700 BOOL deliver_give_up = FALSE;
1701 BOOL list_queue = FALSE;
1702 BOOL list_options = FALSE;
1703 BOOL list_config = FALSE;
1704 BOOL local_queue_only;
1705 BOOL one_msg_action = FALSE;
1706 BOOL opt_D_used = FALSE;
1707 BOOL queue_only_set = FALSE;
1708 BOOL receiving_message = TRUE;
1709 BOOL sender_ident_set = FALSE;
1710 BOOL session_local_queue_only;
1712 BOOL removed_privilege = FALSE;
1713 BOOL usage_wanted = FALSE;
1714 BOOL verify_address_mode = FALSE;
1715 BOOL verify_as_sender = FALSE;
1716 BOOL rcpt_verify_quota = FALSE;
1717 BOOL version_printed = FALSE;
1718 uschar *alias_arg = NULL;
1719 uschar *called_as = US"";
1720 uschar *cmdline_syslog_name = NULL;
1721 uschar *start_queue_run_id = NULL;
1722 uschar *stop_queue_run_id = NULL;
1723 uschar *expansion_test_message = NULL;
1724 const uschar *ftest_domain = NULL;
1725 const uschar *ftest_localpart = NULL;
1726 const uschar *ftest_prefix = NULL;
1727 const uschar *ftest_suffix = NULL;
1728 uschar *log_oneline = NULL;
1729 uschar *malware_test_file = NULL;
1730 uschar *real_sender_address;
1731 uschar *originator_home = US"/";
1735 struct stat statbuf;
1736 pid_t passed_qr_pid = (pid_t)0;
1737 int passed_qr_pipe = -1;
1738 gid_t group_list[EXIM_GROUPLIST_SIZE];
1740 /* For the -bI: flag */
1741 enum commandline_info info_flag = CMDINFO_NONE;
1742 BOOL info_stdout = FALSE;
1744 /* Possible options for -R and -S */
1746 static uschar *rsopts[] = { US"f", US"ff", US"r", US"rf", US"rff" };
1748 /* Need to define this in case we need to change the environment in order
1749 to get rid of a bogus time zone. We have to make it char rather than uschar
1750 because some OS define it in /usr/include/unistd.h. */
1752 extern char **environ;
1754 #ifdef MEASURE_TIMING
1755 (void)gettimeofday(×tamp_startup, NULL);
1758 store_init(); /* Initialise the memory allocation susbsystem */
1759 pcre_init(); /* Set up memory handling for pcre */
1761 /* If the Exim user and/or group and/or the configuration file owner/group were
1762 defined by ref:name at build time, we must now find the actual uid/gid values.
1763 This is a feature to make the lives of binary distributors easier. */
1765 #ifdef EXIM_USERNAME
1766 if (route_finduser(US EXIM_USERNAME, &pw, &exim_uid))
1769 exim_fail("exim: refusing to run with uid 0 for \"%s\"\n", EXIM_USERNAME);
1771 /* If ref:name uses a number as the name, route_finduser() returns
1772 TRUE with exim_uid set and pw coerced to NULL. */
1774 exim_gid = pw->pw_gid;
1775 #ifndef EXIM_GROUPNAME
1778 "exim: ref:name should specify a usercode, not a group.\n"
1779 "exim: can't let you get away with it unless you also specify a group.\n");
1783 exim_fail("exim: failed to find uid for user name \"%s\"\n", EXIM_USERNAME);
1786 #ifdef EXIM_GROUPNAME
1787 if (!route_findgroup(US EXIM_GROUPNAME, &exim_gid))
1788 exim_fail("exim: failed to find gid for group name \"%s\"\n", EXIM_GROUPNAME);
1791 #ifdef CONFIGURE_OWNERNAME
1792 if (!route_finduser(US CONFIGURE_OWNERNAME, NULL, &config_uid))
1793 exim_fail("exim: failed to find uid for user name \"%s\"\n",
1794 CONFIGURE_OWNERNAME);
1797 /* We default the system_filter_user to be the Exim run-time user, as a
1798 sane non-root value. */
1799 system_filter_uid = exim_uid;
1801 #ifdef CONFIGURE_GROUPNAME
1802 if (!route_findgroup(US CONFIGURE_GROUPNAME, &config_gid))
1803 exim_fail("exim: failed to find gid for group name \"%s\"\n",
1804 CONFIGURE_GROUPNAME);
1807 /* In the Cygwin environment, some initialization used to need doing.
1808 It was fudged in by means of this macro; now no longer but we'll leave
1809 it in case of others. */
1815 /* Check a field which is patched when we are running Exim within its
1816 testing harness; do a fast initial check, and then the whole thing. */
1818 f.running_in_test_harness =
1819 *running_status == '<' && Ustrcmp(running_status, "<<<testing>>>") == 0;
1820 if (f.running_in_test_harness)
1823 /* Protect against abusive argv[0] */
1824 exim_str_fail_toolong(argv[0], PATH_MAX, "argv[0]");
1826 /* The C standard says that the equivalent of setlocale(LC_ALL, "C") is obeyed
1827 at the start of a program; however, it seems that some environments do not
1828 follow this. A "strange" locale can affect the formatting of timestamps, so we
1831 setlocale(LC_ALL, "C");
1833 /* Get the offset between CLOCK_MONOTONIC/CLOCK_BOOTTIME and wallclock */
1835 #ifdef _POSIX_MONOTONIC_CLOCK
1839 /* Set up the default handler for timing using alarm(). */
1841 os_non_restarting_signal(SIGALRM, sigalrm_handler);
1843 /* Ensure we have a buffer for constructing log entries. Use malloc directly,
1844 because store_malloc writes a log entry on failure. */
1846 if (!(log_buffer = US malloc(LOG_BUFFER_SIZE)))
1847 exim_fail("exim: failed to get store for log buffer\n");
1849 /* Initialize the default log options. */
1851 bits_set(log_selector, log_selector_size, log_default);
1853 /* Set log_stderr to stderr, provided that stderr exists. This gets reset to
1854 NULL when the daemon is run and the file is closed. We have to use this
1855 indirection, because some systems don't allow writing to the variable "stderr".
1858 if (fstat(fileno(stderr), &statbuf) >= 0) log_stderr = stderr;
1860 /* Ensure there is a big buffer for temporary use in several places. It is put
1861 in malloc store so that it can be freed for enlargement if necessary. */
1863 big_buffer = store_malloc(big_buffer_size);
1865 /* Set up the handler for the data request signal, and set the initial
1866 descriptive text. */
1868 process_info = store_get(PROCESS_INFO_SIZE, TRUE); /* tainted */
1869 set_process_info("initializing");
1870 os_restarting_signal(SIGUSR1, usr1_handler); /* exiwhat */
1871 signal(SIGSEGV, segv_handler); /* log faults */
1873 /* If running in a dockerized environment, the TERM signal is only
1874 delegated to the PID 1 if we request it by setting an signal handler */
1875 if (getpid() == 1) signal(SIGTERM, term_handler);
1877 /* SIGHUP is used to get the daemon to reconfigure. It gets set as appropriate
1878 in the daemon code. For the rest of Exim's uses, we ignore it. */
1880 signal(SIGHUP, SIG_IGN);
1882 /* We don't want to die on pipe errors as the code is written to handle
1883 the write error instead. */
1885 signal(SIGPIPE, SIG_IGN);
1887 /* Under some circumstance on some OS, Exim can get called with SIGCHLD
1888 set to SIG_IGN. This causes subprocesses that complete before the parent
1889 process waits for them not to hang around, so when Exim calls wait(), nothing
1890 is there. The wait() code has been made robust against this, but let's ensure
1891 that SIGCHLD is set to SIG_DFL, because it's tidier to wait and get a process
1892 ending status. We use sigaction rather than plain signal() on those OS where
1893 SA_NOCLDWAIT exists, because we want to be sure it is turned off. (There was a
1894 problem on AIX with this.) */
1898 struct sigaction act;
1899 act.sa_handler = SIG_DFL;
1900 sigemptyset(&(act.sa_mask));
1902 sigaction(SIGCHLD, &act, NULL);
1905 signal(SIGCHLD, SIG_DFL);
1908 /* Save the arguments for use if we re-exec exim as a daemon after receiving
1913 /* Set up the version number. Set up the leading 'E' for the external form of
1914 message ids, set the pointer to the internal form, and initialize it to
1915 indicate no message being processed. */
1918 message_id_option[0] = '-';
1919 message_id_external = message_id_option + 1;
1920 message_id_external[0] = 'E';
1921 message_id = message_id_external + 1;
1924 /* Set the umask to zero so that any files Exim creates using open() are
1925 created with the modes that it specifies. NOTE: Files created with fopen() have
1926 a problem, which was not recognized till rather late (February 2006). With this
1927 umask, such files will be world writeable. (They are all content scanning files
1928 in the spool directory, which isn't world-accessible, so this is not a
1929 disaster, but it's untidy.) I don't want to change this overall setting,
1930 however, because it will interact badly with the open() calls. Instead, there's
1931 now a function called modefopen() that fiddles with the umask while calling
1936 /* Precompile the regular expression for matching a message id. Keep this in
1937 step with the code that generates ids in the accept.c module. We need to do
1938 this here, because the -M options check their arguments for syntactic validity
1939 using mac_ismsgid, which uses this. */
1942 regex_must_compile(US"^(?:[^\\W_]{6}-){2}[^\\W_]{2}$", FALSE, TRUE);
1944 /* Precompile the regular expression that is used for matching an SMTP error
1945 code, possibly extended, at the start of an error message. Note that the
1946 terminating whitespace character is included. */
1949 regex_must_compile(US"^\\d\\d\\d\\s(?:\\d\\.\\d\\d?\\d?\\.\\d\\d?\\d?\\s)?",
1952 #ifdef WHITELIST_D_MACROS
1953 /* Precompile the regular expression used to filter the content of macros
1954 given to -D for permissibility. */
1956 regex_whitelisted_macro =
1957 regex_must_compile(US"^[A-Za-z0-9_/.-]*$", FALSE, TRUE);
1960 for (i = 0; i < REGEX_VARS; i++) regex_vars[i] = NULL;
1962 /* If the program is called as "mailq" treat it as equivalent to "exim -bp";
1963 this seems to be a generally accepted convention, since one finds symbolic
1964 links called "mailq" in standard OS configurations. */
1966 if ((namelen == 5 && Ustrcmp(argv[0], "mailq") == 0) ||
1967 (namelen > 5 && Ustrncmp(argv[0] + namelen - 6, "/mailq", 6) == 0))
1970 receiving_message = FALSE;
1971 called_as = US"-mailq";
1974 /* If the program is called as "rmail" treat it as equivalent to
1975 "exim -i -oee", thus allowing UUCP messages to be input using non-SMTP mode,
1976 i.e. preventing a single dot on a line from terminating the message, and
1977 returning with zero return code, even in cases of error (provided an error
1978 message has been sent). */
1980 if ((namelen == 5 && Ustrcmp(argv[0], "rmail") == 0) ||
1981 (namelen > 5 && Ustrncmp(argv[0] + namelen - 6, "/rmail", 6) == 0))
1984 called_as = US"-rmail";
1985 errors_sender_rc = EXIT_SUCCESS;
1988 /* If the program is called as "rsmtp" treat it as equivalent to "exim -bS";
1989 this is a smail convention. */
1991 if ((namelen == 5 && Ustrcmp(argv[0], "rsmtp") == 0) ||
1992 (namelen > 5 && Ustrncmp(argv[0] + namelen - 6, "/rsmtp", 6) == 0))
1994 smtp_input = smtp_batched_input = TRUE;
1995 called_as = US"-rsmtp";
1998 /* If the program is called as "runq" treat it as equivalent to "exim -q";
1999 this is a smail convention. */
2001 if ((namelen == 4 && Ustrcmp(argv[0], "runq") == 0) ||
2002 (namelen > 4 && Ustrncmp(argv[0] + namelen - 5, "/runq", 5) == 0))
2005 receiving_message = FALSE;
2006 called_as = US"-runq";
2009 /* If the program is called as "newaliases" treat it as equivalent to
2010 "exim -bi"; this is a sendmail convention. */
2012 if ((namelen == 10 && Ustrcmp(argv[0], "newaliases") == 0) ||
2013 (namelen > 10 && Ustrncmp(argv[0] + namelen - 11, "/newaliases", 11) == 0))
2016 receiving_message = FALSE;
2017 called_as = US"-newaliases";
2020 /* Save the original effective uid for a couple of uses later. It should
2021 normally be root, but in some esoteric environments it may not be. */
2023 original_euid = geteuid();
2024 original_egid = getegid();
2026 /* Get the real uid and gid. If the caller is root, force the effective uid/gid
2027 to be the same as the real ones. This makes a difference only if Exim is setuid
2028 (or setgid) to something other than root, which could be the case in some
2029 special configurations. */
2031 real_uid = getuid();
2032 real_gid = getgid();
2034 if (real_uid == root_uid)
2036 if ((rv = setgid(real_gid)))
2037 exim_fail("exim: setgid(%ld) failed: %s\n",
2038 (long int)real_gid, strerror(errno));
2039 if ((rv = setuid(real_uid)))
2040 exim_fail("exim: setuid(%ld) failed: %s\n",
2041 (long int)real_uid, strerror(errno));
2044 /* If neither the original real uid nor the original euid was root, Exim is
2045 running in an unprivileged state. */
2047 unprivileged = (real_uid != root_uid && original_euid != root_uid);
2049 /* For most of the args-parsing we need to use permanent pool memory */
2051 int old_pool = store_pool;
2052 store_pool = POOL_PERM;
2054 /* Scan the program's arguments. Some can be dealt with right away; others are
2055 simply recorded for checking and handling afterwards. Do a high-level switch
2056 on the second character (the one after '-'), to save some effort. */
2058 for (i = 1; i < argc; i++)
2060 BOOL badarg = FALSE;
2061 uschar * arg = argv[i];
2065 /* An argument not starting with '-' is the start of a recipients list;
2066 break out of the options-scanning loop. */
2074 /* An option consisting of -- terminates the options */
2076 if (Ustrcmp(arg, "--") == 0)
2078 recipients_arg = i + 1;
2082 /* Handle flagged options */
2084 switchchar = arg[1];
2087 /* Make all -ex options synonymous with -oex arguments, since that
2088 is assumed by various callers. Also make -qR options synonymous with -R
2089 options, as that seems to be required as well. Allow for -qqR too, and
2090 the same for -S options. */
2092 if (Ustrncmp(arg+1, "oe", 2) == 0 ||
2093 Ustrncmp(arg+1, "qR", 2) == 0 ||
2094 Ustrncmp(arg+1, "qS", 2) == 0)
2096 switchchar = arg[2];
2099 else if (Ustrncmp(arg+1, "qqR", 3) == 0 || Ustrncmp(arg+1, "qqS", 3) == 0)
2101 switchchar = arg[3];
2103 f.queue_2stage = TRUE;
2106 /* Make -r synonymous with -f, since it is a documented alias */
2108 else if (arg[1] == 'r') switchchar = 'f';
2110 /* Make -ov synonymous with -v */
2112 else if (Ustrcmp(arg, "-ov") == 0)
2118 /* deal with --option_aliases */
2119 else if (switchchar == '-')
2121 if (Ustrcmp(argrest, "help") == 0)
2123 usage_wanted = TRUE;
2126 else if (Ustrcmp(argrest, "version") == 0)
2133 /* High-level switch on active initial letter */
2138 /* sendmail uses -Ac and -Am to control which .cf file is used;
2141 if (!*argrest) { badarg = TRUE; break; }
2144 BOOL ignore = FALSE;
2149 if (*(argrest + 1) == '\0')
2153 if (!ignore) badarg = TRUE;
2157 /* -Btype is a sendmail option for 7bit/8bit setting. Exim is 8-bit clean
2158 so has no need of it. */
2161 if (!*argrest) i++; /* Skip over the type */
2167 receiving_message = FALSE; /* Reset TRUE for -bm, -bS, -bs below */
2171 /* -bd: Run in daemon mode, awaiting SMTP connections.
2172 -bdf: Ditto, but in the foreground.
2175 f.daemon_listen = TRUE;
2176 if (*argrest == 'f') f.background_daemon = FALSE;
2177 else if (*argrest) badarg = TRUE;
2180 /* -be: Run in expansion test mode
2181 -bem: Ditto, but read a message from a file first
2184 expansion_test = checking = TRUE;
2185 if (*argrest == 'm')
2187 if (++i >= argc) { badarg = TRUE; break; }
2188 expansion_test_message = argv[i];
2191 if (*argrest) badarg = TRUE;
2194 /* -bF: Run system filter test */
2196 filter_test |= checking = FTEST_SYSTEM;
2197 if (*argrest) badarg = TRUE;
2198 else if (++i < argc) filter_test_sfile = argv[i];
2199 else exim_fail("exim: file name expected after %s\n", argv[i-1]);
2202 /* -bf: Run user filter test
2203 -bfd: Set domain for filter testing
2204 -bfl: Set local part for filter testing
2205 -bfp: Set prefix for filter testing
2206 -bfs: Set suffix for filter testing
2211 filter_test |= checking = FTEST_USER;
2212 if (++i < argc) filter_test_ufile = argv[i];
2213 else exim_fail("exim: file name expected after %s\n", argv[i-1]);
2218 exim_fail("exim: string expected after %s\n", arg);
2219 if (Ustrcmp(argrest, "d") == 0) ftest_domain = exim_str_fail_toolong(argv[i], EXIM_DOMAINNAME_MAX, "-bfd");
2220 else if (Ustrcmp(argrest, "l") == 0) ftest_localpart = exim_str_fail_toolong(argv[i], EXIM_LOCALPART_MAX, "-bfl");
2221 else if (Ustrcmp(argrest, "p") == 0) ftest_prefix = exim_str_fail_toolong(argv[i], EXIM_LOCALPART_MAX, "-bfp");
2222 else if (Ustrcmp(argrest, "s") == 0) ftest_suffix = exim_str_fail_toolong(argv[i], EXIM_LOCALPART_MAX, "-bfs");
2227 /* -bh: Host checking - an IP address must follow. */
2229 if (!*argrest || Ustrcmp(argrest, "c") == 0)
2231 if (++i >= argc) { badarg = TRUE; break; }
2232 sender_host_address = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_IPADDR_MAX, "-bh"), TRUE);
2233 host_checking = checking = f.log_testing_mode = TRUE;
2234 f.host_checking_callout = *argrest == 'c';
2235 message_logs = FALSE;
2240 /* -bi: This option is used by sendmail to initialize *the* alias file,
2241 though it has the -oA option to specify a different file. Exim has no
2242 concept of *the* alias file, but since Sun's YP make script calls
2243 sendmail this way, some support must be provided. */
2245 if (!*argrest) bi_option = TRUE;
2249 /* -bI: provide information, of the type to follow after a colon.
2250 This is an Exim flag. */
2252 if (Ustrlen(argrest) >= 1 && *argrest == ':')
2254 uschar *p = argrest+1;
2255 info_flag = CMDINFO_HELP;
2257 if (strcmpic(p, CUS"sieve") == 0)
2259 info_flag = CMDINFO_SIEVE;
2262 else if (strcmpic(p, CUS"dscp") == 0)
2264 info_flag = CMDINFO_DSCP;
2267 else if (strcmpic(p, CUS"help") == 0)
2273 /* -bm: Accept and deliver message - the default option. Reinstate
2274 receiving_message, which got turned off for all -b options.
2275 -bmalware: test the filename given for malware */
2277 if (!*argrest) receiving_message = TRUE;
2278 else if (Ustrcmp(argrest, "alware") == 0)
2280 if (++i >= argc) { badarg = TRUE; break; }
2282 malware_test_file = argv[i];
2287 /* -bnq: For locally originating messages, do not qualify unqualified
2288 addresses. In the envelope, this causes errors; in header lines they
2291 if (Ustrcmp(argrest, "q") == 0)
2293 f.allow_unqualified_sender = FALSE;
2294 f.allow_unqualified_recipient = FALSE;
2299 /* -bpxx: List the contents of the mail queue, in various forms. If
2300 the option is -bpc, just a queue count is needed. Otherwise, if the
2301 first letter after p is r, then order is random. */
2303 if (*argrest == 'c')
2306 if (*++argrest) badarg = TRUE;
2310 if (*argrest == 'r')
2312 list_queue_option = 8;
2315 else list_queue_option = 0;
2319 /* -bp: List the contents of the mail queue, top-level only */
2323 /* -bpu: List the contents of the mail queue, top-level undelivered */
2325 else if (Ustrcmp(argrest, "u") == 0) list_queue_option += 1;
2327 /* -bpa: List the contents of the mail queue, including all delivered */
2329 else if (Ustrcmp(argrest, "a") == 0) list_queue_option += 2;
2331 /* Unknown after -bp[r] */
2337 /* -bP: List the configuration variables given as the address list.
2338 Force -v, so configuration errors get displayed. */
2341 /* -bP config: we need to setup here, because later,
2342 when list_options is checked, the config is read already */
2345 else if (argv[i+1] && Ustrcmp(argv[i+1], "config") == 0)
2348 readconf_save_config(version_string);
2352 list_options = TRUE;
2353 debug_selector |= D_v;
2354 debug_file = stderr;
2358 /* -brt: Test retry configuration lookup */
2360 if (Ustrcmp(argrest, "t") == 0)
2363 test_retry_arg = i + 1;
2367 /* -brw: Test rewrite configuration */
2369 else if (Ustrcmp(argrest, "w") == 0)
2372 test_rewrite_arg = i + 1;
2378 /* -bS: Read SMTP commands on standard input, but produce no replies -
2379 all errors are reported by sending messages. */
2382 smtp_input = smtp_batched_input = receiving_message = TRUE;
2386 /* -bs: Read SMTP commands on standard input and produce SMTP replies
2387 on standard output. */
2389 if (!*argrest) smtp_input = receiving_message = TRUE;
2393 /* -bt: address testing mode */
2396 f.address_test_mode = checking = f.log_testing_mode = TRUE;
2400 /* -bv: verify addresses */
2403 verify_address_mode = checking = f.log_testing_mode = TRUE;
2405 /* -bvs: verify sender addresses */
2407 else if (Ustrcmp(argrest, "s") == 0)
2409 verify_address_mode = checking = f.log_testing_mode = TRUE;
2410 verify_as_sender = TRUE;
2415 /* -bV: Print version string and support details */
2419 printf("Exim version %s #%s built %s\n", version_string,
2420 version_cnumber, version_date);
2421 printf("%s\n", CS version_copyright);
2422 version_printed = TRUE;
2423 show_whats_supported(stdout);
2424 f.log_testing_mode = TRUE;
2429 /* -bw: inetd wait mode, accept a listening socket as stdin */
2431 f.inetd_wait_mode = TRUE;
2432 f.background_daemon = FALSE;
2433 f.daemon_listen = TRUE;
2435 if ((inetd_wait_timeout = readconf_readtime(argrest, 0, FALSE)) <= 0)
2436 exim_fail("exim: bad time value %s: abandoned\n", argv[i]);
2447 /* -C: change configuration file list; ignore if it isn't really
2448 a change! Enforce a prefix check if required. */
2452 if (++i < argc) argrest = argv[i]; else { badarg = TRUE; break; }
2453 if (Ustrcmp(config_main_filelist, argrest) != 0)
2455 #ifdef ALT_CONFIG_PREFIX
2457 int len = Ustrlen(ALT_CONFIG_PREFIX);
2458 const uschar *list = argrest;
2460 /* The argv is untainted, so big_buffer (also untainted) is ok to use */
2461 while((filename = string_nextinlist(&list, &sep, big_buffer,
2463 if ( ( Ustrlen(filename) < len
2464 || Ustrncmp(filename, ALT_CONFIG_PREFIX, len) != 0
2465 || Ustrstr(filename, "/../") != NULL
2467 && (Ustrcmp(filename, "/dev/null") != 0 || real_uid != root_uid)
2469 exim_fail("-C Permission denied\n");
2471 if (real_uid != root_uid)
2473 #ifdef TRUSTED_CONFIG_LIST
2475 if (real_uid != exim_uid
2476 #ifdef CONFIGURE_OWNER
2477 && real_uid != config_uid
2480 f.trusted_config = FALSE;
2483 FILE *trust_list = Ufopen(TRUSTED_CONFIG_LIST, "rb");
2486 struct stat statbuf;
2488 if (fstat(fileno(trust_list), &statbuf) != 0 ||
2489 (statbuf.st_uid != root_uid /* owner not root */
2490 #ifdef CONFIGURE_OWNER
2491 && statbuf.st_uid != config_uid /* owner not the special one */
2494 (statbuf.st_gid != root_gid /* group not root */
2495 #ifdef CONFIGURE_GROUP
2496 && statbuf.st_gid != config_gid /* group not the special one */
2498 && (statbuf.st_mode & 020) != 0 /* group writeable */
2500 (statbuf.st_mode & 2) != 0) /* world writeable */
2502 f.trusted_config = FALSE;
2507 /* Well, the trust list at least is up to scratch... */
2509 uschar *trusted_configs[32];
2512 int old_pool = store_pool;
2513 store_pool = POOL_MAIN;
2515 reset_point = store_mark();
2516 while (Ufgets(big_buffer, big_buffer_size, trust_list))
2518 uschar *start = big_buffer, *nl;
2519 while (*start && isspace(*start))
2523 nl = Ustrchr(start, '\n');
2526 trusted_configs[nr_configs++] = string_copy(start);
2527 if (nr_configs == nelem(trusted_configs))
2535 const uschar *list = argrest;
2537 while (f.trusted_config && (filename = string_nextinlist(&list,
2538 &sep, big_buffer, big_buffer_size)))
2540 for (i=0; i < nr_configs; i++)
2541 if (Ustrcmp(filename, trusted_configs[i]) == 0)
2543 if (i == nr_configs)
2545 f.trusted_config = FALSE;
2550 else /* No valid prefixes found in trust_list file. */
2551 f.trusted_config = FALSE;
2552 store_reset(reset_point);
2553 store_pool = old_pool;
2556 else /* Could not open trust_list file. */
2557 f.trusted_config = FALSE;
2560 /* Not root; don't trust config */
2561 f.trusted_config = FALSE;
2565 config_main_filelist = argrest;
2566 f.config_changed = TRUE;
2571 /* -D: set up a macro definition */
2574 #ifdef DISABLE_D_OPTION
2575 exim_fail("exim: -D is not available in this Exim binary\n");
2581 uschar *s = argrest;
2584 while (isspace(*s)) s++;
2586 if (*s < 'A' || *s > 'Z')
2587 exim_fail("exim: macro name set by -D must start with "
2588 "an upper case letter\n");
2590 while (isalnum(*s) || *s == '_')
2592 if (ptr < sizeof(name)-1) name[ptr++] = *s;
2596 if (ptr == 0) { badarg = TRUE; break; }
2597 while (isspace(*s)) s++;
2600 if (*s++ != '=') { badarg = TRUE; break; }
2601 while (isspace(*s)) s++;
2604 for (m = macros_user; m; m = m->next)
2605 if (Ustrcmp(m->name, name) == 0)
2606 exim_fail("exim: duplicated -D in command line\n");
2608 m = macro_create(name, s, TRUE);
2610 if (clmacro_count >= MAX_CLMACROS)
2611 exim_fail("exim: too many -D options on command line\n");
2612 clmacros[clmacro_count++] =
2613 string_sprintf("-D%s=%s", m->name, m->replacement);
2618 /* -d: Set debug level (see also -v below) or set the drop_cr option.
2619 The latter is now a no-op, retained for compatibility only. If -dd is used,
2620 debugging subprocesses of the daemon is disabled. */
2623 if (Ustrcmp(argrest, "ropcr") == 0)
2625 /* drop_cr = TRUE; */
2628 /* Use an intermediate variable so that we don't set debugging while
2629 decoding the debugging bits. */
2633 unsigned int selector = D_default;
2636 if (*argrest == 'd')
2638 f.debug_daemon = TRUE;
2642 decode_bits(&selector, 1, debug_notall, argrest,
2643 debug_options, debug_options_count, US"debug", 0);
2644 debug_selector = selector;
2649 /* -E: This is a local error message. This option is not intended for
2650 external use at all, but is not restricted to trusted callers because it
2651 does no harm (just suppresses certain error messages) and if Exim is run
2652 not setuid root it won't always be trusted when it generates error
2653 messages using this option. If there is a message id following -E, point
2654 message_reference at it, for logging. */
2657 f.local_error_message = TRUE;
2658 if (mac_ismsgid(argrest)) message_reference = argrest;
2662 /* -ex: The vacation program calls sendmail with the undocumented "-eq"
2663 option, so it looks as if historically the -oex options are also callable
2664 without the leading -o. So we have to accept them. Before the switch,
2665 anything starting -oe has been converted to -e. Exim does not support all
2666 of the sendmail error options. */
2669 if (Ustrcmp(argrest, "e") == 0)
2671 arg_error_handling = ERRORS_SENDER;
2672 errors_sender_rc = EXIT_SUCCESS;
2674 else if (Ustrcmp(argrest, "m") == 0) arg_error_handling = ERRORS_SENDER;
2675 else if (Ustrcmp(argrest, "p") == 0) arg_error_handling = ERRORS_STDERR;
2676 else if (Ustrcmp(argrest, "q") == 0) arg_error_handling = ERRORS_STDERR;
2677 else if (Ustrcmp(argrest, "w") == 0) arg_error_handling = ERRORS_SENDER;
2682 /* -F: Set sender's full name, used instead of the gecos entry from
2683 the password file. Since users can usually alter their gecos entries,
2684 there's no security involved in using this instead. The data can follow
2685 the -F or be in the next argument. */
2689 if (++i < argc) argrest = argv[i]; else { badarg = TRUE; break; }
2690 originator_name = string_copy_taint(exim_str_fail_toolong(argrest, EXIM_HUMANNAME_MAX, "-F"), TRUE);
2691 f.sender_name_forced = TRUE;
2695 /* -f: Set sender's address - this value is only actually used if Exim is
2696 run by a trusted user, or if untrusted_set_sender is set and matches the
2697 address, except that the null address can always be set by any user. The
2698 test for this happens later, when the value given here is ignored when not
2699 permitted. For an untrusted user, the actual sender is still put in Sender:
2700 if it doesn't match the From: header (unless no_local_from_check is set).
2701 The data can follow the -f or be in the next argument. The -r switch is an
2702 obsolete form of -f but since there appear to be programs out there that
2703 use anything that sendmail has ever supported, better accept it - the
2704 synonymizing is done before the switch above.
2706 At this stage, we must allow domain literal addresses, because we don't
2707 know what the setting of allow_domain_literals is yet. Ditto for trailing
2708 dots and strip_trailing_dot. */
2712 int dummy_start, dummy_end;
2715 if (i+1 < argc) argrest = argv[++i]; else { badarg = TRUE; break; }
2716 (void) exim_str_fail_toolong(argrest, EXIM_DISPLAYMAIL_MAX, "-f");
2718 *(sender_address = store_get(1, FALSE)) = '\0'; /* Ensure writeable memory */
2721 uschar * temp = argrest + Ustrlen(argrest) - 1;
2722 while (temp >= argrest && isspace(*temp)) temp--;
2723 if (temp >= argrest && *temp == '.') f_end_dot = TRUE;
2724 allow_domain_literals = TRUE;
2725 strip_trailing_dot = TRUE;
2727 allow_utf8_domains = TRUE;
2729 if (!(sender_address = parse_extract_address(argrest, &errmess,
2730 &dummy_start, &dummy_end, &sender_address_domain, TRUE)))
2731 exim_fail("exim: bad -f address \"%s\": %s\n", argrest, errmess);
2733 sender_address = string_copy_taint(sender_address, TRUE);
2735 message_smtputf8 = string_is_utf8(sender_address);
2736 allow_utf8_domains = FALSE;
2738 allow_domain_literals = FALSE;
2739 strip_trailing_dot = FALSE;
2741 f.sender_address_forced = TRUE;
2745 /* -G: sendmail invocation to specify that it's a gateway submission and
2746 sendmail may complain about problems instead of fixing them.
2747 We make it equivalent to an ACL "control = suppress_local_fixups" and do
2748 not at this time complain about problems. */
2754 /* -h: Set the hop count for an incoming message. Exim does not currently
2755 support this; it always computes it by counting the Received: headers.
2756 To put it in will require a change to the spool header file format. */
2760 if (++i < argc) argrest = argv[i]; else { badarg = TRUE; break; }
2761 if (!isdigit(*argrest)) badarg = TRUE;
2765 /* -i: Set flag so dot doesn't end non-SMTP input (same as -oi, seems
2766 not to be documented for sendmail but mailx (at least) uses it) */
2769 if (!*argrest) f.dot_ends = FALSE; else badarg = TRUE;
2773 /* -L: set the identifier used for syslog; equivalent to setting
2774 syslog_processname in the config file, but needs to be an admin option. */
2778 if (++i < argc) argrest = argv[i]; else { badarg = TRUE; break; }
2779 if ((sz = Ustrlen(argrest)) > 32)
2780 exim_fail("exim: the -L syslog name is too long: \"%s\"\n", argrest);
2782 exim_fail("exim: the -L syslog name is too short\n");
2783 cmdline_syslog_name = string_copy_taint(argrest, TRUE);
2787 receiving_message = FALSE;
2789 /* -MC: continue delivery of another message via an existing open
2790 file descriptor. This option is used for an internal call by the
2791 smtp transport when there is a pending message waiting to go to an
2792 address to which it has got a connection. Five subsequent arguments are
2793 required: transport name, host name, IP address, sequence number, and
2794 message_id. Transports may decline to create new processes if the sequence
2795 number gets too big. The channel is stdin. This (-MC) must be the last
2796 argument. There's a subsequent check that the real-uid is privileged.
2798 If we are running in the test harness. delay for a bit, to let the process
2799 that set this one up complete. This makes for repeatability of the logging,
2802 if (Ustrcmp(argrest, "C") == 0)
2804 union sockaddr_46 interface_sock;
2805 EXIM_SOCKLEN_T size = sizeof(interface_sock);
2808 exim_fail("exim: too many or too few arguments after -MC\n");
2810 if (msg_action_arg >= 0)
2811 exim_fail("exim: incompatible arguments\n");
2813 continue_transport = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_DRIVERNAME_MAX, "-C internal transport"), TRUE);
2814 continue_hostname = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_HOSTNAME_MAX, "-C internal hostname"), TRUE);
2815 continue_host_address = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_IPADDR_MAX, "-C internal hostaddr"), TRUE);
2816 continue_sequence = Uatoi(argv[++i]);
2817 msg_action = MSG_DELIVER;
2818 msg_action_arg = ++i;
2819 forced_delivery = TRUE;
2820 queue_run_pid = passed_qr_pid;
2821 queue_run_pipe = passed_qr_pipe;
2823 if (!mac_ismsgid(argv[i]))
2824 exim_fail("exim: malformed message id %s after -MC option\n",
2827 /* Set up $sending_ip_address and $sending_port, unless proxied */
2829 if (!continue_proxy_cipher)
2830 if (getsockname(fileno(stdin), (struct sockaddr *)(&interface_sock),
2832 sending_ip_address = host_ntoa(-1, &interface_sock, NULL,
2835 exim_fail("exim: getsockname() failed after -MC option: %s\n",
2838 testharness_pause_ms(500);
2842 else if (*argrest == 'C' && argrest[1] && !argrest[2])
2846 /* -MCA: set the smtp_authenticated flag; this is useful only when it
2847 precedes -MC (see above). The flag indicates that the host to which
2848 Exim is connected has accepted an AUTH sequence. */
2850 case 'A': f.smtp_authenticated = TRUE; break;
2852 /* -MCD: set the smtp_use_dsn flag; this indicates that the host
2853 that exim is connected to supports the esmtp extension DSN */
2855 case 'D': smtp_peer_options |= OPTION_DSN; break;
2857 /* -MCd: for debug, set a process-purpose string */
2859 case 'd': if (++i < argc)
2860 process_purpose = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_DRIVERNAME_MAX, "-MCd"), TRUE);
2864 /* -MCG: set the queue name, to a non-default value. Arguably, anything
2865 from the commandline should be tainted - but we will need an untainted
2866 value for the spoolfile when doing a -odi delivery process. */
2868 case 'G': if (++i < argc) queue_name = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_DRIVERNAME_MAX, "-MCG"), FALSE);
2872 /* -MCK: the peer offered CHUNKING. Must precede -MC */
2874 case 'K': smtp_peer_options |= OPTION_CHUNKING; break;
2876 #ifdef EXPERIMENTAL_ESMTP_LIMITS
2877 /* -MCL: peer used LIMITS RCPTMAX and/or RCPTDOMAINMAX */
2878 case 'L': if (++i < argc) continue_limit_mail = Uatoi(argv[i]);
2880 if (++i < argc) continue_limit_rcpt = Uatoi(argv[i]);
2882 if (++i < argc) continue_limit_rcptdom = Uatoi(argv[i]);
2887 /* -MCP: set the smtp_use_pipelining flag; this is useful only when
2888 it preceded -MC (see above) */
2890 case 'P': smtp_peer_options |= OPTION_PIPE; break;
2892 #ifdef SUPPORT_SOCKS
2893 /* -MCp: Socks proxy in use; nearside IP, port, external IP, port */
2894 case 'p': proxy_session = TRUE;
2897 proxy_local_address = string_copy_taint(argv[i], TRUE);
2900 proxy_local_port = Uatoi(argv[i]);
2903 proxy_external_address = string_copy_taint(argv[i], TRUE);
2906 proxy_external_port = Uatoi(argv[i]);
2912 /* -MCQ: pass on the pid of the queue-running process that started
2913 this chain of deliveries and the fd of its synchronizing pipe; this
2914 is useful only when it precedes -MC (see above) */
2916 case 'Q': if (++i < argc) passed_qr_pid = (pid_t)(Uatol(argv[i]));
2918 if (++i < argc) passed_qr_pipe = (int)(Uatol(argv[i]));
2922 /* -MCq: do a quota check on the given recipient for the given size
2923 of message. Separate from -MC. */
2924 case 'q': rcpt_verify_quota = TRUE;
2925 if (++i < argc) message_size = Uatoi(argv[i]);
2929 /* -MCS: set the smtp_use_size flag; this is useful only when it
2930 precedes -MC (see above) */
2932 case 'S': smtp_peer_options |= OPTION_SIZE; break;
2935 /* -MCs: used with -MCt; SNI was sent */
2936 /* -MCr: ditto, DANE */
2939 case 's': if (++i < argc)
2941 continue_proxy_sni = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_HOSTNAME_MAX, "-MCr/-MCs"), TRUE);
2942 if (argrest[1] == 'r') continue_proxy_dane = TRUE;
2947 /* -MCt: similar to -MCT below but the connection is still open
2948 via a proxy process which handles the TLS context and coding.
2949 Require three arguments for the proxied local address and port,
2950 and the TLS cipher. */
2952 case 't': if (++i < argc)
2953 sending_ip_address = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_IPADDR_MAX, "-MCt IP"), TRUE);
2956 sending_port = (int)(Uatol(argv[i]));
2959 continue_proxy_cipher = string_copy_taint(exim_str_fail_toolong(argv[i], EXIM_CIPHERNAME_MAX, "-MCt cipher"), TRUE);
2963 /* -MCT: set the tls_offered flag; this is useful only when it
2964 precedes -MC (see above). The flag indicates that the host to which
2965 Exim is connected has offered TLS support. */
2967 case 'T': smtp_peer_options |= OPTION_TLS; break;
2970 default: badarg = TRUE; break;
2975 /* -M[x]: various operations on the following list of message ids:
2976 -M deliver the messages, ignoring next retry times and thawing
2977 -Mc deliver the messages, checking next retry times, no thawing
2978 -Mf freeze the messages
2979 -Mg give up on the messages
2980 -Mt thaw the messages
2981 -Mrm remove the messages
2982 In the above cases, this must be the last option. There are also the
2983 following options which are followed by a single message id, and which
2984 act on that message. Some of them use the "recipient" addresses as well.
2985 -Mar add recipient(s)
2986 -MG move to a different queue
2987 -Mmad mark all recipients delivered
2988 -Mmd mark recipients(s) delivered
2990 -Mset load a message for use with -be
2992 -Mvc show copy (of whole message, in RFC 2822 format)
2999 msg_action = MSG_DELIVER;
3000 forced_delivery = f.deliver_force_thaw = TRUE;
3002 else if (Ustrcmp(argrest, "ar") == 0)
3004 msg_action = MSG_ADD_RECIPIENT;
3005 one_msg_action = TRUE;
3007 else if (Ustrcmp(argrest, "c") == 0) msg_action = MSG_DELIVER;
3008 else if (Ustrcmp(argrest, "es") == 0)
3010 msg_action = MSG_EDIT_SENDER;
3011 one_msg_action = TRUE;
3013 else if (Ustrcmp(argrest, "f") == 0) msg_action = MSG_FREEZE;
3014 else if (Ustrcmp(argrest, "g") == 0)
3016 msg_action = MSG_DELIVER;
3017 deliver_give_up = TRUE;
3019 else if (Ustrcmp(argrest, "G") == 0)
3021 msg_action = MSG_SETQUEUE;
3022 queue_name_dest = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_DRIVERNAME_MAX, "-MG"), TRUE);
3024 else if (Ustrcmp(argrest, "mad") == 0)
3026 msg_action = MSG_MARK_ALL_DELIVERED;
3028 else if (Ustrcmp(argrest, "md") == 0)
3030 msg_action = MSG_MARK_DELIVERED;
3031 one_msg_action = TRUE;
3033 else if (Ustrcmp(argrest, "rm") == 0) msg_action = MSG_REMOVE;
3034 else if (Ustrcmp(argrest, "set") == 0)
3036 msg_action = MSG_LOAD;
3037 one_msg_action = TRUE;
3039 else if (Ustrcmp(argrest, "t") == 0) msg_action = MSG_THAW;
3040 else if (Ustrcmp(argrest, "vb") == 0)
3042 msg_action = MSG_SHOW_BODY;
3043 one_msg_action = TRUE;
3045 else if (Ustrcmp(argrest, "vc") == 0)
3047 msg_action = MSG_SHOW_COPY;
3048 one_msg_action = TRUE;
3050 else if (Ustrcmp(argrest, "vh") == 0)
3052 msg_action = MSG_SHOW_HEADER;
3053 one_msg_action = TRUE;
3055 else if (Ustrcmp(argrest, "vl") == 0)
3057 msg_action = MSG_SHOW_LOG;
3058 one_msg_action = TRUE;
3060 else { badarg = TRUE; break; }
3062 /* All the -Mxx options require at least one message id. */
3064 msg_action_arg = i + 1;
3065 if (msg_action_arg >= argc)
3066 exim_fail("exim: no message ids given after %s option\n", arg);
3068 /* Some require only message ids to follow */
3070 if (!one_msg_action)
3072 for (int j = msg_action_arg; j < argc; j++) if (!mac_ismsgid(argv[j]))
3073 exim_fail("exim: malformed message id %s after %s option\n",
3075 goto END_ARG; /* Remaining args are ids */
3078 /* Others require only one message id, possibly followed by addresses,
3079 which will be handled as normal arguments. */
3083 if (!mac_ismsgid(argv[msg_action_arg]))
3084 exim_fail("exim: malformed message id %s after %s option\n",
3085 argv[msg_action_arg], arg);
3091 /* Some programs seem to call the -om option without the leading o;
3092 for sendmail it askes for "me too". Exim always does this. */
3095 if (*argrest) badarg = TRUE;
3099 /* -N: don't do delivery - a debugging option that stops transports doing
3100 their thing. It implies debugging at the D_v level. */
3105 f.dont_deliver = TRUE;
3106 debug_selector |= D_v;
3107 debug_file = stderr;
3113 /* -n: This means "don't alias" in sendmail, apparently.
3114 For normal invocations, it has no effect.
3115 It may affect some other options. */
3121 /* -O: Just ignore it. In sendmail, apparently -O option=value means set
3122 option to the specified value. This form uses long names. We need to handle
3123 -O option=value and -Ooption=value. */
3128 exim_fail("exim: string expected after -O\n");
3134 /* -oA: Set an argument for the bi command (sendmail's "alternate alias
3137 if (!*(alias_arg = argrest))
3138 if (i+1 < argc) alias_arg = argv[++i];
3139 else exim_fail("exim: string expected after -oA\n");
3142 /* -oB: Set a connection message max value for remote deliveries */
3145 uschar * p = argrest;
3147 if (i+1 < argc && isdigit((argv[i+1][0])))
3151 connection_max_messages = 1;
3158 exim_fail("exim: number expected after -oB\n");
3159 connection_max_messages = Uatoi(p);
3164 /* -odb: background delivery */
3167 if (Ustrcmp(argrest, "b") == 0)
3169 f.synchronous_delivery = FALSE;
3170 arg_queue_only = FALSE;
3171 queue_only_set = TRUE;
3174 /* -odd: testsuite-only: add no inter-process delays */
3176 else if (Ustrcmp(argrest, "d") == 0)
3177 f.testsuite_delays = FALSE;
3179 /* -odf: foreground delivery (smail-compatible option); same effect as
3180 -odi: interactive (synchronous) delivery (sendmail-compatible option)
3183 else if (Ustrcmp(argrest, "f") == 0 || Ustrcmp(argrest, "i") == 0)
3185 f.synchronous_delivery = TRUE;
3186 arg_queue_only = FALSE;
3187 queue_only_set = TRUE;
3190 /* -odq: queue only */
3192 else if (Ustrcmp(argrest, "q") == 0)
3194 f.synchronous_delivery = FALSE;
3195 arg_queue_only = TRUE;
3196 queue_only_set = TRUE;
3199 /* -odqs: queue SMTP only - do local deliveries and remote routing,
3200 but no remote delivery */
3202 else if (Ustrcmp(argrest, "qs") == 0)
3204 f.queue_smtp = TRUE;
3205 arg_queue_only = FALSE;
3206 queue_only_set = TRUE;
3211 /* -oex: Sendmail error flags. As these are also accepted without the
3212 leading -o prefix, for compatibility with vacation and other callers,
3213 they are handled with -e above. */
3215 /* -oi: Set flag so dot doesn't end non-SMTP input (same as -i)
3216 -oitrue: Another sendmail syntax for the same */
3219 if (!*argrest || Ustrcmp(argrest, "true") == 0)
3224 /* -oM*: Set various characteristics for an incoming message; actually
3225 acted on for trusted callers only. */
3230 exim_fail("exim: data expected after -oM%s\n", argrest);
3232 /* -oMa: Set sender host address */
3234 if (Ustrcmp(argrest, "a") == 0)
3235 sender_host_address = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_IPADDR_MAX, "-oMa"), TRUE);
3237 /* -oMaa: Set authenticator name */
3239 else if (Ustrcmp(argrest, "aa") == 0)
3240 sender_host_authenticated = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_DRIVERNAME_MAX, "-oMaa"), TRUE);
3242 /* -oMas: setting authenticated sender */
3244 else if (Ustrcmp(argrest, "as") == 0)
3245 authenticated_sender = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_EMAILADDR_MAX, "-oMas"), TRUE);
3247 /* -oMai: setting authenticated id */
3249 else if (Ustrcmp(argrest, "ai") == 0)
3250 authenticated_id = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_EMAILADDR_MAX, "-oMas"), TRUE);
3252 /* -oMi: Set incoming interface address */
3254 else if (Ustrcmp(argrest, "i") == 0)
3255 interface_address = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_IPADDR_MAX, "-oMi"), TRUE);
3257 /* -oMm: Message reference */
3259 else if (Ustrcmp(argrest, "m") == 0)
3261 if (!mac_ismsgid(argv[i+1]))
3262 exim_fail("-oMm must be a valid message ID\n");
3263 if (!f.trusted_config)
3264 exim_fail("-oMm must be called by a trusted user/config\n");
3265 message_reference = argv[++i];
3268 /* -oMr: Received protocol */
3270 else if (Ustrcmp(argrest, "r") == 0)
3272 if (received_protocol)
3273 exim_fail("received_protocol is set already\n");
3275 received_protocol = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_DRIVERNAME_MAX, "-oMr"), TRUE);
3277 /* -oMs: Set sender host name */
3279 else if (Ustrcmp(argrest, "s") == 0)
3280 sender_host_name = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_HOSTNAME_MAX, "-oMs"), TRUE);
3282 /* -oMt: Set sender ident */
3284 else if (Ustrcmp(argrest, "t") == 0)
3286 sender_ident_set = TRUE;
3287 sender_ident = string_copy_taint(exim_str_fail_toolong(argv[++i], EXIM_IDENTUSER_MAX, "-oMt"), TRUE);
3290 /* Else a bad argument */
3297 /* -om: Me-too flag for aliases. Exim always does this. Some programs
3298 seem to call this as -m (undocumented), so that is also accepted (see
3300 /* -oo: An ancient flag for old-style addresses which still seems to
3301 crop up in some calls (see in SCO). */
3305 if (*argrest) badarg = TRUE;
3308 /* -oP <name>: set pid file path for daemon
3309 -oPX: delete pid file of daemon */
3312 if (!f.running_in_test_harness && real_uid != root_uid && real_uid != exim_uid)
3313 exim_fail("exim: only uid=%d or uid=%d can use -oP and -oPX "
3314 "(uid=%d euid=%d | %d)\n",
3315 root_uid, exim_uid, getuid(), geteuid(), real_uid);
3316 if (!*argrest) override_pid_file_path = argv[++i];
3317 else if (Ustrcmp(argrest, "X") == 0) delete_pid_file();
3322 /* -or <n>: set timeout for non-SMTP acceptance
3323 -os <n>: set timeout for SMTP acceptance */
3328 int * tp = argrest[-1] == 'r'
3329 ? &arg_receive_timeout : &arg_smtp_receive_timeout;
3331 *tp = readconf_readtime(argrest, 0, FALSE);
3332 else if (i+1 < argc)
3333 *tp = readconf_readtime(argv[++i], 0, FALSE);
3336 exim_fail("exim: bad time value %s: abandoned\n", argv[i]);
3340 /* -oX <list>: Override local_interfaces and/or default daemon ports */
3341 /* Limits: Is there a real limit we want here? 1024 is very arbitrary. */
3344 if (*argrest) badarg = TRUE;
3345 else override_local_interfaces = string_copy_taint(exim_str_fail_toolong(argv[++i], 1024, "-oX"), TRUE);
3348 /* -oY: Override creation of daemon notifier socket */
3351 if (*argrest) badarg = TRUE;
3352 else notifier_socket = NULL;
3355 /* Unknown -o argument */
3363 /* -ps: force Perl startup; -pd force delayed Perl startup */
3367 if (*argrest == 's' && argrest[1] == 0)
3369 perl_start_option = 1;
3372 if (*argrest == 'd' && argrest[1] == 0)
3374 perl_start_option = -1;
3379 /* -panythingelse is taken as the Sendmail-compatible argument -prval:sval,
3380 which sets the host protocol and host name */
3383 if (i+1 < argc) argrest = argv[++i]; else { badarg = TRUE; break; }
3387 uschar * hn = Ustrchr(argrest, ':');
3389 if (received_protocol)
3390 exim_fail("received_protocol is set already\n");
3393 received_protocol = string_copy_taint(exim_str_fail_toolong(argrest, EXIM_DRIVERNAME_MAX, "-p<protocol>"), TRUE);
3396 (void) exim_str_fail_toolong(argrest, (EXIM_DRIVERNAME_MAX+1+EXIM_HOSTNAME_MAX), "-p<protocol>:<host>");
3397 received_protocol = string_copyn_taint(argrest, hn - argrest, TRUE);
3398 sender_host_name = string_copy_taint(hn + 1, TRUE);
3405 receiving_message = FALSE;
3406 if (queue_interval >= 0)
3407 exim_fail("exim: -q specified more than once\n");
3409 /* -qq...: Do queue runs in a 2-stage manner */
3411 if (*argrest == 'q')
3413 f.queue_2stage = TRUE;
3417 /* -qi...: Do only first (initial) deliveries */
3419 if (*argrest == 'i')
3421 f.queue_run_first_delivery = TRUE;
3425 /* -qf...: Run the queue, forcing deliveries
3426 -qff..: Ditto, forcing thawing as well */
3428 if (*argrest == 'f')
3430 f.queue_run_force = TRUE;
3431 if (*++argrest == 'f')
3433 f.deliver_force_thaw = TRUE;
3438 /* -q[f][f]l...: Run the queue only on local deliveries */
3440 if (*argrest == 'l')
3442 f.queue_run_local = TRUE;
3446 /* -q[f][f][l][G<name>]... Work on the named queue */
3448 if (*argrest == 'G')
3451 for (argrest++, i = 0; argrest[i] && argrest[i] != '/'; ) i++;
3452 exim_len_fail_toolong(i, EXIM_DRIVERNAME_MAX, "-q*G<name>");
3453 queue_name = string_copyn(argrest, i);
3455 if (*argrest == '/') argrest++;
3458 /* -q[f][f][l][G<name>]: Run the queue, optionally forced, optionally local
3459 only, optionally named, optionally starting from a given message id. */
3461 if (!(list_queue || count_queue))
3463 && (i + 1 >= argc || argv[i+1][0] == '-' || mac_ismsgid(argv[i+1])))
3466 if (i+1 < argc && mac_ismsgid(argv[i+1]))
3467 start_queue_run_id = string_copy_taint(argv[++i], TRUE);
3468 if (i+1 < argc && mac_ismsgid(argv[i+1]))
3469 stop_queue_run_id = string_copy_taint(argv[++i], TRUE);
3472 /* -q[f][f][l][G<name>/]<n>: Run the queue at regular intervals, optionally
3473 forced, optionally local only, optionally named. */
3475 else if ((queue_interval = readconf_readtime(*argrest ? argrest : argv[++i],
3477 exim_fail("exim: bad time value %s: abandoned\n", argv[i]);
3481 case 'R': /* Synonymous with -qR... */
3483 const uschar *tainted_selectstr;
3485 receiving_message = FALSE;
3487 /* -Rf: As -R (below) but force all deliveries,
3488 -Rff: Ditto, but also thaw all frozen messages,
3489 -Rr: String is regex
3490 -Rrf: Regex and force
3491 -Rrff: Regex and force and thaw
3493 in all cases provided there are no further characters in this
3497 for (int i = 0; i < nelem(rsopts); i++)
3498 if (Ustrcmp(argrest, rsopts[i]) == 0)
3500 if (i != 2) f.queue_run_force = TRUE;
3501 if (i >= 2) f.deliver_selectstring_regex = TRUE;
3502 if (i == 1 || i == 4) f.deliver_force_thaw = TRUE;
3503 argrest += Ustrlen(rsopts[i]);
3506 /* -R: Set string to match in addresses for forced queue run to
3507 pick out particular messages. */
3509 /* Avoid attacks from people providing very long strings, and do so before
3512 tainted_selectstr = argrest;
3513 else if (i+1 < argc)
3514 tainted_selectstr = argv[++i];
3516 exim_fail("exim: string expected after -R\n");
3517 deliver_selectstring = string_copy_taint(exim_str_fail_toolong(tainted_selectstr, EXIM_EMAILADDR_MAX, "-R"), TRUE);
3521 /* -r: an obsolete synonym for -f (see above) */
3524 /* -S: Like -R but works on sender. */
3526 case 'S': /* Synonymous with -qS... */
3528 const uschar *tainted_selectstr;
3530 receiving_message = FALSE;
3532 /* -Sf: As -S (below) but force all deliveries,
3533 -Sff: Ditto, but also thaw all frozen messages,
3534 -Sr: String is regex
3535 -Srf: Regex and force
3536 -Srff: Regex and force and thaw
3538 in all cases provided there are no further characters in this
3542 for (int i = 0; i < nelem(rsopts); i++)
3543 if (Ustrcmp(argrest, rsopts[i]) == 0)
3545 if (i != 2) f.queue_run_force = TRUE;
3546 if (i >= 2) f.deliver_selectstring_sender_regex = TRUE;
3547 if (i == 1 || i == 4) f.deliver_force_thaw = TRUE;
3548 argrest += Ustrlen(rsopts[i]);
3551 /* -S: Set string to match in addresses for forced queue run to
3552 pick out particular messages. */
3555 tainted_selectstr = argrest;
3556 else if (i+1 < argc)
3557 tainted_selectstr = argv[++i];
3559 exim_fail("exim: string expected after -S\n");
3560 deliver_selectstring_sender = string_copy_taint(exim_str_fail_toolong(tainted_selectstr, EXIM_EMAILADDR_MAX, "-S"), TRUE);
3564 /* -Tqt is an option that is exclusively for use by the testing suite.
3565 It is not recognized in other circumstances. It allows for the setting up
3566 of explicit "queue times" so that various warning/retry things can be
3567 tested. Otherwise variability of clock ticks etc. cause problems. */
3570 if (f.running_in_test_harness && Ustrcmp(argrest, "qt") == 0)
3571 fudged_queue_times = string_copy_taint(argv[++i], TRUE);
3576 /* -t: Set flag to extract recipients from body of message. */
3579 if (!*argrest) extract_recipients = TRUE;
3581 /* -ti: Set flag to extract recipients from body of message, and also
3582 specify that dot does not end the message. */
3584 else if (Ustrcmp(argrest, "i") == 0)
3586 extract_recipients = TRUE;
3590 /* -tls-on-connect: don't wait for STARTTLS (for old clients) */
3593 else if (Ustrcmp(argrest, "ls-on-connect") == 0) tls_in.on_connect = TRUE;
3600 /* -U: This means "initial user submission" in sendmail, apparently. The
3601 doc claims that in future sendmail may refuse syntactically invalid
3602 messages instead of fixing them. For the moment, we just ignore it. */
3608 /* -v: verify things - this is a very low-level debugging */
3613 debug_selector |= D_v;
3614 debug_file = stderr;
3620 /* -x: AIX uses this to indicate some fancy 8-bit character stuff:
3622 The -x flag tells the sendmail command that mail from a local
3623 mail program has National Language Support (NLS) extended characters
3624 in the body of the mail item. The sendmail command can send mail with
3625 extended NLS characters across networks that normally corrupts these
3628 As Exim is 8-bit clean, it just ignores this flag. */
3631 if (*argrest) badarg = TRUE;
3634 /* -X: in sendmail: takes one parameter, logfile, and sends debugging
3635 logs to that file. We swallow the parameter and otherwise ignore it. */
3640 exim_fail("exim: string expected after -X\n");
3643 /* -z: a line of text to log */
3648 log_oneline = string_copy_taint(exim_str_fail_toolong(argv[i], 2048, "-z logtext"), TRUE);
3650 exim_fail("exim: file name expected after %s\n", argv[i-1]);
3653 /* All other initial characters are errors */
3658 } /* End of high-level switch statement */
3660 /* Failed to recognize the option, or syntax error */
3663 exim_fail("exim abandoned: unknown, malformed, or incomplete "
3664 "option %s\n", arg);
3668 /* If -R or -S have been specified without -q, assume a single queue run. */
3670 if ( (deliver_selectstring || deliver_selectstring_sender)
3671 && queue_interval < 0)
3676 store_pool = old_pool;
3679 /* If usage_wanted is set we call the usage function - which never returns */
3680 if (usage_wanted) exim_usage(called_as);
3682 /* Arguments have been processed. Check for incompatibilities. */
3683 if ( ( (smtp_input || extract_recipients || recipients_arg < argc)
3684 && ( f.daemon_listen || queue_interval >= 0 || bi_option
3685 || test_retry_arg >= 0 || test_rewrite_arg >= 0
3686 || filter_test != FTEST_NONE
3687 || msg_action_arg > 0 && !one_msg_action
3689 || ( msg_action_arg > 0
3690 && ( f.daemon_listen || queue_interval > 0 || list_options
3691 || checking && msg_action != MSG_LOAD
3692 || bi_option || test_retry_arg >= 0 || test_rewrite_arg >= 0
3694 || ( (f.daemon_listen || queue_interval > 0)
3695 && ( sender_address || list_options || list_queue || checking
3698 || f.daemon_listen && queue_interval == 0
3699 || f.inetd_wait_mode && queue_interval >= 0
3701 && ( checking || smtp_input || extract_recipients
3702 || filter_test != FTEST_NONE || bi_option
3704 || ( verify_address_mode
3705 && ( f.address_test_mode || smtp_input || extract_recipients
3706 || filter_test != FTEST_NONE || bi_option
3708 || ( f.address_test_mode
3709 && ( smtp_input || extract_recipients || filter_test != FTEST_NONE
3713 && (sender_address || filter_test != FTEST_NONE || extract_recipients)
3715 || deliver_selectstring && queue_interval < 0
3716 || msg_action == MSG_LOAD && (!expansion_test || expansion_test_message)
3718 exim_fail("exim: incompatible command-line options or arguments\n");
3720 /* If debugging is set up, set the file and the file descriptor to pass on to
3721 child processes. It should, of course, be 2 for stderr. Also, force the daemon
3722 to run in the foreground. */
3724 if (debug_selector != 0)
3726 debug_file = stderr;
3727 debug_fd = fileno(debug_file);
3728 f.background_daemon = FALSE;
3729 testharness_pause_ms(100); /* lets caller finish */
3730 if (debug_selector != D_v) /* -v only doesn't show this */
3732 debug_printf("Exim version %s uid=%ld gid=%ld pid=%d D=%x\n",
3733 version_string, (long int)real_uid, (long int)real_gid, (int)getpid(),
3735 if (!version_printed)
3736 show_whats_supported(stderr);
3740 /* When started with root privilege, ensure that the limits on the number of
3741 open files and the number of processes (where that is accessible) are
3742 sufficiently large, or are unset, in case Exim has been called from an
3743 environment where the limits are screwed down. Not all OS have the ability to
3744 change some of these limits. */
3748 DEBUG(D_any) debug_print_ids(US"Exim has no root privilege:");
3754 #ifdef RLIMIT_NOFILE
3755 if (getrlimit(RLIMIT_NOFILE, &rlp) < 0)
3757 log_write(0, LOG_MAIN|LOG_PANIC, "getrlimit(RLIMIT_NOFILE) failed: %s",
3759 rlp.rlim_cur = rlp.rlim_max = 0;
3762 /* I originally chose 1000 as a nice big number that was unlikely to
3763 be exceeded. It turns out that some older OS have a fixed upper limit of
3766 if (rlp.rlim_cur < 1000)
3768 rlp.rlim_cur = rlp.rlim_max = 1000;
3769 if (setrlimit(RLIMIT_NOFILE, &rlp) < 0)
3771 rlp.rlim_cur = rlp.rlim_max = 256;
3772 if (setrlimit(RLIMIT_NOFILE, &rlp) < 0)
3773 log_write(0, LOG_MAIN|LOG_PANIC, "setrlimit(RLIMIT_NOFILE) failed: %s",
3780 if (getrlimit(RLIMIT_NPROC, &rlp) < 0)
3782 log_write(0, LOG_MAIN|LOG_PANIC, "getrlimit(RLIMIT_NPROC) failed: %s",
3784 rlp.rlim_cur = rlp.rlim_max = 0;
3787 # ifdef RLIM_INFINITY
3788 if (rlp.rlim_cur != RLIM_INFINITY && rlp.rlim_cur < 1000)
3790 rlp.rlim_cur = rlp.rlim_max = RLIM_INFINITY;
3792 if (rlp.rlim_cur < 1000)
3794 rlp.rlim_cur = rlp.rlim_max = 1000;
3796 if (setrlimit(RLIMIT_NPROC, &rlp) < 0)
3797 log_write(0, LOG_MAIN|LOG_PANIC, "setrlimit(RLIMIT_NPROC) failed: %s",
3803 /* Exim is normally entered as root (but some special configurations are
3804 possible that don't do this). However, it always spins off sub-processes that
3805 set their uid and gid as required for local delivery. We don't want to pass on
3806 any extra groups that root may belong to, so we want to get rid of them all at
3809 We need to obey setgroups() at this stage, before possibly giving up root
3810 privilege for a changed configuration file, but later on we might need to
3811 check on the additional groups for the admin user privilege - can't do that
3812 till after reading the config, which might specify the exim gid. Therefore,
3813 save the group list here first. */
3815 if ((group_count = getgroups(nelem(group_list), group_list)) < 0)
3816 exim_fail("exim: getgroups() failed: %s\n", strerror(errno));
3818 /* There is a fundamental difference in some BSD systems in the matter of
3819 groups. FreeBSD and BSDI are known to be different; NetBSD and OpenBSD are
3820 known not to be different. On the "different" systems there is a single group
3821 list, and the first entry in it is the current group. On all other versions of
3822 Unix there is a supplementary group list, which is in *addition* to the current
3823 group. Consequently, to get rid of all extraneous groups on a "standard" system
3824 you pass over 0 groups to setgroups(), while on a "different" system you pass
3825 over a single group - the current group, which is always the first group in the
3826 list. Calling setgroups() with zero groups on a "different" system results in
3827 an error return. The following code should cope with both types of system.
3829 Unfortunately, recent MacOS, which should be a FreeBSD, "helpfully" succeeds
3830 the "setgroups() with zero groups" - and changes the egid.
3831 Thanks to that we had to stash the original_egid above, for use below
3832 in the call to exim_setugid().
3834 However, if this process isn't running as root, setgroups() can't be used
3835 since you have to be root to run it, even if throwing away groups.
3836 Except, sigh, for Hurd - where you can.
3837 Not being root here happens only in some unusual configurations. */
3840 #ifndef OS_SETGROUPS_ZERO_DROPS_ALL
3841 && setgroups(0, NULL) != 0
3843 && setgroups(1, group_list) != 0)
3844 exim_fail("exim: setgroups() failed: %s\n", strerror(errno));
3846 /* If the configuration file name has been altered by an argument on the
3847 command line (either a new file name or a macro definition) and the caller is
3848 not root, or if this is a filter testing run, remove any setuid privilege the
3849 program has and run as the underlying user.
3851 The exim user is locked out of this, which severely restricts the use of -C
3854 Otherwise, set the real ids to the effective values (should be root unless run
3855 from inetd, which it can either be root or the exim uid, if one is configured).
3857 There is a private mechanism for bypassing some of this, in order to make it
3858 possible to test lots of configurations automatically, without having either to
3859 recompile each time, or to patch in an actual configuration file name and other
3860 values (such as the path name). If running in the test harness, pretend that
3861 configuration file changes and macro definitions haven't happened. */
3864 (!f.trusted_config || /* Config changed, or */
3865 !macros_trusted(opt_D_used)) && /* impermissible macros and */
3866 real_uid != root_uid && /* Not root, and */
3867 !f.running_in_test_harness /* Not fudged */
3869 expansion_test /* expansion testing */
3871 filter_test != FTEST_NONE) /* Filter testing */
3873 setgroups(group_count, group_list);
3874 exim_setugid(real_uid, real_gid, FALSE,
3875 US"-C, -D, -be or -bf forces real uid");
3876 removed_privilege = TRUE;
3878 /* In the normal case when Exim is called like this, stderr is available
3879 and should be used for any logging information because attempts to write
3880 to the log will usually fail. To arrange this, we unset really_exim. However,
3881 if no stderr is available there is no point - we might as well have a go
3882 at the log (if it fails, syslog will be written).
3884 Note that if the invoker is Exim, the logs remain available. Messing with
3885 this causes unlogged successful deliveries. */
3887 if (log_stderr && real_uid != exim_uid)
3888 f.really_exim = FALSE;
3891 /* Privilege is to be retained for the moment. It may be dropped later,
3892 depending on the job that this Exim process has been asked to do. For now, set
3893 the real uid to the effective so that subsequent re-execs of Exim are done by a
3897 exim_setugid(geteuid(), original_egid, FALSE, US"forcing real = effective");
3899 /* If testing a filter, open the file(s) now, before wasting time doing other
3900 setups and reading the message. */
3902 if (filter_test & FTEST_SYSTEM)
3903 if ((filter_sfd = Uopen(filter_test_sfile, O_RDONLY, 0)) < 0)
3904 exim_fail("exim: failed to open %s: %s\n", filter_test_sfile,
3907 if (filter_test & FTEST_USER)
3908 if ((filter_ufd = Uopen(filter_test_ufile, O_RDONLY, 0)) < 0)
3909 exim_fail("exim: failed to open %s: %s\n", filter_test_ufile,
3912 /* Initialise lookup_list
3913 If debugging, already called above via version reporting.
3914 In either case, we initialise the list of available lookups while running
3915 as root. All dynamically modules are loaded from a directory which is
3916 hard-coded into the binary and is code which, if not a module, would be
3917 part of Exim already. Ability to modify the content of the directory
3918 is equivalent to the ability to modify a setuid binary!
3920 This needs to happen before we read the main configuration. */
3923 /*XXX this excrescence could move to the testsuite standard config setup file */
3925 if (f.running_in_test_harness) smtputf8_advertise_hosts = NULL;
3928 /* Read the main runtime configuration data; this gives up if there
3929 is a failure. It leaves the configuration file open so that the subsequent
3930 configuration data for delivery can be read if needed.
3932 NOTE: immediately after opening the configuration file we change the working
3933 directory to "/"! Later we change to $spool_directory. We do it there, because
3934 during readconf_main() some expansion takes place already. */
3936 /* Store the initial cwd before we change directories. Can be NULL if the
3937 dir has already been unlinked. */
3938 initial_cwd = os_getcwd(NULL, 0);
3939 if (!initial_cwd && errno)
3940 exim_fail("exim: getting initial cwd failed: %s\n", strerror(errno));
3942 if (initial_cwd && (strlen(CCS initial_cwd) >= BIG_BUFFER_SIZE))
3943 exim_fail("exim: initial cwd is far too long (%d)\n", Ustrlen(CCS initial_cwd));
3946 -be[m] expansion test -
3947 -b[fF] filter test new
3949 -bmalware malware_test_file new
3951 -brw rewrite test new
3953 -bv[s] address verify -
3955 -bP <option> (except -bP config, which sets list_config)
3957 If any of these options is set, we suppress warnings about configuration
3958 issues (currently about tls_advertise_hosts and keep_environment not being
3962 int old_pool = store_pool;
3963 #ifdef MEASURE_TIMING
3964 struct timeval t0, diff;
3965 (void)gettimeofday(&t0, NULL);
3968 store_pool = POOL_CONFIG;
3969 readconf_main(checking || list_options);
3970 store_pool = old_pool;
3972 #ifdef MEASURE_TIMING
3973 report_time_since(&t0, US"readconf_main (delta)");
3977 /* Now in directory "/" */
3979 if (cleanup_environment() == FALSE)
3980 log_write(0, LOG_PANIC_DIE, "Can't cleanup environment");
3983 /* If an action on specific messages is requested, or if a daemon or queue
3984 runner is being started, we need to know if Exim was called by an admin user.
3985 This is the case if the real user is root or exim, or if the real group is
3986 exim, or if one of the supplementary groups is exim or a group listed in
3987 admin_groups. We don't fail all message actions immediately if not admin_user,
3988 since some actions can be performed by non-admin users. Instead, set admin_user
3989 for later interrogation. */
3991 if (real_uid == root_uid || real_uid == exim_uid || real_gid == exim_gid)
3992 f.admin_user = TRUE;
3994 for (int i = 0; i < group_count && !f.admin_user; i++)
3995 if (group_list[i] == exim_gid)
3996 f.admin_user = TRUE;
3997 else if (admin_groups)
3998 for (int j = 1; j <= (int)admin_groups[0] && !f.admin_user; j++)
3999 if (admin_groups[j] == group_list[i])
4000 f.admin_user = TRUE;
4002 /* Another group of privileged users are the trusted users. These are root,
4003 exim, and any caller matching trusted_users or trusted_groups. Trusted callers
4004 are permitted to specify sender_addresses with -f on the command line, and
4005 other message parameters as well. */
4007 if (real_uid == root_uid || real_uid == exim_uid)
4008 f.trusted_caller = TRUE;
4012 for (int i = 1; i <= (int)trusted_users[0] && !f.trusted_caller; i++)
4013 if (trusted_users[i] == real_uid)
4014 f.trusted_caller = TRUE;
4017 for (int i = 1; i <= (int)trusted_groups[0] && !f.trusted_caller; i++)
4018 if (trusted_groups[i] == real_gid)
4019 f.trusted_caller = TRUE;
4020 else for (int j = 0; j < group_count && !f.trusted_caller; j++)
4021 if (trusted_groups[i] == group_list[j])
4022 f.trusted_caller = TRUE;
4025 /* At this point, we know if the user is privileged and some command-line
4026 options become possibly impermissible, depending upon the configuration file. */
4028 if (checking && commandline_checks_require_admin && !f.admin_user)
4029 exim_fail("exim: those command-line flags are set to require admin\n");
4031 /* Handle the decoding of logging options. */
4033 decode_bits(log_selector, log_selector_size, log_notall,
4034 log_selector_string, log_options, log_options_count, US"log", 0);
4038 debug_printf("configuration file is %s\n", config_main_filename);
4039 debug_printf("log selectors =");
4040 for (int i = 0; i < log_selector_size; i++)
4041 debug_printf(" %08x", log_selector[i]);
4045 /* If domain literals are not allowed, check the sender address that was
4046 supplied with -f. Ditto for a stripped trailing dot. */
4050 if (sender_address[sender_address_domain] == '[' && !allow_domain_literals)
4051 exim_fail("exim: bad -f address \"%s\": domain literals not "
4052 "allowed\n", sender_address);
4053 if (f_end_dot && !strip_trailing_dot)
4054 exim_fail("exim: bad -f address \"%s.\": domain is malformed "
4055 "(trailing dot not allowed)\n", sender_address);
4058 /* See if an admin user overrode our logging. */
4060 if (cmdline_syslog_name)
4063 syslog_processname = cmdline_syslog_name;
4064 log_file_path = string_copy(CUS"syslog");
4067 /* not a panic, non-privileged users should not be able to spam paniclog */
4069 "exim: you lack sufficient privilege to specify syslog process name\n");
4071 /* Paranoia check of maximum lengths of certain strings. There is a check
4072 on the length of the log file path in log.c, which will come into effect
4073 if there are any calls to write the log earlier than this. However, if we
4074 get this far but the string is very long, it is better to stop now than to
4075 carry on and (e.g.) receive a message and then have to collapse. The call to
4076 log_write() from here will cause the ultimate panic collapse if the complete
4077 file name exceeds the buffer length. */
4079 if (Ustrlen(log_file_path) > 200)
4080 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
4081 "log_file_path is longer than 200 chars: aborting");
4083 if (Ustrlen(pid_file_path) > 200)
4084 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
4085 "pid_file_path is longer than 200 chars: aborting");
4087 if (Ustrlen(spool_directory) > 200)
4088 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
4089 "spool_directory is longer than 200 chars: aborting");
4091 /* Length check on the process name given to syslog for its TAG field,
4092 which is only permitted to be 32 characters or less. See RFC 3164. */
4094 if (Ustrlen(syslog_processname) > 32)
4095 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
4096 "syslog_processname is longer than 32 chars: aborting");
4101 log_write(0, LOG_MAIN, "%s", log_oneline);
4102 return EXIT_SUCCESS;
4105 return EXIT_FAILURE;
4107 /* In some operating systems, the environment variable TMPDIR controls where
4108 temporary files are created; Exim doesn't use these (apart from when delivering
4109 to MBX mailboxes), but called libraries such as DBM libraries may require them.
4110 If TMPDIR is found in the environment, reset it to the value defined in the
4111 EXIM_TMPDIR macro, if this macro is defined. For backward compatibility this
4112 macro may be called TMPDIR in old "Local/Makefile"s. It's converted to
4113 EXIM_TMPDIR by the build scripts.
4117 if (environ) for (uschar ** p = USS environ; *p; p++)
4118 if (Ustrncmp(*p, "TMPDIR=", 7) == 0 && Ustrcmp(*p+7, EXIM_TMPDIR) != 0)
4120 uschar * newp = store_malloc(Ustrlen(EXIM_TMPDIR) + 8);
4121 sprintf(CS newp, "TMPDIR=%s", EXIM_TMPDIR);
4123 DEBUG(D_any) debug_printf("reset TMPDIR=%s in environment\n", EXIM_TMPDIR);
4127 /* Timezone handling. If timezone_string is "utc", set a flag to cause all
4128 timestamps to be in UTC (gmtime() is used instead of localtime()). Otherwise,
4129 we may need to get rid of a bogus timezone setting. This can arise when Exim is
4130 called by a user who has set the TZ variable. This then affects the timestamps
4131 in log files and in Received: headers, and any created Date: header lines. The
4132 required timezone is settable in the configuration file, so nothing can be done
4133 about this earlier - but hopefully nothing will normally be logged earlier than
4134 this. We have to make a new environment if TZ is wrong, but don't bother if
4135 timestamps_utc is set, because then all times are in UTC anyway. */
4137 if (timezone_string && strcmpic(timezone_string, US"UTC") == 0)
4138 f.timestamps_utc = TRUE;
4141 uschar *envtz = US getenv("TZ");
4143 ? !timezone_string || Ustrcmp(timezone_string, envtz) != 0
4144 : timezone_string != NULL
4147 uschar **p = USS environ;
4151 if (environ) while (*p++) count++;
4152 if (!envtz) count++;
4153 newp = new = store_malloc(sizeof(uschar *) * (count + 1));
4154 if (environ) for (p = USS environ; *p; p++)
4155 if (Ustrncmp(*p, "TZ=", 3) != 0) *newp++ = *p;
4156 if (timezone_string)
4158 *newp = store_malloc(Ustrlen(timezone_string) + 4);
4159 sprintf(CS *newp++, "TZ=%s", timezone_string);
4164 DEBUG(D_any) debug_printf("Reset TZ to %s: time is %s\n", timezone_string,
4165 tod_stamp(tod_log));
4169 /* Handle the case when we have removed the setuid privilege because of -C or
4170 -D. This means that the caller of Exim was not root.
4172 There is a problem if we were running as the Exim user. The sysadmin may
4173 expect this case to retain privilege because "the binary was called by the
4174 Exim user", but it hasn't, because either the -D option set macros, or the
4175 -C option set a non-trusted configuration file. There are two possibilities:
4177 (1) If deliver_drop_privilege is set, Exim is not going to re-exec in order
4178 to do message deliveries. Thus, the fact that it is running as a
4179 non-privileged user is plausible, and might be wanted in some special
4180 configurations. However, really_exim will have been set false when
4181 privilege was dropped, to stop Exim trying to write to its normal log
4182 files. Therefore, re-enable normal log processing, assuming the sysadmin
4183 has set up the log directory correctly.
4185 (2) If deliver_drop_privilege is not set, the configuration won't work as
4186 apparently intended, and so we log a panic message. In order to retain
4187 root for -C or -D, the caller must either be root or be invoking a
4188 trusted configuration file (when deliver_drop_privilege is false). */
4190 if ( removed_privilege
4191 && (!f.trusted_config || opt_D_used)
4192 && real_uid == exim_uid)
4193 if (deliver_drop_privilege)
4194 f.really_exim = TRUE; /* let logging work normally */
4196 log_write(0, LOG_MAIN|LOG_PANIC,
4197 "exim user lost privilege for using %s option",
4198 f.trusted_config? "-D" : "-C");
4200 /* Start up Perl interpreter if Perl support is configured and there is a
4201 perl_startup option, and the configuration or the command line specifies
4202 initializing starting. Note that the global variables are actually called
4203 opt_perl_xxx to avoid clashing with perl's namespace (perl_*). */
4206 if (perl_start_option != 0)
4207 opt_perl_at_start = (perl_start_option > 0);
4208 if (opt_perl_at_start && opt_perl_startup != NULL)
4211 DEBUG(D_any) debug_printf("Starting Perl interpreter\n");
4212 if ((errstr = init_perl(opt_perl_startup)))
4213 exim_fail("exim: error in perl_startup code: %s\n", errstr);
4214 opt_perl_started = TRUE;
4216 #endif /* EXIM_PERL */
4218 /* Log the arguments of the call if the configuration file said so. This is
4219 a debugging feature for finding out what arguments certain MUAs actually use.
4220 Don't attempt it if logging is disabled, or if listing variables or if
4221 verifying/testing addresses or expansions. */
4223 if ( (debug_selector & D_any || LOGGING(arguments))
4224 && f.really_exim && !list_options && !checking)
4226 uschar *p = big_buffer;
4227 Ustrcpy(p, US"cwd= (failed)");
4234 snprintf(CS p, big_buffer_size - (p - big_buffer), "%s", CCS initial_cwd);
4235 p += Ustrlen(CCS p);
4238 (void)string_format(p, big_buffer_size - (p - big_buffer), " %d args:", argc);
4240 for (int i = 0; i < argc; i++)
4242 int len = Ustrlen(argv[i]);
4243 const uschar *printing;
4245 if (p + len + 8 >= big_buffer + big_buffer_size)
4247 Ustrcpy(p, US" ...");
4248 log_write(0, LOG_MAIN, "%s", big_buffer);
4249 Ustrcpy(big_buffer, US"...");
4252 printing = string_printing(argv[i]);
4253 if (!*printing) quote = US"\"";
4256 const uschar *pp = printing;
4258 while (*pp) if (isspace(*pp++)) { quote = US"\""; break; }
4260 p += sprintf(CS p, " %s%.*s%s", quote, (int)(big_buffer_size -
4261 (p - big_buffer) - 4), printing, quote);
4264 if (LOGGING(arguments))
4265 log_write(0, LOG_MAIN, "%s", big_buffer);
4267 debug_printf("%s\n", big_buffer);
4270 /* Set the working directory to be the top-level spool directory. We don't rely
4271 on this in the code, which always uses fully qualified names, but it's useful
4272 for core dumps etc. Don't complain if it fails - the spool directory might not
4273 be generally accessible and calls with the -C option (and others) have lost
4274 privilege by now. Before the chdir, we try to ensure that the directory exists.
4277 if (Uchdir(spool_directory) != 0)
4279 (void) directory_make(spool_directory, US"", SPOOL_DIRECTORY_MODE, FALSE);
4280 (void) Uchdir(spool_directory);
4283 /* Handle calls with the -bi option. This is a sendmail option to rebuild *the*
4284 alias file. Exim doesn't have such a concept, but this call is screwed into
4285 Sun's YP makefiles. Handle this by calling a configured script, as the real
4286 user who called Exim. The -oA option can be used to pass an argument to the
4291 (void) fclose(config_file);
4292 if (bi_command && *bi_command)
4296 argv[i++] = bi_command;
4297 if (alias_arg) argv[i++] = alias_arg;
4300 setgroups(group_count, group_list);
4301 exim_setugid(real_uid, real_gid, FALSE, US"running bi_command");
4303 DEBUG(D_exec) debug_printf("exec '%.256s' %s%.256s%s\n", argv[0],
4304 argv[1] ? "'" : "", argv[1] ? argv[1] : US"", argv[1] ? "'" : "");
4306 execv(CS argv[0], (char *const *)argv);
4307 exim_fail("exim: exec '%s' failed: %s\n", argv[0], strerror(errno));
4311 DEBUG(D_any) debug_printf("-bi used but bi_command not set; exiting\n");
4316 /* We moved the admin/trusted check to be immediately after reading the
4317 configuration file. We leave these prints here to ensure that syslog setup,
4318 logfile setup, and so on has already happened. */
4320 if (f.trusted_caller) DEBUG(D_any) debug_printf("trusted user\n");
4321 if (f.admin_user) DEBUG(D_any) debug_printf("admin user\n");
4323 /* Only an admin user may start the daemon or force a queue run in the default
4324 configuration, but the queue run restriction can be relaxed. Only an admin
4325 user may request that a message be returned to its sender forthwith. Only an
4326 admin user may specify a debug level greater than D_v (because it might show
4327 passwords, etc. in lookup queries). Only an admin user may request a queue
4328 count. Only an admin user can use the test interface to scan for email
4329 (because Exim will be in the spool dir and able to look at mails). */
4333 BOOL debugset = (debug_selector & ~D_v) != 0;
4334 if ( deliver_give_up || f.daemon_listen || malware_test_file
4335 || count_queue && queue_list_requires_admin
4336 || list_queue && queue_list_requires_admin
4337 || queue_interval >= 0 && prod_requires_admin
4338 || queue_name_dest && prod_requires_admin
4339 || debugset && !f.running_in_test_harness
4341 exim_fail("exim:%s permission denied\n", debugset ? " debugging" : "");
4344 /* If the real user is not root or the exim uid, the argument for passing
4345 in an open TCP/IP connection for another message is not permitted, nor is
4346 running with the -N option for any delivery action, unless this call to exim is
4347 one that supplied an input message, or we are using a patched exim for
4348 regression testing. */
4350 if ( real_uid != root_uid && real_uid != exim_uid
4351 && ( continue_hostname
4353 && (queue_interval >= 0 || f.daemon_listen || msg_action_arg > 0)
4355 && !f.running_in_test_harness
4357 exim_fail("exim: Permission denied\n");
4359 /* If the caller is not trusted, certain arguments are ignored when running for
4360 real, but are permitted when checking things (-be, -bv, -bt, -bh, -bf, -bF).
4361 Note that authority for performing certain actions on messages is tested in the
4362 queue_action() function. */
4364 if (!f.trusted_caller && !checking)
4366 sender_host_name = sender_host_address = interface_address =
4367 sender_ident = received_protocol = NULL;
4368 sender_host_port = interface_port = 0;
4369 sender_host_authenticated = authenticated_sender = authenticated_id = NULL;
4372 /* If a sender host address is set, extract the optional port number off the
4373 end of it and check its syntax. Do the same thing for the interface address.
4374 Exim exits if the syntax is bad. */
4378 if (sender_host_address)
4379 sender_host_port = check_port(sender_host_address);
4380 if (interface_address)
4381 interface_port = check_port(interface_address);
4384 /* If the caller is trusted, then they can use -G to suppress_local_fixups. */
4387 if (f.trusted_caller)
4389 f.suppress_local_fixups = f.suppress_local_fixups_default = TRUE;
4390 DEBUG(D_acl) debug_printf("suppress_local_fixups forced on by -G\n");
4393 exim_fail("exim: permission denied (-G requires a trusted user)\n");
4396 /* If an SMTP message is being received check to see if the standard input is a
4397 TCP/IP socket. If it is, we assume that Exim was called from inetd if the
4398 caller is root or the Exim user, or if the port is a privileged one. Otherwise,
4403 union sockaddr_46 inetd_sock;
4404 EXIM_SOCKLEN_T size = sizeof(inetd_sock);
4405 if (getpeername(0, (struct sockaddr *)(&inetd_sock), &size) == 0)
4407 int family = ((struct sockaddr *)(&inetd_sock))->sa_family;
4408 if (family == AF_INET || family == AF_INET6)
4410 union sockaddr_46 interface_sock;
4411 size = sizeof(interface_sock);
4413 if (getsockname(0, (struct sockaddr *)(&interface_sock), &size) == 0)
4414 interface_address = host_ntoa(-1, &interface_sock, NULL,
4417 if (host_is_tls_on_connect_port(interface_port)) tls_in.on_connect = TRUE;
4419 if (real_uid == root_uid || real_uid == exim_uid || interface_port < 1024)
4422 sender_host_address = host_ntoa(-1, (struct sockaddr *)(&inetd_sock),
4423 NULL, &sender_host_port);
4424 if (mua_wrapper) log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Input from "
4425 "inetd is not supported when mua_wrapper is set");
4429 "exim: Permission denied (unprivileged user, unprivileged port)\n");
4434 /* If the load average is going to be needed while receiving a message, get it
4435 now for those OS that require the first call to os_getloadavg() to be done as
4436 root. There will be further calls later for each message received. */
4438 #ifdef LOAD_AVG_NEEDS_ROOT
4439 if ( receiving_message
4440 && (queue_only_load >= 0 || (f.is_inetd && smtp_load_reserve >= 0)))
4441 load_average = OS_GETLOADAVG();
4444 /* The queue_only configuration option can be overridden by -odx on the command
4445 line, except that if queue_only_override is false, queue_only cannot be unset
4446 from the command line. */
4448 if (queue_only_set && (queue_only_override || arg_queue_only))
4449 queue_only = arg_queue_only;
4451 /* The receive_timeout and smtp_receive_timeout options can be overridden by
4454 if (arg_receive_timeout >= 0) receive_timeout = arg_receive_timeout;
4455 if (arg_smtp_receive_timeout >= 0)
4456 smtp_receive_timeout = arg_smtp_receive_timeout;
4458 /* If Exim was started with root privilege, unless we have already removed the
4459 root privilege above as a result of -C, -D, -be, -bf or -bF, remove it now
4460 except when starting the daemon or doing some kind of delivery or address
4461 testing (-bt). These are the only cases when root need to be retained. We run
4462 as exim for -bv and -bh. However, if deliver_drop_privilege is set, root is
4463 retained only for starting the daemon. We always do the initgroups() in this
4464 situation (controlled by the TRUE below), in order to be as close as possible
4465 to the state Exim usually runs in. */
4467 if ( !unprivileged /* originally had root AND */
4468 && !removed_privilege /* still got root AND */
4469 && !f.daemon_listen /* not starting the daemon */
4470 && queue_interval <= 0 /* (either kind of daemon) */
4471 && ( /* AND EITHER */
4472 deliver_drop_privilege /* requested unprivileged */
4474 queue_interval < 0 /* not running the queue */
4475 && ( msg_action_arg < 0 /* and */
4476 || msg_action != MSG_DELIVER /* not delivering */
4478 && (!checking || !f.address_test_mode) /* not address checking */
4479 && !rcpt_verify_quota /* and not quota checking */
4481 exim_setugid(exim_uid, exim_gid, TRUE, US"privilege not needed");
4483 /* When we are retaining a privileged uid, we still change to the exim gid. */
4488 DEBUG(D_any) debug_printf("dropping to exim gid; retaining priv uid\n");
4489 rv = setgid(exim_gid);
4490 /* Impact of failure is that some stuff might end up with an incorrect group.
4491 We track this for failures from root, since any attempt to change privilege
4492 by root should succeed and failures should be examined. For non-root,
4493 there's no security risk. For me, it's { exim -bV } on a just-built binary,
4494 no need to complain then. */
4496 if (!(unprivileged || removed_privilege))
4497 exim_fail("exim: changing group failed: %s\n", strerror(errno));
4500 DEBUG(D_any) debug_printf("changing group to %ld failed: %s\n",
4501 (long int)exim_gid, strerror(errno));
4505 /* Handle a request to scan a file for malware */
4506 if (malware_test_file)
4508 #ifdef WITH_CONTENT_SCAN
4510 set_process_info("scanning file for malware");
4511 if ((result = malware_in_file(malware_test_file)) == FAIL)
4513 printf("No malware found.\n");
4518 printf("Malware lookup returned non-okay/fail: %d\n", result);
4522 printf("Malware found: %s\n", malware_name);
4524 printf("Malware scan detected malware of unknown name.\n");
4526 printf("Malware scanning not enabled at compile time.\n");
4531 /* Handle a request to list the delivery queue */
4535 set_process_info("listing the queue");
4536 queue_list(list_queue_option, argv + recipients_arg, argc - recipients_arg);
4540 /* Handle a request to count the delivery queue */
4544 set_process_info("counting the queue");
4545 fprintf(stdout, "%u\n", queue_count());
4549 /* Handle actions on specific messages, except for the force delivery and
4550 message load actions, which are done below. Some actions take a whole list of
4551 message ids, which are known to continue up to the end of the arguments. Others
4552 take a single message id and then operate on the recipients list. */
4554 if (msg_action_arg > 0 && msg_action != MSG_DELIVER && msg_action != MSG_LOAD)
4556 int yield = EXIT_SUCCESS;
4557 set_process_info("acting on specified messages");
4559 /* ACL definitions may be needed when removing a message (-Mrm) because
4560 event_action gets expanded */
4562 if (msg_action == MSG_REMOVE)
4564 int old_pool = store_pool;
4565 store_pool = POOL_CONFIG;
4567 store_pool = old_pool;
4568 store_writeprotect(POOL_CONFIG);
4571 if (!one_msg_action)
4573 for (i = msg_action_arg; i < argc; i++)
4574 if (!queue_action(argv[i], msg_action, NULL, 0, 0))
4575 yield = EXIT_FAILURE;
4578 case MSG_REMOVE: case MSG_FREEZE: case MSG_THAW: break;
4579 default: printf("\n"); break;
4583 else if (!queue_action(argv[msg_action_arg], msg_action, argv, argc,
4584 recipients_arg)) yield = EXIT_FAILURE;
4588 /* We used to set up here to skip reading the ACL section, on
4589 (msg_action_arg > 0 || (queue_interval == 0 && !f.daemon_listen)
4590 Now, since the intro of the ${acl } expansion, ACL definitions may be
4591 needed in transports so we lost the optimisation. */
4594 int old_pool = store_pool;
4595 #ifdef MEASURE_TIMING
4596 struct timeval t0, diff;
4597 (void)gettimeofday(&t0, NULL);
4600 store_pool = POOL_CONFIG;
4602 store_pool = old_pool;
4603 store_writeprotect(POOL_CONFIG);
4605 #ifdef MEASURE_TIMING
4606 report_time_since(&t0, US"readconf_rest (delta)");
4610 /* Handle a request to check quota */
4611 if (rcpt_verify_quota)
4612 if (real_uid != root_uid && real_uid != exim_uid)
4613 exim_fail("exim: Permission denied\n");
4614 else if (recipients_arg >= argc)
4615 exim_fail("exim: missing recipient for quota check\n");
4618 verify_quota(argv[recipients_arg]);
4619 exim_exit(EXIT_SUCCESS);
4622 /* Handle the -brt option. This is for checking out retry configurations.
4623 The next three arguments are a domain name or a complete address, and
4624 optionally two error numbers. All it does is to call the function that
4625 scans the retry configuration data. */
4627 if (test_retry_arg >= 0)
4629 retry_config *yield;
4630 int basic_errno = 0;
4632 const uschar *s1, *s2;
4634 if (test_retry_arg >= argc)
4636 printf("-brt needs a domain or address argument\n");
4637 exim_exit(EXIT_FAILURE);
4639 s1 = exim_str_fail_toolong(argv[test_retry_arg++], EXIM_EMAILADDR_MAX, "-brt");
4642 /* If the first argument contains no @ and no . it might be a local user
4643 or it might be a single-component name. Treat as a domain. */
4645 if (Ustrchr(s1, '@') == NULL && Ustrchr(s1, '.') == NULL)
4647 printf("Warning: \"%s\" contains no '@' and no '.' characters. It is "
4648 "being \ntreated as a one-component domain, not as a local part.\n\n",
4652 /* There may be an optional second domain arg. */
4654 if (test_retry_arg < argc && Ustrchr(argv[test_retry_arg], '.') != NULL)
4655 s2 = exim_str_fail_toolong(argv[test_retry_arg++], EXIM_DOMAINNAME_MAX, "-brt 2nd");
4657 /* The final arg is an error name */
4659 if (test_retry_arg < argc)
4661 const uschar *ss = exim_str_fail_toolong(argv[test_retry_arg], EXIM_DRIVERNAME_MAX, "-brt 3rd");
4663 readconf_retry_error(ss, ss + Ustrlen(ss), &basic_errno, &more_errno);
4666 printf("%s\n", CS error);
4667 return EXIT_FAILURE;
4670 /* For the {MAIL,RCPT,DATA}_4xx errors, a value of 255 means "any", and a
4671 code > 100 as an error is for matching codes to the decade. Turn them into
4672 a real error code, off the decade. */
4674 if (basic_errno == ERRNO_MAIL4XX ||
4675 basic_errno == ERRNO_RCPT4XX ||
4676 basic_errno == ERRNO_DATA4XX)
4678 int code = (more_errno >> 8) & 255;
4680 more_errno = (more_errno & 0xffff00ff) | (21 << 8);
4681 else if (code > 100)
4682 more_errno = (more_errno & 0xffff00ff) | ((code - 96) << 8);
4686 if (!(yield = retry_find_config(s1, s2, basic_errno, more_errno)))
4687 printf("No retry information found\n");
4690 more_errno = yield->more_errno;
4691 printf("Retry rule: %s ", yield->pattern);
4693 if (yield->basic_errno == ERRNO_EXIMQUOTA)
4695 printf("quota%s%s ",
4696 (more_errno > 0)? "_" : "",
4697 (more_errno > 0)? readconf_printtime(more_errno) : US"");
4699 else if (yield->basic_errno == ECONNREFUSED)
4701 printf("refused%s%s ",
4702 (more_errno > 0)? "_" : "",
4703 (more_errno == 'M')? "MX" :
4704 (more_errno == 'A')? "A" : "");
4706 else if (yield->basic_errno == ETIMEDOUT)
4709 if ((more_errno & RTEF_CTOUT) != 0) printf("_connect");
4711 if (more_errno != 0) printf("_%s",
4712 (more_errno == 'M')? "MX" : "A");
4715 else if (yield->basic_errno == ERRNO_AUTHFAIL)
4716 printf("auth_failed ");
4719 for (retry_rule * r = yield->rules; r; r = r->next)
4721 printf("%c,%s", r->rule, readconf_printtime(r->timeout)); /* Do not */
4722 printf(",%s", readconf_printtime(r->p1)); /* amalgamate */
4728 printf(",%d.", x/1000);
4742 exim_exit(EXIT_SUCCESS);
4745 /* Handle a request to list one or more configuration options */
4746 /* If -n was set, we suppress some information */
4751 set_process_info("listing variables");
4752 if (recipients_arg >= argc)
4753 fail = !readconf_print(US"all", NULL, flag_n);
4754 else for (i = recipients_arg; i < argc; i++)
4757 (Ustrcmp(argv[i], "router") == 0 ||
4758 Ustrcmp(argv[i], "transport") == 0 ||
4759 Ustrcmp(argv[i], "authenticator") == 0 ||
4760 Ustrcmp(argv[i], "macro") == 0 ||
4761 Ustrcmp(argv[i], "environment") == 0))
4763 fail |= !readconf_print(exim_str_fail_toolong(argv[i+1], EXIM_DRIVERNAME_MAX, "-bP name"), argv[i], flag_n);
4767 fail = !readconf_print(exim_str_fail_toolong(argv[i], EXIM_DRIVERNAME_MAX, "-bP item"), NULL, flag_n);
4769 exim_exit(fail ? EXIT_FAILURE : EXIT_SUCCESS);
4774 set_process_info("listing config");
4775 exim_exit(readconf_print(US"config", NULL, flag_n)
4776 ? EXIT_SUCCESS : EXIT_FAILURE);
4780 /* Initialise subsystems as required. */
4784 /* Handle a request to deliver one or more messages that are already on the
4785 queue. Values of msg_action other than MSG_DELIVER and MSG_LOAD are dealt with
4786 above. MSG_LOAD is handled with -be (which is the only time it applies) below.
4788 Delivery of specific messages is typically used for a small number when
4789 prodding by hand (when the option forced_delivery will be set) or when
4790 re-execing to regain root privilege. Each message delivery must happen in a
4791 separate process, so we fork a process for each one, and run them sequentially
4792 so that debugging output doesn't get intertwined, and to avoid spawning too
4793 many processes if a long list is given. However, don't fork for the last one;
4794 this saves a process in the common case when Exim is called to deliver just one
4797 if (msg_action_arg > 0 && msg_action != MSG_LOAD)
4799 if (prod_requires_admin && !f.admin_user)
4801 fprintf(stderr, "exim: Permission denied\n");
4802 exim_exit(EXIT_FAILURE);
4804 set_process_info("delivering specified messages");
4805 if (deliver_give_up) forced_delivery = f.deliver_force_thaw = TRUE;
4806 for (i = msg_action_arg; i < argc; i++)
4810 /*XXX This use of argv[i] for msg_id should really be tainted, but doing
4811 that runs into a later copy into the untainted global message_id[] */
4812 /*XXX Do we need a length limit check here? */
4814 (void)deliver_message(argv[i], forced_delivery, deliver_give_up);
4815 else if ((pid = exim_fork(US"cmdline-delivery")) == 0)
4817 (void)deliver_message(argv[i], forced_delivery, deliver_give_up);
4818 exim_underbar_exit(EXIT_SUCCESS);
4822 fprintf(stderr, "failed to fork delivery process for %s: %s\n", argv[i],
4824 exim_exit(EXIT_FAILURE);
4828 exim_exit(EXIT_SUCCESS);
4832 /* If only a single queue run is requested, without SMTP listening, we can just
4833 turn into a queue runner, with an optional starting message id. */
4835 if (queue_interval == 0 && !f.daemon_listen)
4837 DEBUG(D_queue_run) debug_printf("Single queue run%s%s%s%s\n",
4838 start_queue_run_id ? US" starting at " : US"",
4839 start_queue_run_id ? start_queue_run_id: US"",
4840 stop_queue_run_id ? US" stopping at " : US"",
4841 stop_queue_run_id ? stop_queue_run_id : US"");
4843 set_process_info("running the '%s' queue (single queue run)", queue_name);
4845 set_process_info("running the queue (single queue run)");
4846 queue_run(start_queue_run_id, stop_queue_run_id, FALSE);
4847 exim_exit(EXIT_SUCCESS);
4851 /* Find the login name of the real user running this process. This is always
4852 needed when receiving a message, because it is written into the spool file. It
4853 may also be used to construct a from: or a sender: header, and in this case we
4854 need the user's full name as well, so save a copy of it, checked for RFC822
4855 syntax and munged if necessary, if it hasn't previously been set by the -F
4856 argument. We may try to get the passwd entry more than once, in case NIS or
4857 other delays are in evidence. Save the home directory for use in filter testing
4862 if ((pw = getpwuid(real_uid)) != NULL)
4864 originator_login = string_copy(US pw->pw_name);
4865 originator_home = string_copy(US pw->pw_dir);
4867 /* If user name has not been set by -F, set it from the passwd entry
4868 unless -f has been used to set the sender address by a trusted user. */
4870 if (!originator_name)
4872 if (!sender_address || (!f.trusted_caller && filter_test == FTEST_NONE))
4874 uschar *name = US pw->pw_gecos;
4875 uschar *amp = Ustrchr(name, '&');
4878 /* Most Unix specify that a '&' character in the gecos field is
4879 replaced by a copy of the login name, and some even specify that
4880 the first character should be upper cased, so that's what we do. */
4885 string_format(buffer, sizeof(buffer), "%.*s%n%s%s",
4886 (int)(amp - name), name, &loffset, originator_login, amp + 1);
4887 buffer[loffset] = toupper(buffer[loffset]);
4891 /* If a pattern for matching the gecos field was supplied, apply
4892 it and then expand the name string. */
4894 if (gecos_pattern && gecos_name)
4896 const pcre2_code *re;
4897 re = regex_must_compile(gecos_pattern, FALSE, TRUE); /* Use malloc */
4899 if (regex_match_and_setup(re, name, 0, -1))
4901 uschar *new_name = expand_string(gecos_name);
4905 DEBUG(D_receive) debug_printf("user name \"%s\" extracted from "
4906 "gecos field \"%s\"\n", new_name, name);
4909 else DEBUG(D_receive) debug_printf("failed to expand gecos_name string "
4910 "\"%s\": %s\n", gecos_name, expand_string_message);
4912 else DEBUG(D_receive) debug_printf("gecos_pattern \"%s\" did not match "
4913 "gecos field \"%s\"\n", gecos_pattern, name);
4914 store_free((void *)re);
4916 originator_name = string_copy(name);
4919 /* A trusted caller has used -f but not -F */
4921 else originator_name = US"";
4924 /* Break the retry loop */
4929 if (++i > finduser_retries) break;
4933 /* If we cannot get a user login, log the incident and give up, unless the
4934 configuration specifies something to use. When running in the test harness,
4935 any setting of unknown_login overrides the actual name. */
4937 if (!originator_login || f.running_in_test_harness)
4941 originator_login = expand_string(unknown_login);
4942 if (!originator_name && unknown_username)
4943 originator_name = expand_string(unknown_username);
4944 if (!originator_name) originator_name = US"";
4946 if (!originator_login)
4947 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to get user name for uid %d",
4951 /* Ensure that the user name is in a suitable form for use as a "phrase" in an
4954 originator_name = US parse_fix_phrase(originator_name, Ustrlen(originator_name));
4956 /* If a message is created by this call of Exim, the uid/gid of its originator
4957 are those of the caller. These values are overridden if an existing message is
4958 read in from the spool. */
4960 originator_uid = real_uid;
4961 originator_gid = real_gid;
4963 DEBUG(D_receive) debug_printf("originator: uid=%d gid=%d login=%s name=%s\n",
4964 (int)originator_uid, (int)originator_gid, originator_login, originator_name);
4966 /* Run in daemon and/or queue-running mode. The function daemon_go() never
4967 returns. We leave this till here so that the originator_ fields are available
4968 for incoming messages via the daemon. The daemon cannot be run in mua_wrapper
4971 if (f.daemon_listen || f.inetd_wait_mode || queue_interval > 0)
4975 fprintf(stderr, "Daemon cannot be run when mua_wrapper is set\n");
4976 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Daemon cannot be run when "
4977 "mua_wrapper is set");
4980 # ifndef DISABLE_TLS
4981 /* This also checks that the library linkage is working and we can call
4982 routines in it, so call even if tls_require_ciphers is unset */
4984 # ifdef MEASURE_TIMING
4985 struct timeval t0, diff;
4986 (void)gettimeofday(&t0, NULL);
4988 if (!tls_dropprivs_validate_require_cipher(FALSE))
4990 # ifdef MEASURE_TIMING
4991 report_time_since(&t0, US"validate_ciphers (delta)");
4999 /* If the sender ident has not been set (by a trusted caller) set it to
5000 the caller. This will get overwritten below for an inetd call. If a trusted
5001 caller has set it empty, unset it. */
5003 if (!sender_ident) sender_ident = originator_login;
5004 else if (!*sender_ident) sender_ident = NULL;
5006 /* Handle the -brw option, which is for checking out rewriting rules. Cause log
5007 writes (on errors) to go to stderr instead. Can't do this earlier, as want the
5008 originator_* variables set. */
5010 if (test_rewrite_arg >= 0)
5012 f.really_exim = FALSE;
5013 if (test_rewrite_arg >= argc)
5015 printf("-brw needs an address argument\n");
5016 exim_exit(EXIT_FAILURE);
5018 rewrite_test(exim_str_fail_toolong(argv[test_rewrite_arg], EXIM_EMAILADDR_MAX, "-brw"));
5019 exim_exit(EXIT_SUCCESS);
5022 /* A locally-supplied message is considered to be coming from a local user
5023 unless a trusted caller supplies a sender address with -f, or is passing in the
5024 message via SMTP (inetd invocation or otherwise). */
5026 if ( !sender_address && !smtp_input
5027 || !f.trusted_caller && filter_test == FTEST_NONE)
5029 f.sender_local = TRUE;
5031 /* A trusted caller can supply authenticated_sender and authenticated_id
5032 via -oMas and -oMai and if so, they will already be set. Otherwise, force
5033 defaults except when host checking. */
5035 if (!authenticated_sender && !host_checking)
5036 authenticated_sender = string_sprintf("%s@%s", originator_login,
5037 qualify_domain_sender);
5038 if (!authenticated_id && !host_checking)
5039 authenticated_id = originator_login;
5042 /* Trusted callers are always permitted to specify the sender address.
5043 Untrusted callers may specify it if it matches untrusted_set_sender, or if what
5044 is specified is the empty address. However, if a trusted caller does not
5045 specify a sender address for SMTP input, we leave sender_address unset. This
5046 causes the MAIL commands to be honoured. */
5048 if ( !smtp_input && !sender_address
5049 || !receive_check_set_sender(sender_address))
5051 /* Either the caller is not permitted to set a general sender, or this is
5052 non-SMTP input and the trusted caller has not set a sender. If there is no
5053 sender, or if a sender other than <> is set, override with the originator's
5054 login (which will get qualified below), except when checking things. */
5056 if ( !sender_address /* No sender_address set */
5058 (sender_address[0] != 0 && /* Non-empty sender address, AND */
5059 !checking)) /* Not running tests, including filter tests */
5061 sender_address = originator_login;
5062 f.sender_address_forced = FALSE;
5063 sender_address_domain = 0;
5067 /* Remember whether an untrusted caller set the sender address */
5069 f.sender_set_untrusted = sender_address != originator_login && !f.trusted_caller;
5071 /* Ensure that the sender address is fully qualified unless it is the empty
5072 address, which indicates an error message, or doesn't exist (root caller, smtp
5073 interface, no -f argument). */
5075 if (sender_address && *sender_address && sender_address_domain == 0)
5076 sender_address = string_sprintf("%s@%s", local_part_quote(sender_address),
5077 qualify_domain_sender);
5079 DEBUG(D_receive) debug_printf("sender address = %s\n", sender_address);
5081 /* Handle a request to verify a list of addresses, or test them for delivery.
5082 This must follow the setting of the sender address, since routers can be
5083 predicated upon the sender. If no arguments are given, read addresses from
5084 stdin. Set debug_level to at least D_v to get full output for address testing.
5087 if (verify_address_mode || f.address_test_mode)
5090 int flags = vopt_qualify;
5092 if (verify_address_mode)
5094 if (!verify_as_sender) flags |= vopt_is_recipient;
5095 DEBUG(D_verify) debug_print_ids(US"Verifying:");
5100 flags |= vopt_is_recipient;
5101 debug_selector |= D_v;
5102 debug_file = stderr;
5103 debug_fd = fileno(debug_file);
5104 DEBUG(D_verify) debug_print_ids(US"Address testing:");
5107 if (recipients_arg < argc)
5108 while (recipients_arg < argc)
5110 /* Supplied addresses are tainted since they come from a user */
5111 uschar * s = string_copy_taint(exim_str_fail_toolong(argv[recipients_arg++], EXIM_DISPLAYMAIL_MAX, "address verification"), TRUE);
5114 BOOL finished = FALSE;
5115 uschar *ss = parse_find_address_end(s, FALSE);
5116 if (*ss == ',') *ss = 0; else finished = TRUE;
5117 test_address(s, flags, &exit_value);
5120 while (*++s == ',' || isspace(*s)) ;
5126 uschar * s = get_stdinput(NULL, NULL);
5128 test_address(string_copy_taint(exim_str_fail_toolong(s, EXIM_DISPLAYMAIL_MAX, "address verification (stdin)"), TRUE), flags, &exit_value);
5132 exim_exit(exit_value);
5135 /* Handle expansion checking. Either expand items on the command line, or read
5136 from stdin if there aren't any. If -Mset was specified, load the message so
5137 that its variables can be used, but restrict this facility to admin users.
5138 Otherwise, if -bem was used, read a message from stdin. */
5142 dns_init(FALSE, FALSE, FALSE);
5143 if (msg_action_arg > 0 && msg_action == MSG_LOAD)
5147 exim_fail("exim: permission denied\n");
5148 message_id = US exim_str_fail_toolong(argv[msg_action_arg], MESSAGE_ID_LENGTH, "message-id");
5149 /* Checking the length of the ID is sufficient to validate it.
5150 Get an untainted version so file opens can be done. */
5151 message_id = string_copy_taint(message_id, FALSE);
5153 spoolname = string_sprintf("%s-H", message_id);
5154 if ((deliver_datafile = spool_open_datafile(message_id)) < 0)
5155 printf ("Failed to load message datafile %s\n", message_id);
5156 if (spool_read_header(spoolname, TRUE, FALSE) != spool_read_OK)
5157 printf ("Failed to load message %s\n", message_id);
5160 /* Read a test message from a file. We fudge it up to be on stdin, saving
5161 stdin itself for later reading of expansion strings. */
5163 else if (expansion_test_message)
5165 int save_stdin = dup(0);
5166 int fd = Uopen(expansion_test_message, O_RDONLY, 0);
5168 exim_fail("exim: failed to open %s: %s\n", expansion_test_message,
5171 filter_test = FTEST_USER; /* Fudge to make it look like filter test */
5172 message_ended = END_NOTENDED;
5173 read_message_body(receive_msg(extract_recipients));
5174 message_linecount += body_linecount;
5175 (void)dup2(save_stdin, 0);
5176 (void)close(save_stdin);
5177 clearerr(stdin); /* Required by Darwin */
5180 /* Only admin users may see config-file macros this way */
5182 if (!f.admin_user) macros_user = macros = mlast = NULL;
5184 /* Allow $recipients for this testing */
5186 f.enable_dollar_recipients = TRUE;
5188 /* Expand command line items */
5190 if (recipients_arg < argc)
5191 while (recipients_arg < argc)
5192 expansion_test_line(exim_str_fail_toolong(argv[recipients_arg++], EXIM_EMAILADDR_MAX, "recipient"));
5198 char *(*fn_readline)(const char *) = NULL;
5199 void (*fn_addhist)(const char *) = NULL;
5203 void *dlhandle = set_readline(&fn_readline, &fn_addhist);
5206 while (s = get_stdinput(fn_readline, fn_addhist))
5207 expansion_test_line(s);
5210 if (dlhandle) dlclose(dlhandle);
5214 /* The data file will be open after -Mset */
5216 if (deliver_datafile >= 0)
5218 (void)close(deliver_datafile);
5219 deliver_datafile = -1;
5222 exim_exit(EXIT_SUCCESS);
5226 /* The active host name is normally the primary host name, but it can be varied
5227 for hosts that want to play several parts at once. We need to ensure that it is
5228 set for host checking, and for receiving messages. */
5230 smtp_active_hostname = primary_hostname;
5231 if (raw_active_hostname != NULL)
5233 uschar *nah = expand_string(raw_active_hostname);
5236 if (!f.expand_string_forcedfail)
5237 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand \"%s\" "
5238 "(smtp_active_hostname): %s", raw_active_hostname,
5239 expand_string_message);
5241 else if (nah[0] != 0) smtp_active_hostname = nah;
5244 /* Handle host checking: this facility mocks up an incoming SMTP call from a
5245 given IP address so that the blocking and relay configuration can be tested.
5246 Unless a sender_ident was set by -oMt, we discard it (the default is the
5247 caller's login name). An RFC 1413 call is made only if we are running in the
5248 test harness and an incoming interface and both ports are specified, because
5249 there is no TCP/IP call to find the ident for. */
5256 if (!sender_ident_set)
5258 sender_ident = NULL;
5259 if (f.running_in_test_harness && sender_host_port
5260 && interface_address && interface_port)
5261 verify_get_ident(1223); /* note hardwired port number */
5264 /* In case the given address is a non-canonical IPv6 address, canonicalize
5265 it. The code works for both IPv4 and IPv6, as it happens. */
5267 size = host_aton(sender_host_address, x);
5268 sender_host_address = store_get(48, FALSE); /* large enough for full IPv6 */
5269 (void)host_nmtoa(size, x, -1, sender_host_address, ':');
5271 /* Now set up for testing */
5273 host_build_sender_fullhost();
5277 f.sender_local = FALSE;
5278 f.sender_host_notsocket = TRUE;
5279 debug_file = stderr;
5280 debug_fd = fileno(debug_file);
5281 fprintf(stdout, "\n**** SMTP testing session as if from host %s\n"
5282 "**** but without any ident (RFC 1413) callback.\n"
5283 "**** This is not for real!\n\n",
5284 sender_host_address);
5286 memset(sender_host_cache, 0, sizeof(sender_host_cache));
5287 if (verify_check_host(&hosts_connection_nolog) == OK)
5288 BIT_CLEAR(log_selector, log_selector_size, Li_smtp_connection);
5289 log_write(L_smtp_connection, LOG_MAIN, "%s", smtp_get_connection_info());
5291 /* NOTE: We do *not* call smtp_log_no_mail() if smtp_start_session() fails,
5292 because a log line has already been written for all its failure exists
5293 (usually "connection refused: <reason>") and writing another one is
5294 unnecessary clutter. */
5296 if (smtp_start_session())
5299 for (; (reset_point = store_mark()); store_reset(reset_point))
5301 if (smtp_setup_msg() <= 0) break;
5302 if (!receive_msg(FALSE)) break;
5304 return_path = sender_address = NULL;
5305 dnslist_domain = dnslist_matched = NULL;
5306 #ifndef DISABLE_DKIM
5307 dkim_cur_signer = NULL;
5310 deliver_localpart_orig = NULL;
5311 deliver_domain_orig = NULL;
5312 callout_address = sending_ip_address = NULL;
5313 deliver_localpart_data = deliver_domain_data =
5314 recipient_data = sender_data = NULL;
5315 sender_rate = sender_rate_limit = sender_rate_period = NULL;
5319 exim_exit(EXIT_SUCCESS);
5323 /* Arrange for message reception if recipients or SMTP were specified;
5324 otherwise complain unless a version print (-bV) happened or this is a filter
5325 verification test or info dump.
5326 In the former case, show the configuration file name. */
5328 if (recipients_arg >= argc && !extract_recipients && !smtp_input)
5330 if (version_printed)
5332 if (Ustrchr(config_main_filelist, ':'))
5333 printf("Configuration file search path is %s\n", config_main_filelist);
5334 printf("Configuration file is %s\n", config_main_filename);
5335 return EXIT_SUCCESS;
5338 if (info_flag != CMDINFO_NONE)
5340 show_exim_information(info_flag, info_stdout ? stdout : stderr);
5341 return info_stdout ? EXIT_SUCCESS : EXIT_FAILURE;
5344 if (filter_test == FTEST_NONE)
5345 exim_usage(called_as);
5349 /* If mua_wrapper is set, Exim is being used to turn an MUA that submits on the
5350 standard input into an MUA that submits to a smarthost over TCP/IP. We know
5351 that we are not called from inetd, because that is rejected above. The
5352 following configuration settings are forced here:
5354 (1) Synchronous delivery (-odi)
5355 (2) Errors to stderr (-oep == -oeq)
5356 (3) No parallel remote delivery
5357 (4) Unprivileged delivery
5359 We don't force overall queueing options because there are several of them;
5360 instead, queueing is avoided below when mua_wrapper is set. However, we do need
5361 to override any SMTP queueing. */
5365 f.synchronous_delivery = TRUE;
5366 arg_error_handling = ERRORS_STDERR;
5367 remote_max_parallel = 1;
5368 deliver_drop_privilege = TRUE;
5369 f.queue_smtp = FALSE;
5370 queue_smtp_domains = NULL;
5372 message_utf8_downconvert = -1; /* convert-if-needed */
5377 /* Prepare to accept one or more new messages on the standard input. When a
5378 message has been read, its id is returned in message_id[]. If doing immediate
5379 delivery, we fork a delivery process for each received message, except for the
5380 last one, where we can save a process switch.
5382 It is only in non-smtp mode that error_handling is allowed to be changed from
5383 its default of ERRORS_SENDER by argument. (Idle thought: are any of the
5384 sendmail error modes other than -oem ever actually used? Later: yes.) */
5386 if (!smtp_input) error_handling = arg_error_handling;
5388 /* If this is an inetd call, ensure that stderr is closed to prevent panic
5389 logging being sent down the socket and make an identd call to get the
5392 else if (f.is_inetd)
5394 (void)fclose(stderr);
5395 exim_nullstd(); /* Re-open to /dev/null */
5396 verify_get_ident(IDENT_PORT);
5397 host_build_sender_fullhost();
5398 set_process_info("handling incoming connection from %s via inetd",
5402 /* If the sender host address has been set, build sender_fullhost if it hasn't
5403 already been done (which it will have been for inetd). This caters for the
5404 case when it is forced by -oMa. However, we must flag that it isn't a socket,
5405 so that the test for IP options is skipped for -bs input. */
5407 if (sender_host_address && !sender_fullhost)
5409 host_build_sender_fullhost();
5410 set_process_info("handling incoming connection from %s via -oMa",
5412 f.sender_host_notsocket = TRUE;
5415 /* Otherwise, set the sender host as unknown except for inetd calls. This
5416 prevents host checking in the case of -bs not from inetd and also for -bS. */
5418 else if (!f.is_inetd) f.sender_host_unknown = TRUE;
5420 /* If stdout does not exist, then dup stdin to stdout. This can happen
5421 if exim is started from inetd. In this case fd 0 will be set to the socket,
5422 but fd 1 will not be set. This also happens for passed SMTP channels. */
5424 if (fstat(1, &statbuf) < 0) (void)dup2(0, 1);
5426 /* Set up the incoming protocol name and the state of the program. Root is
5427 allowed to force received protocol via the -oMr option above. If we have come
5428 via inetd, the process info has already been set up. We don't set
5429 received_protocol here for smtp input, as it varies according to
5430 batch/HELO/EHLO/AUTH/TLS. */
5434 if (!f.is_inetd) set_process_info("accepting a local %sSMTP message from <%s>",
5435 smtp_batched_input? "batched " : "",
5436 (sender_address!= NULL)? sender_address : originator_login);
5440 int old_pool = store_pool;
5441 store_pool = POOL_PERM;
5442 if (!received_protocol)
5443 received_protocol = string_sprintf("local%s", called_as);
5444 store_pool = old_pool;
5445 set_process_info("accepting a local non-SMTP message from <%s>",
5449 /* Initialize the session_local_queue-only flag (this will be ignored if
5450 mua_wrapper is set) */
5453 session_local_queue_only = queue_only;
5455 /* For non-SMTP and for batched SMTP input, check that there is enough space on
5456 the spool if so configured. On failure, we must not attempt to send an error
5457 message! (For interactive SMTP, the check happens at MAIL FROM and an SMTP
5458 error code is given.) */
5460 if ((!smtp_input || smtp_batched_input) && !receive_check_fs(0))
5461 exim_fail("exim: insufficient disk space\n");
5463 /* If this is smtp input of any kind, real or batched, handle the start of the
5466 NOTE: We do *not* call smtp_log_no_mail() if smtp_start_session() fails,
5467 because a log line has already been written for all its failure exists
5468 (usually "connection refused: <reason>") and writing another one is
5469 unnecessary clutter. */
5475 memset(sender_host_cache, 0, sizeof(sender_host_cache));
5476 if (verify_check_host(&hosts_connection_nolog) == OK)
5477 BIT_CLEAR(log_selector, log_selector_size, Li_smtp_connection);
5478 log_write(L_smtp_connection, LOG_MAIN, "%s", smtp_get_connection_info());
5479 if (!smtp_start_session())
5482 exim_exit(EXIT_SUCCESS);
5486 /* Otherwise, set up the input size limit here. */
5490 thismessage_size_limit = expand_string_integer(message_size_limit, TRUE);
5491 if (expand_string_message)
5492 if (thismessage_size_limit == -1)
5493 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand "
5494 "message_size_limit: %s", expand_string_message);
5496 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "invalid value for "
5497 "message_size_limit: %s", expand_string_message);
5500 /* Loop for several messages when reading SMTP input. If we fork any child
5501 processes, we don't want to wait for them unless synchronous delivery is
5502 requested, so set SIGCHLD to SIG_IGN in that case. This is not necessarily the
5503 same as SIG_DFL, despite the fact that documentation often lists the default as
5504 "ignore". This is a confusing area. This is what I know:
5506 At least on some systems (e.g. Solaris), just setting SIG_IGN causes child
5507 processes that complete simply to go away without ever becoming defunct. You
5508 can't then wait for them - but we don't want to wait for them in the
5509 non-synchronous delivery case. However, this behaviour of SIG_IGN doesn't
5510 happen for all OS (e.g. *BSD is different).
5512 But that's not the end of the story. Some (many? all?) systems have the
5513 SA_NOCLDWAIT option for sigaction(). This requests the behaviour that Solaris
5514 has by default, so it seems that the difference is merely one of default
5515 (compare restarting vs non-restarting signals).
5517 To cover all cases, Exim sets SIG_IGN with SA_NOCLDWAIT here if it can. If not,
5518 it just sets SIG_IGN. To be on the safe side it also calls waitpid() at the end
5519 of the loop below. Paranoia rules.
5521 February 2003: That's *still* not the end of the story. There are now versions
5522 of Linux (where SIG_IGN does work) that are picky. If, having set SIG_IGN, a
5523 process then calls waitpid(), a grumble is written to the system log, because
5524 this is logically inconsistent. In other words, it doesn't like the paranoia.
5525 As a consequence of this, the waitpid() below is now excluded if we are sure
5526 that SIG_IGN works. */
5528 if (!f.synchronous_delivery)
5531 struct sigaction act;
5532 act.sa_handler = SIG_IGN;
5533 sigemptyset(&(act.sa_mask));
5534 act.sa_flags = SA_NOCLDWAIT;
5535 sigaction(SIGCHLD, &act, NULL);
5537 signal(SIGCHLD, SIG_IGN);
5541 /* Save the current store pool point, for resetting at the start of
5542 each message, and save the real sender address, if any. */
5544 real_sender_address = sender_address;
5546 /* Loop to receive messages; receive_msg() returns TRUE if there are more
5547 messages to be read (SMTP input), or FALSE otherwise (not SMTP, or SMTP channel
5550 for (BOOL more = TRUE; more; )
5552 rmark reset_point = store_mark();
5555 /* Handle the SMTP case; call smtp_setup_mst() to deal with the initial SMTP
5556 input and build the recipients list, before calling receive_msg() to read the
5557 message proper. Whatever sender address is given in the SMTP transaction is
5558 often ignored for local senders - we use the actual sender, which is normally
5559 either the underlying user running this process or a -f argument provided by
5560 a trusted caller. It is saved in real_sender_address. The test for whether to
5561 accept the SMTP sender is encapsulated in receive_check_set_sender(). */
5566 if ((rc = smtp_setup_msg()) > 0)
5568 if (real_sender_address != NULL &&
5569 !receive_check_set_sender(sender_address))
5571 sender_address = raw_sender = real_sender_address;
5572 sender_address_unrewritten = NULL;
5575 /* For batched SMTP, we have to run the acl_not_smtp_start ACL, since it
5576 isn't really SMTP, so no other ACL will run until the acl_not_smtp one at
5577 the very end. The result of the ACL is ignored (as for other non-SMTP
5578 messages). It is run for its potential side effects. */
5580 if (smtp_batched_input && acl_not_smtp_start != NULL)
5582 uschar *user_msg, *log_msg;
5583 f.enable_dollar_recipients = TRUE;
5584 (void)acl_check(ACL_WHERE_NOTSMTP_START, NULL, acl_not_smtp_start,
5585 &user_msg, &log_msg);
5586 f.enable_dollar_recipients = FALSE;
5589 /* Now get the data for the message */
5591 more = receive_msg(extract_recipients);
5594 cancel_cutthrough_connection(TRUE, US"receive dropped");
5595 if (more) goto MORELOOP;
5596 smtp_log_no_mail(); /* Log no mail if configured */
5597 exim_exit(EXIT_FAILURE);
5602 cancel_cutthrough_connection(TRUE, US"message setup dropped");
5603 smtp_log_no_mail(); /* Log no mail if configured */
5604 exim_exit(rc ? EXIT_FAILURE : EXIT_SUCCESS);
5608 /* In the non-SMTP case, we have all the information from the command
5609 line, but must process it in case it is in the more general RFC822
5610 format, and in any case, to detect syntax errors. Also, it appears that
5611 the use of comma-separated lists as single arguments is common, so we
5612 had better support them. */
5617 int count = argc - recipients_arg;
5618 uschar **list = argv + recipients_arg;
5620 /* These options cannot be changed dynamically for non-SMTP messages */
5622 f.active_local_sender_retain = local_sender_retain;
5623 f.active_local_from_check = local_from_check;
5625 /* Save before any rewriting */
5627 raw_sender = string_copy(sender_address);
5629 /* Loop for each argument (supplied by user hence tainted) */
5631 for (int i = 0; i < count; i++)
5633 int start, end, domain;
5635 /* There can be multiple addresses, so EXIM_DISPLAYMAIL_MAX (tuned for 1) is too short.
5636 * We'll still want to cap it to something, just in case. */
5637 uschar * s = string_copy_taint(exim_str_fail_toolong(list[i], BIG_BUFFER_SIZE, "address argument"), TRUE);
5639 /* Loop for each comma-separated address */
5643 BOOL finished = FALSE;
5645 uschar *ss = parse_find_address_end(s, FALSE);
5647 if (*ss == ',') *ss = 0; else finished = TRUE;
5649 /* Check max recipients - if -t was used, these aren't recipients */
5651 if (recipients_max > 0 && ++rcount > recipients_max &&
5652 !extract_recipients)
5653 if (error_handling == ERRORS_STDERR)
5655 fprintf(stderr, "exim: too many recipients\n");
5656 exim_exit(EXIT_FAILURE);
5660 moan_to_sender(ERRMESS_TOOMANYRECIP, NULL, NULL, stdin, TRUE)?
5661 errors_sender_rc : EXIT_FAILURE;
5665 BOOL b = allow_utf8_domains;
5666 allow_utf8_domains = TRUE;
5669 parse_extract_address(s, &errmess, &start, &end, &domain, FALSE);
5673 if (string_is_utf8(recipient)) message_smtputf8 = TRUE;
5674 else allow_utf8_domains = b;
5679 if (domain == 0 && !f.allow_unqualified_recipient)
5682 errmess = US"unqualified recipient address not allowed";
5686 if (error_handling == ERRORS_STDERR)
5688 fprintf(stderr, "exim: bad recipient address \"%s\": %s\n",
5689 string_printing(list[i]), errmess);
5690 exim_exit(EXIT_FAILURE);
5696 eblock.text1 = string_printing(list[i]);
5697 eblock.text2 = errmess;
5699 moan_to_sender(ERRMESS_BADARGADDRESS, &eblock, NULL, stdin, TRUE)?
5700 errors_sender_rc : EXIT_FAILURE;
5703 receive_add_recipient(string_copy_taint(recipient, TRUE), -1);
5706 while (*(++s) != 0 && (*s == ',' || isspace(*s)));
5710 /* Show the recipients when debugging */
5714 if (sender_address) debug_printf("Sender: %s\n", sender_address);
5715 if (recipients_list)
5717 debug_printf("Recipients:\n");
5718 for (int i = 0; i < recipients_count; i++)
5719 debug_printf(" %s\n", recipients_list[i].address);
5723 /* Run the acl_not_smtp_start ACL if required. The result of the ACL is
5724 ignored; rejecting here would just add complication, and it can just as
5725 well be done later. Allow $recipients to be visible in the ACL. */
5727 if (acl_not_smtp_start)
5729 uschar *user_msg, *log_msg;
5730 f.enable_dollar_recipients = TRUE;
5731 (void)acl_check(ACL_WHERE_NOTSMTP_START, NULL, acl_not_smtp_start,
5732 &user_msg, &log_msg);
5733 f.enable_dollar_recipients = FALSE;
5736 /* Pause for a while waiting for input. If none received in that time,
5737 close the logfile, if we had one open; then if we wait for a long-running
5738 datasource (months, in one use-case) log rotation will not leave us holding
5741 if (!receive_timeout)
5743 struct timeval t = { .tv_sec = 30*60, .tv_usec = 0 }; /* 30 minutes */
5746 FD_ZERO(&r); FD_SET(0, &r);
5747 if (select(1, &r, NULL, NULL, &t) == 0) mainlog_close();
5750 /* Read the data for the message. If filter_test is not FTEST_NONE, this
5751 will just read the headers for the message, and not write anything onto the
5754 message_ended = END_NOTENDED;
5755 more = receive_msg(extract_recipients);
5757 /* more is always FALSE here (not SMTP message) when reading a message
5758 for real; when reading the headers of a message for filter testing,
5759 it is TRUE if the headers were terminated by '.' and FALSE otherwise. */
5761 if (!message_id[0]) exim_exit(EXIT_FAILURE);
5762 } /* Non-SMTP message reception */
5764 /* If this is a filter testing run, there are headers in store, but
5765 no message on the spool. Run the filtering code in testing mode, setting
5766 the domain to the qualify domain and the local part to the current user,
5767 unless they have been set by options. The prefix and suffix are left unset
5768 unless specified. The the return path is set to to the sender unless it has
5769 already been set from a return-path header in the message. */
5771 if (filter_test != FTEST_NONE)
5773 deliver_domain = ftest_domain ? ftest_domain : qualify_domain_recipient;
5774 deliver_domain_orig = deliver_domain;
5775 deliver_localpart = ftest_localpart ? US ftest_localpart : originator_login;
5776 deliver_localpart_orig = deliver_localpart;
5777 deliver_localpart_prefix = US ftest_prefix;
5778 deliver_localpart_suffix = US ftest_suffix;
5779 deliver_home = originator_home;
5783 printf("Return-path copied from sender\n");
5784 return_path = string_copy(sender_address);
5787 printf("Return-path = %s\n", (return_path[0] == 0)? US"<>" : return_path);
5788 printf("Sender = %s\n", (sender_address[0] == 0)? US"<>" : sender_address);
5790 receive_add_recipient(
5791 string_sprintf("%s%s%s@%s",
5792 ftest_prefix ? ftest_prefix : US"",
5794 ftest_suffix ? ftest_suffix : US"",
5795 deliver_domain), -1);
5797 printf("Recipient = %s\n", recipients_list[0].address);
5798 if (ftest_prefix) printf("Prefix = %s\n", ftest_prefix);
5799 if (ftest_suffix) printf("Suffix = %s\n", ftest_suffix);
5801 if (chdir("/")) /* Get away from wherever the user is running this from */
5803 DEBUG(D_receive) debug_printf("chdir(\"/\") failed\n");
5804 exim_exit(EXIT_FAILURE);
5807 /* Now we run either a system filter test, or a user filter test, or both.
5808 In the latter case, headers added by the system filter will persist and be
5809 available to the user filter. We need to copy the filter variables
5812 if (filter_test & FTEST_SYSTEM)
5813 if (!filter_runtest(filter_sfd, filter_test_sfile, TRUE, more))
5814 exim_exit(EXIT_FAILURE);
5816 memcpy(filter_sn, filter_n, sizeof(filter_sn));
5818 if (filter_test & FTEST_USER)
5819 if (!filter_runtest(filter_ufd, filter_test_ufile, FALSE, more))
5820 exim_exit(EXIT_FAILURE);
5822 exim_exit(EXIT_SUCCESS);
5825 /* Else act on the result of message reception. We should not get here unless
5826 message_id[0] is non-zero. If queue_only is set, session_local_queue_only
5827 will be TRUE. If it is not, check on the number of messages received in this
5830 if ( !session_local_queue_only
5831 && smtp_accept_queue_per_connection > 0
5832 && receive_messagecount > smtp_accept_queue_per_connection)
5834 session_local_queue_only = TRUE;
5835 queue_only_reason = 2;
5838 /* Initialize local_queue_only from session_local_queue_only. If it is false,
5839 and queue_only_load is set, check that the load average is below it. If it is
5840 not, set local_queue_only TRUE. If queue_only_load_latch is true (the
5841 default), we put the whole session into queue_only mode. It then remains this
5842 way for any subsequent messages on the same SMTP connection. This is a
5843 deliberate choice; even though the load average may fall, it doesn't seem
5844 right to deliver later messages on the same call when not delivering earlier
5845 ones. However, there are odd cases where this is not wanted, so this can be
5846 changed by setting queue_only_load_latch false. */
5848 if (!(local_queue_only = session_local_queue_only) && queue_only_load >= 0)
5849 if ((local_queue_only = (load_average = OS_GETLOADAVG()) > queue_only_load))
5851 queue_only_reason = 3;
5852 if (queue_only_load_latch) session_local_queue_only = TRUE;
5855 /* If running as an MUA wrapper, all queueing options and freezing options
5859 local_queue_only = f.queue_only_policy = f.deliver_freeze = FALSE;
5861 /* Log the queueing here, when it will get a message id attached, but
5862 not if queue_only is set (case 0). Case 1 doesn't happen here (too many
5865 if (local_queue_only)
5867 cancel_cutthrough_connection(TRUE, US"no delivery; queueing");
5868 switch(queue_only_reason)
5871 log_write(L_delay_delivery,
5872 LOG_MAIN, "no immediate delivery: more than %d messages "
5873 "received in one connection", smtp_accept_queue_per_connection);
5877 log_write(L_delay_delivery,
5878 LOG_MAIN, "no immediate delivery: load average %.2f",
5879 (double)load_average/1000.0);
5884 else if (f.queue_only_policy || f.deliver_freeze)
5885 cancel_cutthrough_connection(TRUE, US"no delivery; queueing");
5887 /* Else do the delivery unless the ACL or local_scan() called for queue only
5888 or froze the message. Always deliver in a separate process. A fork failure is
5889 not a disaster, as the delivery will eventually happen on a subsequent queue
5890 run. The search cache must be tidied before the fork, as the parent will
5891 do it before exiting. The child will trigger a lookup failure and
5892 thereby defer the delivery if it tries to use (for example) a cached ldap
5893 connection that the parent has called unbind on. */
5900 if ((pid = exim_fork(US"local-accept-delivery")) == 0)
5903 close_unwanted(); /* Close unwanted file descriptors and TLS */
5904 exim_nullstd(); /* Ensure std{in,out,err} exist */
5906 /* Re-exec Exim if we need to regain privilege (note: in mua_wrapper
5907 mode, deliver_drop_privilege is forced TRUE). */
5909 if (geteuid() != root_uid && !deliver_drop_privilege && !unprivileged)
5911 delivery_re_exec(CEE_EXEC_EXIT);
5912 /* Control does not return here. */
5915 /* No need to re-exec */
5917 rc = deliver_message(message_id, FALSE, FALSE);
5919 exim_underbar_exit(!mua_wrapper || rc == DELIVER_MUA_SUCCEEDED
5920 ? EXIT_SUCCESS : EXIT_FAILURE);
5925 cancel_cutthrough_connection(TRUE, US"delivery fork failed");
5926 log_write(0, LOG_MAIN|LOG_PANIC, "failed to fork automatic delivery "
5927 "process: %s", strerror(errno));
5931 release_cutthrough_connection(US"msg passed for delivery");
5933 /* In the parent, wait if synchronous delivery is required. This will
5934 always be the case in MUA wrapper mode. */
5936 if (f.synchronous_delivery)
5939 while (wait(&status) != pid);
5940 if ((status & 0x00ff) != 0)
5941 log_write(0, LOG_MAIN|LOG_PANIC,
5942 "process %d crashed with signal %d while delivering %s",
5943 (int)pid, status & 0x00ff, message_id);
5944 if (mua_wrapper && (status & 0xffff) != 0) exim_exit(EXIT_FAILURE);
5949 /* The loop will repeat if more is TRUE. If we do not know know that the OS
5950 automatically reaps children (see comments above the loop), clear away any
5951 finished subprocesses here, in case there are lots of messages coming in
5952 from the same source. */
5954 #ifndef SIG_IGN_WORKS
5955 while (waitpid(-1, NULL, WNOHANG) > 0);
5959 return_path = sender_address = NULL;
5960 authenticated_sender = NULL;
5961 deliver_localpart_orig = NULL;
5962 deliver_domain_orig = NULL;
5963 deliver_host = deliver_host_address = NULL;
5964 dnslist_domain = dnslist_matched = NULL;
5965 #ifdef WITH_CONTENT_SCAN
5966 malware_name = NULL;
5968 callout_address = NULL;
5969 sending_ip_address = NULL;
5970 deliver_localpart_data = deliver_domain_data =
5971 recipient_data = sender_data = NULL;
5973 for(int i = 0; i < REGEX_VARS; i++) regex_vars[i] = NULL;
5975 store_reset(reset_point);
5978 exim_exit(EXIT_SUCCESS); /* Never returns */
5979 return 0; /* To stop compiler warning */