2 * Copyright (c) 1998-2006, 2008, 2009, 2011 Sendmail, Inc. and its suppliers.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
16 #include <sm/sendmail.h>
18 #include <sm/signal.h>
21 SM_UNUSED(static char copyright[]) =
22 "@(#) Copyright (c) 1998-2003 Sendmail, Inc. and its suppliers.\n\
23 All rights reserved.\n\
24 Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.\n\
25 Copyright (c) 1988, 1993\n\
26 The Regents of the University of California. All rights reserved.\n";
29 SM_RCSID("@(#)$Id: main.c,v 8.981 2012/06/14 23:54:02 ca Exp $")
32 #if NETINET || NETINET6
33 # include <arpa/inet.h>
34 #endif /* NETINET || NETINET6 */
37 #include <sendmail/pathnames.h>
40 DebugNoPRestart = SM_DEBUG_INITIALIZER("no_persistent_restart",
41 "@(#)$Debug: no_persistent_restart - don't restart, log only $");
43 static void dump_class __P((STAB *, int));
44 static void obsolete __P((char **));
45 static void testmodeline __P((char *, ENVELOPE *));
46 static char *getextenv __P((const char *));
47 static void sm_printoptions __P((char **));
48 static SIGFUNC_DECL intindebug __P((int));
49 static SIGFUNC_DECL sighup __P((int));
50 static SIGFUNC_DECL sigpipe __P((int));
51 static SIGFUNC_DECL sigterm __P((int));
53 static SIGFUNC_DECL sigusr1 __P((int));
57 ** SENDMAIL -- Post mail to a set of destinations.
59 ** This is the basic mail router. All user mail programs should
60 ** call this routine to actually deliver mail. Sendmail in
61 ** turn calls a bunch of mail servers that do the real work of
62 ** delivering the mail.
64 ** Sendmail is driven by settings read in from /etc/mail/sendmail.cf
65 ** (read by readcf.c).
68 ** /usr/lib/sendmail [flags] addr ...
70 ** See the associated documentation for details.
73 ** Eric Allman, UCB/INGRES (until 10/81).
74 ** Britton-Lee, Inc., purveyors of fine
75 ** database computers (11/81 - 10/88).
76 ** International Computer Science Institute
78 ** UCB/Mammoth Project (10/89 - 7/95).
79 ** InReference, Inc. (8/95 - 1/97).
80 ** Sendmail, Inc. (1/98 - present).
81 ** The support of my employers is gratefully acknowledged.
82 ** Few of them (Britton-Lee in particular) have had
83 ** anything to gain from my involvement in this project.
85 ** Gregory Neil Shapiro,
86 ** Worcester Polytechnic Institute (until 3/98).
87 ** Sendmail, Inc. (3/98 - present).
90 ** Sendmail, Inc. (12/98 - present).
93 char *FullName; /* sender's full name */
94 ENVELOPE BlankEnvelope; /* a "blank" envelope */
95 static ENVELOPE MainEnvelope; /* the envelope around the basic letter */
96 ADDRESS NullAddress = /* a null address */
98 char *CommandLineArgs; /* command line args for pid file */
99 bool Warn_Q_option = false; /* warn about Q option use */
100 static int MissingFds = 0; /* bit map of fds missing on startup */
101 char *Mbdb = "pw"; /* mailbox database defaults to /etc/passwd */
104 GIDSET_T InitialGidSet[NGROUPS_MAX];
105 #endif /* NGROUPS_MAX */
107 #define MAXCONFIGLEVEL 10 /* highest config version level known */
110 static sasl_callback_t srvcallbacks[] =
112 { SASL_CB_VERIFYFILE, (sasl_callback_ft)&safesaslfile, NULL },
113 { SASL_CB_PROXY_POLICY, (sasl_callback_ft)&proxy_policy, NULL },
114 { SASL_CB_LIST_END, NULL, NULL }
118 unsigned int SubmitMode;
119 int SyslogPrefixLen; /* estimated length of syslog prefix */
120 #define PIDLEN 6 /* pid length for computing SyslogPrefixLen */
122 # define SL_FUDGE 10 /* fudge offset for SyslogPrefixLen */
123 #endif /* ! SL_FUDGE */
124 #define SLDLL 8 /* est. length of default syslog label */
127 /* Some options are dangerous to allow users to use in non-submit mode */
128 #define CHECK_AGAINST_OPMODE(cmd) \
131 OpMode != MD_DELIVER && OpMode != MD_SMTP && \
132 OpMode != MD_ARPAFTP && OpMode != MD_CHECKCONFIG && \
133 OpMode != MD_VERIFY && OpMode != MD_TEST) \
135 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
136 "WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \
140 if (extraprivs && queuerun) \
142 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
143 "WARNING: Ignoring submission mode -%c option with -q\n", \
150 main(argc, argv, envp)
157 extern char Version[];
164 int qgrp = NOQGRP; /* queue group to process */
166 BITMAP256 *p_flags = NULL; /* daemon flags */
167 bool warn_C_flag = false;
168 bool auth = true; /* whether to set e_auth_param */
169 char warn_f_flag = '\0';
170 bool run_in_foreground = false; /* -bD mode */
171 bool queuerun = false, debug = false;
174 char *nullserver = NULL;
175 char *authinfo = NULL;
176 char *sysloglabel = NULL; /* label for syslog */
177 char *conffile = NULL; /* name of .cf file */
178 char *queuegroup = NULL; /* queue group to process */
179 char *quarantining = NULL; /* quarantine queue items? */
182 bool queuepersistent = false; /* queue runner process runs forever */
183 bool foregroundqueue = false; /* queue run in foreground */
184 bool save_val; /* to save some bool var. */
185 int cftype; /* which cf file to use? */
187 static time_t starttime = 0; /* when was process started */
188 struct stat traf_st; /* for TrafficLog FIFO check */
190 char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */
191 static char rnamebuf[MAXNAME]; /* holds RealUserName */
192 char *emptyenviron[1];
195 #endif /* STARTTLS */
198 extern int DtableSize;
202 extern char **environ;
204 extern void sm_sasl_init __P((void));
209 #endif /* USE_ENVIRON */
211 /* turn off profiling */
214 /* install default exception handler */
215 sm_exc_newthread(fatal_error);
217 /* set the default in/out channel so errors reported to screen */
219 OutChannel = smioout;
222 ** Check to see if we reentered.
223 ** This would normally happen if e_putheader or e_putbody
224 ** were NULL when invoked.
229 syserr("main: reentered!");
232 starttime = curtime();
234 /* avoid null pointer dereferences */
235 TermEscape.te_rv_on = TermEscape.te_under_on = TermEscape.te_normal = "";
240 /* Check if sendmail is running with extra privs */
241 extraprivs = (RealUid != 0 &&
242 (geteuid() != getuid() || getegid() != getgid()));
244 CurrentPid = getpid();
246 /* get whatever .cf file is right for the opmode */
247 cftype = SM_GET_RIGHT_CF;
249 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
250 DtableSize = getdtsize();
251 if (DtableSize > 256)
255 ** Be sure we have enough file descriptors.
256 ** But also be sure that 0, 1, & 2 are open.
259 /* reset errno and fill_errno; the latter is used way down below */
260 errno = fill_errno = 0;
261 fill_fd(STDIN_FILENO, NULL);
264 fill_fd(STDOUT_FILENO, NULL);
267 fill_fd(STDERR_FILENO, NULL);
271 sm_closefrom(STDERR_FILENO + 1, DtableSize);
277 # define SM_LOG_STR "sendmail"
278 # endif /* ! SM_LOG_STR */
280 openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
281 # else /* LOG_MAIL */
282 openlog(SM_LOG_STR, LOG_PID);
283 # endif /* LOG_MAIL */
287 ** Seed the random number generator.
288 ** Used for queue file names, picking a queue directory, and
294 /* do machine-dependent initializations */
298 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
300 /* reset status from syserr() calls for missing file descriptors */
304 SubmitMode = SUBMIT_UNKNOWN;
305 #if _FFR_LOCAL_DAEMON
308 V6LoopbackAddrFound = false;
309 # endif /* NETINET6 */
310 #endif /* _FFR_LOCAL_DAEMON */
312 checkfd012("after openlog");
315 tTsetup(tTdvect, sizeof(tTdvect), "0-99.1,*_trace_*.1");
318 /* save initial group set for future checks */
319 i = getgroups(NGROUPS_MAX, InitialGidSet);
322 InitialGidSet[0] = (GID_T) -1;
325 while (i < NGROUPS_MAX)
326 InitialGidSet[i++] = InitialGidSet[0];
327 #endif /* NGROUPS_MAX */
329 /* drop group id privileges (RunAsUser not yet set) */
330 dp = drop_privileges(false);
334 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
337 /* arrange to dump state on user-1 signal */
338 (void) sm_signal(SIGUSR1, sigusr1);
342 /* ignore user-1 signal */
343 (void) sm_signal(SIGUSR1, SIG_IGN);
347 /* initialize for setproctitle */
348 initsetproctitle(argc, argv, envp);
350 /* Handle any non-getoptable constructions. */
354 ** Do a quick prescan of the argument list.
358 /* find initial opMode */
361 p = strrchr(*av, '/');
364 if (strcmp(p, "newaliases") == 0)
365 OpMode = MD_INITALIAS;
366 else if (strcmp(p, "mailq") == 0)
368 else if (strcmp(p, "smtpd") == 0)
370 else if (strcmp(p, "hoststat") == 0)
371 OpMode = MD_HOSTSTAT;
372 else if (strcmp(p, "purgestat") == 0)
373 OpMode = MD_PURGESTAT;
375 #if defined(__osf__) || defined(_AIX3)
376 # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:x"
377 #endif /* defined(__osf__) || defined(_AIX3) */
378 #if defined(sony_news)
379 # define OPTIONS "A:B:b:C:cD:d:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
380 #endif /* defined(sony_news) */
382 # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
383 #endif /* ! OPTIONS */
385 /* Set to 0 to allow -b; need to check optarg before using it! */
387 while ((j = getopt(argc, argv, OPTIONS)) != -1)
391 case 'b': /* operations mode */
392 j = (optarg == NULL) ? ' ' : *optarg;
409 #endif /* _FFR_CHECKCONFIG */
413 #if _FFR_LOCAL_DAEMON
418 #endif /* _FFR_LOCAL_DAEMON */
421 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
422 "Frozen configurations unsupported\n");
426 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
427 "Invalid operation mode %c\n",
437 syserr("-D file must be before -d");
441 dp = drop_privileges(true);
443 smdebug = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
444 optarg, SM_IO_APPEND, NULL);
447 syserr("cannot open %s", optarg);
448 ExitStat = EX_CANTCREAT;
451 sm_debug_setfile(smdebug);
457 (void) sm_io_setvbuf(sm_debug_file(), SM_TIME_DEFAULT,
458 (char *) NULL, SM_IO_NBF,
462 case 'G': /* relay (gateway) submission */
463 SubmitMode = SUBMIT_MTA;
469 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
470 "option requires an argument -- '%c'",
474 j = SM_MIN(strlen(optarg), 32) + 1;
475 sysloglabel = xalloc(j);
476 (void) sm_strlcpy(sysloglabel, optarg, j);
477 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
483 /* just check if it is there */
490 /* Don't leak queue information via debug flags */
491 if (extraprivs && queuerun && debug)
493 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
494 "WARNING: Can not use -d with -q. Disabling debugging.\n");
496 sm_debug_setfile(NULL);
497 (void) memset(tTdvect, '\0', sizeof(tTdvect));
501 if (sysloglabel != NULL)
503 /* Sanitize the string */
504 for (p = sysloglabel; *p != '\0'; p++)
506 if (!isascii(*p) || !isprint(*p) || *p == '%')
511 openlog(sysloglabel, LOG_PID, LOG_MAIL);
512 # else /* LOG_MAIL */
513 openlog(sysloglabel, LOG_PID);
514 # endif /* LOG_MAIL */
518 /* set up the blank envelope */
519 BlankEnvelope.e_puthdr = putheader;
520 BlankEnvelope.e_putbody = putbody;
521 BlankEnvelope.e_xfp = NULL;
522 STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
523 CurEnv = &BlankEnvelope;
524 STRUCTCOPY(NullAddress, MainEnvelope.e_from);
527 ** Set default values for variables.
528 ** These cannot be in initialized data space.
531 setdefaults(&BlankEnvelope);
532 initmacros(&BlankEnvelope);
536 if (OpMode == MD_DAEMON)
537 DaemonPid = CurrentPid; /* needed for finis() to work */
539 pw = sm_getpwuid(RealUid);
541 (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof(rnamebuf));
543 (void) sm_snprintf(rnamebuf, sizeof(rnamebuf), "Unknown UID %d",
546 RealUserName = rnamebuf;
550 sm_dprintf("Version %s\n", Version);
551 finis(false, true, EX_OK);
556 ** if running non-set-user-ID binary as non-root, pretend
557 ** we are the RunAsUid
560 if (RealUid != 0 && geteuid() == RealUid)
563 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
567 else if (geteuid() != 0)
568 RunAsUid = geteuid();
571 if (RealUid != 0 && EffGid == RealGid)
576 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
577 (int) geteuid(), (int) getuid(),
578 (int) getegid(), (int) getgid());
579 sm_dprintf("main: RunAsUser = %d:%d\n",
580 (int) RunAsUid, (int) RunAsGid);
583 /* save command line arguments */
585 for (av = argv; *av != NULL; )
586 j += strlen(*av++) + 1;
587 SaveArgv = (char **) xalloc(sizeof(char *) * (argc + 1));
588 CommandLineArgs = xalloc(j);
590 for (av = argv, i = 0; *av != NULL; )
594 SaveArgv[i++] = newstr(*av);
597 (void) sm_strlcpy(p, *av++, j);
606 extern char *CompileOptions[];
608 sm_dprintf("Version %s\n Compiled with:", Version);
609 sm_printoptions(CompileOptions);
613 extern char *OsCompileOptions[];
615 sm_dprintf(" OS Defines:");
616 sm_printoptions(OsCompileOptions);
618 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
619 #endif /* _PATH_UNIX */
621 sm_dprintf(" Conf file:\t%s (default for MSP)\n",
622 getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
624 sm_dprintf(" Conf file:\t%s (default for MTA)\n",
625 getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
627 sm_dprintf(" Pid file:\t%s (default)\n", PidFile);
632 extern char *SmCompileOptions[];
634 sm_dprintf(" libsm Defines:");
635 sm_printoptions(SmCompileOptions);
640 extern char *FFRCompileOptions[];
642 sm_dprintf(" FFR Defines:");
643 sm_printoptions(FFRCompileOptions);
646 /* clear sendmail's environment */
647 ExternalEnviron = environ;
648 emptyenviron[0] = NULL;
649 environ = emptyenviron;
652 ** restore any original TZ setting until TimeZoneSpec has been
653 ** determined - or early log messages may get bogus time stamps
656 if ((p = getextenv("TZ")) != NULL)
661 /* XXX check for reasonable length? */
662 tzlen = strlen(p) + 4;
664 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
666 /* XXX check return code? */
670 /* prime the child environment */
671 sm_setuserenv("AGENT", "sendmail");
673 (void) sm_signal(SIGPIPE, SIG_IGN);
674 OldUmask = umask(022);
675 FullName = getextenv("NAME");
676 if (FullName != NULL)
677 FullName = newstr(FullName);
680 ** Initialize name server if it is going to be used.
684 if (!bitset(RES_INIT, _res.options))
687 _res.options |= RES_DEBUG;
689 _res.options &= ~RES_DEBUG;
690 # ifdef RES_NOALIASES
691 _res.options |= RES_NOALIASES;
692 # endif /* RES_NOALIASES */
693 TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
694 TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
695 TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
696 TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
697 TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
698 TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
699 #endif /* NAMED_BIND */
704 /* initialize some macros, etc. */
705 init_vendor_macros(&BlankEnvelope);
708 macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
711 hp = myhostname(jbuf, sizeof(jbuf));
714 struct utsname utsname;
717 sm_dprintf("Canonical name: %s\n", jbuf);
718 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
719 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
722 p = strchr(jbuf, '.');
723 if (p != NULL && p[1] != '\0')
724 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm', &p[1]);
726 if (uname(&utsname) >= 0)
727 p = utsname.nodename;
731 sm_dprintf("uname failed (%s)\n",
732 sm_errstring(errno));
737 sm_dprintf(" UUCP nodename: %s\n", p);
738 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
744 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
747 sm_dprintf("\ta.k.a.: %s\n", *av);
750 #if NETINET || NETINET6
751 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
755 char buf6[INET6_ADDRSTRLEN];
757 # endif /* NETINET6 */
760 # endif /* NETINET */
764 switch (hp->h_addrtype)
768 if (hp->h_length != INADDRSZ)
771 memmove(&ia, hp->h_addr_list[i], INADDRSZ);
772 (void) sm_snprintf(ipbuf, sizeof(ipbuf),
773 "[%.100s]", inet_ntoa(ia));
775 # endif /* NETINET */
779 if (hp->h_length != IN6ADDRSZ)
782 memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
783 addr = anynet_ntop(&ia6, buf6, sizeof(buf6));
785 (void) sm_snprintf(ipbuf, sizeof(ipbuf),
788 # endif /* NETINET6 */
790 if (ipbuf[0] == '\0')
794 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
795 setclass('w', ipbuf);
797 #endif /* NETINET || NETINET6 */
801 #endif /* NETINET6 */
805 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
807 /* current load average */
810 QueueLimitRecipient = (QUEUE_CHAR *) NULL;
811 QueueLimitSender = (QUEUE_CHAR *) NULL;
812 QueueLimitId = (QUEUE_CHAR *) NULL;
813 QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
820 while ((j = getopt(argc, argv, OPTIONS)) != -1)
824 case 'b': /* operations mode */
828 case 'A': /* use Alternate sendmail/submit.cf */
829 cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
830 : SM_GET_SENDMAIL_CF;
833 case 'B': /* body type */
834 CHECK_AGAINST_OPMODE(j);
835 BlankEnvelope.e_bodytype = newstr(optarg);
838 case 'C': /* select configuration file (already done) */
841 conffile = newstr(optarg);
842 dp = drop_privileges(true);
848 case 'd': /* debugging */
852 case 'f': /* from address */
853 case 'r': /* obsolete -f flag */
854 CHECK_AGAINST_OPMODE(j);
857 usrerr("More than one \"from\" person");
861 if (optarg[0] == '\0')
864 from = newstr(denlstring(optarg, true, true));
865 if (strcmp(RealUserName, from) != 0)
869 case 'F': /* set full name */
870 CHECK_AGAINST_OPMODE(j);
871 FullName = newstr(optarg);
874 case 'G': /* relay (gateway) submission */
876 CHECK_AGAINST_OPMODE(j);
879 case 'h': /* hop count */
880 CHECK_AGAINST_OPMODE(j);
881 BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
883 (void) sm_snprintf(buf, sizeof(buf), "%d",
884 BlankEnvelope.e_hopcount);
885 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
889 usrerr("Bad hop count (%s)", optarg);
894 case 'L': /* program label */
898 case 'n': /* don't alias */
899 CHECK_AGAINST_OPMODE(j);
903 case 'N': /* delivery status notifications */
904 CHECK_AGAINST_OPMODE(j);
905 DefaultNotify |= QHASNOTIFY;
906 macdefine(&BlankEnvelope.e_macro, A_TEMP,
907 macid("{dsn_notify}"), optarg);
908 if (sm_strcasecmp(optarg, "never") == 0)
910 for (p = optarg; p != NULL; optarg = p)
915 if (sm_strcasecmp(optarg, "success") == 0)
916 DefaultNotify |= QPINGONSUCCESS;
917 else if (sm_strcasecmp(optarg, "failure") == 0)
918 DefaultNotify |= QPINGONFAILURE;
919 else if (sm_strcasecmp(optarg, "delay") == 0)
920 DefaultNotify |= QPINGONDELAY;
923 usrerr("Invalid -N argument");
929 case 'o': /* set option */
930 setoption(*optarg, optarg + 1, false, true,
934 case 'O': /* set option (long form) */
935 setoption(' ', optarg, false, true, &BlankEnvelope);
938 case 'p': /* set protocol */
939 CHECK_AGAINST_OPMODE(j);
940 p = strchr(optarg, ':');
948 cleanstrcpy(ep, p, i);
949 macdefine(&BlankEnvelope.e_macro,
955 i = strlen(optarg) + 1;
957 cleanstrcpy(ep, optarg, i);
958 macdefine(&BlankEnvelope.e_macro, A_HEAP,
963 case 'Q': /* change quarantining on queued items */
965 if (OpMode != MD_DELIVER &&
966 OpMode != MD_QUEUERUN)
968 usrerr("Can not use -Q with -b%c", OpMode);
973 if (OpMode == MD_DELIVER)
974 set_op_mode(MD_QUEUERUN);
978 quarantining = newstr(optarg);
981 case 'q': /* run queue files at intervals */
983 if (OpMode != MD_DELIVER &&
984 OpMode != MD_DAEMON &&
985 OpMode != MD_FGDAEMON &&
986 OpMode != MD_PRINT &&
987 OpMode != MD_PRINTNQE &&
988 OpMode != MD_QUEUERUN)
990 usrerr("Can not use -q with -b%c", OpMode);
995 /* don't override -bd, -bD or -bp */
996 if (OpMode == MD_DELIVER)
997 set_op_mode(MD_QUEUERUN);
1000 negate = optarg[0] == '!';
1003 /* negate meaning of pattern match */
1004 optarg++; /* skip '!' for next switch */
1009 case 'G': /* Limit by queue group name */
1012 usrerr("Can not use -q!G");
1013 ExitStat = EX_USAGE;
1016 if (queuegroup != NULL)
1018 usrerr("Can not use multiple -qG options");
1019 ExitStat = EX_USAGE;
1022 queuegroup = newstr(&optarg[1]);
1025 case 'I': /* Limit by ID */
1026 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1027 new->queue_match = newstr(&optarg[1]);
1028 new->queue_negate = negate;
1029 new->queue_next = QueueLimitId;
1033 case 'R': /* Limit by recipient */
1034 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1035 new->queue_match = newstr(&optarg[1]);
1036 new->queue_negate = negate;
1037 new->queue_next = QueueLimitRecipient;
1038 QueueLimitRecipient = new;
1041 case 'S': /* Limit by sender */
1042 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1043 new->queue_match = newstr(&optarg[1]);
1044 new->queue_negate = negate;
1045 new->queue_next = QueueLimitSender;
1046 QueueLimitSender = new;
1049 case 'f': /* foreground queue run */
1050 foregroundqueue = true;
1053 case 'Q': /* Limit by quarantine message */
1054 if (optarg[1] != '\0')
1056 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1057 new->queue_match = newstr(&optarg[1]);
1058 new->queue_negate = negate;
1059 new->queue_next = QueueLimitQuarantine;
1060 QueueLimitQuarantine = new;
1062 QueueMode = QM_QUARANTINE;
1065 case 'L': /* act on lost items */
1066 QueueMode = QM_LOST;
1069 case 'p': /* Persistent queue */
1070 queuepersistent = true;
1071 if (QueueIntvl == 0)
1073 if (optarg[1] == '\0')
1080 QueueIntvl = convtime(optarg, 'm');
1083 usrerr("Invalid -q value");
1084 ExitStat = EX_USAGE;
1087 /* check for bad conversion */
1089 ExitStat = EX_USAGE;
1094 case 'R': /* DSN RET: what to return */
1095 CHECK_AGAINST_OPMODE(j);
1096 if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1098 usrerr("Duplicate -R flag");
1099 ExitStat = EX_USAGE;
1102 BlankEnvelope.e_flags |= EF_RET_PARAM;
1103 if (sm_strcasecmp(optarg, "hdrs") == 0)
1104 BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1105 else if (sm_strcasecmp(optarg, "full") != 0)
1107 usrerr("Invalid -R value");
1108 ExitStat = EX_USAGE;
1110 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1111 macid("{dsn_ret}"), optarg);
1114 case 't': /* read recipients from message */
1115 CHECK_AGAINST_OPMODE(j);
1119 case 'V': /* DSN ENVID: set "original" envelope id */
1120 CHECK_AGAINST_OPMODE(j);
1121 if (!xtextok(optarg))
1123 usrerr("Invalid syntax in -V flag");
1124 ExitStat = EX_USAGE;
1128 BlankEnvelope.e_envid = newstr(optarg);
1129 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1130 macid("{dsn_envid}"), optarg);
1134 case 'X': /* traffic log file */
1135 dp = drop_privileges(true);
1137 if (stat(optarg, &traf_st) == 0 &&
1138 S_ISFIFO(traf_st.st_mode))
1139 TrafficLogFile = sm_io_open(SmFtStdio,
1142 SM_IO_WRONLY, NULL);
1144 TrafficLogFile = sm_io_open(SmFtStdio,
1147 SM_IO_APPEND, NULL);
1148 if (TrafficLogFile == NULL)
1150 syserr("cannot open %s", optarg);
1151 ExitStat = EX_CANTCREAT;
1154 (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1155 NULL, SM_IO_LBF, 0);
1158 /* compatibility flags */
1159 case 'c': /* connect to non-local mailers */
1160 case 'i': /* don't let dot stop me */
1161 case 'm': /* send to me too */
1162 case 'T': /* set timeout interval */
1163 case 'v': /* give blow-by-blow description */
1164 setoption(j, "T", false, true, &BlankEnvelope);
1167 case 'e': /* error message disposition */
1168 case 'M': /* define macro */
1169 setoption(j, optarg, false, true, &BlankEnvelope);
1172 case 's': /* save From lines in headers */
1173 setoption('f', "T", false, true, &BlankEnvelope);
1177 case 'I': /* initialize alias DBM file */
1178 set_op_mode(MD_INITALIAS);
1182 #if defined(__osf__) || defined(_AIX3)
1183 case 'x': /* random flag that OSF/1 & AIX mailx passes */
1185 #endif /* defined(__osf__) || defined(_AIX3) */
1186 #if defined(sony_news)
1188 case 'J': /* ignore flags for Japanese code conversion
1189 implemented on Sony NEWS */
1191 #endif /* defined(sony_news) */
1194 finis(true, true, EX_USAGE);
1200 /* if we've had errors so far, exit now */
1201 if ((ExitStat != EX_OK && OpMode != MD_TEST && OpMode != MD_CHECKCONFIG) ||
1202 ExitStat == EX_OSERR)
1204 finis(false, true, ExitStat);
1208 if (bitset(SUBMIT_MTA, SubmitMode))
1210 /* If set daemon_flags on command line, don't reset it */
1211 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1212 macdefine(&BlankEnvelope.e_macro, A_PERM,
1213 macid("{daemon_flags}"), "CC f");
1215 else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1217 SubmitMode = SUBMIT_MSA;
1219 /* If set daemon_flags on command line, don't reset it */
1220 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1221 macdefine(&BlankEnvelope.e_macro, A_PERM,
1222 macid("{daemon_flags}"), "c u");
1226 ** Do basic initialization.
1227 ** Read system control file.
1228 ** Extract special fields for local use.
1232 checkfd012("before readcf");
1234 vendor_pre_defaults(&BlankEnvelope);
1236 readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1237 safecf, &BlankEnvelope);
1238 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1239 ConfigFileRead = true;
1240 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1241 vendor_post_defaults(&BlankEnvelope);
1243 /* now we can complain about missing fds */
1244 if (MissingFds != 0 && LogLevel > 8)
1249 if (bitset(1 << STDIN_FILENO, MissingFds))
1250 (void) sm_strlcat(mbuf, ", stdin", sizeof(mbuf));
1251 if (bitset(1 << STDOUT_FILENO, MissingFds))
1252 (void) sm_strlcat(mbuf, ", stdout", sizeof(mbuf));
1253 if (bitset(1 << STDERR_FILENO, MissingFds))
1254 (void) sm_strlcat(mbuf, ", stderr", sizeof(mbuf));
1256 /* Notice: fill_errno is from high above: fill_fd() */
1257 sm_syslog(LOG_WARNING, NOQID,
1258 "File descriptors missing on startup: %s; %s",
1259 &mbuf[2], sm_errstring(fill_errno));
1262 /* Remove the ability for a normal user to send signals */
1263 if (RealUid != 0 && RealUid != geteuid())
1265 uid_t new_uid = geteuid();
1269 ** Since we can differentiate between uid and euid,
1270 ** make the uid a different user so the real user
1271 ** can't send signals. However, it doesn't need to be
1272 ** root (euid has root).
1278 sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1279 if (setreuid(new_uid, geteuid()) < 0)
1281 syserr("main: setreuid(%d, %d) failed",
1282 (int) new_uid, (int) geteuid());
1283 finis(false, true, EX_OSERR);
1287 sm_dprintf("Now running as e/ruid %d:%d\n",
1288 (int) geteuid(), (int) getuid());
1289 #else /* HASSETREUID */
1291 ** Have to change both effective and real so need to
1292 ** change them both to effective to keep privs.
1296 sm_dprintf("Changing uid to %d\n", (int) new_uid);
1297 if (setuid(new_uid) < 0)
1299 syserr("main: setuid(%d) failed", (int) new_uid);
1300 finis(false, true, EX_OSERR);
1304 sm_dprintf("Now running as e/ruid %d:%d\n",
1305 (int) geteuid(), (int) getuid());
1306 #endif /* HASSETREUID */
1310 if (FallbackMX != NULL)
1311 (void) getfallbackmxrr(FallbackMX);
1312 #endif /* NAMED_BIND */
1314 if (SuperSafe == SAFE_INTERACTIVE && !SM_IS_INTERACTIVE(CurEnv->e_sendmode))
1316 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1317 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1320 if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1322 usrerr("Mail submission program cannot be used as daemon");
1323 finis(false, true, EX_USAGE);
1326 if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1327 OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1328 OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1331 /* set up the basic signal handlers */
1332 if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1333 (void) sm_signal(SIGINT, intsig);
1334 (void) sm_signal(SIGTERM, intsig);
1336 /* Enforce use of local time (null string overrides this) */
1337 if (TimeZoneSpec == NULL)
1339 else if (TimeZoneSpec[0] != '\0')
1340 sm_setuserenv("TZ", TimeZoneSpec);
1342 sm_setuserenv("TZ", NULL);
1345 /* initialize mailbox database */
1346 i = sm_mbdb_initialize(Mbdb);
1349 usrerr("Can't initialize mailbox database \"%s\": %s",
1350 Mbdb, sm_strexit(i));
1354 /* avoid denial-of-service attacks */
1357 if (OpMode == MD_TEST)
1359 /* can't be done after readcf if RunAs* is used */
1360 dp = drop_privileges(true);
1363 finis(false, true, dp);
1367 else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1369 /* drop privileges -- daemon mode done after socket/bind */
1370 dp = drop_privileges(false);
1372 if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1374 usrerr("Mail submission program must have RunAsUser set to non root user");
1375 finis(false, true, EX_CONFIG);
1381 _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1382 _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1383 #endif /* NAMED_BIND */
1386 ** Find our real host name for future logging.
1389 authinfo = getauthinfo(STDIN_FILENO, &forged);
1390 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1392 /* suppress error printing if errors mailed back or whatever */
1393 if (BlankEnvelope.e_errormode != EM_PRINT)
1396 /* set up the $=m class now, after .cf has a chance to redefine $m */
1397 expand("\201m", jbuf, sizeof(jbuf), &BlankEnvelope);
1398 if (jbuf[0] != '\0')
1399 setclass('m', jbuf);
1401 /* probe interfaces and locate any additional names */
1402 if (DontProbeInterfaces != DPI_PROBENONE)
1407 char pidpath[MAXPATHLEN];
1409 /* Now we know which .cf file we use */
1410 sm_dprintf(" Conf file:\t%s (selected)\n",
1411 getcfname(OpMode, SubmitMode, cftype, conffile));
1412 expand(PidFile, pidpath, sizeof(pidpath), &BlankEnvelope);
1413 sm_dprintf(" Pid file:\t%s (selected)\n", pidpath);
1418 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1419 sm_dprintf("\n (short domain name) $w = ");
1420 xputs(sm_debug_file(), macvalue('w', &BlankEnvelope));
1421 sm_dprintf("\n (canonical domain name) $j = ");
1422 xputs(sm_debug_file(), macvalue('j', &BlankEnvelope));
1423 sm_dprintf("\n (subdomain name) $m = ");
1424 xputs(sm_debug_file(), macvalue('m', &BlankEnvelope));
1425 sm_dprintf("\n (node name) $k = ");
1426 xputs(sm_debug_file(), macvalue('k', &BlankEnvelope));
1427 sm_dprintf("\n========================================================\n\n");
1431 ** Do more command line checking -- these are things that
1432 ** have to modify the results of reading the config file.
1435 /* process authorization warnings from command line */
1437 auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1438 RealUserName, conffile);
1439 if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1440 auth_warning(&BlankEnvelope, "Processed from queue %s",
1442 if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1443 RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1444 sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1447 /* check body type for legality */
1448 i = check_bodytype(BlankEnvelope.e_bodytype);
1449 if (i == BODYTYPE_ILLEGAL)
1451 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1452 BlankEnvelope.e_bodytype = NULL;
1454 else if (i != BODYTYPE_NONE)
1455 SevenBitInput = (i == BODYTYPE_7BIT);
1457 /* tweak default DSN notifications */
1458 if (DefaultNotify == 0)
1459 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1461 /* check for sane configuration level */
1462 if (ConfigLevel > MAXCONFIGLEVEL)
1464 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1465 ConfigLevel, Version, MAXCONFIGLEVEL);
1468 /* need MCI cache to have persistence */
1469 if (HostStatDir != NULL && MaxMciCache == 0)
1472 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1473 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1476 /* need HostStatusDir in order to have SingleThreadDelivery */
1477 if (SingleThreadDelivery && HostStatDir == NULL)
1479 SingleThreadDelivery = false;
1480 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1481 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1485 j = sm_memstat_open();
1486 if (j < 0 && (RefuseLowMem > 0 || QueueLowMem > 0) && LogLevel > 4)
1488 sm_syslog(LOG_WARNING, NOQID,
1489 "cannot get memory statistics, settings ignored, error=%d"
1492 #endif /* _FFR_MEMSTAT */
1494 /* check for permissions */
1496 RealUid != TrustedUid)
1498 char *action = NULL;
1503 if (quarantining != NULL)
1504 action = "quarantine jobs";
1507 /* Normal users can do a single queue run */
1508 if (QueueIntvl == 0)
1512 /* but not persistent queue runners */
1514 action = "start a queue runner daemon";
1519 action = "purge host status";
1525 action = "run daemon";
1528 sm_dprintf("Deny user %d attempt to %s\n",
1529 (int) RealUid, action);
1532 sm_syslog(LOG_ALERT, NOQID,
1533 "user %d attempted to %s",
1534 (int) RealUid, action);
1536 usrerr("Permission denied (real uid not trusted)");
1537 finis(false, true, EX_USAGE);
1542 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1545 ** If -bv and RestrictExpand,
1546 ** drop privs to prevent normal
1547 ** users from reading private
1548 ** aliases/forwards/:include:s
1552 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1555 dp = drop_privileges(true);
1557 /* Fake address safety */
1559 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1560 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1565 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1567 CurEnv->e_id = NULL;
1568 finis(true, true, dp);
1575 case MD_CHECKCONFIG:
1580 /* Nothing special to check */
1584 if (!wordinclass(RealUserName, 't'))
1587 sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1590 sm_syslog(LOG_ALERT, NOQID,
1591 "user %d attempted to rebuild the alias map",
1594 usrerr("Permission denied (real uid not trusted)");
1595 finis(false, true, EX_USAGE);
1601 usrerr("User %d cannot rebuild aliases in mail submission program",
1603 finis(false, true, EX_USAGE);
1609 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1613 ** If -v and RestrictExpand, reset
1614 ** Verbose to prevent normal users
1615 ** from seeing the expansion of
1616 ** aliases/forwards/:include:s
1620 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1629 BlankEnvelope.e_flags |= EF_METOO;
1634 /* don't have persistent host status in test mode */
1638 case MD_CHECKCONFIG:
1641 BlankEnvelope.e_errormode = EM_PRINT;
1646 BlankEnvelope.e_errormode = EM_PRINT;
1648 /* arrange to exit cleanly on hangup signal */
1649 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1650 (void) sm_signal(SIGHUP, intsig);
1652 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1653 "Notice: -bv may give misleading output for non-privileged user\n");
1657 run_in_foreground = true;
1658 set_op_mode(MD_DAEMON);
1662 vendor_daemon_setup(&BlankEnvelope);
1664 /* remove things that don't make sense in daemon mode */
1668 /* arrange to restart on hangup signal */
1669 if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1670 sm_syslog(LOG_WARNING, NOQID,
1671 "daemon invoked without full pathname; kill -1 won't work");
1676 BlankEnvelope.e_errormode = EM_PRINT;
1681 /* arrange to exit cleanly on hangup signal */
1682 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1683 (void) sm_signal(SIGHUP, intsig);
1687 /* special considerations for FullName */
1688 if (FullName != NULL)
1692 /* full names can't have newlines */
1693 if (strchr(FullName, '\n') != NULL)
1695 full = newstr(denlstring(FullName, true, true));
1699 /* check for characters that may have to be quoted */
1700 if (!rfc822_string(FullName))
1703 ** Quote a full name with special characters
1704 ** as a comment so crackaddr() doesn't destroy
1705 ** the name portion of the address.
1708 FullName = addquotes(FullName, NULL);
1710 sm_free(full); /* XXX */
1714 /* do heuristic mode adjustment */
1717 /* turn off noconnect option */
1718 setoption('c', "F", true, false, &BlankEnvelope);
1720 /* turn on interactive delivery */
1721 setoption('d', "", true, false, &BlankEnvelope);
1725 /* check for vendor mismatch */
1726 if (VendorCode != VENDOR_CODE)
1728 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1729 getvendor(VENDOR_CODE), getvendor(VendorCode));
1731 #endif /* VENDOR_CODE */
1733 /* check for out of date configuration level */
1734 if (ConfigLevel < MAXCONFIGLEVEL)
1736 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1737 Version, MAXCONFIGLEVEL, ConfigLevel);
1740 if (ConfigLevel < 3)
1743 /* set options that were previous macros */
1744 if (SmtpGreeting == NULL)
1746 if (ConfigLevel < 7 &&
1747 (p = macvalue('e', &BlankEnvelope)) != NULL)
1748 SmtpGreeting = newstr(p);
1750 SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1752 if (UnixFromLine == NULL)
1754 if (ConfigLevel < 7 &&
1755 (p = macvalue('l', &BlankEnvelope)) != NULL)
1756 UnixFromLine = newstr(p);
1758 UnixFromLine = "From \201g \201d";
1760 SmtpError[0] = '\0';
1762 /* our name for SMTP codes */
1763 expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope);
1764 if (jbuf[0] == '\0')
1765 PSTRSET(MyHostName, "localhost");
1767 PSTRSET(MyHostName, jbuf);
1768 if (strchr(MyHostName, '.') == NULL)
1769 message("WARNING: local host name (%s) is not qualified; see cf/README: WHO AM I?",
1772 /* make certain that this name is part of the $=w class */
1773 setclass('w', MyHostName);
1775 /* fill in the structure of the *default* queue */
1776 st = stab("mqueue", ST_QUEUE, ST_FIND);
1778 syserr("No default queue (mqueue) defined");
1780 set_def_queueval(st->s_quegrp, true);
1782 /* the indices of built-in mailers */
1783 st = stab("local", ST_MAILER, ST_FIND);
1785 LocalMailer = st->s_mailer;
1786 else if (OpMode != MD_TEST || !warn_C_flag)
1787 syserr("No local mailer defined");
1789 st = stab("prog", ST_MAILER, ST_FIND);
1791 syserr("No prog mailer defined");
1794 ProgMailer = st->s_mailer;
1795 clrbitn(M_MUSER, ProgMailer->m_flags);
1798 st = stab("*file*", ST_MAILER, ST_FIND);
1800 syserr("No *file* mailer defined");
1803 FileMailer = st->s_mailer;
1804 clrbitn(M_MUSER, FileMailer->m_flags);
1807 st = stab("*include*", ST_MAILER, ST_FIND);
1809 syserr("No *include* mailer defined");
1811 InclMailer = st->s_mailer;
1813 if (ConfigLevel < 6)
1815 /* heuristic tweaking of local mailer for back compat */
1816 if (LocalMailer != NULL)
1818 setbitn(M_ALIASABLE, LocalMailer->m_flags);
1819 setbitn(M_HASPWENT, LocalMailer->m_flags);
1820 setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1821 setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1822 setbitn(M_CHECKPROG, LocalMailer->m_flags);
1823 setbitn(M_CHECKFILE, LocalMailer->m_flags);
1824 setbitn(M_CHECKUDB, LocalMailer->m_flags);
1826 if (ProgMailer != NULL)
1827 setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1828 if (FileMailer != NULL)
1829 setbitn(M_RUNASRCPT, FileMailer->m_flags);
1831 if (ConfigLevel < 7)
1833 if (LocalMailer != NULL)
1834 setbitn(M_VRFY250, LocalMailer->m_flags);
1835 if (ProgMailer != NULL)
1836 setbitn(M_VRFY250, ProgMailer->m_flags);
1837 if (FileMailer != NULL)
1838 setbitn(M_VRFY250, FileMailer->m_flags);
1841 /* MIME Content-Types that cannot be transfer encoded */
1842 setclass('n', "multipart/signed");
1844 /* MIME message/xxx subtypes that can be treated as messages */
1845 setclass('s', "rfc822");
1847 /* MIME Content-Transfer-Encodings that can be encoded */
1848 setclass('e', "7bit");
1849 setclass('e', "8bit");
1850 setclass('e', "binary");
1853 /* MIME Content-Types that should be treated as binary */
1854 setclass('b', "image");
1855 setclass('b', "audio");
1856 setclass('b', "video");
1857 setclass('b', "application/octet-stream");
1858 #endif /* USE_B_CLASS */
1860 /* MIME headers which have fields to check for overflow */
1861 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1862 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1864 /* MIME headers to check for length overflow */
1865 setclass(macid("{checkMIMETextHeaders}"), "content-description");
1867 /* MIME headers to check for overflow and rebalance */
1868 setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1869 setclass(macid("{checkMIMEHeaders}"), "content-id");
1870 setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1871 setclass(macid("{checkMIMEHeaders}"), "content-type");
1872 setclass(macid("{checkMIMEHeaders}"), "mime-version");
1874 /* Macros to save in the queue file -- don't remove any */
1875 setclass(macid("{persistentMacros}"), "r");
1876 setclass(macid("{persistentMacros}"), "s");
1877 setclass(macid("{persistentMacros}"), "_");
1878 setclass(macid("{persistentMacros}"), "{if_addr}");
1879 setclass(macid("{persistentMacros}"), "{daemon_flags}");
1881 /* operate in queue directory */
1882 if (QueueDir == NULL || *QueueDir == '\0')
1884 if (OpMode != MD_TEST)
1886 syserr("QueueDirectory (Q) option must be set");
1887 ExitStat = EX_CONFIG;
1892 if (OpMode != MD_TEST)
1893 setup_queues(OpMode == MD_DAEMON);
1896 /* check host status directory for validity */
1897 if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1899 /* cannot use this value */
1900 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1901 "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1902 HostStatDir, sm_errstring(errno));
1906 if (OpMode == MD_QUEUERUN &&
1907 RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1911 /* check to see if we own the queue directory */
1912 if (stat(".", &stbuf) < 0)
1913 syserr("main: cannot stat %s", QueueDir);
1914 if (stbuf.st_uid != RealUid)
1916 /* nope, really a botch */
1918 usrerr("You do not have permission to process the queue");
1919 finis(false, true, EX_NOPERM);
1925 /* sanity checks on milter filters */
1926 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1928 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1929 setup_daemon_milters();
1933 /* Convert queuegroup string to qgrp number */
1934 if (queuegroup != NULL)
1936 qgrp = name2qid(queuegroup);
1940 usrerr("Queue group %s unknown", queuegroup);
1941 finis(false, true, ExitStat);
1946 /* if checking config or have had errors so far, exit now */
1947 if (OpMode == MD_CHECKCONFIG || (ExitStat != EX_OK && OpMode != MD_TEST))
1949 finis(false, true, ExitStat);
1954 /* sendmail specific SASL initialization */
1959 checkfd012("before main() initmaps");
1963 ** Do operation-mode-dependent initialization.
1969 /* print the queue */
1971 (void) dropenvelope(&BlankEnvelope, true, false);
1972 (void) sm_signal(SIGPIPE, sigpipe);
1977 /* Selecting a particular queue group to run */
1978 for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1982 (void) print_single_queue(qgrp, j);
1984 finis(false, true, EX_OK);
1988 finis(false, true, EX_OK);
1993 /* print number of entries in queue */
1994 (void) dropenvelope(&BlankEnvelope, true, false);
1995 (void) sm_signal(SIGPIPE, sigpipe);
1996 printnqe(smioout, NULL);
1997 finis(false, true, EX_OK);
2002 /* only handle quarantining here */
2003 if (quarantining == NULL)
2006 if (QueueMode != QM_QUARANTINE &&
2007 QueueMode != QM_NORMAL)
2010 usrerr("Can not use -Q with -q%c", QueueMode);
2011 ExitStat = EX_USAGE;
2012 finis(false, true, ExitStat);
2015 quarantine_queue(quarantining, qgrp);
2016 finis(false, true, EX_OK);
2020 (void) sm_signal(SIGPIPE, sigpipe);
2021 (void) mci_traverse_persistent(mci_print_persistent, NULL);
2022 finis(false, true, EX_OK);
2027 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2028 finis(false, true, EX_OK);
2033 /* initialize maps */
2035 finis(false, true, ExitStat);
2041 /* reset DSN parameters */
2042 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2043 macdefine(&BlankEnvelope.e_macro, A_PERM,
2044 macid("{dsn_notify}"), NULL);
2045 BlankEnvelope.e_envid = NULL;
2046 macdefine(&BlankEnvelope.e_macro, A_PERM,
2047 macid("{dsn_envid}"), NULL);
2048 BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2049 macdefine(&BlankEnvelope.e_macro, A_PERM,
2050 macid("{dsn_ret}"), NULL);
2052 /* don't open maps for daemon -- done below in child */
2058 /* print configuration table (or at least part of it) */
2061 for (i = 0; i < MAXMAILERS; i++)
2063 if (Mailer[i] != NULL)
2064 printmailer(sm_debug_file(), Mailer[i]);
2069 ** Switch to the main envelope.
2072 CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2073 sm_rpool_new_x(NULL));
2074 MainEnvelope.e_flags = BlankEnvelope.e_flags;
2077 ** If test mode, read addresses from stdin and process.
2080 if (OpMode == MD_TEST)
2082 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2087 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2088 "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2089 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2090 "Enter <ruleset> <address>\n");
2092 macdefine(&(MainEnvelope.e_macro), A_PERM,
2093 macid("{addr_type}"), "e r");
2098 (void) sm_signal(SIGINT, intindebug);
2099 (void) sm_releasesignal(SIGINT);
2101 (void) sm_io_fprintf(smioout,
2104 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2105 if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2106 sizeof(buf)) == NULL)
2107 testmodeline("/quit", &MainEnvelope);
2108 p = strchr(buf, '\n');
2112 (void) sm_io_fprintf(smioout,
2115 testmodeline(buf, &MainEnvelope);
2117 SM_EXCEPT(exc, "[!F]*")
2120 ** 8.10 just prints \n on interrupt.
2121 ** I'm printing the exception here in case
2122 ** sendmail is extended to raise additional
2123 ** exceptions in this context.
2126 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2128 sm_exc_print(exc, smioout);
2136 if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER ||
2137 OpMode == MD_ARPAFTP)
2139 /* check whether STARTTLS is turned off for the client */
2140 if (chkclientmodifiers(D_NOTLS))
2143 else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2146 /* check whether STARTTLS is turned off */
2147 if (chkdaemonmodifiers(D_NOTLS) && chkclientmodifiers(D_NOTLS))
2150 else /* other modes don't need STARTTLS */
2155 /* basic TLS initialization */
2156 tls_ok = init_tls_library();
2159 if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2161 /* disable TLS for client */
2164 #endif /* STARTTLS */
2167 ** If collecting stuff from the queue, go start doing that.
2170 if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2175 /* init TLS for client, ignore result for now */
2176 (void) initclttls(tls_ok);
2177 #endif /* STARTTLS */
2180 ** The parent process of the caller of runqueue() needs
2181 ** to stay around for a possible SIGTERM. The SIGTERM will
2182 ** tell this process that all of the queue runners children
2183 ** need to be sent SIGTERM as well. At the same time, we
2184 ** want to return control to the command line. So we do an
2188 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2191 ** If the fork() failed we should still try to do
2192 ** the queue run. If it succeeded then the child
2193 ** is going to start the run and wait for all
2194 ** of the children to finish.
2199 /* Reset global flags */
2200 RestartRequest = NULL;
2201 ShutdownRequest = NULL;
2204 /* disconnect from terminal */
2205 disconnect(2, CurEnv);
2208 CurrentPid = getpid();
2211 int rwgflags = RWG_NONE;
2214 ** To run a specific queue group mark it to
2215 ** be run, select the work group it's in and
2216 ** increment the work counter.
2219 for (i = 0; i < NumQueue && Queue[i] != NULL;
2221 Queue[i]->qg_nextrun = (time_t) -1;
2222 Queue[qgrp]->qg_nextrun = 0;
2224 rwgflags |= RWG_VERBOSE;
2225 if (queuepersistent)
2226 rwgflags |= RWG_PERSISTENT;
2227 rwgflags |= RWG_FORCE;
2228 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2232 (void) runqueue(false, Verbose,
2233 queuepersistent, true);
2235 /* set the title to make it easier to find */
2236 sm_setproctitle(true, CurEnv, "Queue control");
2237 (void) sm_signal(SIGCHLD, SIG_DFL);
2238 while (CurChildren > 0)
2244 while ((ret = sm_wait(&status)) <= 0)
2246 if (errno == ECHILD)
2249 ** Oops... something got messed
2250 ** up really bad. Waiting for
2251 ** non-existent children
2252 ** shouldn't happen. Let's get
2262 /* something is really really wrong */
2263 if (errno == ECHILD)
2265 sm_syslog(LOG_ERR, NOQID,
2266 "queue control process: lost all children: wait returned ECHILD");
2270 /* Only drop when a child gives status */
2271 if (WIFSTOPPED(status))
2274 proc_list_drop(ret, status, NULL);
2277 finis(true, true, ExitStat);
2282 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2284 /* check whether AUTH is turned off for the server */
2285 if (!chkdaemonmodifiers(D_NOAUTH) &&
2286 (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2287 syserr("!sasl_server_init failed! [%s]",
2288 sasl_errstring(i, NULL, NULL));
2292 if (OpMode == MD_SMTP)
2294 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2295 PROC_DAEMON, 0, -1, NULL);
2297 /* clean up background delivery children */
2298 (void) sm_signal(SIGCHLD, reapchild);
2302 ** If a daemon, wait for a request.
2303 ** getrequests will always return in a child.
2304 ** If we should also be processing the queue, start
2305 ** doing it in background.
2306 ** We check for any errors that might have happened
2310 if (OpMode == MD_DAEMON || QueueIntvl > 0)
2314 /* avoid cleanup in finis(), DaemonPid will be set below */
2316 if (!run_in_foreground && !tTd(99, 100))
2318 /* put us in background */
2321 syserr("daemon: cannot fork");
2324 finis(false, true, EX_OK);
2329 ** Initialize exception stack and default exception
2330 ** handler for child process.
2333 /* Reset global flags */
2334 RestartRequest = NULL;
2335 RestartWorkGroup = false;
2336 ShutdownRequest = NULL;
2338 CurrentPid = getpid();
2340 sm_exc_newthread(fatal_error);
2342 /* disconnect from our controlling tty */
2343 disconnect(2, &MainEnvelope);
2347 if (OpMode == MD_DAEMON)
2349 (void) sm_strlcat(dtype, "+SMTP", sizeof(dtype));
2350 DaemonPid = CurrentPid;
2354 (void) sm_strlcat2(dtype,
2356 ? "+persistent-queueing@"
2358 pintvl(QueueIntvl, true),
2362 (void) sm_strlcat(dtype, "+debugging", sizeof(dtype));
2364 sm_syslog(LOG_INFO, NOQID,
2365 "starting daemon (%s): %s", Version, dtype + 1);
2370 /* save daemon type in a macro for possible PidFile use */
2371 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2372 macid("{daemon_info}"), dtype + 1);
2374 /* save queue interval in a macro for possible PidFile use */
2375 macdefine(&MainEnvelope.e_macro, A_TEMP,
2376 macid("{queue_interval}"), pintvl(QueueIntvl, true));
2378 /* workaround: can't seem to release the signal in the parent */
2379 (void) sm_signal(SIGHUP, sighup);
2380 (void) sm_releasesignal(SIGHUP);
2381 (void) sm_signal(SIGTERM, sigterm);
2388 int rwgflags = RWG_NONE;
2391 ** To run a specific queue group mark it to
2392 ** be run, select the work group it's in and
2393 ** increment the work counter.
2396 for (i = 0; i < NumQueue && Queue[i] != NULL;
2398 Queue[i]->qg_nextrun = (time_t) -1;
2399 Queue[qgrp]->qg_nextrun = 0;
2401 rwgflags |= RWG_VERBOSE;
2402 if (queuepersistent)
2403 rwgflags |= RWG_PERSISTENT;
2404 rwgflags |= RWG_FORCE;
2405 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2409 #endif /* _FFR_RUNPQG */
2410 (void) runqueue(true, false, queuepersistent,
2414 ** If queuepersistent but not in daemon mode then
2415 ** we're going to do the queue runner monitoring here.
2416 ** If in daemon mode then the monitoring will happen
2420 if (OpMode != MD_DAEMON && queuepersistent)
2423 ** Write the pid to file
2424 ** XXX Overwrites sendmail.pid
2427 log_sendmail_pid(&MainEnvelope);
2429 /* set the title to make it easier to find */
2430 sm_setproctitle(true, CurEnv, "Queue control");
2431 (void) sm_signal(SIGCHLD, SIG_DFL);
2432 while (CurChildren > 0)
2440 while ((ret = sm_wait(&status)) <= 0)
2443 ** Waiting for non-existent
2444 ** children shouldn't happen.
2445 ** Let's get out of here if
2449 if (errno == ECHILD)
2457 /* something is really really wrong */
2458 if (errno == ECHILD)
2460 sm_syslog(LOG_ERR, NOQID,
2461 "persistent queue runner control process: lost all children: wait returned ECHILD");
2465 if (WIFSTOPPED(status))
2468 /* Probe only on a child status */
2469 proc_list_drop(ret, status, &group);
2471 if (WIFSIGNALED(status))
2473 if (WCOREDUMP(status))
2475 sm_syslog(LOG_ERR, NOQID,
2476 "persistent queue runner=%d core dumped, signal=%d",
2477 group, WTERMSIG(status));
2479 /* don't restart this */
2480 mark_work_group_restart(
2485 sm_syslog(LOG_ERR, NOQID,
2486 "persistent queue runner=%d died, pid=%ld, signal=%d",
2492 ** When debugging active, don't
2493 ** restart the persistent queues.
2494 ** But do log this as info.
2497 if (sm_debug_active(&DebugNoPRestart,
2500 sm_syslog(LOG_DEBUG, NOQID,
2501 "persistent queue runner=%d, exited",
2503 mark_work_group_restart(group,
2508 finis(true, true, ExitStat);
2512 if (OpMode != MD_DAEMON)
2517 ** Write the pid to file
2518 ** XXX Overwrites sendmail.pid
2521 log_sendmail_pid(&MainEnvelope);
2523 /* set the title to make it easier to find */
2525 (void) sm_strlcpyn(qtype, sizeof(qtype), 4,
2527 pintvl(QueueIntvl, true),
2530 sm_setproctitle(true, CurEnv, qtype);
2538 (void) runqueue(true, false,
2543 (void) dropenvelope(&MainEnvelope, true, false);
2546 /* init TLS for server, ignore result for now */
2547 (void) initsrvtls(tls_ok);
2548 #endif /* STARTTLS */
2551 p_flags = getrequests(&MainEnvelope);
2553 /* drop privileges */
2554 (void) drop_privileges(false);
2557 ** Get authentication data
2558 ** Set _ macro in BlankEnvelope before calling newenvelope().
2561 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2563 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2565 sm_syslog(LOG_INFO, NOQID,
2566 "main: where=after_getauthinfo, RealHostAddr=%s",
2567 anynet_ntoa(&RealHostAddr));
2569 /* at this point we are in a child: reset state */
2570 sm_rpool_free(MainEnvelope.e_rpool);
2571 (void) newenvelope(&MainEnvelope, &MainEnvelope,
2572 sm_rpool_new_x(NULL));
2577 /* log connection information */
2578 sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2582 ** If running SMTP protocol, start collecting and executing
2583 ** commands. This will never return.
2586 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2591 ** Save some macros for check_* rulesets.
2598 (void) sm_snprintf(ipbuf, sizeof(ipbuf), "[%.100s]",
2599 anynet_ntoa(&RealHostAddr));
2600 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2601 macid("{client_name}"), ipbuf);
2604 macdefine(&BlankEnvelope.e_macro, A_PERM,
2605 macid("{client_name}"), RealHostName);
2606 macdefine(&BlankEnvelope.e_macro, A_PERM,
2607 macid("{client_ptr}"), RealHostName);
2608 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2609 macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2612 switch (RealHostAddr.sa.sa_family)
2616 (void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2617 RealHostAddr.sin.sin_port);
2619 #endif /* NETINET */
2622 (void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2623 RealHostAddr.sin6.sin6_port);
2625 #endif /* NETINET6 */
2627 (void) sm_snprintf(pbuf, sizeof(pbuf), "0");
2630 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2631 macid("{client_port}"), pbuf);
2633 if (OpMode == MD_DAEMON)
2635 ENVELOPE *saved_env;
2637 /* validate the connection */
2640 CurEnv = &BlankEnvelope;
2641 nullserver = validate_connection(&RealHostAddr,
2642 macvalue(macid("{client_name}"),
2645 if (bitset(EF_DISCARD, BlankEnvelope.e_flags))
2646 MainEnvelope.e_flags |= EF_DISCARD;
2650 else if (p_flags == NULL)
2652 p_flags = (BITMAP256 *) xalloc(sizeof(*p_flags));
2656 if (OpMode == MD_SMTP)
2657 (void) initsrvtls(tls_ok);
2658 #endif /* STARTTLS */
2660 /* turn off profiling */
2662 smtp(nullserver, *p_flags, &MainEnvelope);
2666 /* turn off profiling */
2668 if (OpMode == MD_DAEMON)
2673 sm_rpool_free(MainEnvelope.e_rpool);
2674 clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2675 if (OpMode == MD_VERIFY)
2677 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2678 PostMasterCopy = NULL;
2682 /* interactive -- all errors are global */
2683 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2687 ** Do basic system initialization and set the sender
2690 initsys(&MainEnvelope);
2691 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2692 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2693 setsender(from, &MainEnvelope, NULL, '\0', false);
2694 if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2695 (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2696 strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2698 auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2699 RealUserName, from, warn_f_flag);
2708 /* set the initial sender for AUTH= to $f@$j */
2709 fv = macvalue('f', &MainEnvelope);
2710 if (fv == NULL || *fv == '\0')
2711 MainEnvelope.e_auth_param = NULL;
2714 if (strchr(fv, '@') == NULL)
2716 i = strlen(fv) + strlen(macvalue('j',
2717 &MainEnvelope)) + 2;
2719 (void) sm_strlcpyn(p, i, 3, fv, "@",
2724 p = sm_strdup_x(fv);
2725 MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2727 sm_free(p); /* XXX */
2730 if (macvalue('s', &MainEnvelope) == NULL)
2731 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2734 if (*av == NULL && !GrabTo)
2736 MainEnvelope.e_to = NULL;
2737 MainEnvelope.e_flags |= EF_GLOBALERRS;
2739 SuperSafe = SAFE_NO;
2740 usrerr("Recipient names must be specified");
2742 /* collect body for UUCP return */
2743 if (OpMode != MD_VERIFY)
2744 collect(InChannel, false, NULL, &MainEnvelope, true);
2745 finis(true, true, EX_USAGE);
2750 ** Scan argv and deliver the message to everyone.
2753 save_val = LogUsrErrs;
2755 sendtoargv(av, &MainEnvelope);
2756 LogUsrErrs = save_val;
2758 /* if we have had errors sofar, arrange a meaningful exit stat */
2759 if (Errors > 0 && ExitStat == EX_OK)
2760 ExitStat = EX_USAGE;
2764 ** If using -t, force not sending to argv recipients, even
2765 ** if they are mentioned in the headers.
2772 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2773 q->q_state = QS_REMOVED;
2775 #endif /* _FFR_FIX_DASHT */
2778 ** Read the input mail.
2781 MainEnvelope.e_to = NULL;
2782 if (OpMode != MD_VERIFY || GrabTo)
2785 unsigned long savedflags;
2788 ** workaround for compiler warning on Irix:
2789 ** do not initialize variable in the definition, but
2791 ** warning(1548): transfer of control bypasses
2792 ** initialization of:
2793 ** variable "savederrors" (declared at line 2570)
2794 ** variable "savedflags" (declared at line 2571)
2798 savederrors = Errors;
2799 savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2800 MainEnvelope.e_flags |= EF_GLOBALERRS;
2801 MainEnvelope.e_flags &= ~EF_FATALERRS;
2804 collect(InChannel, false, NULL, &MainEnvelope, true);
2806 /* header checks failed */
2812 /* Log who the mail would have gone to */
2813 logundelrcpts(&MainEnvelope,
2814 MainEnvelope.e_message,
2818 finis(true, true, ExitStat);
2823 /* bail out if message too large */
2824 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2826 finis(true, true, ExitStat != EX_OK ? ExitStat
2832 /* set message size */
2833 (void) sm_snprintf(buf, sizeof(buf), "%ld",
2834 PRT_NONNEGL(MainEnvelope.e_msgsize));
2835 macdefine(&MainEnvelope.e_macro, A_TEMP,
2836 macid("{msg_size}"), buf);
2838 Errors = savederrors;
2839 MainEnvelope.e_flags |= savedflags;
2844 sm_dprintf("From person = \"%s\"\n",
2845 MainEnvelope.e_from.q_paddr);
2847 /* Check if quarantining stats should be updated */
2848 if (MainEnvelope.e_quarmsg != NULL)
2849 markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2852 ** Actually send everything.
2853 ** If verifying, just ack.
2858 if (!split_by_recipient(&MainEnvelope) &&
2859 bitset(EF_FATALERRS, MainEnvelope.e_flags))
2863 /* make sure we deliver at least the first envelope */
2864 i = FastSplit > 0 ? 0 : -1;
2865 for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2869 e->e_from.q_state = QS_SENDER;
2872 sm_dprintf("main[%d]: QS_SENDER ", i);
2873 printaddr(sm_debug_file(), &e->e_from, false);
2879 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2880 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2881 #endif /* NAMED_BIND */
2882 next = e->e_sibling;
2883 e->e_sibling = NULL;
2885 /* after FastSplit envelopes: queue up */
2886 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2887 e->e_sibling = next;
2892 ** Don't send return error message if in VERIFY mode.
2895 finis(true, true, ExitStat);
2900 ** STOP_SENDMAIL -- Stop the running program
2915 /* reset uid for process accounting */
2917 (void) setuid(RealUid);
2921 ** FINIS -- Clean up and exit.
2924 ** drop -- whether or not to drop CurEnv envelope
2925 ** cleanup -- call exit() or _exit()?
2926 ** exitstat -- exit status to use for exit() call
2936 finis(drop, cleanup, exitstat)
2939 volatile int exitstat;
2941 char pidpath[MAXPATHLEN];
2944 /* Still want to process new timeouts added below */
2946 (void) sm_releasesignal(SIGALRM);
2950 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2952 CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2953 printenvflags(CurEnv);
2956 printopenfds(false);
2960 ** Clean up. This might raise E:mta.quickabort
2963 /* clean up temp files */
2964 CurEnv->e_to = NULL;
2967 if (CurEnv->e_id != NULL)
2971 r = dropenvelope(CurEnv, true, false);
2972 if (exitstat == EX_OK)
2974 sm_rpool_free(CurEnv->e_rpool);
2975 CurEnv->e_rpool = NULL;
2977 /* these may have pointed to the rpool */
2978 CurEnv->e_to = NULL;
2979 CurEnv->e_message = NULL;
2980 CurEnv->e_statmsg = NULL;
2981 CurEnv->e_quarmsg = NULL;
2982 CurEnv->e_bodytype = NULL;
2983 CurEnv->e_id = NULL;
2984 CurEnv->e_envid = NULL;
2985 CurEnv->e_auth_param = NULL;
2988 poststats(StatFile);
2991 /* flush any cached connections */
2992 mci_flush(true, NULL);
2994 /* close maps belonging to this pid */
2998 /* close UserDatabase */
3007 /* clean up extended load average stuff */
3017 sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
3019 if (exitstat == EX_TEMPFAIL ||
3020 CurEnv->e_errormode == EM_BERKNET)
3023 /* XXX clean up queues and related data structures */
3027 cleanup_shm(DaemonPid == pid);
3028 #endif /* SM_CONF_SHM */
3030 /* close locked pid file */
3031 close_sendmail_pid();
3033 if (DaemonPid == pid || PidFilePid == pid)
3035 /* blow away the pid file */
3036 expand(PidFile, pidpath, sizeof(pidpath), CurEnv);
3037 (void) unlink(pidpath);
3040 /* reset uid for process accounting */
3042 sm_mbdb_terminate();
3044 (void) sm_memstat_close();
3045 #endif /* _FFR_MEMSTAT */
3046 (void) setuid(RealUid);
3048 /* dump the heap, if we are checking for memory leaks */
3049 if (sm_debug_active(&SmHeapCheck, 2))
3050 sm_heap_report(smioout,
3051 sm_debug_level(&SmHeapCheck) - 1);
3052 #endif /* SM_HEAP_CHECK */
3053 if (sm_debug_active(&SmXtrapReport, 1))
3054 sm_dprintf("xtrap count = %d\n", SmXtrapCount);
3062 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
3065 ** sig -- incoming signal.
3071 ** longjmps back to test mode loop.
3073 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3074 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3078 /* Type of an exception generated on SIGINT during address test mode. */
3079 static const SM_EXC_TYPE_T EtypeInterrupt =
3093 int save_errno = errno;
3095 FIX_SYSV_SIGNAL(sig, intindebug);
3097 CHECK_CRITICAL(sig);
3099 sm_exc_raisenew_x(&EtypeInterrupt);
3101 return SIGFUNC_RETURN;
3104 ** SIGTERM -- SIGTERM handler for the daemon
3107 ** sig -- signal number.
3113 ** Sets ShutdownRequest which will hopefully trigger
3114 ** the daemon to exit.
3116 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3117 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3126 int save_errno = errno;
3128 FIX_SYSV_SIGNAL(sig, sigterm);
3129 ShutdownRequest = "signal";
3131 return SIGFUNC_RETURN;
3134 ** SIGHUP -- handle a SIGHUP signal
3137 ** sig -- incoming signal.
3143 ** Sets RestartRequest which should cause the daemon
3146 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3147 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3156 int save_errno = errno;
3158 FIX_SYSV_SIGNAL(sig, sighup);
3159 RestartRequest = "signal";
3161 return SIGFUNC_RETURN;
3164 ** SIGPIPE -- signal handler for SIGPIPE
3167 ** sig -- incoming signal.
3173 ** Sets StopRequest which should cause the mailq/hoststatus
3176 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3177 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3186 int save_errno = errno;
3188 FIX_SYSV_SIGNAL(sig, sigpipe);
3191 return SIGFUNC_RETURN;
3194 ** INTSIG -- clean up on interrupt
3196 ** This just arranges to exit. It pessimizes in that it
3197 ** may resend a message.
3200 ** sig -- incoming signal.
3206 ** Unlocks the current job.
3208 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3209 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3219 int save_errno = errno;
3221 FIX_SYSV_SIGNAL(sig, intsig);
3223 CHECK_CRITICAL(sig);
3224 sm_allsignals(true);
3229 /* Clean-up on aborted stdin message submission */
3230 if (OpMode == MD_SMTP ||
3231 OpMode == MD_DELIVER ||
3232 OpMode == MD_ARPAFTP)
3234 if (CurEnv->e_id != NULL)
3238 fn = queuename(CurEnv, DATAFL_LETTER);
3241 fn = queuename(CurEnv, ANYQFL_LETTER);
3249 if (sig != 0 && LogLevel > 79)
3250 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3251 if (OpMode != MD_TEST)
3252 unlockqueue(CurEnv);
3254 finis(drop, false, EX_OK);
3258 ** DISCONNECT -- remove our connection with any foreground process
3261 ** droplev -- how "deeply" we should drop the line.
3262 ** 0 -- ignore signals, mail back errors, make sure
3263 ** output goes to stdout.
3264 ** 1 -- also, make stdout go to /dev/null.
3265 ** 2 -- also, disconnect from controlling terminal
3266 ** (only for daemon mode).
3267 ** e -- the current envelope.
3273 ** Trys to insure that we are immune to vagaries of
3274 ** the controlling tty.
3278 disconnect(droplev, e)
3280 register ENVELOPE *e;
3285 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3286 sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3287 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3290 sm_dprintf("don't\n");
3294 sm_syslog(LOG_DEBUG, e->e_id,
3295 "disconnect level %d",
3298 /* be sure we don't get nasty signals */
3299 (void) sm_signal(SIGINT, SIG_IGN);
3300 (void) sm_signal(SIGQUIT, SIG_IGN);
3302 /* we can't communicate with our caller, so.... */
3304 CurEnv->e_errormode = EM_MAIL;
3306 DisConnected = true;
3308 /* all input from /dev/null */
3309 if (InChannel != smioin)
3311 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3314 if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3315 SM_IO_RDONLY, NULL, smioin) == NULL)
3316 sm_syslog(LOG_ERR, e->e_id,
3317 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3318 SM_PATH_DEVNULL, sm_errstring(errno));
3321 ** output to the transcript
3322 ** We also compare the fd numbers here since OutChannel
3323 ** might be a layer on top of smioout due to encryption
3327 if (OutChannel != smioout &&
3328 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3329 sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3331 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3332 OutChannel = smioout;
3336 ** Has smioout been closed? Reopen it.
3337 ** This shouldn't happen anymore, the code is here
3338 ** just as a reminder.
3341 if (smioout->sm_magic == NULL &&
3342 sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3343 SM_IO_WRONLY, NULL, smioout) == NULL)
3344 sm_syslog(LOG_ERR, e->e_id,
3345 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3346 SM_PATH_DEVNULL, sm_errstring(errno));
3351 fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3354 sm_syslog(LOG_ERR, e->e_id,
3355 "disconnect: open(\"%s\") failed: %s",
3356 SM_PATH_DEVNULL, sm_errstring(errno));
3358 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3361 (void) dup2(fd, STDOUT_FILENO);
3362 (void) dup2(fd, STDERR_FILENO);
3367 /* drop our controlling TTY completely if possible */
3375 checkfd012("disconnect");
3379 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3392 while ((ap = *++argv) != NULL)
3394 /* Return if "--" or not an option of any form. */
3395 if (ap[0] != '-' || ap[1] == '-')
3398 /* Don't allow users to use "-Q." or "-Q ." */
3399 if ((ap[1] == 'Q' && ap[2] == '.') ||
3400 (ap[1] == 'Q' && argv[1] != NULL &&
3401 argv[1][0] == '.' && argv[1][1] == '\0'))
3403 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3404 "Can not use -Q.\n");
3408 /* skip over options that do have a value */
3409 op = strchr(OPTIONS, ap[1]);
3410 if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3412 #if defined(sony_news)
3413 ap[1] != 'E' && ap[1] != 'J' &&
3414 #endif /* defined(sony_news) */
3415 argv[1] != NULL && argv[1][0] != '-')
3421 /* If -C doesn't have an argument, use sendmail.cf. */
3422 #define __DEFPATH "sendmail.cf"
3423 if (ap[1] == 'C' && ap[2] == '\0')
3425 *argv = xalloc(sizeof(__DEFPATH) + 2);
3426 (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3430 /* If -q doesn't have an argument, run it once. */
3431 if (ap[1] == 'q' && ap[2] == '\0')
3434 /* If -Q doesn't have an argument, disable quarantining */
3435 if (ap[1] == 'Q' && ap[2] == '\0')
3438 /* if -d doesn't have an argument, use 0-99.1 */
3439 if (ap[1] == 'd' && ap[2] == '\0')
3442 #if defined(sony_news)
3443 /* if -E doesn't have an argument, use -EC */
3444 if (ap[1] == 'E' && ap[2] == '\0')
3447 /* if -J doesn't have an argument, use -JJ */
3448 if (ap[1] == 'J' && ap[2] == '\0')
3450 #endif /* defined(sony_news) */
3454 ** AUTH_WARNING -- specify authorization warning
3457 ** e -- the current envelope.
3458 ** msg -- the text of the message.
3459 ** args -- arguments to the message.
3467 auth_warning(register ENVELOPE *e, const char *msg, ...)
3468 #else /* __STDC__ */
3469 auth_warning(e, msg, va_alist)
3470 register ENVELOPE *e;
3473 #endif /* __STDC__ */
3478 if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3481 static char hostbuf[48];
3483 if (hostbuf[0] == '\0')
3487 hp = myhostname(hostbuf, sizeof(hostbuf));
3494 #endif /* NETINET6 */
3497 (void) sm_strlcpyn(buf, sizeof(buf), 2, hostbuf, ": ");
3498 p = &buf[strlen(buf)];
3499 SM_VA_START(ap, msg);
3500 (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3502 addheader("X-Authentication-Warning", buf, 0, e, true);
3504 sm_syslog(LOG_INFO, e->e_id,
3505 "Authentication-Warning: %.400s",
3510 ** GETEXTENV -- get from external environment
3513 ** envar -- the name of the variable to retrieve
3516 ** The value, if any.
3527 for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3529 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3530 return &(*envp)[l + 1];
3535 ** SM_SETUSERENV -- set an environment variable in the propagated environment
3538 ** envar -- the name of the environment variable.
3539 ** value -- the value to which it should be set. If
3540 ** null, this is extracted from the incoming
3541 ** environment. If that is not set, the call
3542 ** to sm_setuserenv is ignored.
3549 sm_setuserenv(envar, value)
3554 char **evp = UserEnviron;
3559 value = getextenv(envar);
3564 /* XXX enforce reasonable size? */
3565 i = strlen(envar) + 1;
3566 l = strlen(value) + i + 1;
3567 p = (char *) xalloc(l);
3568 (void) sm_strlcpyn(p, l, 3, envar, "=", value);
3570 while (*evp != NULL && strncmp(*evp, p, i) != 0)
3576 else if (evp < &UserEnviron[MAXUSERENVIRON])
3582 /* make sure it is in our environment as well */
3584 syserr("sm_setuserenv: putenv(%s) failed", p);
3587 ** DUMPSTATE -- dump state
3596 register char *j = macvalue('j', CurEnv);
3598 extern int NextMacroId;
3600 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3601 "--- dumping state on %s: $j = %s ---",
3603 j == NULL ? "<NULL>" : j);
3606 if (!wordinclass(j, 'w'))
3607 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3608 "*** $j not in $=w ***");
3610 sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3611 sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3612 NextMacroId, MAXMACROID);
3613 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3615 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3616 mci_dump_all(smioout, true);
3617 rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3621 register char **pvp;
3622 char *pv[MAXATOM + 1];
3625 status = REWRITE(pv, rs, CurEnv);
3626 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3627 "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3629 for (pvp = pv; *pvp != NULL; pvp++)
3630 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3632 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3637 ** SIGUSR1 -- Signal a request to dump state.
3640 ** sig -- calling signal.
3645 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3646 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3649 ** XXX: More work is needed for this signal handler.
3657 int save_errno = errno;
3659 FIX_SYSV_SIGNAL(sig, sigusr1);
3661 CHECK_CRITICAL(sig);
3662 dumpstate("user signal");
3665 # endif /* SM_HEAP_CHECK */
3667 return SIGFUNC_RETURN;
3669 #endif /* SIGUSR1 */
3672 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3675 ** to_real_uid -- if set, drop to the real uid instead
3676 ** of the RunAsUser.
3679 ** EX_OSERR if the setuid failed.
3684 drop_privileges(to_real_uid)
3688 GIDSET_T emptygidset[1];
3691 sm_dprintf("drop_privileges(%d): Real[UG]id=%d:%d, get[ug]id=%d:%d, gete[ug]id=%d:%d, RunAs[UG]id=%d:%d\n",
3693 (int) RealUid, (int) RealGid,
3694 (int) getuid(), (int) getgid(),
3695 (int) geteuid(), (int) getegid(),
3696 (int) RunAsUid, (int) RunAsGid);
3700 RunAsUserName = RealUserName;
3706 /* make sure no one can grab open descriptors for secret files */
3708 sm_mbdb_terminate();
3710 /* reset group permissions; these can be set later */
3711 emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3714 ** Notice: on some OS (Linux...) the setgroups() call causes
3715 ** a logfile entry if sendmail is not run by root.
3716 ** However, it is unclear (no POSIX standard) whether
3717 ** setgroups() can only succeed if executed by root.
3718 ** So for now we keep it as it is; if you want to change it, use
3719 ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3722 if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3724 syserr("drop_privileges: setgroups(1, %d) failed",
3725 (int) emptygidset[0]);
3729 /* reset primary group id */
3733 ** Drop gid to real gid.
3734 ** On some OS we must reset the effective[/real[/saved]] gid,
3735 ** and then use setgid() to finally drop all group privileges.
3736 ** Later on we check whether we can get back the
3741 if (setegid(RunAsGid) < 0)
3743 syserr("drop_privileges: setegid(%d) failed",
3747 #else /* HASSETEGID */
3749 if (setregid(RunAsGid, RunAsGid) < 0)
3751 syserr("drop_privileges: setregid(%d, %d) failed",
3752 (int) RunAsGid, (int) RunAsGid);
3755 # else /* HASSETREGID */
3757 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3759 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3760 (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3763 # endif /* HASSETRESGID */
3764 # endif /* HASSETREGID */
3765 #endif /* HASSETEGID */
3767 if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3769 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3771 syserr("drop_privileges: setgid(%d) failed",
3776 if (rval == EX_OK && getegid() != RunAsGid)
3778 syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3779 (int) getegid(), (int) RunAsGid);
3784 /* fiddle with uid */
3785 if (to_real_uid || RunAsUid != 0)
3790 ** Try to setuid(RunAsUid).
3791 ** euid must be RunAsUid,
3792 ** ruid must be RunAsUid unless (e|r)uid wasn't 0
3793 ** and we didn't have to drop privileges to the real uid.
3796 if (setuid(RunAsUid) < 0 ||
3797 geteuid() != RunAsUid ||
3798 (getuid() != RunAsUid &&
3799 (to_real_uid || geteuid() == 0 || getuid() == 0)))
3803 ** if ruid != RunAsUid, euid == RunAsUid, then
3804 ** try resetting just the real uid, then using
3805 ** setuid() to drop the saved-uid as well.
3808 if (geteuid() == RunAsUid)
3810 if (setreuid(RunAsUid, -1) < 0)
3812 syserr("drop_privileges: setreuid(%d, -1) failed",
3816 if (setuid(RunAsUid) < 0)
3818 syserr("drop_privileges: second setuid(%d) attempt failed",
3824 #endif /* HASSETREUID */
3826 syserr("drop_privileges: setuid(%d) failed",
3832 if (RunAsUid != 0 && setuid(0) == 0)
3835 ** Believe it or not, the Linux capability model
3836 ** allows a non-root process to override setuid()
3837 ** on a process running as root and prevent that
3838 ** process from dropping privileges.
3841 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3844 else if (RunAsUid != euid && setuid(euid) == 0)
3847 ** Some operating systems will keep the saved-uid
3848 ** if a non-root effective-uid calls setuid(real-uid)
3849 ** making it possible to set it back again later.
3852 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3857 if ((to_real_uid || RunAsGid != 0) &&
3858 rval == EX_OK && RunAsGid != EffGid &&
3859 getuid() != 0 && geteuid() != 0)
3862 if (setgid(EffGid) == 0)
3864 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3872 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3873 (int) geteuid(), (int) getuid(),
3874 (int) getegid(), (int) getgid());
3875 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3876 (int) RunAsUid, (int) RunAsGid);
3878 sm_dprintf("drop_privileges: rval = %d\n", rval);
3883 ** FILL_FD -- make sure a file descriptor has been properly allocated
3885 ** Used to make sure that stdin/out/err are allocated on startup
3888 ** fd -- the file descriptor to be filled.
3889 ** where -- a string used for logging. If NULL, this is
3890 ** being called on startup, and logging should
3897 ** possibly changes MissingFds
3908 if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3912 syserr("fill_fd: %s: fd %d not open", where, fd);
3914 MissingFds |= 1 << fd;
3915 i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3918 syserr("!fill_fd: %s: cannot open %s",
3919 where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3928 ** SM_PRINTOPTIONS -- print options
3931 ** options -- array of options.
3938 sm_printoptions(options)
3948 if (ll + strlen(*av) > 63)
3957 sm_dprintf("%s", *av);
3958 ll += strlen(*av++) + 1;
3964 ** TO8BIT -- convert \octal sequences in a test mode input line
3967 ** str -- the input line.
3973 ** replaces \0octal in str with octal value.
3976 static bool to8bit __P((char *));
3991 while ((c = (*str++ & 0377)) != '\0')
3997 (nxtc = (*str & 0377)) == '0')
4000 while ((nxtc = (*str & 0377)) != '\0' &&
4001 isascii(nxtc) && isdigit(nxtc))
4018 q = quote_internal_chars(in, in, &len);
4020 sm_strlcpy(in, q, len);
4026 ** TESTMODELINE -- process a test mode input line
4029 ** line -- the input line.
4030 ** e -- the current environment.
4033 ** .X process X as a configuration line
4034 ** =X dump a configuration item (such as mailers)
4035 ** $X dump a macro or class
4036 ** /X try an activity
4037 ** X normal process through rule set X
4041 testmodeline(line, e)
4047 auto char *delimptr;
4056 static int tryflags = RF_COPYNONE;
4057 char exbuf[MAXLINE];
4059 extern unsigned char TokTypeNoC[];
4062 /* skip leading spaces */
4063 while (*line == ' ')
4078 case '.': /* config-style settings */
4082 mid = macid_parse(&line[2], &delimptr);
4086 lbp = translate_dollars(delimptr, lbuf, &lbs);
4087 macdefine(&e->e_macro, A_TEMP, mid, lbp);
4093 if (line[2] == '\0') /* not to call syserr() */
4096 mid = macid_parse(&line[2], &delimptr);
4100 lbp = translate_dollars(delimptr, lbuf, &lbs);
4101 expand(lbp, exbuf, sizeof(exbuf), e);
4110 while (*p != '\0' && isascii(*p) && isspace(*p))
4113 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4124 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4125 "Usage: .[DC]macro value(s)\n");
4129 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4130 "Unknown \".\" command %s\n", line);
4135 case '=': /* config-style settings */
4138 case 'S': /* dump rule set */
4139 rs = strtorwset(&line[2], NULL, ST_FIND);
4142 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4143 "Undefined ruleset %s\n", &line[2]);
4146 rw = RewriteRules[rs];
4151 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4156 xputs(smioout, *s++);
4157 (void) sm_io_putc(smioout,
4158 SM_TIME_DEFAULT, ' ');
4160 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4162 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4167 xputs(smioout, *s++);
4168 (void) sm_io_putc(smioout,
4169 SM_TIME_DEFAULT, ' ');
4171 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4173 } while ((rw = rw->r_next) != NULL);
4177 for (i = 0; i < MAXMAILERS; i++)
4179 if (Mailer[i] != NULL)
4180 printmailer(smioout, Mailer[i]);
4185 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4186 "Usage: =Sruleset or =M\n");
4190 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4191 "Unknown \"=\" command %s\n", line);
4196 case '-': /* set command-line-like opts */
4204 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4205 "Usage: -d{debug arguments}\n");
4209 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4210 "Unknown \"-\" command %s\n", line);
4218 mid = macid(&line[2]);
4220 stabapply(dump_class, mid);
4223 mid = macid(&line[1]);
4226 p = macvalue(mid, e);
4228 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4233 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4238 case '/': /* miscellaneous commands */
4239 p = &line[strlen(line)];
4240 while (--p >= line && isascii(*p) && isspace(*p))
4242 p = strpbrk(line, " \t");
4245 while (isascii(*p) && isspace(*p))
4250 if (line[1] == '\0')
4252 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4253 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4256 if (sm_strcasecmp(&line[1], "quit") == 0)
4258 CurEnv->e_id = NULL;
4259 finis(true, true, ExitStat);
4262 if (sm_strcasecmp(&line[1], "mx") == 0)
4265 /* look up MX records */
4268 char *mxhosts[MAXMXHOSTS + 1];
4272 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4273 "Usage: /mx address\n");
4276 nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4278 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4279 "getmxrr(%s) returns %d value(s):\n",
4281 for (i = 0; i < nmx; i++)
4282 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4283 "\t%s\n", mxhosts[i]);
4284 #else /* NAMED_BIND */
4285 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4286 "No MX code compiled in\n");
4287 #endif /* NAMED_BIND */
4289 else if (sm_strcasecmp(&line[1], "canon") == 0)
4291 char host[MAXHOSTNAMELEN];
4295 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4296 "Usage: /canon address\n");
4299 else if (sm_strlcpy(host, p, sizeof(host)) >= sizeof(host))
4301 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4305 (void) getcanonname(host, sizeof(host), !HasWildcardMX,
4307 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4308 "getcanonname(%s) returns %s\n",
4311 else if (sm_strcasecmp(&line[1], "map") == 0)
4313 auto int rcode = EX_OK;
4318 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4319 "Usage: /map mapname key\n");
4322 for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q)); q++)
4326 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4327 "No key specified\n");
4331 map = stab(p, ST_MAP, ST_FIND);
4334 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4335 "Map named \"%s\" not found\n", p);
4338 if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4339 !openmap(&(map->s_map)))
4341 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4342 "Map named \"%s\" not open\n", p);
4345 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4346 "map_lookup: %s (%s) ", p, q);
4349 p = (*map->s_map.map_class->map_lookup)
4350 (&map->s_map, q, av, &rcode);
4352 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4356 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4357 "returns %s (%d)\n", p,
4360 else if (sm_strcasecmp(&line[1], "try") == 0)
4364 auto int rcode = EX_OK;
4366 q = strpbrk(p, " \t");
4369 while (isascii(*q) && isspace(*q))
4372 if (q == NULL || *q == '\0')
4374 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4375 "Usage: /try mailer address\n");
4378 st = stab(p, ST_MAILER, ST_FIND);
4381 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4382 "Unknown mailer %s\n", p);
4386 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4387 "Trying %s %s address %s for mailer %s\n",
4388 bitset(RF_HEADERADDR, tryflags) ? "header"
4390 bitset(RF_SENDERADDR, tryflags) ? "sender"
4391 : "recipient", q, p);
4392 p = remotename(q, m, tryflags, &rcode, CurEnv);
4393 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4394 "Rcode = %d, addr = %s\n",
4395 rcode, p == NULL ? "<NULL>" : p);
4398 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4402 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4403 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4406 for (; *p != '\0'; p++)
4412 tryflags |= RF_HEADERADDR;
4417 tryflags &= ~RF_HEADERADDR;
4422 tryflags |= RF_SENDERADDR;
4427 tryflags &= ~RF_SENDERADDR;
4431 exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4433 exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4435 macdefine(&e->e_macro, A_TEMP,
4436 macid("{addr_type}"), exbuf);
4438 else if (sm_strcasecmp(&line[1], "parse") == 0)
4442 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4443 "Usage: /parse address\n");
4446 q = crackaddr(p, e);
4447 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4448 "Cracked address = ");
4450 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4451 "\nParsing %s %s address\n",
4452 bitset(RF_HEADERADDR, tryflags) ?
4453 "header" : "envelope",
4454 bitset(RF_SENDERADDR, tryflags) ?
4455 "sender" : "recipient");
4456 if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4458 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4460 else if (a.q_host != NULL && a.q_host[0] != '\0')
4461 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4462 "mailer %s, host %s, user %s\n",
4467 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4468 "mailer %s, user %s\n",
4473 else if (sm_strcasecmp(&line[1], "header") == 0)
4477 ul = chompheader(p, CHHDR_CHECK|CHHDR_USER, NULL, e);
4478 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4483 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4484 "Unknown \"/\" command %s\n",
4487 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4491 for (p = line; isascii(*p) && isspace(*p); p++)
4494 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4498 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4504 eightbit = to8bit(p + 1);
4505 if (invalidaddr(p + 1, NULL, true))
4509 register char **pvp;
4510 char pvpbuf[PSBUFSIZE];
4512 pvp = prescan(++p, ',', pvpbuf, sizeof(pvpbuf), &delimptr,
4513 ConfigLevel >= 9 ? TokTypeNoC : ExtTokenTab, false);
4521 rs = strtorwset(p, NULL, ST_FIND);
4524 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4525 "Undefined ruleset %s\n",
4529 status = REWRITE(pvp, rs, e);
4530 if (status != EX_OK)
4531 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4532 "== Ruleset %s (%d) status %d\n",
4536 cataddr(pvp, NULL, exbuf, sizeof(exbuf), '\0',
4538 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4542 while (*p != '\0' && *p++ != ',')
4545 } while (*(p = delimptr) != '\0');
4546 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4554 if (s->s_symtype != ST_CLASS)
4556 if (bitnset(bitidx(id), s->s_class))
4557 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4562 ** An exception type used to create QuickAbort exceptions.
4563 ** This is my first cut at converting QuickAbort from longjmp to exceptions.
4564 ** These exceptions have a single integer argument, which is the argument
4565 ** to longjmp in the original code (either 1 or 2). I don't know the
4566 ** significance of 1 vs 2: the calls to setjmp don't care.
4569 const SM_EXC_TYPE_T EtypeQuickAbort =