2 * Copyright (c) 1998-2006, 2008, 2009, 2011 Proofpoint, 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-2013 Proofpoint, 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.988 2013/11/23 02:52:37 gshapiro 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 - 9/13).
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 - 10/13).
88 ** Proofpoint, Inc. (10/13 - present).
91 ** Sendmail, Inc. (12/98 - 10/13).
92 ** Proofpoint, Inc. (10/13 - present).
95 char *FullName; /* sender's full name */
96 ENVELOPE BlankEnvelope; /* a "blank" envelope */
97 static ENVELOPE MainEnvelope; /* the envelope around the basic letter */
98 ADDRESS NullAddress = /* a null address */
100 char *CommandLineArgs; /* command line args for pid file */
101 bool Warn_Q_option = false; /* warn about Q option use */
102 static int MissingFds = 0; /* bit map of fds missing on startup */
103 char *Mbdb = "pw"; /* mailbox database defaults to /etc/passwd */
106 GIDSET_T InitialGidSet[NGROUPS_MAX];
107 #endif /* NGROUPS_MAX */
109 #define MAXCONFIGLEVEL 10 /* highest config version level known */
112 static sasl_callback_t srvcallbacks[] =
114 { SASL_CB_VERIFYFILE, (sasl_callback_ft)&safesaslfile, NULL },
115 { SASL_CB_PROXY_POLICY, (sasl_callback_ft)&proxy_policy, NULL },
116 { SASL_CB_LIST_END, NULL, NULL }
120 unsigned int SubmitMode;
121 int SyslogPrefixLen; /* estimated length of syslog prefix */
122 #define PIDLEN 6 /* pid length for computing SyslogPrefixLen */
124 # define SL_FUDGE 10 /* fudge offset for SyslogPrefixLen */
125 #endif /* ! SL_FUDGE */
126 #define SLDLL 8 /* est. length of default syslog label */
129 /* Some options are dangerous to allow users to use in non-submit mode */
130 #define CHECK_AGAINST_OPMODE(cmd) \
133 OpMode != MD_DELIVER && OpMode != MD_SMTP && \
134 OpMode != MD_ARPAFTP && OpMode != MD_CHECKCONFIG && \
135 OpMode != MD_VERIFY && OpMode != MD_TEST) \
137 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
138 "WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \
142 if (extraprivs && queuerun) \
144 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
145 "WARNING: Ignoring submission mode -%c option with -q\n", \
152 main(argc, argv, envp)
159 extern char Version[];
166 int qgrp = NOQGRP; /* queue group to process */
168 BITMAP256 *p_flags = NULL; /* daemon flags */
169 bool warn_C_flag = false;
170 bool auth = true; /* whether to set e_auth_param */
171 char warn_f_flag = '\0';
172 bool run_in_foreground = false; /* -bD mode */
173 bool queuerun = false, debug = false;
176 char *nullserver = NULL;
177 char *authinfo = NULL;
178 char *sysloglabel = NULL; /* label for syslog */
179 char *conffile = NULL; /* name of .cf file */
180 char *queuegroup = NULL; /* queue group to process */
181 char *quarantining = NULL; /* quarantine queue items? */
184 bool queuepersistent = false; /* queue runner process runs forever */
185 bool foregroundqueue = false; /* queue run in foreground */
186 bool save_val; /* to save some bool var. */
187 int cftype; /* which cf file to use? */
189 static time_t starttime = 0; /* when was process started */
190 struct stat traf_st; /* for TrafficLog FIFO check */
192 char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */
193 static char rnamebuf[MAXNAME]; /* holds RealUserName */
194 char *emptyenviron[1];
197 #endif /* STARTTLS */
200 extern int DtableSize;
204 extern char **environ;
206 extern void sm_sasl_init __P((void));
211 #endif /* USE_ENVIRON */
213 /* turn off profiling */
216 /* install default exception handler */
217 sm_exc_newthread(fatal_error);
219 /* set the default in/out channel so errors reported to screen */
221 OutChannel = smioout;
224 ** Check to see if we reentered.
225 ** This would normally happen if e_putheader or e_putbody
226 ** were NULL when invoked.
231 syserr("main: reentered!");
234 starttime = curtime();
236 /* avoid null pointer dereferences */
237 TermEscape.te_rv_on = TermEscape.te_under_on = TermEscape.te_normal = "";
242 /* Check if sendmail is running with extra privs */
243 extraprivs = (RealUid != 0 &&
244 (geteuid() != getuid() || getegid() != getgid()));
246 CurrentPid = getpid();
248 /* get whatever .cf file is right for the opmode */
249 cftype = SM_GET_RIGHT_CF;
251 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
252 DtableSize = getdtsize();
253 if (DtableSize > 256)
257 ** Be sure we have enough file descriptors.
258 ** But also be sure that 0, 1, & 2 are open.
261 /* reset errno and fill_errno; the latter is used way down below */
262 errno = fill_errno = 0;
263 fill_fd(STDIN_FILENO, NULL);
266 fill_fd(STDOUT_FILENO, NULL);
269 fill_fd(STDERR_FILENO, NULL);
273 sm_closefrom(STDERR_FILENO + 1, DtableSize);
279 # define SM_LOG_STR "sendmail"
280 # endif /* ! SM_LOG_STR */
282 openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
283 # else /* LOG_MAIL */
284 openlog(SM_LOG_STR, LOG_PID);
285 # endif /* LOG_MAIL */
289 ** Seed the random number generator.
290 ** Used for queue file names, picking a queue directory, and
296 /* do machine-dependent initializations */
300 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
302 /* reset status from syserr() calls for missing file descriptors */
306 SubmitMode = SUBMIT_UNKNOWN;
307 #if _FFR_LOCAL_DAEMON
310 V6LoopbackAddrFound = false;
311 # endif /* NETINET6 */
312 #endif /* _FFR_LOCAL_DAEMON */
314 checkfd012("after openlog");
317 tTsetup(tTdvect, sizeof(tTdvect), "0-99.1,*_trace_*.1");
320 /* save initial group set for future checks */
321 i = getgroups(NGROUPS_MAX, InitialGidSet);
324 InitialGidSet[0] = (GID_T) -1;
327 while (i < NGROUPS_MAX)
328 InitialGidSet[i++] = InitialGidSet[0];
329 #endif /* NGROUPS_MAX */
331 /* drop group id privileges (RunAsUser not yet set) */
332 dp = drop_privileges(false);
336 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
339 /* arrange to dump state on user-1 signal */
340 (void) sm_signal(SIGUSR1, sigusr1);
344 /* ignore user-1 signal */
345 (void) sm_signal(SIGUSR1, SIG_IGN);
349 /* initialize for setproctitle */
350 initsetproctitle(argc, argv, envp);
352 /* Handle any non-getoptable constructions. */
356 ** Do a quick prescan of the argument list.
360 /* find initial opMode */
363 p = strrchr(*av, '/');
366 if (strcmp(p, "newaliases") == 0)
367 OpMode = MD_INITALIAS;
368 else if (strcmp(p, "mailq") == 0)
370 else if (strcmp(p, "smtpd") == 0)
372 else if (strcmp(p, "hoststat") == 0)
373 OpMode = MD_HOSTSTAT;
374 else if (strcmp(p, "purgestat") == 0)
375 OpMode = MD_PURGESTAT;
377 #if defined(__osf__) || defined(_AIX3)
378 # 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"
379 #endif /* defined(__osf__) || defined(_AIX3) */
380 #if defined(sony_news)
381 # 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:"
382 #endif /* defined(sony_news) */
384 # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
385 #endif /* ! OPTIONS */
387 /* Set to 0 to allow -b; need to check optarg before using it! */
389 while ((j = getopt(argc, argv, OPTIONS)) != -1)
393 case 'b': /* operations mode */
394 j = (optarg == NULL) ? ' ' : *optarg;
411 #endif /* _FFR_CHECKCONFIG */
415 #if _FFR_LOCAL_DAEMON
420 #endif /* _FFR_LOCAL_DAEMON */
423 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
424 "Frozen configurations unsupported\n");
428 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
429 "Invalid operation mode %c\n",
439 syserr("-D file must be before -d");
443 dp = drop_privileges(true);
445 smdebug = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
446 optarg, SM_IO_APPEND, NULL);
449 syserr("cannot open %s", optarg);
450 ExitStat = EX_CANTCREAT;
453 sm_debug_setfile(smdebug);
459 (void) sm_io_setvbuf(sm_debug_file(), SM_TIME_DEFAULT,
460 (char *) NULL, SM_IO_NBF,
464 case 'G': /* relay (gateway) submission */
465 SubmitMode = SUBMIT_MTA;
471 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
472 "option requires an argument -- '%c'",
476 j = SM_MIN(strlen(optarg), 32) + 1;
477 sysloglabel = xalloc(j);
478 (void) sm_strlcpy(sysloglabel, optarg, j);
479 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
485 /* just check if it is there */
492 /* Don't leak queue information via debug flags */
493 if (extraprivs && queuerun && debug)
495 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
496 "WARNING: Can not use -d with -q. Disabling debugging.\n");
498 sm_debug_setfile(NULL);
499 (void) memset(tTdvect, '\0', sizeof(tTdvect));
503 if (sysloglabel != NULL)
505 /* Sanitize the string */
506 for (p = sysloglabel; *p != '\0'; p++)
508 if (!isascii(*p) || !isprint(*p) || *p == '%')
513 openlog(sysloglabel, LOG_PID, LOG_MAIL);
514 # else /* LOG_MAIL */
515 openlog(sysloglabel, LOG_PID);
516 # endif /* LOG_MAIL */
520 /* set up the blank envelope */
521 BlankEnvelope.e_puthdr = putheader;
522 BlankEnvelope.e_putbody = putbody;
523 BlankEnvelope.e_xfp = NULL;
524 STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
525 CurEnv = &BlankEnvelope;
526 STRUCTCOPY(NullAddress, MainEnvelope.e_from);
529 ** Set default values for variables.
530 ** These cannot be in initialized data space.
533 setdefaults(&BlankEnvelope);
534 initmacros(&BlankEnvelope);
538 if (OpMode == MD_DAEMON)
539 DaemonPid = CurrentPid; /* needed for finis() to work */
541 pw = sm_getpwuid(RealUid);
543 (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof(rnamebuf));
545 (void) sm_snprintf(rnamebuf, sizeof(rnamebuf), "Unknown UID %d",
548 RealUserName = rnamebuf;
552 sm_dprintf("Version %s\n", Version);
553 finis(false, true, EX_OK);
558 ** if running non-set-user-ID binary as non-root, pretend
559 ** we are the RunAsUid
562 if (RealUid != 0 && geteuid() == RealUid)
565 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
569 else if (geteuid() != 0)
570 RunAsUid = geteuid();
573 if (RealUid != 0 && EffGid == RealGid)
578 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
579 (int) geteuid(), (int) getuid(),
580 (int) getegid(), (int) getgid());
581 sm_dprintf("main: RunAsUser = %d:%d\n",
582 (int) RunAsUid, (int) RunAsGid);
585 /* save command line arguments */
587 for (av = argv; *av != NULL; )
588 j += strlen(*av++) + 1;
589 SaveArgv = (char **) xalloc(sizeof(char *) * (argc + 1));
590 CommandLineArgs = xalloc(j);
592 for (av = argv, i = 0; *av != NULL; )
596 SaveArgv[i++] = newstr(*av);
599 (void) sm_strlcpy(p, *av++, j);
608 extern char *CompileOptions[];
610 sm_dprintf("Version %s\n Compiled with:", Version);
611 sm_printoptions(CompileOptions);
615 extern char *OsCompileOptions[];
617 sm_dprintf(" OS Defines:");
618 sm_printoptions(OsCompileOptions);
620 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
621 #endif /* _PATH_UNIX */
623 sm_dprintf(" Conf file:\t%s (default for MSP)\n",
624 getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
626 sm_dprintf(" Conf file:\t%s (default for MTA)\n",
627 getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
629 sm_dprintf(" Pid file:\t%s (default)\n", PidFile);
634 extern char *SmCompileOptions[];
636 sm_dprintf(" libsm Defines:");
637 sm_printoptions(SmCompileOptions);
642 extern char *FFRCompileOptions[];
644 sm_dprintf(" FFR Defines:");
645 sm_printoptions(FFRCompileOptions);
648 /* clear sendmail's environment */
649 ExternalEnviron = environ;
650 emptyenviron[0] = NULL;
651 environ = emptyenviron;
654 ** restore any original TZ setting until TimeZoneSpec has been
655 ** determined - or early log messages may get bogus time stamps
658 if ((p = getextenv("TZ")) != NULL)
663 /* XXX check for reasonable length? */
664 tzlen = strlen(p) + 4;
666 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
668 /* XXX check return code? */
672 /* prime the child environment */
673 sm_setuserenv("AGENT", "sendmail");
675 (void) sm_signal(SIGPIPE, SIG_IGN);
676 OldUmask = umask(022);
677 FullName = getextenv("NAME");
678 if (FullName != NULL)
679 FullName = newstr(FullName);
682 ** Initialize name server if it is going to be used.
686 if (!bitset(RES_INIT, _res.options))
689 _res.options |= RES_DEBUG;
691 _res.options &= ~RES_DEBUG;
692 # ifdef RES_NOALIASES
693 _res.options |= RES_NOALIASES;
694 # endif /* RES_NOALIASES */
695 TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
696 TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
697 TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
698 TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
699 TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
700 TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
701 #endif /* NAMED_BIND */
706 /* initialize some macros, etc. */
707 init_vendor_macros(&BlankEnvelope);
710 macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
713 hp = myhostname(jbuf, sizeof(jbuf));
716 struct utsname utsname;
719 sm_dprintf("Canonical name: %s\n", jbuf);
720 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
721 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
724 p = strchr(jbuf, '.');
725 if (p != NULL && p[1] != '\0')
726 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm', &p[1]);
728 if (uname(&utsname) >= 0)
729 p = utsname.nodename;
733 sm_dprintf("uname failed (%s)\n",
734 sm_errstring(errno));
739 sm_dprintf(" UUCP nodename: %s\n", p);
740 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
746 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
749 sm_dprintf("\ta.k.a.: %s\n", *av);
752 #if NETINET || NETINET6
753 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
757 char buf6[INET6_ADDRSTRLEN];
759 # endif /* NETINET6 */
762 # endif /* NETINET */
766 switch (hp->h_addrtype)
770 if (hp->h_length != INADDRSZ)
773 memmove(&ia, hp->h_addr_list[i], INADDRSZ);
774 (void) sm_snprintf(ipbuf, sizeof(ipbuf),
775 "[%.100s]", inet_ntoa(ia));
777 # endif /* NETINET */
781 if (hp->h_length != IN6ADDRSZ)
784 memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
785 addr = anynet_ntop(&ia6, buf6, sizeof(buf6));
787 (void) sm_snprintf(ipbuf, sizeof(ipbuf),
790 # endif /* NETINET6 */
792 if (ipbuf[0] == '\0')
796 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
797 setclass('w', ipbuf);
799 #endif /* NETINET || NETINET6 */
803 #endif /* NETINET6 */
807 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
809 /* current load average */
812 QueueLimitRecipient = (QUEUE_CHAR *) NULL;
813 QueueLimitSender = (QUEUE_CHAR *) NULL;
814 QueueLimitId = (QUEUE_CHAR *) NULL;
815 QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
822 while ((j = getopt(argc, argv, OPTIONS)) != -1)
826 case 'b': /* operations mode */
830 case 'A': /* use Alternate sendmail/submit.cf */
831 cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
832 : SM_GET_SENDMAIL_CF;
835 case 'B': /* body type */
836 CHECK_AGAINST_OPMODE(j);
837 BlankEnvelope.e_bodytype = newstr(optarg);
840 case 'C': /* select configuration file (already done) */
843 conffile = newstr(optarg);
844 dp = drop_privileges(true);
850 case 'd': /* debugging */
854 case 'f': /* from address */
855 case 'r': /* obsolete -f flag */
856 CHECK_AGAINST_OPMODE(j);
859 usrerr("More than one \"from\" person");
863 if (optarg[0] == '\0')
866 from = newstr(denlstring(optarg, true, true));
867 if (strcmp(RealUserName, from) != 0)
871 case 'F': /* set full name */
872 CHECK_AGAINST_OPMODE(j);
873 FullName = newstr(optarg);
876 case 'G': /* relay (gateway) submission */
878 CHECK_AGAINST_OPMODE(j);
881 case 'h': /* hop count */
882 CHECK_AGAINST_OPMODE(j);
883 BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
885 (void) sm_snprintf(buf, sizeof(buf), "%d",
886 BlankEnvelope.e_hopcount);
887 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
891 usrerr("Bad hop count (%s)", optarg);
896 case 'L': /* program label */
900 case 'n': /* don't alias */
901 CHECK_AGAINST_OPMODE(j);
905 case 'N': /* delivery status notifications */
906 CHECK_AGAINST_OPMODE(j);
907 DefaultNotify |= QHASNOTIFY;
908 macdefine(&BlankEnvelope.e_macro, A_TEMP,
909 macid("{dsn_notify}"), optarg);
910 if (sm_strcasecmp(optarg, "never") == 0)
912 for (p = optarg; p != NULL; optarg = p)
917 if (sm_strcasecmp(optarg, "success") == 0)
918 DefaultNotify |= QPINGONSUCCESS;
919 else if (sm_strcasecmp(optarg, "failure") == 0)
920 DefaultNotify |= QPINGONFAILURE;
921 else if (sm_strcasecmp(optarg, "delay") == 0)
922 DefaultNotify |= QPINGONDELAY;
925 usrerr("Invalid -N argument");
931 case 'o': /* set option */
932 setoption(*optarg, optarg + 1, false, true,
936 case 'O': /* set option (long form) */
937 setoption(' ', optarg, false, true, &BlankEnvelope);
940 case 'p': /* set protocol */
941 CHECK_AGAINST_OPMODE(j);
942 p = strchr(optarg, ':');
950 cleanstrcpy(ep, p, i);
951 macdefine(&BlankEnvelope.e_macro,
957 i = strlen(optarg) + 1;
959 cleanstrcpy(ep, optarg, i);
960 macdefine(&BlankEnvelope.e_macro, A_HEAP,
965 case 'Q': /* change quarantining on queued items */
967 if (OpMode != MD_DELIVER &&
968 OpMode != MD_QUEUERUN)
970 usrerr("Can not use -Q with -b%c", OpMode);
975 if (OpMode == MD_DELIVER)
976 set_op_mode(MD_QUEUERUN);
980 quarantining = newstr(optarg);
983 case 'q': /* run queue files at intervals */
985 if (OpMode != MD_DELIVER &&
986 OpMode != MD_DAEMON &&
987 OpMode != MD_FGDAEMON &&
988 OpMode != MD_PRINT &&
989 OpMode != MD_PRINTNQE &&
990 OpMode != MD_QUEUERUN)
992 usrerr("Can not use -q with -b%c", OpMode);
997 /* don't override -bd, -bD or -bp */
998 if (OpMode == MD_DELIVER)
999 set_op_mode(MD_QUEUERUN);
1002 negate = optarg[0] == '!';
1005 /* negate meaning of pattern match */
1006 optarg++; /* skip '!' for next switch */
1011 case 'G': /* Limit by queue group name */
1014 usrerr("Can not use -q!G");
1015 ExitStat = EX_USAGE;
1018 if (queuegroup != NULL)
1020 usrerr("Can not use multiple -qG options");
1021 ExitStat = EX_USAGE;
1024 queuegroup = newstr(&optarg[1]);
1027 case 'I': /* Limit by ID */
1028 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1029 new->queue_match = newstr(&optarg[1]);
1030 new->queue_negate = negate;
1031 new->queue_next = QueueLimitId;
1035 case 'R': /* Limit by recipient */
1036 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1037 new->queue_match = newstr(&optarg[1]);
1038 new->queue_negate = negate;
1039 new->queue_next = QueueLimitRecipient;
1040 QueueLimitRecipient = new;
1043 case 'S': /* Limit by sender */
1044 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1045 new->queue_match = newstr(&optarg[1]);
1046 new->queue_negate = negate;
1047 new->queue_next = QueueLimitSender;
1048 QueueLimitSender = new;
1051 case 'f': /* foreground queue run */
1052 foregroundqueue = true;
1055 case 'Q': /* Limit by quarantine message */
1056 if (optarg[1] != '\0')
1058 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1059 new->queue_match = newstr(&optarg[1]);
1060 new->queue_negate = negate;
1061 new->queue_next = QueueLimitQuarantine;
1062 QueueLimitQuarantine = new;
1064 QueueMode = QM_QUARANTINE;
1067 case 'L': /* act on lost items */
1068 QueueMode = QM_LOST;
1071 case 'p': /* Persistent queue */
1072 queuepersistent = true;
1073 if (QueueIntvl == 0)
1075 if (optarg[1] == '\0')
1082 QueueIntvl = convtime(optarg, 'm');
1085 usrerr("Invalid -q value");
1086 ExitStat = EX_USAGE;
1089 /* check for bad conversion */
1091 ExitStat = EX_USAGE;
1096 case 'R': /* DSN RET: what to return */
1097 CHECK_AGAINST_OPMODE(j);
1098 if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1100 usrerr("Duplicate -R flag");
1101 ExitStat = EX_USAGE;
1104 BlankEnvelope.e_flags |= EF_RET_PARAM;
1105 if (sm_strcasecmp(optarg, "hdrs") == 0)
1106 BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1107 else if (sm_strcasecmp(optarg, "full") != 0)
1109 usrerr("Invalid -R value");
1110 ExitStat = EX_USAGE;
1112 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1113 macid("{dsn_ret}"), optarg);
1116 case 't': /* read recipients from message */
1117 CHECK_AGAINST_OPMODE(j);
1121 case 'V': /* DSN ENVID: set "original" envelope id */
1122 CHECK_AGAINST_OPMODE(j);
1123 if (!xtextok(optarg))
1125 usrerr("Invalid syntax in -V flag");
1126 ExitStat = EX_USAGE;
1130 BlankEnvelope.e_envid = newstr(optarg);
1131 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1132 macid("{dsn_envid}"), optarg);
1136 case 'X': /* traffic log file */
1137 dp = drop_privileges(true);
1139 if (stat(optarg, &traf_st) == 0 &&
1140 S_ISFIFO(traf_st.st_mode))
1141 TrafficLogFile = sm_io_open(SmFtStdio,
1144 SM_IO_WRONLY, NULL);
1146 TrafficLogFile = sm_io_open(SmFtStdio,
1149 SM_IO_APPEND, NULL);
1150 if (TrafficLogFile == NULL)
1152 syserr("cannot open %s", optarg);
1153 ExitStat = EX_CANTCREAT;
1156 (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1157 NULL, SM_IO_LBF, 0);
1160 /* compatibility flags */
1161 case 'c': /* connect to non-local mailers */
1162 case 'i': /* don't let dot stop me */
1163 case 'm': /* send to me too */
1164 case 'T': /* set timeout interval */
1165 case 'v': /* give blow-by-blow description */
1166 setoption(j, "T", false, true, &BlankEnvelope);
1169 case 'e': /* error message disposition */
1170 case 'M': /* define macro */
1171 setoption(j, optarg, false, true, &BlankEnvelope);
1174 case 's': /* save From lines in headers */
1175 setoption('f', "T", false, true, &BlankEnvelope);
1179 case 'I': /* initialize alias DBM file */
1180 set_op_mode(MD_INITALIAS);
1184 #if defined(__osf__) || defined(_AIX3)
1185 case 'x': /* random flag that OSF/1 & AIX mailx passes */
1187 #endif /* defined(__osf__) || defined(_AIX3) */
1188 #if defined(sony_news)
1190 case 'J': /* ignore flags for Japanese code conversion
1191 implemented on Sony NEWS */
1193 #endif /* defined(sony_news) */
1196 finis(true, true, EX_USAGE);
1202 /* if we've had errors so far, exit now */
1203 if ((ExitStat != EX_OK && OpMode != MD_TEST && OpMode != MD_CHECKCONFIG) ||
1204 ExitStat == EX_OSERR)
1206 finis(false, true, ExitStat);
1210 if (bitset(SUBMIT_MTA, SubmitMode))
1212 /* If set daemon_flags on command line, don't reset it */
1213 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1214 macdefine(&BlankEnvelope.e_macro, A_PERM,
1215 macid("{daemon_flags}"), "CC f");
1217 else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1219 SubmitMode = SUBMIT_MSA;
1221 /* If set daemon_flags on command line, don't reset it */
1222 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1223 macdefine(&BlankEnvelope.e_macro, A_PERM,
1224 macid("{daemon_flags}"), "c u");
1228 ** Do basic initialization.
1229 ** Read system control file.
1230 ** Extract special fields for local use.
1234 checkfd012("before readcf");
1236 vendor_pre_defaults(&BlankEnvelope);
1238 readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1239 safecf, &BlankEnvelope);
1240 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1241 ConfigFileRead = true;
1242 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1243 vendor_post_defaults(&BlankEnvelope);
1245 /* now we can complain about missing fds */
1246 if (MissingFds != 0 && LogLevel > 8)
1251 if (bitset(1 << STDIN_FILENO, MissingFds))
1252 (void) sm_strlcat(mbuf, ", stdin", sizeof(mbuf));
1253 if (bitset(1 << STDOUT_FILENO, MissingFds))
1254 (void) sm_strlcat(mbuf, ", stdout", sizeof(mbuf));
1255 if (bitset(1 << STDERR_FILENO, MissingFds))
1256 (void) sm_strlcat(mbuf, ", stderr", sizeof(mbuf));
1258 /* Notice: fill_errno is from high above: fill_fd() */
1259 sm_syslog(LOG_WARNING, NOQID,
1260 "File descriptors missing on startup: %s; %s",
1261 &mbuf[2], sm_errstring(fill_errno));
1264 /* Remove the ability for a normal user to send signals */
1265 if (RealUid != 0 && RealUid != geteuid())
1267 uid_t new_uid = geteuid();
1271 ** Since we can differentiate between uid and euid,
1272 ** make the uid a different user so the real user
1273 ** can't send signals. However, it doesn't need to be
1274 ** root (euid has root).
1280 sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1281 if (setreuid(new_uid, geteuid()) < 0)
1283 syserr("main: setreuid(%d, %d) failed",
1284 (int) new_uid, (int) geteuid());
1285 finis(false, true, EX_OSERR);
1289 sm_dprintf("Now running as e/ruid %d:%d\n",
1290 (int) geteuid(), (int) getuid());
1291 #else /* HASSETREUID */
1293 ** Have to change both effective and real so need to
1294 ** change them both to effective to keep privs.
1298 sm_dprintf("Changing uid to %d\n", (int) new_uid);
1299 if (setuid(new_uid) < 0)
1301 syserr("main: setuid(%d) failed", (int) new_uid);
1302 finis(false, true, EX_OSERR);
1306 sm_dprintf("Now running as e/ruid %d:%d\n",
1307 (int) geteuid(), (int) getuid());
1308 #endif /* HASSETREUID */
1312 if (FallbackMX != NULL)
1313 (void) getfallbackmxrr(FallbackMX);
1314 #endif /* NAMED_BIND */
1316 if (SuperSafe == SAFE_INTERACTIVE && !SM_IS_INTERACTIVE(CurEnv->e_sendmode))
1318 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1319 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1322 if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1324 usrerr("Mail submission program cannot be used as daemon");
1325 finis(false, true, EX_USAGE);
1328 if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1329 OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1330 OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1333 /* set up the basic signal handlers */
1334 if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1335 (void) sm_signal(SIGINT, intsig);
1336 (void) sm_signal(SIGTERM, intsig);
1338 /* Enforce use of local time (null string overrides this) */
1339 if (TimeZoneSpec == NULL)
1341 else if (TimeZoneSpec[0] != '\0')
1342 sm_setuserenv("TZ", TimeZoneSpec);
1344 sm_setuserenv("TZ", NULL);
1347 /* initialize mailbox database */
1348 i = sm_mbdb_initialize(Mbdb);
1351 usrerr("Can't initialize mailbox database \"%s\": %s",
1352 Mbdb, sm_strexit(i));
1356 /* avoid denial-of-service attacks */
1359 if (OpMode == MD_TEST)
1361 /* can't be done after readcf if RunAs* is used */
1362 dp = drop_privileges(true);
1365 finis(false, true, dp);
1369 else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1371 /* drop privileges -- daemon mode done after socket/bind */
1372 dp = drop_privileges(false);
1374 if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1376 usrerr("Mail submission program must have RunAsUser set to non root user");
1377 finis(false, true, EX_CONFIG);
1383 _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1384 _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1385 #endif /* NAMED_BIND */
1388 ** Find our real host name for future logging.
1391 authinfo = getauthinfo(STDIN_FILENO, &forged);
1392 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1394 /* suppress error printing if errors mailed back or whatever */
1395 if (BlankEnvelope.e_errormode != EM_PRINT)
1398 /* set up the $=m class now, after .cf has a chance to redefine $m */
1399 expand("\201m", jbuf, sizeof(jbuf), &BlankEnvelope);
1400 if (jbuf[0] != '\0')
1401 setclass('m', jbuf);
1403 /* probe interfaces and locate any additional names */
1404 if (DontProbeInterfaces != DPI_PROBENONE)
1409 char pidpath[MAXPATHLEN];
1411 /* Now we know which .cf file we use */
1412 sm_dprintf(" Conf file:\t%s (selected)\n",
1413 getcfname(OpMode, SubmitMode, cftype, conffile));
1414 expand(PidFile, pidpath, sizeof(pidpath), &BlankEnvelope);
1415 sm_dprintf(" Pid file:\t%s (selected)\n", pidpath);
1420 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1421 sm_dprintf("\n (short domain name) $w = ");
1422 xputs(sm_debug_file(), macvalue('w', &BlankEnvelope));
1423 sm_dprintf("\n (canonical domain name) $j = ");
1424 xputs(sm_debug_file(), macvalue('j', &BlankEnvelope));
1425 sm_dprintf("\n (subdomain name) $m = ");
1426 xputs(sm_debug_file(), macvalue('m', &BlankEnvelope));
1427 sm_dprintf("\n (node name) $k = ");
1428 xputs(sm_debug_file(), macvalue('k', &BlankEnvelope));
1429 sm_dprintf("\n========================================================\n\n");
1433 ** Do more command line checking -- these are things that
1434 ** have to modify the results of reading the config file.
1437 /* process authorization warnings from command line */
1439 auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1440 RealUserName, conffile);
1441 if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1442 auth_warning(&BlankEnvelope, "Processed from queue %s",
1444 if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1445 RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1446 sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1449 /* check body type for legality */
1450 i = check_bodytype(BlankEnvelope.e_bodytype);
1451 if (i == BODYTYPE_ILLEGAL)
1453 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1454 BlankEnvelope.e_bodytype = NULL;
1456 else if (i != BODYTYPE_NONE)
1457 SevenBitInput = (i == BODYTYPE_7BIT);
1459 /* tweak default DSN notifications */
1460 if (DefaultNotify == 0)
1461 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1463 /* check for sane configuration level */
1464 if (ConfigLevel > MAXCONFIGLEVEL)
1466 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1467 ConfigLevel, Version, MAXCONFIGLEVEL);
1470 /* need MCI cache to have persistence */
1471 if (HostStatDir != NULL && MaxMciCache == 0)
1474 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1475 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1478 /* need HostStatusDir in order to have SingleThreadDelivery */
1479 if (SingleThreadDelivery && HostStatDir == NULL)
1481 SingleThreadDelivery = false;
1482 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1483 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1487 j = sm_memstat_open();
1488 if (j < 0 && (RefuseLowMem > 0 || QueueLowMem > 0) && LogLevel > 4)
1490 sm_syslog(LOG_WARNING, NOQID,
1491 "cannot get memory statistics, settings ignored, error=%d"
1494 #endif /* _FFR_MEMSTAT */
1496 /* check for permissions */
1498 RealUid != TrustedUid)
1500 char *action = NULL;
1505 if (quarantining != NULL)
1506 action = "quarantine jobs";
1509 /* Normal users can do a single queue run */
1510 if (QueueIntvl == 0)
1514 /* but not persistent queue runners */
1516 action = "start a queue runner daemon";
1521 action = "purge host status";
1527 action = "run daemon";
1530 sm_dprintf("Deny user %d attempt to %s\n",
1531 (int) RealUid, action);
1534 sm_syslog(LOG_ALERT, NOQID,
1535 "user %d attempted to %s",
1536 (int) RealUid, action);
1538 usrerr("Permission denied (real uid not trusted)");
1539 finis(false, true, EX_USAGE);
1544 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1547 ** If -bv and RestrictExpand,
1548 ** drop privs to prevent normal
1549 ** users from reading private
1550 ** aliases/forwards/:include:s
1554 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1557 dp = drop_privileges(true);
1559 /* Fake address safety */
1561 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1562 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1567 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1569 CurEnv->e_id = NULL;
1570 finis(true, true, dp);
1577 case MD_CHECKCONFIG:
1582 /* Nothing special to check */
1586 if (!wordinclass(RealUserName, 't'))
1589 sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1592 sm_syslog(LOG_ALERT, NOQID,
1593 "user %d attempted to rebuild the alias map",
1596 usrerr("Permission denied (real uid not trusted)");
1597 finis(false, true, EX_USAGE);
1603 usrerr("User %d cannot rebuild aliases in mail submission program",
1605 finis(false, true, EX_USAGE);
1611 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1615 ** If -v and RestrictExpand, reset
1616 ** Verbose to prevent normal users
1617 ** from seeing the expansion of
1618 ** aliases/forwards/:include:s
1622 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1631 BlankEnvelope.e_flags |= EF_METOO;
1636 /* don't have persistent host status in test mode */
1640 case MD_CHECKCONFIG:
1643 BlankEnvelope.e_errormode = EM_PRINT;
1648 BlankEnvelope.e_errormode = EM_PRINT;
1650 /* arrange to exit cleanly on hangup signal */
1651 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1652 (void) sm_signal(SIGHUP, intsig);
1654 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1655 "Notice: -bv may give misleading output for non-privileged user\n");
1659 run_in_foreground = true;
1660 set_op_mode(MD_DAEMON);
1664 vendor_daemon_setup(&BlankEnvelope);
1666 /* remove things that don't make sense in daemon mode */
1670 /* arrange to restart on hangup signal */
1671 if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1672 sm_syslog(LOG_WARNING, NOQID,
1673 "daemon invoked without full pathname; kill -1 won't work");
1678 BlankEnvelope.e_errormode = EM_PRINT;
1683 /* arrange to exit cleanly on hangup signal */
1684 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1685 (void) sm_signal(SIGHUP, intsig);
1689 /* special considerations for FullName */
1690 if (FullName != NULL)
1694 /* full names can't have newlines */
1695 if (strchr(FullName, '\n') != NULL)
1697 full = newstr(denlstring(FullName, true, true));
1701 /* check for characters that may have to be quoted */
1702 if (!rfc822_string(FullName))
1705 ** Quote a full name with special characters
1706 ** as a comment so crackaddr() doesn't destroy
1707 ** the name portion of the address.
1710 FullName = addquotes(FullName, NULL);
1712 sm_free(full); /* XXX */
1716 /* do heuristic mode adjustment */
1719 /* turn off noconnect option */
1720 setoption('c', "F", true, false, &BlankEnvelope);
1722 /* turn on interactive delivery */
1723 setoption('d', "", true, false, &BlankEnvelope);
1727 /* check for vendor mismatch */
1728 if (VendorCode != VENDOR_CODE)
1730 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1731 getvendor(VENDOR_CODE), getvendor(VendorCode));
1733 #endif /* VENDOR_CODE */
1735 /* check for out of date configuration level */
1736 if (ConfigLevel < MAXCONFIGLEVEL)
1738 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1739 Version, MAXCONFIGLEVEL, ConfigLevel);
1742 if (ConfigLevel < 3)
1745 /* set options that were previous macros */
1746 if (SmtpGreeting == NULL)
1748 if (ConfigLevel < 7 &&
1749 (p = macvalue('e', &BlankEnvelope)) != NULL)
1750 SmtpGreeting = newstr(p);
1752 SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1754 if (UnixFromLine == NULL)
1756 if (ConfigLevel < 7 &&
1757 (p = macvalue('l', &BlankEnvelope)) != NULL)
1758 UnixFromLine = newstr(p);
1760 UnixFromLine = "From \201g \201d";
1762 SmtpError[0] = '\0';
1764 /* our name for SMTP codes */
1765 expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope);
1766 if (jbuf[0] == '\0')
1767 PSTRSET(MyHostName, "localhost");
1769 PSTRSET(MyHostName, jbuf);
1770 if (strchr(MyHostName, '.') == NULL)
1771 message("WARNING: local host name (%s) is not qualified; see cf/README: WHO AM I?",
1774 /* make certain that this name is part of the $=w class */
1775 setclass('w', MyHostName);
1777 /* fill in the structure of the *default* queue */
1778 st = stab("mqueue", ST_QUEUE, ST_FIND);
1780 syserr("No default queue (mqueue) defined");
1782 set_def_queueval(st->s_quegrp, true);
1784 /* the indices of built-in mailers */
1785 st = stab("local", ST_MAILER, ST_FIND);
1787 LocalMailer = st->s_mailer;
1788 else if (OpMode != MD_TEST || !warn_C_flag)
1789 syserr("No local mailer defined");
1791 st = stab("prog", ST_MAILER, ST_FIND);
1793 syserr("No prog mailer defined");
1796 ProgMailer = st->s_mailer;
1797 clrbitn(M_MUSER, ProgMailer->m_flags);
1800 st = stab("*file*", ST_MAILER, ST_FIND);
1802 syserr("No *file* mailer defined");
1805 FileMailer = st->s_mailer;
1806 clrbitn(M_MUSER, FileMailer->m_flags);
1809 st = stab("*include*", ST_MAILER, ST_FIND);
1811 syserr("No *include* mailer defined");
1813 InclMailer = st->s_mailer;
1815 if (ConfigLevel < 6)
1817 /* heuristic tweaking of local mailer for back compat */
1818 if (LocalMailer != NULL)
1820 setbitn(M_ALIASABLE, LocalMailer->m_flags);
1821 setbitn(M_HASPWENT, LocalMailer->m_flags);
1822 setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1823 setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1824 setbitn(M_CHECKPROG, LocalMailer->m_flags);
1825 setbitn(M_CHECKFILE, LocalMailer->m_flags);
1826 setbitn(M_CHECKUDB, LocalMailer->m_flags);
1828 if (ProgMailer != NULL)
1829 setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1830 if (FileMailer != NULL)
1831 setbitn(M_RUNASRCPT, FileMailer->m_flags);
1833 if (ConfigLevel < 7)
1835 if (LocalMailer != NULL)
1836 setbitn(M_VRFY250, LocalMailer->m_flags);
1837 if (ProgMailer != NULL)
1838 setbitn(M_VRFY250, ProgMailer->m_flags);
1839 if (FileMailer != NULL)
1840 setbitn(M_VRFY250, FileMailer->m_flags);
1843 /* MIME Content-Types that cannot be transfer encoded */
1844 setclass('n', "multipart/signed");
1846 /* MIME message/xxx subtypes that can be treated as messages */
1847 setclass('s', "rfc822");
1849 /* MIME Content-Transfer-Encodings that can be encoded */
1850 setclass('e', "7bit");
1851 setclass('e', "8bit");
1852 setclass('e', "binary");
1855 /* MIME Content-Types that should be treated as binary */
1856 setclass('b', "image");
1857 setclass('b', "audio");
1858 setclass('b', "video");
1859 setclass('b', "application/octet-stream");
1860 #endif /* USE_B_CLASS */
1862 /* MIME headers which have fields to check for overflow */
1863 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1864 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1866 /* MIME headers to check for length overflow */
1867 setclass(macid("{checkMIMETextHeaders}"), "content-description");
1869 /* MIME headers to check for overflow and rebalance */
1870 setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1871 setclass(macid("{checkMIMEHeaders}"), "content-id");
1872 setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1873 setclass(macid("{checkMIMEHeaders}"), "content-type");
1874 setclass(macid("{checkMIMEHeaders}"), "mime-version");
1876 /* Macros to save in the queue file -- don't remove any */
1877 setclass(macid("{persistentMacros}"), "r");
1878 setclass(macid("{persistentMacros}"), "s");
1879 setclass(macid("{persistentMacros}"), "_");
1880 setclass(macid("{persistentMacros}"), "{if_addr}");
1881 setclass(macid("{persistentMacros}"), "{daemon_flags}");
1883 /* operate in queue directory */
1884 if (QueueDir == NULL || *QueueDir == '\0')
1886 if (OpMode != MD_TEST)
1888 syserr("QueueDirectory (Q) option must be set");
1889 ExitStat = EX_CONFIG;
1894 if (OpMode != MD_TEST)
1895 setup_queues(OpMode == MD_DAEMON);
1898 /* check host status directory for validity */
1899 if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1901 /* cannot use this value */
1902 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1903 "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1904 HostStatDir, sm_errstring(errno));
1908 if (OpMode == MD_QUEUERUN &&
1909 RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1913 /* check to see if we own the queue directory */
1914 if (stat(".", &stbuf) < 0)
1915 syserr("main: cannot stat %s", QueueDir);
1916 if (stbuf.st_uid != RealUid)
1918 /* nope, really a botch */
1920 usrerr("You do not have permission to process the queue");
1921 finis(false, true, EX_NOPERM);
1927 /* sanity checks on milter filters */
1928 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1930 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1931 setup_daemon_milters();
1935 /* Convert queuegroup string to qgrp number */
1936 if (queuegroup != NULL)
1938 qgrp = name2qid(queuegroup);
1942 usrerr("Queue group %s unknown", queuegroup);
1943 finis(false, true, ExitStat);
1948 /* if checking config or have had errors so far, exit now */
1949 if (OpMode == MD_CHECKCONFIG || (ExitStat != EX_OK && OpMode != MD_TEST))
1951 finis(false, true, ExitStat);
1956 /* sendmail specific SASL initialization */
1961 checkfd012("before main() initmaps");
1965 ** Do operation-mode-dependent initialization.
1971 /* print the queue */
1973 (void) dropenvelope(&BlankEnvelope, true, false);
1974 (void) sm_signal(SIGPIPE, sigpipe);
1979 /* Selecting a particular queue group to run */
1980 for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1984 (void) print_single_queue(qgrp, j);
1986 finis(false, true, EX_OK);
1990 finis(false, true, EX_OK);
1995 /* print number of entries in queue */
1996 (void) dropenvelope(&BlankEnvelope, true, false);
1997 (void) sm_signal(SIGPIPE, sigpipe);
1998 printnqe(smioout, NULL);
1999 finis(false, true, EX_OK);
2004 /* only handle quarantining here */
2005 if (quarantining == NULL)
2008 if (QueueMode != QM_QUARANTINE &&
2009 QueueMode != QM_NORMAL)
2012 usrerr("Can not use -Q with -q%c", QueueMode);
2013 ExitStat = EX_USAGE;
2014 finis(false, true, ExitStat);
2017 quarantine_queue(quarantining, qgrp);
2018 finis(false, true, EX_OK);
2022 (void) sm_signal(SIGPIPE, sigpipe);
2023 (void) mci_traverse_persistent(mci_print_persistent, NULL);
2024 finis(false, true, EX_OK);
2029 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2030 finis(false, true, EX_OK);
2035 /* initialize maps */
2037 finis(false, true, ExitStat);
2043 /* reset DSN parameters */
2044 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2045 macdefine(&BlankEnvelope.e_macro, A_PERM,
2046 macid("{dsn_notify}"), NULL);
2047 BlankEnvelope.e_envid = NULL;
2048 macdefine(&BlankEnvelope.e_macro, A_PERM,
2049 macid("{dsn_envid}"), NULL);
2050 BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2051 macdefine(&BlankEnvelope.e_macro, A_PERM,
2052 macid("{dsn_ret}"), NULL);
2054 /* don't open maps for daemon -- done below in child */
2060 /* print configuration table (or at least part of it) */
2063 for (i = 0; i < MAXMAILERS; i++)
2065 if (Mailer[i] != NULL)
2066 printmailer(sm_debug_file(), Mailer[i]);
2071 ** Switch to the main envelope.
2074 CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2075 sm_rpool_new_x(NULL));
2076 MainEnvelope.e_flags = BlankEnvelope.e_flags;
2079 ** If test mode, read addresses from stdin and process.
2082 if (OpMode == MD_TEST)
2084 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2089 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2090 "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2091 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2092 "Enter <ruleset> <address>\n");
2094 macdefine(&(MainEnvelope.e_macro), A_PERM,
2095 macid("{addr_type}"), "e r");
2100 (void) sm_signal(SIGINT, intindebug);
2101 (void) sm_releasesignal(SIGINT);
2103 (void) sm_io_fprintf(smioout,
2106 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2107 if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2109 testmodeline("/quit", &MainEnvelope);
2110 p = strchr(buf, '\n');
2114 (void) sm_io_fprintf(smioout,
2117 testmodeline(buf, &MainEnvelope);
2119 SM_EXCEPT(exc, "[!F]*")
2122 ** 8.10 just prints \n on interrupt.
2123 ** I'm printing the exception here in case
2124 ** sendmail is extended to raise additional
2125 ** exceptions in this context.
2128 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2130 sm_exc_print(exc, smioout);
2138 if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER ||
2139 OpMode == MD_ARPAFTP)
2141 /* check whether STARTTLS is turned off for the client */
2142 if (chkclientmodifiers(D_NOTLS))
2145 else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2148 /* check whether STARTTLS is turned off */
2149 if (chkdaemonmodifiers(D_NOTLS) && chkclientmodifiers(D_NOTLS))
2152 else /* other modes don't need STARTTLS */
2157 /* basic TLS initialization */
2158 tls_ok = init_tls_library(FipsMode);
2159 if (!tls_ok && FipsMode)
2161 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2162 "ERROR: FIPSMode failed to initialize\n");
2167 if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2169 /* disable TLS for client */
2172 #endif /* STARTTLS */
2175 ** If collecting stuff from the queue, go start doing that.
2178 if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2183 /* init TLS for client, ignore result for now */
2184 (void) initclttls(tls_ok);
2185 #endif /* STARTTLS */
2188 ** The parent process of the caller of runqueue() needs
2189 ** to stay around for a possible SIGTERM. The SIGTERM will
2190 ** tell this process that all of the queue runners children
2191 ** need to be sent SIGTERM as well. At the same time, we
2192 ** want to return control to the command line. So we do an
2196 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2199 ** If the fork() failed we should still try to do
2200 ** the queue run. If it succeeded then the child
2201 ** is going to start the run and wait for all
2202 ** of the children to finish.
2207 /* Reset global flags */
2208 RestartRequest = NULL;
2209 ShutdownRequest = NULL;
2212 /* disconnect from terminal */
2213 disconnect(2, CurEnv);
2216 CurrentPid = getpid();
2219 int rwgflags = RWG_NONE;
2222 ** To run a specific queue group mark it to
2223 ** be run, select the work group it's in and
2224 ** increment the work counter.
2227 for (i = 0; i < NumQueue && Queue[i] != NULL;
2229 Queue[i]->qg_nextrun = (time_t) -1;
2230 Queue[qgrp]->qg_nextrun = 0;
2232 rwgflags |= RWG_VERBOSE;
2233 if (queuepersistent)
2234 rwgflags |= RWG_PERSISTENT;
2235 rwgflags |= RWG_FORCE;
2236 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2240 (void) runqueue(false, Verbose,
2241 queuepersistent, true);
2243 /* set the title to make it easier to find */
2244 sm_setproctitle(true, CurEnv, "Queue control");
2245 (void) sm_signal(SIGCHLD, SIG_DFL);
2246 while (CurChildren > 0)
2252 while ((ret = sm_wait(&status)) <= 0)
2254 if (errno == ECHILD)
2257 ** Oops... something got messed
2258 ** up really bad. Waiting for
2259 ** non-existent children
2260 ** shouldn't happen. Let's get
2270 /* something is really really wrong */
2271 if (errno == ECHILD)
2273 sm_syslog(LOG_ERR, NOQID,
2274 "queue control process: lost all children: wait returned ECHILD");
2278 /* Only drop when a child gives status */
2279 if (WIFSTOPPED(status))
2282 proc_list_drop(ret, status, NULL);
2285 finis(true, true, ExitStat);
2290 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2292 /* check whether AUTH is turned off for the server */
2293 if (!chkdaemonmodifiers(D_NOAUTH) &&
2294 (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2295 syserr("!sasl_server_init failed! [%s]",
2296 sasl_errstring(i, NULL, NULL));
2300 if (OpMode == MD_SMTP)
2302 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2303 PROC_DAEMON, 0, -1, NULL);
2305 /* clean up background delivery children */
2306 (void) sm_signal(SIGCHLD, reapchild);
2310 ** If a daemon, wait for a request.
2311 ** getrequests will always return in a child.
2312 ** If we should also be processing the queue, start
2313 ** doing it in background.
2314 ** We check for any errors that might have happened
2318 if (OpMode == MD_DAEMON || QueueIntvl > 0)
2322 /* avoid cleanup in finis(), DaemonPid will be set below */
2324 if (!run_in_foreground && !tTd(99, 100))
2326 /* put us in background */
2329 syserr("daemon: cannot fork");
2332 finis(false, true, EX_OK);
2337 ** Initialize exception stack and default exception
2338 ** handler for child process.
2341 /* Reset global flags */
2342 RestartRequest = NULL;
2343 RestartWorkGroup = false;
2344 ShutdownRequest = NULL;
2346 CurrentPid = getpid();
2348 sm_exc_newthread(fatal_error);
2350 /* disconnect from our controlling tty */
2351 disconnect(2, &MainEnvelope);
2355 if (OpMode == MD_DAEMON)
2357 (void) sm_strlcat(dtype, "+SMTP", sizeof(dtype));
2358 DaemonPid = CurrentPid;
2362 (void) sm_strlcat2(dtype,
2364 ? "+persistent-queueing@"
2366 pintvl(QueueIntvl, true),
2370 (void) sm_strlcat(dtype, "+debugging", sizeof(dtype));
2372 sm_syslog(LOG_INFO, NOQID,
2373 "starting daemon (%s): %s", Version, dtype + 1);
2378 /* save daemon type in a macro for possible PidFile use */
2379 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2380 macid("{daemon_info}"), dtype + 1);
2382 /* save queue interval in a macro for possible PidFile use */
2383 macdefine(&MainEnvelope.e_macro, A_TEMP,
2384 macid("{queue_interval}"), pintvl(QueueIntvl, true));
2386 /* workaround: can't seem to release the signal in the parent */
2387 (void) sm_signal(SIGHUP, sighup);
2388 (void) sm_releasesignal(SIGHUP);
2389 (void) sm_signal(SIGTERM, sigterm);
2396 int rwgflags = RWG_NONE;
2399 ** To run a specific queue group mark it to
2400 ** be run, select the work group it's in and
2401 ** increment the work counter.
2404 for (i = 0; i < NumQueue && Queue[i] != NULL;
2406 Queue[i]->qg_nextrun = (time_t) -1;
2407 Queue[qgrp]->qg_nextrun = 0;
2409 rwgflags |= RWG_VERBOSE;
2410 if (queuepersistent)
2411 rwgflags |= RWG_PERSISTENT;
2412 rwgflags |= RWG_FORCE;
2413 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2417 #endif /* _FFR_RUNPQG */
2418 (void) runqueue(true, false, queuepersistent,
2422 ** If queuepersistent but not in daemon mode then
2423 ** we're going to do the queue runner monitoring here.
2424 ** If in daemon mode then the monitoring will happen
2428 if (OpMode != MD_DAEMON && queuepersistent)
2431 ** Write the pid to file
2432 ** XXX Overwrites sendmail.pid
2435 log_sendmail_pid(&MainEnvelope);
2437 /* set the title to make it easier to find */
2438 sm_setproctitle(true, CurEnv, "Queue control");
2439 (void) sm_signal(SIGCHLD, SIG_DFL);
2440 while (CurChildren > 0)
2448 while ((ret = sm_wait(&status)) <= 0)
2451 ** Waiting for non-existent
2452 ** children shouldn't happen.
2453 ** Let's get out of here if
2457 if (errno == ECHILD)
2465 /* something is really really wrong */
2466 if (errno == ECHILD)
2468 sm_syslog(LOG_ERR, NOQID,
2469 "persistent queue runner control process: lost all children: wait returned ECHILD");
2473 if (WIFSTOPPED(status))
2476 /* Probe only on a child status */
2477 proc_list_drop(ret, status, &group);
2479 if (WIFSIGNALED(status))
2481 if (WCOREDUMP(status))
2483 sm_syslog(LOG_ERR, NOQID,
2484 "persistent queue runner=%d core dumped, signal=%d",
2485 group, WTERMSIG(status));
2487 /* don't restart this */
2488 mark_work_group_restart(
2493 sm_syslog(LOG_ERR, NOQID,
2494 "persistent queue runner=%d died, pid=%ld, signal=%d",
2500 ** When debugging active, don't
2501 ** restart the persistent queues.
2502 ** But do log this as info.
2505 if (sm_debug_active(&DebugNoPRestart,
2508 sm_syslog(LOG_DEBUG, NOQID,
2509 "persistent queue runner=%d, exited",
2511 mark_work_group_restart(group,
2516 finis(true, true, ExitStat);
2520 if (OpMode != MD_DAEMON)
2525 ** Write the pid to file
2526 ** XXX Overwrites sendmail.pid
2529 log_sendmail_pid(&MainEnvelope);
2531 /* set the title to make it easier to find */
2533 (void) sm_strlcpyn(qtype, sizeof(qtype), 4,
2535 pintvl(QueueIntvl, true),
2538 sm_setproctitle(true, CurEnv, qtype);
2546 (void) runqueue(true, false,
2551 (void) dropenvelope(&MainEnvelope, true, false);
2554 /* init TLS for server, ignore result for now */
2555 (void) initsrvtls(tls_ok);
2556 #endif /* STARTTLS */
2559 p_flags = getrequests(&MainEnvelope);
2561 /* drop privileges */
2562 (void) drop_privileges(false);
2565 ** Get authentication data
2566 ** Set _ macro in BlankEnvelope before calling newenvelope().
2569 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2571 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2573 sm_syslog(LOG_INFO, NOQID,
2574 "main: where=after_getauthinfo, RealHostAddr=%s",
2575 anynet_ntoa(&RealHostAddr));
2577 /* at this point we are in a child: reset state */
2578 sm_rpool_free(MainEnvelope.e_rpool);
2579 (void) newenvelope(&MainEnvelope, &MainEnvelope,
2580 sm_rpool_new_x(NULL));
2585 /* log connection information */
2586 sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2590 ** If running SMTP protocol, start collecting and executing
2591 ** commands. This will never return.
2594 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2599 ** Save some macros for check_* rulesets.
2606 (void) sm_snprintf(ipbuf, sizeof(ipbuf), "[%.100s]",
2607 anynet_ntoa(&RealHostAddr));
2608 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2609 macid("{client_name}"), ipbuf);
2612 macdefine(&BlankEnvelope.e_macro, A_PERM,
2613 macid("{client_name}"), RealHostName);
2614 macdefine(&BlankEnvelope.e_macro, A_PERM,
2615 macid("{client_ptr}"), RealHostName);
2616 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2617 macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2620 switch (RealHostAddr.sa.sa_family)
2624 (void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2625 RealHostAddr.sin.sin_port);
2627 #endif /* NETINET */
2630 (void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2631 RealHostAddr.sin6.sin6_port);
2633 #endif /* NETINET6 */
2635 (void) sm_snprintf(pbuf, sizeof(pbuf), "0");
2638 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2639 macid("{client_port}"), pbuf);
2641 if (OpMode == MD_DAEMON)
2643 ENVELOPE *saved_env;
2645 /* validate the connection */
2648 CurEnv = &BlankEnvelope;
2649 nullserver = validate_connection(&RealHostAddr,
2650 macvalue(macid("{client_name}"),
2653 if (bitset(EF_DISCARD, BlankEnvelope.e_flags))
2654 MainEnvelope.e_flags |= EF_DISCARD;
2658 else if (p_flags == NULL)
2660 p_flags = (BITMAP256 *) xalloc(sizeof(*p_flags));
2664 if (OpMode == MD_SMTP)
2665 (void) initsrvtls(tls_ok);
2666 #endif /* STARTTLS */
2668 /* turn off profiling */
2670 smtp(nullserver, *p_flags, &MainEnvelope);
2674 /* turn off profiling */
2676 if (OpMode == MD_DAEMON)
2681 sm_rpool_free(MainEnvelope.e_rpool);
2682 clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2683 if (OpMode == MD_VERIFY)
2685 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2686 PostMasterCopy = NULL;
2690 /* interactive -- all errors are global */
2691 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2695 ** Do basic system initialization and set the sender
2698 initsys(&MainEnvelope);
2699 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2700 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2701 setsender(from, &MainEnvelope, NULL, '\0', false);
2702 if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2703 (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2704 strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2706 auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2707 RealUserName, from, warn_f_flag);
2716 /* set the initial sender for AUTH= to $f@$j */
2717 fv = macvalue('f', &MainEnvelope);
2718 if (fv == NULL || *fv == '\0')
2719 MainEnvelope.e_auth_param = NULL;
2722 if (strchr(fv, '@') == NULL)
2724 i = strlen(fv) + strlen(macvalue('j',
2725 &MainEnvelope)) + 2;
2727 (void) sm_strlcpyn(p, i, 3, fv, "@",
2732 p = sm_strdup_x(fv);
2733 MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2735 sm_free(p); /* XXX */
2738 if (macvalue('s', &MainEnvelope) == NULL)
2739 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2742 if (*av == NULL && !GrabTo)
2744 MainEnvelope.e_to = NULL;
2745 MainEnvelope.e_flags |= EF_GLOBALERRS;
2747 SuperSafe = SAFE_NO;
2748 usrerr("Recipient names must be specified");
2750 /* collect body for UUCP return */
2751 if (OpMode != MD_VERIFY)
2752 collect(InChannel, false, NULL, &MainEnvelope, true);
2753 finis(true, true, EX_USAGE);
2758 ** Scan argv and deliver the message to everyone.
2761 save_val = LogUsrErrs;
2763 sendtoargv(av, &MainEnvelope);
2764 LogUsrErrs = save_val;
2766 /* if we have had errors sofar, arrange a meaningful exit stat */
2767 if (Errors > 0 && ExitStat == EX_OK)
2768 ExitStat = EX_USAGE;
2772 ** If using -t, force not sending to argv recipients, even
2773 ** if they are mentioned in the headers.
2780 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2781 q->q_state = QS_REMOVED;
2783 #endif /* _FFR_FIX_DASHT */
2786 ** Read the input mail.
2789 MainEnvelope.e_to = NULL;
2790 if (OpMode != MD_VERIFY || GrabTo)
2793 unsigned long savedflags;
2796 ** workaround for compiler warning on Irix:
2797 ** do not initialize variable in the definition, but
2799 ** warning(1548): transfer of control bypasses
2800 ** initialization of:
2801 ** variable "savederrors" (declared at line 2570)
2802 ** variable "savedflags" (declared at line 2571)
2806 savederrors = Errors;
2807 savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2808 MainEnvelope.e_flags |= EF_GLOBALERRS;
2809 MainEnvelope.e_flags &= ~EF_FATALERRS;
2812 collect(InChannel, false, NULL, &MainEnvelope, true);
2814 /* header checks failed */
2820 /* Log who the mail would have gone to */
2821 logundelrcpts(&MainEnvelope,
2822 MainEnvelope.e_message,
2826 finis(true, true, ExitStat);
2831 /* bail out if message too large */
2832 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2834 finis(true, true, ExitStat != EX_OK ? ExitStat
2840 /* set message size */
2841 (void) sm_snprintf(buf, sizeof(buf), "%ld",
2842 PRT_NONNEGL(MainEnvelope.e_msgsize));
2843 macdefine(&MainEnvelope.e_macro, A_TEMP,
2844 macid("{msg_size}"), buf);
2846 Errors = savederrors;
2847 MainEnvelope.e_flags |= savedflags;
2852 sm_dprintf("From person = \"%s\"\n",
2853 MainEnvelope.e_from.q_paddr);
2855 /* Check if quarantining stats should be updated */
2856 if (MainEnvelope.e_quarmsg != NULL)
2857 markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2860 ** Actually send everything.
2861 ** If verifying, just ack.
2866 if (!split_by_recipient(&MainEnvelope) &&
2867 bitset(EF_FATALERRS, MainEnvelope.e_flags))
2871 /* make sure we deliver at least the first envelope */
2872 i = FastSplit > 0 ? 0 : -1;
2873 for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2877 e->e_from.q_state = QS_SENDER;
2880 sm_dprintf("main[%d]: QS_SENDER ", i);
2881 printaddr(sm_debug_file(), &e->e_from, false);
2887 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2888 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2889 #endif /* NAMED_BIND */
2890 next = e->e_sibling;
2891 e->e_sibling = NULL;
2893 /* after FastSplit envelopes: queue up */
2894 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2895 e->e_sibling = next;
2900 ** Don't send return error message if in VERIFY mode.
2903 finis(true, true, ExitStat);
2908 ** STOP_SENDMAIL -- Stop the running program
2923 /* reset uid for process accounting */
2925 (void) setuid(RealUid);
2929 ** FINIS -- Clean up and exit.
2932 ** drop -- whether or not to drop CurEnv envelope
2933 ** cleanup -- call exit() or _exit()?
2934 ** exitstat -- exit status to use for exit() call
2944 finis(drop, cleanup, exitstat)
2947 volatile int exitstat;
2949 char pidpath[MAXPATHLEN];
2952 /* Still want to process new timeouts added below */
2954 (void) sm_releasesignal(SIGALRM);
2958 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2960 CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2961 printenvflags(CurEnv);
2964 printopenfds(false);
2968 ** Clean up. This might raise E:mta.quickabort
2971 /* clean up temp files */
2972 CurEnv->e_to = NULL;
2975 if (CurEnv->e_id != NULL)
2979 r = dropenvelope(CurEnv, true, false);
2980 if (exitstat == EX_OK)
2982 sm_rpool_free(CurEnv->e_rpool);
2983 CurEnv->e_rpool = NULL;
2985 /* these may have pointed to the rpool */
2986 CurEnv->e_to = NULL;
2987 CurEnv->e_message = NULL;
2988 CurEnv->e_statmsg = NULL;
2989 CurEnv->e_quarmsg = NULL;
2990 CurEnv->e_bodytype = NULL;
2991 CurEnv->e_id = NULL;
2992 CurEnv->e_envid = NULL;
2993 CurEnv->e_auth_param = NULL;
2996 poststats(StatFile);
2999 /* flush any cached connections */
3000 mci_flush(true, NULL);
3002 /* close maps belonging to this pid */
3006 /* close UserDatabase */
3015 /* clean up extended load average stuff */
3025 sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
3027 if (exitstat == EX_TEMPFAIL ||
3028 CurEnv->e_errormode == EM_BERKNET)
3031 /* XXX clean up queues and related data structures */
3035 cleanup_shm(DaemonPid == pid);
3036 #endif /* SM_CONF_SHM */
3038 /* close locked pid file */
3039 close_sendmail_pid();
3041 if (DaemonPid == pid || PidFilePid == pid)
3043 /* blow away the pid file */
3044 expand(PidFile, pidpath, sizeof(pidpath), CurEnv);
3045 (void) unlink(pidpath);
3048 /* reset uid for process accounting */
3050 sm_mbdb_terminate();
3052 (void) sm_memstat_close();
3053 #endif /* _FFR_MEMSTAT */
3054 (void) setuid(RealUid);
3056 /* dump the heap, if we are checking for memory leaks */
3057 if (sm_debug_active(&SmHeapCheck, 2))
3058 sm_heap_report(smioout,
3059 sm_debug_level(&SmHeapCheck) - 1);
3060 #endif /* SM_HEAP_CHECK */
3061 if (sm_debug_active(&SmXtrapReport, 1))
3062 sm_dprintf("xtrap count = %d\n", SmXtrapCount);
3070 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
3073 ** sig -- incoming signal.
3079 ** longjmps back to test mode loop.
3081 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3082 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3086 /* Type of an exception generated on SIGINT during address test mode. */
3087 static const SM_EXC_TYPE_T EtypeInterrupt =
3101 int save_errno = errno;
3103 FIX_SYSV_SIGNAL(sig, intindebug);
3105 CHECK_CRITICAL(sig);
3107 sm_exc_raisenew_x(&EtypeInterrupt);
3109 return SIGFUNC_RETURN;
3112 ** SIGTERM -- SIGTERM handler for the daemon
3115 ** sig -- signal number.
3121 ** Sets ShutdownRequest which will hopefully trigger
3122 ** the daemon to exit.
3124 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3125 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3134 int save_errno = errno;
3136 FIX_SYSV_SIGNAL(sig, sigterm);
3137 ShutdownRequest = "signal";
3139 return SIGFUNC_RETURN;
3142 ** SIGHUP -- handle a SIGHUP signal
3145 ** sig -- incoming signal.
3151 ** Sets RestartRequest which should cause the daemon
3154 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3155 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3164 int save_errno = errno;
3166 FIX_SYSV_SIGNAL(sig, sighup);
3167 RestartRequest = "signal";
3169 return SIGFUNC_RETURN;
3172 ** SIGPIPE -- signal handler for SIGPIPE
3175 ** sig -- incoming signal.
3181 ** Sets StopRequest which should cause the mailq/hoststatus
3184 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3185 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3194 int save_errno = errno;
3196 FIX_SYSV_SIGNAL(sig, sigpipe);
3199 return SIGFUNC_RETURN;
3202 ** INTSIG -- clean up on interrupt
3204 ** This just arranges to exit. It pessimizes in that it
3205 ** may resend a message.
3208 ** sig -- incoming signal.
3214 ** Unlocks the current job.
3216 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3217 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3227 int save_errno = errno;
3229 FIX_SYSV_SIGNAL(sig, intsig);
3231 CHECK_CRITICAL(sig);
3232 sm_allsignals(true);
3237 /* Clean-up on aborted stdin message submission */
3238 if (OpMode == MD_SMTP ||
3239 OpMode == MD_DELIVER ||
3240 OpMode == MD_ARPAFTP)
3242 if (CurEnv->e_id != NULL)
3246 fn = queuename(CurEnv, DATAFL_LETTER);
3249 fn = queuename(CurEnv, ANYQFL_LETTER);
3257 if (sig != 0 && LogLevel > 79)
3258 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3259 if (OpMode != MD_TEST)
3260 unlockqueue(CurEnv);
3262 finis(drop, false, EX_OK);
3266 ** DISCONNECT -- remove our connection with any foreground process
3269 ** droplev -- how "deeply" we should drop the line.
3270 ** 0 -- ignore signals, mail back errors, make sure
3271 ** output goes to stdout.
3272 ** 1 -- also, make stdout go to /dev/null.
3273 ** 2 -- also, disconnect from controlling terminal
3274 ** (only for daemon mode).
3275 ** e -- the current envelope.
3281 ** Trys to insure that we are immune to vagaries of
3282 ** the controlling tty.
3286 disconnect(droplev, e)
3288 register ENVELOPE *e;
3293 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3294 sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3295 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3298 sm_dprintf("don't\n");
3302 sm_syslog(LOG_DEBUG, e->e_id,
3303 "disconnect level %d",
3306 /* be sure we don't get nasty signals */
3307 (void) sm_signal(SIGINT, SIG_IGN);
3308 (void) sm_signal(SIGQUIT, SIG_IGN);
3310 /* we can't communicate with our caller, so.... */
3312 CurEnv->e_errormode = EM_MAIL;
3314 DisConnected = true;
3316 /* all input from /dev/null */
3317 if (InChannel != smioin)
3319 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3322 if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3323 SM_IO_RDONLY, NULL, smioin) == NULL)
3324 sm_syslog(LOG_ERR, e->e_id,
3325 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3326 SM_PATH_DEVNULL, sm_errstring(errno));
3329 ** output to the transcript
3330 ** We also compare the fd numbers here since OutChannel
3331 ** might be a layer on top of smioout due to encryption
3335 if (OutChannel != smioout &&
3336 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3337 sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3339 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3340 OutChannel = smioout;
3344 ** Has smioout been closed? Reopen it.
3345 ** This shouldn't happen anymore, the code is here
3346 ** just as a reminder.
3349 if (smioout->sm_magic == NULL &&
3350 sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3351 SM_IO_WRONLY, NULL, smioout) == NULL)
3352 sm_syslog(LOG_ERR, e->e_id,
3353 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3354 SM_PATH_DEVNULL, sm_errstring(errno));
3359 fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3362 sm_syslog(LOG_ERR, e->e_id,
3363 "disconnect: open(\"%s\") failed: %s",
3364 SM_PATH_DEVNULL, sm_errstring(errno));
3366 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3369 (void) dup2(fd, STDOUT_FILENO);
3370 (void) dup2(fd, STDERR_FILENO);
3375 /* drop our controlling TTY completely if possible */
3383 checkfd012("disconnect");
3387 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3400 while ((ap = *++argv) != NULL)
3402 /* Return if "--" or not an option of any form. */
3403 if (ap[0] != '-' || ap[1] == '-')
3406 /* Don't allow users to use "-Q." or "-Q ." */
3407 if ((ap[1] == 'Q' && ap[2] == '.') ||
3408 (ap[1] == 'Q' && argv[1] != NULL &&
3409 argv[1][0] == '.' && argv[1][1] == '\0'))
3411 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3412 "Can not use -Q.\n");
3416 /* skip over options that do have a value */
3417 op = strchr(OPTIONS, ap[1]);
3418 if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3420 #if defined(sony_news)
3421 ap[1] != 'E' && ap[1] != 'J' &&
3422 #endif /* defined(sony_news) */
3423 argv[1] != NULL && argv[1][0] != '-')
3429 /* If -C doesn't have an argument, use sendmail.cf. */
3430 #define __DEFPATH "sendmail.cf"
3431 if (ap[1] == 'C' && ap[2] == '\0')
3433 *argv = xalloc(sizeof(__DEFPATH) + 2);
3434 (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3438 /* If -q doesn't have an argument, run it once. */
3439 if (ap[1] == 'q' && ap[2] == '\0')
3442 /* If -Q doesn't have an argument, disable quarantining */
3443 if (ap[1] == 'Q' && ap[2] == '\0')
3446 /* if -d doesn't have an argument, use 0-99.1 */
3447 if (ap[1] == 'd' && ap[2] == '\0')
3450 #if defined(sony_news)
3451 /* if -E doesn't have an argument, use -EC */
3452 if (ap[1] == 'E' && ap[2] == '\0')
3455 /* if -J doesn't have an argument, use -JJ */
3456 if (ap[1] == 'J' && ap[2] == '\0')
3458 #endif /* defined(sony_news) */
3462 ** AUTH_WARNING -- specify authorization warning
3465 ** e -- the current envelope.
3466 ** msg -- the text of the message.
3467 ** args -- arguments to the message.
3475 auth_warning(register ENVELOPE *e, const char *msg, ...)
3476 #else /* __STDC__ */
3477 auth_warning(e, msg, va_alist)
3478 register ENVELOPE *e;
3481 #endif /* __STDC__ */
3486 if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3489 static char hostbuf[48];
3491 if (hostbuf[0] == '\0')
3495 hp = myhostname(hostbuf, sizeof(hostbuf));
3502 #endif /* NETINET6 */
3505 (void) sm_strlcpyn(buf, sizeof(buf), 2, hostbuf, ": ");
3506 p = &buf[strlen(buf)];
3507 SM_VA_START(ap, msg);
3508 (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3510 addheader("X-Authentication-Warning", buf, 0, e, true);
3512 sm_syslog(LOG_INFO, e->e_id,
3513 "Authentication-Warning: %.400s",
3518 ** GETEXTENV -- get from external environment
3521 ** envar -- the name of the variable to retrieve
3524 ** The value, if any.
3535 for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3537 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3538 return &(*envp)[l + 1];
3543 ** SM_SETUSERENV -- set an environment variable in the propagated environment
3546 ** envar -- the name of the environment variable.
3547 ** value -- the value to which it should be set. If
3548 ** null, this is extracted from the incoming
3549 ** environment. If that is not set, the call
3550 ** to sm_setuserenv is ignored.
3557 sm_setuserenv(envar, value)
3562 char **evp = UserEnviron;
3567 value = getextenv(envar);
3572 /* XXX enforce reasonable size? */
3573 i = strlen(envar) + 1;
3574 l = strlen(value) + i + 1;
3575 p = (char *) xalloc(l);
3576 (void) sm_strlcpyn(p, l, 3, envar, "=", value);
3578 while (*evp != NULL && strncmp(*evp, p, i) != 0)
3584 else if (evp < &UserEnviron[MAXUSERENVIRON])
3590 /* make sure it is in our environment as well */
3592 syserr("sm_setuserenv: putenv(%s) failed", p);
3595 ** DUMPSTATE -- dump state
3604 register char *j = macvalue('j', CurEnv);
3606 extern int NextMacroId;
3608 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3609 "--- dumping state on %s: $j = %s ---",
3611 j == NULL ? "<NULL>" : j);
3614 if (!wordinclass(j, 'w'))
3615 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3616 "*** $j not in $=w ***");
3618 sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3619 sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3620 NextMacroId, MAXMACROID);
3621 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3623 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3624 mci_dump_all(smioout, true);
3625 rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3629 register char **pvp;
3630 char *pv[MAXATOM + 1];
3633 status = REWRITE(pv, rs, CurEnv);
3634 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3635 "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3637 for (pvp = pv; *pvp != NULL; pvp++)
3638 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3640 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3645 ** SIGUSR1 -- Signal a request to dump state.
3648 ** sig -- calling signal.
3653 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3654 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3657 ** XXX: More work is needed for this signal handler.
3665 int save_errno = errno;
3667 FIX_SYSV_SIGNAL(sig, sigusr1);
3669 CHECK_CRITICAL(sig);
3670 dumpstate("user signal");
3673 # endif /* SM_HEAP_CHECK */
3675 return SIGFUNC_RETURN;
3677 #endif /* SIGUSR1 */
3680 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3683 ** to_real_uid -- if set, drop to the real uid instead
3684 ** of the RunAsUser.
3687 ** EX_OSERR if the setuid failed.
3692 drop_privileges(to_real_uid)
3696 GIDSET_T emptygidset[1];
3699 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",
3701 (int) RealUid, (int) RealGid,
3702 (int) getuid(), (int) getgid(),
3703 (int) geteuid(), (int) getegid(),
3704 (int) RunAsUid, (int) RunAsGid);
3708 RunAsUserName = RealUserName;
3714 /* make sure no one can grab open descriptors for secret files */
3716 sm_mbdb_terminate();
3718 /* reset group permissions; these can be set later */
3719 emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3722 ** Notice: on some OS (Linux...) the setgroups() call causes
3723 ** a logfile entry if sendmail is not run by root.
3724 ** However, it is unclear (no POSIX standard) whether
3725 ** setgroups() can only succeed if executed by root.
3726 ** So for now we keep it as it is; if you want to change it, use
3727 ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3730 if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3732 syserr("drop_privileges: setgroups(1, %d) failed",
3733 (int) emptygidset[0]);
3737 /* reset primary group id */
3741 ** Drop gid to real gid.
3742 ** On some OS we must reset the effective[/real[/saved]] gid,
3743 ** and then use setgid() to finally drop all group privileges.
3744 ** Later on we check whether we can get back the
3749 if (setegid(RunAsGid) < 0)
3751 syserr("drop_privileges: setegid(%d) failed",
3755 #else /* HASSETEGID */
3757 if (setregid(RunAsGid, RunAsGid) < 0)
3759 syserr("drop_privileges: setregid(%d, %d) failed",
3760 (int) RunAsGid, (int) RunAsGid);
3763 # else /* HASSETREGID */
3765 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3767 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3768 (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3771 # endif /* HASSETRESGID */
3772 # endif /* HASSETREGID */
3773 #endif /* HASSETEGID */
3775 if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3777 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3779 syserr("drop_privileges: setgid(%d) failed",
3784 if (rval == EX_OK && getegid() != RunAsGid)
3786 syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3787 (int) getegid(), (int) RunAsGid);
3792 /* fiddle with uid */
3793 if (to_real_uid || RunAsUid != 0)
3798 ** Try to setuid(RunAsUid).
3799 ** euid must be RunAsUid,
3800 ** ruid must be RunAsUid unless (e|r)uid wasn't 0
3801 ** and we didn't have to drop privileges to the real uid.
3804 if (setuid(RunAsUid) < 0 ||
3805 geteuid() != RunAsUid ||
3806 (getuid() != RunAsUid &&
3807 (to_real_uid || geteuid() == 0 || getuid() == 0)))
3811 ** if ruid != RunAsUid, euid == RunAsUid, then
3812 ** try resetting just the real uid, then using
3813 ** setuid() to drop the saved-uid as well.
3816 if (geteuid() == RunAsUid)
3818 if (setreuid(RunAsUid, -1) < 0)
3820 syserr("drop_privileges: setreuid(%d, -1) failed",
3824 if (setuid(RunAsUid) < 0)
3826 syserr("drop_privileges: second setuid(%d) attempt failed",
3832 #endif /* HASSETREUID */
3834 syserr("drop_privileges: setuid(%d) failed",
3840 if (RunAsUid != 0 && setuid(0) == 0)
3843 ** Believe it or not, the Linux capability model
3844 ** allows a non-root process to override setuid()
3845 ** on a process running as root and prevent that
3846 ** process from dropping privileges.
3849 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3852 else if (RunAsUid != euid && setuid(euid) == 0)
3855 ** Some operating systems will keep the saved-uid
3856 ** if a non-root effective-uid calls setuid(real-uid)
3857 ** making it possible to set it back again later.
3860 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3865 if ((to_real_uid || RunAsGid != 0) &&
3866 rval == EX_OK && RunAsGid != EffGid &&
3867 getuid() != 0 && geteuid() != 0)
3870 if (setgid(EffGid) == 0)
3872 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3880 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3881 (int) geteuid(), (int) getuid(),
3882 (int) getegid(), (int) getgid());
3883 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3884 (int) RunAsUid, (int) RunAsGid);
3886 sm_dprintf("drop_privileges: rval = %d\n", rval);
3891 ** FILL_FD -- make sure a file descriptor has been properly allocated
3893 ** Used to make sure that stdin/out/err are allocated on startup
3896 ** fd -- the file descriptor to be filled.
3897 ** where -- a string used for logging. If NULL, this is
3898 ** being called on startup, and logging should
3905 ** possibly changes MissingFds
3916 if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3920 syserr("fill_fd: %s: fd %d not open", where, fd);
3922 MissingFds |= 1 << fd;
3923 i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3926 syserr("!fill_fd: %s: cannot open %s",
3927 where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3936 ** SM_PRINTOPTIONS -- print options
3939 ** options -- array of options.
3946 sm_printoptions(options)
3956 if (ll + strlen(*av) > 63)
3965 sm_dprintf("%s", *av);
3966 ll += strlen(*av++) + 1;
3972 ** TO8BIT -- convert \octal sequences in a test mode input line
3975 ** str -- the input line.
3981 ** replaces \0octal in str with octal value.
3984 static bool to8bit __P((char *));
3999 while ((c = (*str++ & 0377)) != '\0')
4005 (nxtc = (*str & 0377)) == '0')
4008 while ((nxtc = (*str & 0377)) != '\0' &&
4009 isascii(nxtc) && isdigit(nxtc))
4026 q = quote_internal_chars(in, in, &len);
4028 sm_strlcpy(in, q, len);
4034 ** TESTMODELINE -- process a test mode input line
4037 ** line -- the input line.
4038 ** e -- the current environment.
4041 ** .X process X as a configuration line
4042 ** =X dump a configuration item (such as mailers)
4043 ** $X dump a macro or class
4044 ** /X try an activity
4045 ** X normal process through rule set X
4049 testmodeline(line, e)
4055 auto char *delimptr;
4064 static int tryflags = RF_COPYNONE;
4065 char exbuf[MAXLINE];
4067 extern unsigned char TokTypeNoC[];
4070 /* skip leading spaces */
4071 while (*line == ' ')
4086 case '.': /* config-style settings */
4090 mid = macid_parse(&line[2], &delimptr);
4094 lbp = translate_dollars(delimptr, lbuf, &lbs);
4095 macdefine(&e->e_macro, A_TEMP, mid, lbp);
4101 if (line[2] == '\0') /* not to call syserr() */
4104 mid = macid_parse(&line[2], &delimptr);
4108 lbp = translate_dollars(delimptr, lbuf, &lbs);
4109 expand(lbp, exbuf, sizeof(exbuf), e);
4118 while (*p != '\0' && isascii(*p) && isspace(*p))
4121 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4132 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4133 "Usage: .[DC]macro value(s)\n");
4137 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4138 "Unknown \".\" command %s\n", line);
4143 case '=': /* config-style settings */
4146 case 'S': /* dump rule set */
4147 rs = strtorwset(&line[2], NULL, ST_FIND);
4150 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4151 "Undefined ruleset %s\n", &line[2]);
4154 rw = RewriteRules[rs];
4159 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4164 xputs(smioout, *s++);
4165 (void) sm_io_putc(smioout,
4166 SM_TIME_DEFAULT, ' ');
4168 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4170 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4175 xputs(smioout, *s++);
4176 (void) sm_io_putc(smioout,
4177 SM_TIME_DEFAULT, ' ');
4179 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4181 } while ((rw = rw->r_next) != NULL);
4185 for (i = 0; i < MAXMAILERS; i++)
4187 if (Mailer[i] != NULL)
4188 printmailer(smioout, Mailer[i]);
4193 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4194 "Usage: =Sruleset or =M\n");
4198 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4199 "Unknown \"=\" command %s\n", line);
4204 case '-': /* set command-line-like opts */
4212 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4213 "Usage: -d{debug arguments}\n");
4217 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4218 "Unknown \"-\" command %s\n", line);
4226 mid = macid(&line[2]);
4228 stabapply(dump_class, mid);
4231 mid = macid(&line[1]);
4234 p = macvalue(mid, e);
4236 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4241 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4246 case '/': /* miscellaneous commands */
4247 p = &line[strlen(line)];
4248 while (--p >= line && isascii(*p) && isspace(*p))
4250 p = strpbrk(line, " \t");
4253 while (isascii(*p) && isspace(*p))
4258 if (line[1] == '\0')
4260 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4261 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4264 if (sm_strcasecmp(&line[1], "quit") == 0)
4266 CurEnv->e_id = NULL;
4267 finis(true, true, ExitStat);
4270 if (sm_strcasecmp(&line[1], "mx") == 0)
4273 /* look up MX records */
4276 char *mxhosts[MAXMXHOSTS + 1];
4280 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4281 "Usage: /mx address\n");
4284 nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4286 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4287 "getmxrr(%s) returns %d value(s):\n",
4289 for (i = 0; i < nmx; i++)
4290 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4291 "\t%s\n", mxhosts[i]);
4292 #else /* NAMED_BIND */
4293 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4294 "No MX code compiled in\n");
4295 #endif /* NAMED_BIND */
4297 else if (sm_strcasecmp(&line[1], "canon") == 0)
4299 char host[MAXHOSTNAMELEN];
4303 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4304 "Usage: /canon address\n");
4307 else if (sm_strlcpy(host, p, sizeof(host)) >= sizeof(host))
4309 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4313 (void) getcanonname(host, sizeof(host), !HasWildcardMX,
4315 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4316 "getcanonname(%s) returns %s\n",
4319 else if (sm_strcasecmp(&line[1], "map") == 0)
4321 auto int rcode = EX_OK;
4326 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4327 "Usage: /map mapname key\n");
4330 for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q)); q++)
4334 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4335 "No key specified\n");
4339 map = stab(p, ST_MAP, ST_FIND);
4342 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4343 "Map named \"%s\" not found\n", p);
4346 if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4347 !openmap(&(map->s_map)))
4349 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4350 "Map named \"%s\" not open\n", p);
4353 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4354 "map_lookup: %s (%s) ", p, q);
4357 p = (*map->s_map.map_class->map_lookup)
4358 (&map->s_map, q, av, &rcode);
4360 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4364 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4365 "returns %s (%d)\n", p,
4368 else if (sm_strcasecmp(&line[1], "try") == 0)
4372 auto int rcode = EX_OK;
4374 q = strpbrk(p, " \t");
4377 while (isascii(*q) && isspace(*q))
4380 if (q == NULL || *q == '\0')
4382 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4383 "Usage: /try mailer address\n");
4386 st = stab(p, ST_MAILER, ST_FIND);
4389 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4390 "Unknown mailer %s\n", p);
4394 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4395 "Trying %s %s address %s for mailer %s\n",
4396 bitset(RF_HEADERADDR, tryflags) ? "header"
4398 bitset(RF_SENDERADDR, tryflags) ? "sender"
4399 : "recipient", q, p);
4400 p = remotename(q, m, tryflags, &rcode, CurEnv);
4401 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4402 "Rcode = %d, addr = %s\n",
4403 rcode, p == NULL ? "<NULL>" : p);
4406 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4410 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4411 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4414 for (; *p != '\0'; p++)
4420 tryflags |= RF_HEADERADDR;
4425 tryflags &= ~RF_HEADERADDR;
4430 tryflags |= RF_SENDERADDR;
4435 tryflags &= ~RF_SENDERADDR;
4439 exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4441 exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4443 macdefine(&e->e_macro, A_TEMP,
4444 macid("{addr_type}"), exbuf);
4446 else if (sm_strcasecmp(&line[1], "parse") == 0)
4450 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4451 "Usage: /parse address\n");
4454 q = crackaddr(p, e);
4455 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4456 "Cracked address = ");
4458 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4459 "\nParsing %s %s address\n",
4460 bitset(RF_HEADERADDR, tryflags) ?
4461 "header" : "envelope",
4462 bitset(RF_SENDERADDR, tryflags) ?
4463 "sender" : "recipient");
4464 if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4466 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4468 else if (a.q_host != NULL && a.q_host[0] != '\0')
4469 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4470 "mailer %s, host %s, user %s\n",
4475 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4476 "mailer %s, user %s\n",
4481 else if (sm_strcasecmp(&line[1], "header") == 0)
4485 ul = chompheader(p, CHHDR_CHECK|CHHDR_USER, NULL, e);
4486 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4489 #if NETINET || NETINET6
4490 else if (sm_strcasecmp(&line[1], "gethostbyname") == 0)
4492 int family = AF_INET;
4494 q = strpbrk(p, " \t");
4497 while (isascii(*q) && isspace(*q))
4500 if (*q != '\0' && (strcmp(q, "inet6") == 0 ||
4501 strcmp(q, "AAAA") == 0))
4503 # endif /* NETINET6 */
4505 (void) sm_gethostbyname(p, family);
4507 #endif /* NETINET || NETINET6 */
4510 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4511 "Unknown \"/\" command %s\n",
4514 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4518 for (p = line; isascii(*p) && isspace(*p); p++)
4521 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4525 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4531 eightbit = to8bit(p + 1);
4532 if (invalidaddr(p + 1, NULL, true))
4536 register char **pvp;
4537 char pvpbuf[PSBUFSIZE];
4539 pvp = prescan(++p, ',', pvpbuf, sizeof(pvpbuf), &delimptr,
4540 ConfigLevel >= 9 ? TokTypeNoC : ExtTokenTab, false);
4548 rs = strtorwset(p, NULL, ST_FIND);
4551 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4552 "Undefined ruleset %s\n",
4556 status = REWRITE(pvp, rs, e);
4557 if (status != EX_OK)
4558 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4559 "== Ruleset %s (%d) status %d\n",
4563 cataddr(pvp, NULL, exbuf, sizeof(exbuf), '\0',
4565 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4569 while (*p != '\0' && *p++ != ',')
4572 } while (*(p = delimptr) != '\0');
4573 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4581 if (s->s_symtype != ST_CLASS)
4583 if (bitnset(bitidx(id), s->s_class))
4584 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4589 ** An exception type used to create QuickAbort exceptions.
4590 ** This is my first cut at converting QuickAbort from longjmp to exceptions.
4591 ** These exceptions have a single integer argument, which is the argument
4592 ** to longjmp in the original code (either 1 or 2). I don't know the
4593 ** significance of 1 vs 2: the calls to setjmp don't care.
4596 const SM_EXC_TYPE_T EtypeQuickAbort =