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>
22 SM_UNUSED(static char copyright[]) =
23 "@(#) Copyright (c) 1998-2013 Proofpoint, Inc. and its suppliers.\n\
24 All rights reserved.\n\
25 Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.\n\
26 Copyright (c) 1988, 1993\n\
27 The Regents of the University of California. All rights reserved.\n";
30 SM_RCSID("@(#)$Id: main.c,v 8.988 2013-11-23 02:52:37 gshapiro Exp $")
33 #if NETINET || NETINET6
34 # include <arpa/inet.h>
36 # include "sm_resolve.h"
41 #include <sendmail/pathnames.h>
45 DebugNoPRestart = SM_DEBUG_INITIALIZER("no_persistent_restart",
46 "@(#)$Debug: no_persistent_restart - don't restart, log only $");
48 static void dump_class __P((STAB *, int));
49 static void obsolete __P((char **));
50 static void testmodeline __P((char *, ENVELOPE *));
51 static char *getextenv __P((const char *));
52 static void sm_printoptions __P((char **));
53 static SIGFUNC_DECL intindebug __P((int));
54 static SIGFUNC_DECL sighup __P((int));
55 static SIGFUNC_DECL sigpipe __P((int));
56 static SIGFUNC_DECL sigterm __P((int));
58 static SIGFUNC_DECL sigusr1 __P((int));
62 ** SENDMAIL -- Post mail to a set of destinations.
64 ** This is the basic mail router. All user mail programs should
65 ** call this routine to actually deliver mail. Sendmail in
66 ** turn calls a bunch of mail servers that do the real work of
67 ** delivering the mail.
69 ** Sendmail is driven by settings read in from /etc/mail/sendmail.cf
70 ** (read by readcf.c).
73 ** /usr/lib/sendmail [flags] addr ...
75 ** See the associated documentation for details.
78 ** Eric Allman, UCB/INGRES (until 10/81).
79 ** Britton-Lee, Inc., purveyors of fine
80 ** database computers (11/81 - 10/88).
81 ** International Computer Science Institute
83 ** UCB/Mammoth Project (10/89 - 7/95).
84 ** InReference, Inc. (8/95 - 1/97).
85 ** Sendmail, Inc. (1/98 - 9/13).
86 ** The support of my employers is gratefully acknowledged.
87 ** Few of them (Britton-Lee in particular) have had
88 ** anything to gain from my involvement in this project.
90 ** Gregory Neil Shapiro,
91 ** Worcester Polytechnic Institute (until 3/98).
92 ** Sendmail, Inc. (3/98 - 10/13).
93 ** Proofpoint, Inc. (10/13 - present).
96 ** Sendmail, Inc. (12/98 - 10/13).
97 ** Proofpoint, Inc. (10/13 - present).
100 char *FullName; /* sender's full name */
101 ENVELOPE BlankEnvelope; /* a "blank" envelope */
102 static ENVELOPE MainEnvelope; /* the envelope around the basic letter */
103 ADDRESS NullAddress = /* a null address */
104 { "", "", NULL, "" };
105 char *CommandLineArgs; /* command line args for pid file */
106 bool Warn_Q_option = false; /* warn about Q option use */
107 static int MissingFds = 0; /* bit map of fds missing on startup */
108 char *Mbdb = "pw"; /* mailbox database defaults to /etc/passwd */
111 GIDSET_T InitialGidSet[NGROUPS_MAX];
114 #define MAXCONFIGLEVEL 10 /* highest config version level known */
117 static sasl_callback_t srvcallbacks[] =
119 { SASL_CB_VERIFYFILE, (sasl_callback_ft)&safesaslfile, NULL },
120 { SASL_CB_PROXY_POLICY, (sasl_callback_ft)&proxy_policy, NULL },
121 { SASL_CB_LIST_END, NULL, NULL }
125 unsigned int SubmitMode;
126 int SyslogPrefixLen; /* estimated length of syslog prefix */
127 #define PIDLEN 6 /* pid length for computing SyslogPrefixLen */
129 # define SL_FUDGE 10 /* fudge offset for SyslogPrefixLen */
131 #define SLDLL 8 /* est. length of default syslog label */
134 /* Some options are dangerous to allow users to use in non-submit mode */
135 #define CHECK_AGAINST_OPMODE(cmd) \
138 OpMode != MD_DELIVER && OpMode != MD_SMTP && \
139 OpMode != MD_ARPAFTP && OpMode != MD_CHECKCONFIG && \
140 OpMode != MD_VERIFY && OpMode != MD_TEST) \
142 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
143 "WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \
147 if (extraprivs && queuerun) \
149 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
150 "WARNING: Ignoring submission mode -%c option with -q\n", \
157 main(argc, argv, envp)
164 extern char Version[];
171 int qgrp = NOQGRP; /* queue group to process */
173 BITMAP256 *p_flags = NULL; /* daemon flags */
174 bool warn_C_flag = false;
175 bool auth = true; /* whether to set e_auth_param */
176 char warn_f_flag = '\0';
177 bool run_in_foreground = false; /* -bD mode */
178 bool queuerun = false, debug = false;
181 char *nullserver = NULL;
182 char *authinfo = NULL;
183 char *sysloglabel = NULL; /* label for syslog */
184 char *conffile = NULL; /* name of .cf file */
185 char *queuegroup = NULL; /* queue group to process */
186 char *quarantining = NULL; /* quarantine queue items? */
189 bool queuepersistent = false; /* queue runner process runs forever */
190 bool foregroundqueue = false; /* queue run in foreground */
191 bool save_val; /* to save some bool var. */
192 int cftype; /* which cf file to use? */
194 static time_t starttime = 0; /* when was process started */
195 struct stat traf_st; /* for TrafficLog FIFO check */
197 char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */
198 static char rnamebuf[MAXNAME]; /* holds RealUserName */
199 char *emptyenviron[1];
205 extern int DtableSize;
209 extern char **environ;
211 extern void sm_sasl_init __P((void));
218 /* turn off profiling */
221 /* install default exception handler */
222 sm_exc_newthread(fatal_error);
224 /* set the default in/out channel so errors reported to screen */
226 OutChannel = smioout;
229 ** Check to see if we reentered.
230 ** This would normally happen if e_putheader or e_putbody
231 ** were NULL when invoked.
236 syserr("main: reentered!");
239 starttime = curtime();
241 /* avoid null pointer dereferences */
242 TermEscape.te_rv_on = TermEscape.te_under_on = TermEscape.te_normal = "";
247 /* Check if sendmail is running with extra privs */
248 extraprivs = (RealUid != 0 &&
249 (geteuid() != getuid() || getegid() != getgid()));
251 CurrentPid = getpid();
253 /* get whatever .cf file is right for the opmode */
254 cftype = SM_GET_RIGHT_CF;
256 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
257 DtableSize = getdtsize();
258 if (DtableSize > 256)
262 ** Be sure we have enough file descriptors.
263 ** But also be sure that 0, 1, & 2 are open.
266 /* reset errno and fill_errno; the latter is used way down below */
267 errno = fill_errno = 0;
268 fill_fd(STDIN_FILENO, NULL);
271 fill_fd(STDOUT_FILENO, NULL);
274 fill_fd(STDERR_FILENO, NULL);
278 sm_closefrom(STDERR_FILENO + 1, DtableSize);
284 # define SM_LOG_STR "sendmail"
287 openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
289 openlog(SM_LOG_STR, LOG_PID);
294 ** Seed the random number generator.
295 ** Used for queue file names, picking a queue directory, and
301 /* do machine-dependent initializations */
305 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
307 /* reset status from syserr() calls for missing file descriptors */
311 SubmitMode = SUBMIT_UNKNOWN;
312 #if _FFR_LOCAL_DAEMON
315 V6LoopbackAddrFound = false;
319 checkfd012("after openlog");
322 tTsetup(tTdvect, sizeof(tTdvect), "0-99.1,*_trace_*.1");
325 /* save initial group set for future checks */
326 i = getgroups(NGROUPS_MAX, InitialGidSet);
329 InitialGidSet[0] = (GID_T) -1;
332 while (i < NGROUPS_MAX)
333 InitialGidSet[i++] = InitialGidSet[0];
334 #endif /* NGROUPS_MAX */
336 /* drop group id privileges (RunAsUser not yet set) */
337 dp = drop_privileges(false);
341 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
344 /* arrange to dump state on user-1 signal */
345 (void) sm_signal(SIGUSR1, sigusr1);
349 /* ignore user-1 signal */
350 (void) sm_signal(SIGUSR1, SIG_IGN);
354 /* initialize for setproctitle */
355 initsetproctitle(argc, argv, envp);
357 /* Handle any non-getoptable constructions. */
361 ** Do a quick prescan of the argument list.
365 /* find initial opMode */
368 p = strrchr(*av, '/');
371 if (strcmp(p, "newaliases") == 0)
372 OpMode = MD_INITALIAS;
373 else if (strcmp(p, "mailq") == 0)
375 else if (strcmp(p, "smtpd") == 0)
377 else if (strcmp(p, "hoststat") == 0)
378 OpMode = MD_HOSTSTAT;
379 else if (strcmp(p, "purgestat") == 0)
380 OpMode = MD_PURGESTAT;
382 #if defined(__osf__) || defined(_AIX3)
383 # 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"
384 #endif /* defined(__osf__) || defined(_AIX3) */
385 #if defined(sony_news)
386 # 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:"
387 #endif /* defined(sony_news) */
389 # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
392 /* Set to 0 to allow -b; need to check optarg before using it! */
394 while ((j = getopt(argc, argv, OPTIONS)) != -1)
398 case 'b': /* operations mode */
399 j = (optarg == NULL) ? ' ' : *optarg;
418 #if _FFR_LOCAL_DAEMON
423 #endif /* _FFR_LOCAL_DAEMON */
426 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
427 "Frozen configurations unsupported\n");
431 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
432 "Invalid operation mode %c\n",
442 syserr("-D file must be before -d");
446 dp = drop_privileges(true);
448 smdebug = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
449 optarg, SM_IO_APPEND, NULL);
452 syserr("cannot open %s", optarg);
453 ExitStat = EX_CANTCREAT;
456 sm_debug_setfile(smdebug);
462 (void) sm_io_setvbuf(sm_debug_file(), SM_TIME_DEFAULT,
463 (char *) NULL, SM_IO_NBF,
467 case 'G': /* relay (gateway) submission */
468 SubmitMode = SUBMIT_MTA;
474 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
475 "option requires an argument -- '%c'",
479 j = SM_MIN(strlen(optarg), 32) + 1;
480 sysloglabel = xalloc(j);
481 (void) sm_strlcpy(sysloglabel, optarg, j);
482 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
488 /* just check if it is there */
495 /* Don't leak queue information via debug flags */
496 if (extraprivs && queuerun && debug)
498 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
499 "WARNING: Can not use -d with -q. Disabling debugging.\n");
501 sm_debug_setfile(NULL);
502 (void) memset(tTdvect, '\0', sizeof(tTdvect));
506 if (sysloglabel != NULL)
508 /* Sanitize the string */
509 for (p = sysloglabel; *p != '\0'; p++)
511 if (!isascii(*p) || !isprint(*p) || *p == '%')
516 openlog(sysloglabel, LOG_PID, LOG_MAIL);
518 openlog(sysloglabel, LOG_PID);
523 /* set up the blank envelope */
524 BlankEnvelope.e_puthdr = putheader;
525 BlankEnvelope.e_putbody = putbody;
526 BlankEnvelope.e_xfp = NULL;
527 STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
528 CurEnv = &BlankEnvelope;
529 STRUCTCOPY(NullAddress, MainEnvelope.e_from);
532 ** Set default values for variables.
533 ** These cannot be in initialized data space.
536 setdefaults(&BlankEnvelope);
537 initmacros(&BlankEnvelope);
541 if (OpMode == MD_DAEMON)
542 DaemonPid = CurrentPid; /* needed for finis() to work */
544 pw = sm_getpwuid(RealUid);
546 (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof(rnamebuf));
548 (void) sm_snprintf(rnamebuf, sizeof(rnamebuf), "Unknown UID %d",
551 RealUserName = rnamebuf;
555 sm_dprintf("Version %s\n", Version);
556 finis(false, true, EX_OK);
561 ** if running non-set-user-ID binary as non-root, pretend
562 ** we are the RunAsUid
565 if (RealUid != 0 && geteuid() == RealUid)
568 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
572 else if (geteuid() != 0)
573 RunAsUid = geteuid();
576 if (RealUid != 0 && EffGid == RealGid)
581 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
582 (int) geteuid(), (int) getuid(),
583 (int) getegid(), (int) getgid());
584 sm_dprintf("main: RunAsUser = %d:%d\n",
585 (int) RunAsUid, (int) RunAsGid);
588 /* save command line arguments */
590 for (av = argv; *av != NULL; )
591 j += strlen(*av++) + 1;
592 SaveArgv = (char **) xalloc(sizeof(char *) * (argc + 1));
593 CommandLineArgs = xalloc(j);
595 for (av = argv, i = 0; *av != NULL; )
599 SaveArgv[i++] = newstr(*av);
602 (void) sm_strlcpy(p, *av++, j);
611 extern char *CompileOptions[];
613 sm_dprintf("Version %s\n Compiled with:", Version);
614 sm_printoptions(CompileOptions);
618 extern char *OsCompileOptions[];
620 sm_dprintf(" OS Defines:");
621 sm_printoptions(OsCompileOptions);
623 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
626 sm_dprintf(" Conf file:\t%s (default for MSP)\n",
627 getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
629 sm_dprintf(" Conf file:\t%s (default for MTA)\n",
630 getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
632 sm_dprintf(" Pid file:\t%s (default)\n", PidFile);
637 extern char *SmCompileOptions[];
639 sm_dprintf(" libsm Defines:");
640 sm_printoptions(SmCompileOptions);
645 extern char *FFRCompileOptions[];
647 sm_dprintf(" FFR Defines:");
648 sm_printoptions(FFRCompileOptions);
654 /* exit(EX_CONFIG) if different? */
655 sm_dprintf(" OpenSSL: compiled 0x%08x\n",
656 (uint) OPENSSL_VERSION_NUMBER);
657 sm_dprintf(" OpenSSL: linked 0x%08x\n",
658 (uint) TLS_version_num());
660 #endif /* STARTTLS */
662 /* clear sendmail's environment */
663 ExternalEnviron = environ;
664 emptyenviron[0] = NULL;
665 environ = emptyenviron;
668 ** restore any original TZ setting until TimeZoneSpec has been
669 ** determined - or early log messages may get bogus time stamps
672 if ((p = getextenv("TZ")) != NULL)
677 /* XXX check for reasonable length? */
678 tzlen = strlen(p) + 4;
680 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
682 /* XXX check return code? */
686 /* prime the child environment */
687 sm_setuserenv("AGENT", "sendmail");
689 (void) sm_signal(SIGPIPE, SIG_IGN);
690 OldUmask = umask(022);
691 FullName = getextenv("NAME");
692 if (FullName != NULL)
693 FullName = newstr(FullName);
696 ** Initialize name server if it is going to be used.
700 if (!bitset(RES_INIT, _res.options))
703 _res.options |= RES_DEBUG;
705 _res.options &= ~RES_DEBUG;
706 # ifdef RES_NOALIASES
707 _res.options |= RES_NOALIASES;
709 TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
710 TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
711 TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
712 TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
713 TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
714 TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
715 #endif /* NAMED_BIND */
720 /* initialize some macros, etc. */
721 init_vendor_macros(&BlankEnvelope);
724 macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
727 hp = myhostname(jbuf, sizeof(jbuf));
730 struct utsname utsname;
733 sm_dprintf("Canonical name: %s\n", jbuf);
734 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
735 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
738 p = strchr(jbuf, '.');
739 if (p != NULL && p[1] != '\0')
740 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm', &p[1]);
742 if (uname(&utsname) >= 0)
743 p = utsname.nodename;
747 sm_dprintf("uname failed (%s)\n",
748 sm_errstring(errno));
753 sm_dprintf(" UUCP nodename: %s\n", p);
754 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
760 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
763 sm_dprintf("\ta.k.a.: %s\n", *av);
766 #if NETINET || NETINET6
767 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
771 char buf6[INET6_ADDRSTRLEN];
773 # endif /* NETINET6 */
780 switch (hp->h_addrtype)
784 if (hp->h_length != INADDRSZ)
787 memmove(&ia, hp->h_addr_list[i], INADDRSZ);
788 (void) sm_snprintf(ipbuf, sizeof(ipbuf),
789 "[%.100s]", inet_ntoa(ia));
791 # endif /* NETINET */
795 if (hp->h_length != IN6ADDRSZ)
798 memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
799 addr = anynet_ntop(&ia6, buf6, sizeof(buf6));
801 (void) sm_snprintf(ipbuf, sizeof(ipbuf),
804 # endif /* NETINET6 */
806 if (ipbuf[0] == '\0')
810 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
811 setclass('w', ipbuf);
813 #endif /* NETINET || NETINET6 */
821 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
823 /* current load average */
826 QueueLimitRecipient = (QUEUE_CHAR *) NULL;
827 QueueLimitSender = (QUEUE_CHAR *) NULL;
828 QueueLimitId = (QUEUE_CHAR *) NULL;
829 QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
836 while ((j = getopt(argc, argv, OPTIONS)) != -1)
840 case 'b': /* operations mode */
844 case 'A': /* use Alternate sendmail/submit.cf */
845 cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
846 : SM_GET_SENDMAIL_CF;
849 case 'B': /* body type */
850 CHECK_AGAINST_OPMODE(j);
851 BlankEnvelope.e_bodytype = newstr(optarg);
854 case 'C': /* select configuration file (already done) */
857 conffile = newstr(optarg);
858 dp = drop_privileges(true);
864 case 'd': /* debugging */
868 case 'f': /* from address */
869 case 'r': /* obsolete -f flag */
870 CHECK_AGAINST_OPMODE(j);
873 usrerr("More than one \"from\" person");
877 if (optarg[0] == '\0')
880 from = newstr(denlstring(optarg, true, true));
881 if (strcmp(RealUserName, from) != 0)
885 case 'F': /* set full name */
886 CHECK_AGAINST_OPMODE(j);
887 FullName = newstr(optarg);
890 case 'G': /* relay (gateway) submission */
892 CHECK_AGAINST_OPMODE(j);
895 case 'h': /* hop count */
896 CHECK_AGAINST_OPMODE(j);
897 BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
899 (void) sm_snprintf(buf, sizeof(buf), "%d",
900 BlankEnvelope.e_hopcount);
901 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
905 usrerr("Bad hop count (%s)", optarg);
910 case 'L': /* program label */
914 case 'n': /* don't alias */
915 CHECK_AGAINST_OPMODE(j);
919 case 'N': /* delivery status notifications */
920 CHECK_AGAINST_OPMODE(j);
921 DefaultNotify |= QHASNOTIFY;
922 macdefine(&BlankEnvelope.e_macro, A_TEMP,
923 macid("{dsn_notify}"), optarg);
924 if (sm_strcasecmp(optarg, "never") == 0)
926 for (p = optarg; p != NULL; optarg = p)
931 if (sm_strcasecmp(optarg, "success") == 0)
932 DefaultNotify |= QPINGONSUCCESS;
933 else if (sm_strcasecmp(optarg, "failure") == 0)
934 DefaultNotify |= QPINGONFAILURE;
935 else if (sm_strcasecmp(optarg, "delay") == 0)
936 DefaultNotify |= QPINGONDELAY;
939 usrerr("Invalid -N argument");
945 case 'o': /* set option */
946 setoption(*optarg, optarg + 1, false, true,
950 case 'O': /* set option (long form) */
951 setoption(' ', optarg, false, true, &BlankEnvelope);
954 case 'p': /* set protocol */
955 CHECK_AGAINST_OPMODE(j);
956 p = strchr(optarg, ':');
964 cleanstrcpy(ep, p, i);
965 macdefine(&BlankEnvelope.e_macro,
971 i = strlen(optarg) + 1;
973 cleanstrcpy(ep, optarg, i);
974 macdefine(&BlankEnvelope.e_macro, A_HEAP,
979 case 'Q': /* change quarantining on queued items */
981 if (OpMode != MD_DELIVER &&
982 OpMode != MD_QUEUERUN)
984 usrerr("Can not use -Q with -b%c", OpMode);
989 if (OpMode == MD_DELIVER)
990 set_op_mode(MD_QUEUERUN);
994 quarantining = newstr(optarg);
997 case 'q': /* run queue files at intervals */
999 if (OpMode != MD_DELIVER &&
1000 OpMode != MD_DAEMON &&
1001 OpMode != MD_FGDAEMON &&
1002 OpMode != MD_PRINT &&
1003 OpMode != MD_PRINTNQE &&
1004 OpMode != MD_QUEUERUN)
1006 usrerr("Can not use -q with -b%c", OpMode);
1007 ExitStat = EX_USAGE;
1011 /* don't override -bd, -bD or -bp */
1012 if (OpMode == MD_DELIVER)
1013 set_op_mode(MD_QUEUERUN);
1016 negate = optarg[0] == '!';
1019 /* negate meaning of pattern match */
1020 optarg++; /* skip '!' for next switch */
1025 case 'G': /* Limit by queue group name */
1028 usrerr("Can not use -q!G");
1029 ExitStat = EX_USAGE;
1032 if (queuegroup != NULL)
1034 usrerr("Can not use multiple -qG options");
1035 ExitStat = EX_USAGE;
1038 queuegroup = newstr(&optarg[1]);
1041 case 'I': /* Limit by ID */
1042 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1043 new->queue_match = newstr(&optarg[1]);
1044 new->queue_negate = negate;
1045 new->queue_next = QueueLimitId;
1049 case 'R': /* Limit by recipient */
1050 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1051 new->queue_match = newstr(&optarg[1]);
1052 new->queue_negate = negate;
1053 new->queue_next = QueueLimitRecipient;
1054 QueueLimitRecipient = new;
1057 case 'S': /* Limit by sender */
1058 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1059 new->queue_match = newstr(&optarg[1]);
1060 new->queue_negate = negate;
1061 new->queue_next = QueueLimitSender;
1062 QueueLimitSender = new;
1065 case 'f': /* foreground queue run */
1066 foregroundqueue = true;
1069 case 'Q': /* Limit by quarantine message */
1070 if (optarg[1] != '\0')
1072 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1073 new->queue_match = newstr(&optarg[1]);
1074 new->queue_negate = negate;
1075 new->queue_next = QueueLimitQuarantine;
1076 QueueLimitQuarantine = new;
1078 QueueMode = QM_QUARANTINE;
1081 case 'L': /* act on lost items */
1082 QueueMode = QM_LOST;
1085 case 'p': /* Persistent queue */
1086 queuepersistent = true;
1087 if (QueueIntvl == 0)
1089 if (optarg[1] == '\0')
1096 QueueIntvl = convtime(optarg, 'm');
1099 usrerr("Invalid -q value");
1100 ExitStat = EX_USAGE;
1103 /* check for bad conversion */
1105 ExitStat = EX_USAGE;
1110 case 'R': /* DSN RET: what to return */
1111 CHECK_AGAINST_OPMODE(j);
1112 if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1114 usrerr("Duplicate -R flag");
1115 ExitStat = EX_USAGE;
1118 BlankEnvelope.e_flags |= EF_RET_PARAM;
1119 if (sm_strcasecmp(optarg, "hdrs") == 0)
1120 BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1121 else if (sm_strcasecmp(optarg, "full") != 0)
1123 usrerr("Invalid -R value");
1124 ExitStat = EX_USAGE;
1126 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1127 macid("{dsn_ret}"), optarg);
1130 case 't': /* read recipients from message */
1131 CHECK_AGAINST_OPMODE(j);
1135 case 'V': /* DSN ENVID: set "original" envelope id */
1136 CHECK_AGAINST_OPMODE(j);
1137 if (!xtextok(optarg))
1139 usrerr("Invalid syntax in -V flag");
1140 ExitStat = EX_USAGE;
1144 BlankEnvelope.e_envid = newstr(optarg);
1145 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1146 macid("{dsn_envid}"), optarg);
1150 case 'X': /* traffic log file */
1151 dp = drop_privileges(true);
1153 if (stat(optarg, &traf_st) == 0 &&
1154 S_ISFIFO(traf_st.st_mode))
1155 TrafficLogFile = sm_io_open(SmFtStdio,
1158 SM_IO_WRONLY, NULL);
1160 TrafficLogFile = sm_io_open(SmFtStdio,
1163 SM_IO_APPEND, NULL);
1164 if (TrafficLogFile == NULL)
1166 syserr("cannot open %s", optarg);
1167 ExitStat = EX_CANTCREAT;
1170 (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1171 NULL, SM_IO_LBF, 0);
1174 /* compatibility flags */
1175 case 'c': /* connect to non-local mailers */
1176 case 'i': /* don't let dot stop me */
1177 case 'm': /* send to me too */
1178 case 'T': /* set timeout interval */
1179 case 'v': /* give blow-by-blow description */
1180 setoption(j, "T", false, true, &BlankEnvelope);
1183 case 'e': /* error message disposition */
1184 case 'M': /* define macro */
1185 setoption(j, optarg, false, true, &BlankEnvelope);
1188 case 's': /* save From lines in headers */
1189 setoption('f', "T", false, true, &BlankEnvelope);
1193 case 'I': /* initialize alias DBM file */
1194 set_op_mode(MD_INITALIAS);
1198 #if defined(__osf__) || defined(_AIX3)
1199 case 'x': /* random flag that OSF/1 & AIX mailx passes */
1202 #if defined(sony_news)
1204 case 'J': /* ignore flags for Japanese code conversion
1205 implemented on Sony NEWS */
1207 #endif /* defined(sony_news) */
1210 finis(true, true, EX_USAGE);
1216 /* if we've had errors so far, exit now */
1217 if ((ExitStat != EX_OK && OpMode != MD_TEST && OpMode != MD_CHECKCONFIG) ||
1218 ExitStat == EX_OSERR)
1220 finis(false, true, ExitStat);
1224 if (bitset(SUBMIT_MTA, SubmitMode))
1226 /* If set daemon_flags on command line, don't reset it */
1227 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1228 macdefine(&BlankEnvelope.e_macro, A_PERM,
1229 macid("{daemon_flags}"), "CC f");
1231 else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1233 SubmitMode = SUBMIT_MSA;
1235 /* If set daemon_flags on command line, don't reset it */
1236 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1237 macdefine(&BlankEnvelope.e_macro, A_PERM,
1238 macid("{daemon_flags}"), "c u");
1242 ** Do basic initialization.
1243 ** Read system control file.
1244 ** Extract special fields for local use.
1248 checkfd012("before readcf");
1250 vendor_pre_defaults(&BlankEnvelope);
1252 readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1253 safecf, &BlankEnvelope);
1254 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1255 ConfigFileRead = true;
1257 vendor_post_defaults(&BlankEnvelope);
1259 /* now we can complain about missing fds */
1260 if (MissingFds != 0 && LogLevel > 8)
1265 if (bitset(1 << STDIN_FILENO, MissingFds))
1266 (void) sm_strlcat(mbuf, ", stdin", sizeof(mbuf));
1267 if (bitset(1 << STDOUT_FILENO, MissingFds))
1268 (void) sm_strlcat(mbuf, ", stdout", sizeof(mbuf));
1269 if (bitset(1 << STDERR_FILENO, MissingFds))
1270 (void) sm_strlcat(mbuf, ", stderr", sizeof(mbuf));
1272 /* Notice: fill_errno is from high above: fill_fd() */
1273 sm_syslog(LOG_WARNING, NOQID,
1274 "File descriptors missing on startup: %s; %s",
1275 &mbuf[2], sm_errstring(fill_errno));
1278 /* Remove the ability for a normal user to send signals */
1279 if (RealUid != 0 && RealUid != geteuid())
1281 uid_t new_uid = geteuid();
1285 ** Since we can differentiate between uid and euid,
1286 ** make the uid a different user so the real user
1287 ** can't send signals. However, it doesn't need to be
1288 ** root (euid has root).
1294 sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1295 if (setreuid(new_uid, geteuid()) < 0)
1297 syserr("main: setreuid(%d, %d) failed",
1298 (int) new_uid, (int) geteuid());
1299 finis(false, true, EX_OSERR);
1303 sm_dprintf("Now running as e/ruid %d:%d\n",
1304 (int) geteuid(), (int) getuid());
1305 #else /* HASSETREUID */
1307 ** Have to change both effective and real so need to
1308 ** change them both to effective to keep privs.
1312 sm_dprintf("Changing uid to %d\n", (int) new_uid);
1313 if (setuid(new_uid) < 0)
1315 syserr("main: setuid(%d) failed", (int) new_uid);
1316 finis(false, true, EX_OSERR);
1320 sm_dprintf("Now running as e/ruid %d:%d\n",
1321 (int) geteuid(), (int) getuid());
1322 #endif /* HASSETREUID */
1326 if (FallbackMX != NULL)
1327 (void) getfallbackmxrr(FallbackMX);
1330 if (SuperSafe == SAFE_INTERACTIVE && !SM_IS_INTERACTIVE(CurEnv->e_sendmode))
1332 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1333 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1336 if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1338 usrerr("Mail submission program cannot be used as daemon");
1339 finis(false, true, EX_USAGE);
1342 if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1343 OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1344 OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1347 /* set up the basic signal handlers */
1348 if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1349 (void) sm_signal(SIGINT, intsig);
1350 (void) sm_signal(SIGTERM, intsig);
1352 /* Enforce use of local time (null string overrides this) */
1353 if (TimeZoneSpec == NULL)
1355 else if (TimeZoneSpec[0] != '\0')
1356 sm_setuserenv("TZ", TimeZoneSpec);
1358 sm_setuserenv("TZ", NULL);
1361 /* initialize mailbox database */
1362 i = sm_mbdb_initialize(Mbdb);
1365 usrerr("Can't initialize mailbox database \"%s\": %s",
1366 Mbdb, sm_strexit(i));
1370 /* avoid denial-of-service attacks */
1373 if (OpMode == MD_TEST)
1375 /* can't be done after readcf if RunAs* is used */
1376 dp = drop_privileges(true);
1379 finis(false, true, dp);
1383 else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1385 /* drop privileges -- daemon mode done after socket/bind */
1386 dp = drop_privileges(false);
1388 if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1390 usrerr("Mail submission program must have RunAsUser set to non root user");
1391 finis(false, true, EX_CONFIG);
1397 _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1398 _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1402 ** Find our real host name for future logging.
1405 authinfo = getauthinfo(STDIN_FILENO, &forged);
1406 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1408 /* suppress error printing if errors mailed back or whatever */
1409 if (BlankEnvelope.e_errormode != EM_PRINT)
1412 /* set up the $=m class now, after .cf has a chance to redefine $m */
1413 expand("\201m", jbuf, sizeof(jbuf), &BlankEnvelope);
1414 if (jbuf[0] != '\0')
1415 setclass('m', jbuf);
1417 /* probe interfaces and locate any additional names */
1418 if (DontProbeInterfaces != DPI_PROBENONE)
1423 char pidpath[MAXPATHLEN];
1425 /* Now we know which .cf file we use */
1426 sm_dprintf(" Conf file:\t%s (selected)\n",
1427 getcfname(OpMode, SubmitMode, cftype, conffile));
1428 expand(PidFile, pidpath, sizeof(pidpath), &BlankEnvelope);
1429 sm_dprintf(" Pid file:\t%s (selected)\n", pidpath);
1434 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1435 sm_dprintf("\n (short domain name) $w = ");
1436 xputs(sm_debug_file(), macvalue('w', &BlankEnvelope));
1437 sm_dprintf("\n (canonical domain name) $j = ");
1438 xputs(sm_debug_file(), macvalue('j', &BlankEnvelope));
1439 sm_dprintf("\n (subdomain name) $m = ");
1440 xputs(sm_debug_file(), macvalue('m', &BlankEnvelope));
1441 sm_dprintf("\n (node name) $k = ");
1442 xputs(sm_debug_file(), macvalue('k', &BlankEnvelope));
1443 sm_dprintf("\n========================================================\n\n");
1447 ** Do more command line checking -- these are things that
1448 ** have to modify the results of reading the config file.
1451 /* process authorization warnings from command line */
1453 auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1454 RealUserName, conffile);
1455 if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1456 auth_warning(&BlankEnvelope, "Processed from queue %s",
1458 if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1459 RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1460 sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1463 /* check body type for legality */
1464 i = check_bodytype(BlankEnvelope.e_bodytype);
1465 if (i == BODYTYPE_ILLEGAL)
1467 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1468 BlankEnvelope.e_bodytype = NULL;
1470 else if (i != BODYTYPE_NONE)
1471 SevenBitInput = (i == BODYTYPE_7BIT);
1473 /* tweak default DSN notifications */
1474 if (DefaultNotify == 0)
1475 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1477 /* check for sane configuration level */
1478 if (ConfigLevel > MAXCONFIGLEVEL)
1480 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1481 ConfigLevel, Version, MAXCONFIGLEVEL);
1484 /* need MCI cache to have persistence */
1485 if (HostStatDir != NULL && MaxMciCache == 0)
1488 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1489 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1492 /* need HostStatusDir in order to have SingleThreadDelivery */
1493 if (SingleThreadDelivery && HostStatDir == NULL)
1495 SingleThreadDelivery = false;
1496 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1497 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1501 j = sm_memstat_open();
1502 if (j < 0 && (RefuseLowMem > 0 || QueueLowMem > 0) && LogLevel > 4)
1504 sm_syslog(LOG_WARNING, NOQID,
1505 "cannot get memory statistics, settings ignored, error=%d"
1508 #endif /* _FFR_MEMSTAT */
1510 /* check for permissions */
1512 RealUid != TrustedUid)
1514 char *action = NULL;
1519 if (quarantining != NULL)
1520 action = "quarantine jobs";
1523 /* Normal users can do a single queue run */
1524 if (QueueIntvl == 0)
1528 /* but not persistent queue runners */
1530 action = "start a queue runner daemon";
1535 action = "purge host status";
1541 action = "run daemon";
1544 sm_dprintf("Deny user %d attempt to %s\n",
1545 (int) RealUid, action);
1548 sm_syslog(LOG_ALERT, NOQID,
1549 "user %d attempted to %s",
1550 (int) RealUid, action);
1552 usrerr("Permission denied (real uid not trusted)");
1553 finis(false, true, EX_USAGE);
1558 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1561 ** If -bv and RestrictExpand,
1562 ** drop privs to prevent normal
1563 ** users from reading private
1564 ** aliases/forwards/:include:s
1568 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1571 dp = drop_privileges(true);
1573 /* Fake address safety */
1575 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1576 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1581 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1583 CurEnv->e_id = NULL;
1584 finis(true, true, dp);
1591 case MD_CHECKCONFIG:
1596 /* Nothing special to check */
1600 if (!wordinclass(RealUserName, 't'))
1603 sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1606 sm_syslog(LOG_ALERT, NOQID,
1607 "user %d attempted to rebuild the alias map",
1610 usrerr("Permission denied (real uid not trusted)");
1611 finis(false, true, EX_USAGE);
1617 usrerr("User %d cannot rebuild aliases in mail submission program",
1619 finis(false, true, EX_USAGE);
1625 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1629 ** If -v and RestrictExpand, reset
1630 ** Verbose to prevent normal users
1631 ** from seeing the expansion of
1632 ** aliases/forwards/:include:s
1636 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1645 BlankEnvelope.e_flags |= EF_METOO;
1650 /* don't have persistent host status in test mode */
1654 case MD_CHECKCONFIG:
1657 BlankEnvelope.e_errormode = EM_PRINT;
1662 BlankEnvelope.e_errormode = EM_PRINT;
1664 /* arrange to exit cleanly on hangup signal */
1665 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1666 (void) sm_signal(SIGHUP, intsig);
1668 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1669 "Notice: -bv may give misleading output for non-privileged user\n");
1673 run_in_foreground = true;
1674 set_op_mode(MD_DAEMON);
1678 vendor_daemon_setup(&BlankEnvelope);
1680 /* remove things that don't make sense in daemon mode */
1684 /* arrange to restart on hangup signal */
1685 if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1686 sm_syslog(LOG_WARNING, NOQID,
1687 "daemon invoked without full pathname; kill -1 won't work");
1692 BlankEnvelope.e_errormode = EM_PRINT;
1697 /* arrange to exit cleanly on hangup signal */
1698 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1699 (void) sm_signal(SIGHUP, intsig);
1703 /* special considerations for FullName */
1704 if (FullName != NULL)
1708 /* full names can't have newlines */
1709 if (strchr(FullName, '\n') != NULL)
1711 full = newstr(denlstring(FullName, true, true));
1715 /* check for characters that may have to be quoted */
1716 if (!rfc822_string(FullName))
1719 ** Quote a full name with special characters
1720 ** as a comment so crackaddr() doesn't destroy
1721 ** the name portion of the address.
1724 FullName = addquotes(FullName, NULL);
1726 sm_free(full); /* XXX */
1730 /* do heuristic mode adjustment */
1733 /* turn off noconnect option */
1734 setoption('c', "F", true, false, &BlankEnvelope);
1736 /* turn on interactive delivery */
1737 setoption('d', "", true, false, &BlankEnvelope);
1741 /* check for vendor mismatch */
1742 if (VendorCode != VENDOR_CODE)
1744 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1745 getvendor(VENDOR_CODE), getvendor(VendorCode));
1747 #endif /* VENDOR_CODE */
1749 /* check for out of date configuration level */
1750 if (ConfigLevel < MAXCONFIGLEVEL)
1752 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1753 Version, MAXCONFIGLEVEL, ConfigLevel);
1756 if (ConfigLevel < 3)
1759 /* set options that were previous macros */
1760 if (SmtpGreeting == NULL)
1762 if (ConfigLevel < 7 &&
1763 (p = macvalue('e', &BlankEnvelope)) != NULL)
1764 SmtpGreeting = newstr(p);
1766 SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1768 if (UnixFromLine == NULL)
1770 if (ConfigLevel < 7 &&
1771 (p = macvalue('l', &BlankEnvelope)) != NULL)
1772 UnixFromLine = newstr(p);
1774 UnixFromLine = "From \201g \201d";
1776 SmtpError[0] = '\0';
1778 /* our name for SMTP codes */
1779 expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope);
1780 if (jbuf[0] == '\0')
1781 PSTRSET(MyHostName, "localhost");
1783 PSTRSET(MyHostName, jbuf);
1784 if (strchr(MyHostName, '.') == NULL)
1785 message("WARNING: local host name (%s) is not qualified; see cf/README: WHO AM I?",
1788 /* make certain that this name is part of the $=w class */
1789 setclass('w', MyHostName);
1791 /* fill in the structure of the *default* queue */
1792 st = stab("mqueue", ST_QUEUE, ST_FIND);
1794 syserr("No default queue (mqueue) defined");
1796 set_def_queueval(st->s_quegrp, true);
1798 /* the indices of built-in mailers */
1799 st = stab("local", ST_MAILER, ST_FIND);
1801 LocalMailer = st->s_mailer;
1802 else if (OpMode != MD_TEST || !warn_C_flag)
1803 syserr("No local mailer defined");
1805 st = stab("prog", ST_MAILER, ST_FIND);
1807 syserr("No prog mailer defined");
1810 ProgMailer = st->s_mailer;
1811 clrbitn(M_MUSER, ProgMailer->m_flags);
1814 st = stab("*file*", ST_MAILER, ST_FIND);
1816 syserr("No *file* mailer defined");
1819 FileMailer = st->s_mailer;
1820 clrbitn(M_MUSER, FileMailer->m_flags);
1823 st = stab("*include*", ST_MAILER, ST_FIND);
1825 syserr("No *include* mailer defined");
1827 InclMailer = st->s_mailer;
1829 if (ConfigLevel < 6)
1831 /* heuristic tweaking of local mailer for back compat */
1832 if (LocalMailer != NULL)
1834 setbitn(M_ALIASABLE, LocalMailer->m_flags);
1835 setbitn(M_HASPWENT, LocalMailer->m_flags);
1836 setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1837 setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1838 setbitn(M_CHECKPROG, LocalMailer->m_flags);
1839 setbitn(M_CHECKFILE, LocalMailer->m_flags);
1840 setbitn(M_CHECKUDB, LocalMailer->m_flags);
1842 if (ProgMailer != NULL)
1843 setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1844 if (FileMailer != NULL)
1845 setbitn(M_RUNASRCPT, FileMailer->m_flags);
1847 if (ConfigLevel < 7)
1849 if (LocalMailer != NULL)
1850 setbitn(M_VRFY250, LocalMailer->m_flags);
1851 if (ProgMailer != NULL)
1852 setbitn(M_VRFY250, ProgMailer->m_flags);
1853 if (FileMailer != NULL)
1854 setbitn(M_VRFY250, FileMailer->m_flags);
1857 /* MIME Content-Types that cannot be transfer encoded */
1858 setclass('n', "multipart/signed");
1860 /* MIME message/xxx subtypes that can be treated as messages */
1861 setclass('s', "rfc822");
1863 setclass('s', "global");
1866 /* MIME Content-Transfer-Encodings that can be encoded */
1867 setclass('e', "7bit");
1868 setclass('e', "8bit");
1869 setclass('e', "binary");
1872 /* MIME Content-Types that should be treated as binary */
1873 setclass('b', "image");
1874 setclass('b', "audio");
1875 setclass('b', "video");
1876 setclass('b', "application/octet-stream");
1877 #endif /* USE_B_CLASS */
1879 /* MIME headers which have fields to check for overflow */
1880 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1881 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1883 /* MIME headers to check for length overflow */
1884 setclass(macid("{checkMIMETextHeaders}"), "content-description");
1886 /* MIME headers to check for overflow and rebalance */
1887 setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1888 setclass(macid("{checkMIMEHeaders}"), "content-id");
1889 setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1890 setclass(macid("{checkMIMEHeaders}"), "content-type");
1891 setclass(macid("{checkMIMEHeaders}"), "mime-version");
1893 /* Macros to save in the queue file -- don't remove any */
1894 setclass(macid("{persistentMacros}"), "r");
1895 setclass(macid("{persistentMacros}"), "s");
1896 setclass(macid("{persistentMacros}"), "_");
1897 setclass(macid("{persistentMacros}"), "{if_addr}");
1898 setclass(macid("{persistentMacros}"), "{daemon_flags}");
1900 /* operate in queue directory */
1901 if (QueueDir == NULL || *QueueDir == '\0')
1903 if (OpMode != MD_TEST)
1905 syserr("QueueDirectory (Q) option must be set");
1906 ExitStat = EX_CONFIG;
1911 if (OpMode != MD_TEST)
1912 setup_queues(OpMode == MD_DAEMON);
1915 /* check host status directory for validity */
1916 if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1918 /* cannot use this value */
1919 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1920 "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1921 HostStatDir, sm_errstring(errno));
1925 if (OpMode == MD_QUEUERUN &&
1926 RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1930 /* check to see if we own the queue directory */
1931 if (stat(".", &stbuf) < 0)
1932 syserr("main: cannot stat %s", QueueDir);
1933 if (stbuf.st_uid != RealUid)
1935 /* nope, really a botch */
1937 usrerr("You do not have permission to process the queue");
1938 finis(false, true, EX_NOPERM);
1944 /* sanity checks on milter filters */
1945 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1947 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1948 setup_daemon_milters();
1952 /* Convert queuegroup string to qgrp number */
1953 if (queuegroup != NULL)
1955 qgrp = name2qid(queuegroup);
1959 usrerr("Queue group %s unknown", queuegroup);
1960 finis(false, true, ExitStat);
1965 /* if checking config or have had errors so far, exit now */
1966 if (OpMode == MD_CHECKCONFIG || (ExitStat != EX_OK && OpMode != MD_TEST))
1968 finis(false, true, ExitStat);
1973 /* sendmail specific SASL initialization */
1978 checkfd012("before main() initmaps");
1982 ** Do operation-mode-dependent initialization.
1988 /* print the queue */
1990 (void) dropenvelope(&BlankEnvelope, true, false);
1991 (void) sm_signal(SIGPIPE, sigpipe);
1994 /* Selecting a particular queue group to run */
1995 for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1999 (void) print_single_queue(qgrp, j);
2001 finis(false, true, EX_OK);
2005 finis(false, true, EX_OK);
2010 /* print number of entries in queue */
2011 (void) dropenvelope(&BlankEnvelope, true, false);
2012 (void) sm_signal(SIGPIPE, sigpipe);
2013 printnqe(smioout, NULL);
2014 finis(false, true, EX_OK);
2019 /* only handle quarantining here */
2020 if (quarantining == NULL)
2023 if (QueueMode != QM_QUARANTINE &&
2024 QueueMode != QM_NORMAL)
2027 usrerr("Can not use -Q with -q%c", QueueMode);
2028 ExitStat = EX_USAGE;
2029 finis(false, true, ExitStat);
2032 quarantine_queue(quarantining, qgrp);
2033 finis(false, true, EX_OK);
2037 (void) sm_signal(SIGPIPE, sigpipe);
2038 (void) mci_traverse_persistent(mci_print_persistent, NULL);
2039 finis(false, true, EX_OK);
2044 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2045 finis(false, true, EX_OK);
2050 /* initialize maps */
2052 finis(false, true, ExitStat);
2058 /* reset DSN parameters */
2059 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2060 macdefine(&BlankEnvelope.e_macro, A_PERM,
2061 macid("{dsn_notify}"), NULL);
2062 BlankEnvelope.e_envid = NULL;
2063 macdefine(&BlankEnvelope.e_macro, A_PERM,
2064 macid("{dsn_envid}"), NULL);
2065 BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2066 macdefine(&BlankEnvelope.e_macro, A_PERM,
2067 macid("{dsn_ret}"), NULL);
2069 /* don't open maps for daemon -- done below in child */
2075 /* print configuration table (or at least part of it) */
2078 for (i = 0; i < MAXMAILERS; i++)
2080 if (Mailer[i] != NULL)
2081 printmailer(sm_debug_file(), Mailer[i]);
2086 ** Switch to the main envelope.
2089 CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2090 sm_rpool_new_x(NULL));
2091 MainEnvelope.e_flags = BlankEnvelope.e_flags;
2094 ** If test mode, read addresses from stdin and process.
2097 if (OpMode == MD_TEST)
2099 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2104 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2105 "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2106 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2107 "Enter <ruleset> <address>\n");
2109 macdefine(&(MainEnvelope.e_macro), A_PERM,
2110 macid("{addr_type}"), "e r");
2115 (void) sm_signal(SIGINT, intindebug);
2116 (void) sm_releasesignal(SIGINT);
2118 (void) sm_io_fprintf(smioout,
2121 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2122 if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2124 testmodeline("/quit", &MainEnvelope);
2125 p = strchr(buf, '\n');
2129 (void) sm_io_fprintf(smioout,
2132 testmodeline(buf, &MainEnvelope);
2134 SM_EXCEPT(exc, "[!F]*")
2137 ** 8.10 just prints \n on interrupt.
2138 ** I'm printing the exception here in case
2139 ** sendmail is extended to raise additional
2140 ** exceptions in this context.
2143 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2145 sm_exc_print(exc, smioout);
2153 if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER ||
2154 OpMode == MD_ARPAFTP)
2156 /* check whether STARTTLS is turned off for the client */
2157 if (chkclientmodifiers(D_NOTLS))
2160 else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2163 /* check whether STARTTLS is turned off */
2164 if (chkdaemonmodifiers(D_NOTLS) && chkclientmodifiers(D_NOTLS))
2167 else /* other modes don't need STARTTLS */
2172 /* basic TLS initialization */
2173 j = init_tls_library(FipsMode);
2176 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2177 "ERROR: TLS failed to initialize\n");
2184 if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2186 /* disable TLS for client */
2189 #endif /* STARTTLS */
2192 ** If collecting stuff from the queue, go start doing that.
2195 if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2200 /* init TLS for client, ignore result for now */
2201 (void) initclttls(tls_ok);
2205 ** The parent process of the caller of runqueue() needs
2206 ** to stay around for a possible SIGTERM. The SIGTERM will
2207 ** tell this process that all of the queue runners children
2208 ** need to be sent SIGTERM as well. At the same time, we
2209 ** want to return control to the command line. So we do an
2213 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2216 ** If the fork() failed we should still try to do
2217 ** the queue run. If it succeeded then the child
2218 ** is going to start the run and wait for all
2219 ** of the children to finish.
2224 /* Reset global flags */
2225 RestartRequest = NULL;
2226 ShutdownRequest = NULL;
2229 /* disconnect from terminal */
2230 disconnect(2, CurEnv);
2233 CurrentPid = getpid();
2236 int rwgflags = RWG_NONE;
2239 ** To run a specific queue group mark it to
2240 ** be run, select the work group it's in and
2241 ** increment the work counter.
2244 for (i = 0; i < NumQueue && Queue[i] != NULL;
2246 Queue[i]->qg_nextrun = (time_t) -1;
2247 Queue[qgrp]->qg_nextrun = 0;
2249 rwgflags |= RWG_VERBOSE;
2250 if (queuepersistent)
2251 rwgflags |= RWG_PERSISTENT;
2252 rwgflags |= RWG_FORCE;
2253 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2257 (void) runqueue(false, Verbose,
2258 queuepersistent, true);
2260 /* set the title to make it easier to find */
2261 sm_setproctitle(true, CurEnv, "Queue control");
2262 (void) sm_signal(SIGCHLD, SIG_DFL);
2263 while (CurChildren > 0)
2269 while ((ret = sm_wait(&status)) <= 0)
2271 if (errno == ECHILD)
2274 ** Oops... something got messed
2275 ** up really bad. Waiting for
2276 ** non-existent children
2277 ** shouldn't happen. Let's get
2287 /* something is really really wrong */
2288 if (errno == ECHILD)
2290 sm_syslog(LOG_ERR, NOQID,
2291 "queue control process: lost all children: wait returned ECHILD");
2295 /* Only drop when a child gives status */
2296 if (WIFSTOPPED(status))
2299 proc_list_drop(ret, status, NULL);
2302 finis(true, true, ExitStat);
2307 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2309 /* check whether AUTH is turned off for the server */
2310 if (!chkdaemonmodifiers(D_NOAUTH) &&
2311 (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2312 syserr("!sasl_server_init failed! [%s]",
2313 sasl_errstring(i, NULL, NULL));
2317 if (OpMode == MD_SMTP)
2319 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2320 PROC_DAEMON, 0, -1, NULL);
2322 /* clean up background delivery children */
2323 (void) sm_signal(SIGCHLD, reapchild);
2327 ** If a daemon, wait for a request.
2328 ** getrequests will always return in a child.
2329 ** If we should also be processing the queue, start
2330 ** doing it in background.
2331 ** We check for any errors that might have happened
2335 if (OpMode == MD_DAEMON || QueueIntvl > 0)
2339 /* avoid cleanup in finis(), DaemonPid will be set below */
2341 if (!run_in_foreground && !tTd(99, 100))
2343 /* put us in background */
2346 syserr("daemon: cannot fork");
2349 finis(false, true, EX_OK);
2354 ** Initialize exception stack and default exception
2355 ** handler for child process.
2358 /* Reset global flags */
2359 RestartRequest = NULL;
2360 RestartWorkGroup = false;
2361 ShutdownRequest = NULL;
2363 CurrentPid = getpid();
2365 sm_exc_newthread(fatal_error);
2367 /* disconnect from our controlling tty */
2368 disconnect(2, &MainEnvelope);
2372 if (OpMode == MD_DAEMON)
2374 (void) sm_strlcat(dtype, "+SMTP", sizeof(dtype));
2375 DaemonPid = CurrentPid;
2379 (void) sm_strlcat2(dtype,
2381 ? "+persistent-queueing@"
2383 pintvl(QueueIntvl, true),
2387 (void) sm_strlcat(dtype, "+debugging", sizeof(dtype));
2389 sm_syslog(LOG_INFO, NOQID,
2390 "starting daemon (%s): %s", Version, dtype + 1);
2395 /* save daemon type in a macro for possible PidFile use */
2396 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2397 macid("{daemon_info}"), dtype + 1);
2399 /* save queue interval in a macro for possible PidFile use */
2400 macdefine(&MainEnvelope.e_macro, A_TEMP,
2401 macid("{queue_interval}"), pintvl(QueueIntvl, true));
2403 /* workaround: can't seem to release the signal in the parent */
2404 (void) sm_signal(SIGHUP, sighup);
2405 (void) sm_releasesignal(SIGHUP);
2406 (void) sm_signal(SIGTERM, sigterm);
2413 int rwgflags = RWG_NONE;
2416 ** To run a specific queue group mark it to
2417 ** be run, select the work group it's in and
2418 ** increment the work counter.
2421 for (i = 0; i < NumQueue && Queue[i] != NULL;
2423 Queue[i]->qg_nextrun = (time_t) -1;
2424 Queue[qgrp]->qg_nextrun = 0;
2426 rwgflags |= RWG_VERBOSE;
2427 if (queuepersistent)
2428 rwgflags |= RWG_PERSISTENT;
2429 rwgflags |= RWG_FORCE;
2430 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2434 #endif /* _FFR_RUNPQG */
2435 (void) runqueue(true, false, queuepersistent,
2439 ** If queuepersistent but not in daemon mode then
2440 ** we're going to do the queue runner monitoring here.
2441 ** If in daemon mode then the monitoring will happen
2445 if (OpMode != MD_DAEMON && queuepersistent)
2448 ** Write the pid to file
2449 ** XXX Overwrites sendmail.pid
2452 log_sendmail_pid(&MainEnvelope);
2454 /* set the title to make it easier to find */
2455 sm_setproctitle(true, CurEnv, "Queue control");
2456 (void) sm_signal(SIGCHLD, SIG_DFL);
2457 while (CurChildren > 0)
2465 while ((ret = sm_wait(&status)) <= 0)
2468 ** Waiting for non-existent
2469 ** children shouldn't happen.
2470 ** Let's get out of here if
2474 if (errno == ECHILD)
2482 /* something is really really wrong */
2483 if (errno == ECHILD)
2485 sm_syslog(LOG_ERR, NOQID,
2486 "persistent queue runner control process: lost all children: wait returned ECHILD");
2490 if (WIFSTOPPED(status))
2493 /* Probe only on a child status */
2494 proc_list_drop(ret, status, &group);
2496 if (WIFSIGNALED(status))
2498 if (WCOREDUMP(status))
2500 sm_syslog(LOG_ERR, NOQID,
2501 "persistent queue runner=%d core dumped, signal=%d",
2502 group, WTERMSIG(status));
2504 /* don't restart this */
2505 mark_work_group_restart(
2510 sm_syslog(LOG_ERR, NOQID,
2511 "persistent queue runner=%d died, pid=%ld, signal=%d",
2517 ** When debugging active, don't
2518 ** restart the persistent queues.
2519 ** But do log this as info.
2522 if (sm_debug_active(&DebugNoPRestart,
2525 sm_syslog(LOG_DEBUG, NOQID,
2526 "persistent queue runner=%d, exited",
2528 mark_work_group_restart(group,
2533 finis(true, true, ExitStat);
2537 if (OpMode != MD_DAEMON)
2542 ** Write the pid to file
2543 ** XXX Overwrites sendmail.pid
2546 log_sendmail_pid(&MainEnvelope);
2548 /* set the title to make it easier to find */
2550 (void) sm_strlcpyn(qtype, sizeof(qtype), 4,
2552 pintvl(QueueIntvl, true),
2555 sm_setproctitle(true, CurEnv, qtype);
2563 (void) runqueue(true, false,
2568 (void) dropenvelope(&MainEnvelope, true, false);
2571 /* init TLS for server, ignore result for now */
2572 (void) initsrvtls(tls_ok);
2576 p_flags = getrequests(&MainEnvelope);
2578 /* drop privileges */
2579 (void) drop_privileges(false);
2582 ** Get authentication data
2583 ** Set _ macro in BlankEnvelope before calling newenvelope().
2587 if (bitnset(D_XCNCT, *p_flags) || bitnset(D_XCNCT_M, *p_flags))
2589 /* copied from getauthinfo() */
2590 if (RealHostName == NULL)
2592 RealHostName = newstr(hostnamebyanyaddr(&RealHostAddr));
2593 if (strlen(RealHostName) > MAXNAME)
2594 RealHostName[MAXNAME] = '\0'; /* XXX - 1 ? */
2596 snprintf(buf, sizeof(buf), "%s [%s]",
2597 RealHostName, anynet_ntoa(&RealHostAddr));
2599 forged = bitnset(D_XCNCT_M, *p_flags);
2602 (void) sm_strlcat(buf, " (may be forged)",
2604 macdefine(&BlankEnvelope.e_macro, A_PERM,
2605 macid("{client_resolve}"), "FORGED");
2608 /* HACK! variable used only two times right below */
2611 sm_syslog(LOG_INFO, NOQID,
2612 "main: where=not_calling_getauthinfo, RealHostAddr=%s",
2613 anynet_ntoa(&RealHostAddr));
2616 /* WARNING: "non-braced" else */
2617 #endif /* _FFR_XCNCT */
2618 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2620 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2622 sm_syslog(LOG_INFO, NOQID,
2623 "main: where=after_getauthinfo, RealHostAddr=%s",
2624 anynet_ntoa(&RealHostAddr));
2626 /* at this point we are in a child: reset state */
2627 sm_rpool_free(MainEnvelope.e_rpool);
2628 (void) newenvelope(&MainEnvelope, &MainEnvelope,
2629 sm_rpool_new_x(NULL));
2637 if (NULL != RealHostName)
2640 p = anynet_ntoa(&RealHostAddr);
2645 /* log connection information */
2646 sm_syslog(LOG_INFO, NULL, "connect from %s", p);
2650 ** If running SMTP protocol, start collecting and executing
2651 ** commands. This will never return.
2654 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2659 ** Save some macros for check_* rulesets.
2666 (void) sm_snprintf(ipbuf, sizeof(ipbuf), "[%.100s]",
2667 anynet_ntoa(&RealHostAddr));
2668 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2669 macid("{client_name}"), ipbuf);
2672 macdefine(&BlankEnvelope.e_macro, A_PERM,
2673 macid("{client_name}"), RealHostName);
2674 macdefine(&BlankEnvelope.e_macro, A_PERM,
2675 macid("{client_ptr}"), RealHostName);
2676 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2677 macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2680 switch (RealHostAddr.sa.sa_family)
2684 (void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2685 ntohs(RealHostAddr.sin.sin_port));
2687 #endif /* NETINET */
2690 (void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2691 ntohs(RealHostAddr.sin6.sin6_port));
2693 #endif /* NETINET6 */
2695 (void) sm_snprintf(pbuf, sizeof(pbuf), "0");
2698 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2699 macid("{client_port}"), pbuf);
2701 if (OpMode == MD_DAEMON)
2703 ENVELOPE *saved_env;
2705 /* validate the connection */
2708 CurEnv = &BlankEnvelope;
2709 nullserver = validate_connection(&RealHostAddr,
2710 macvalue(macid("{client_name}"),
2713 if (bitset(EF_DISCARD, BlankEnvelope.e_flags))
2714 MainEnvelope.e_flags |= EF_DISCARD;
2718 else if (p_flags == NULL)
2720 p_flags = (BITMAP256 *) xalloc(sizeof(*p_flags));
2724 if (OpMode == MD_SMTP)
2725 (void) initsrvtls(tls_ok);
2728 /* turn off profiling */
2730 smtp(nullserver, *p_flags, &MainEnvelope);
2734 /* turn off profiling */
2736 if (OpMode == MD_DAEMON)
2741 sm_rpool_free(MainEnvelope.e_rpool);
2742 clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2743 if (OpMode == MD_VERIFY)
2745 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2746 PostMasterCopy = NULL;
2750 /* interactive -- all errors are global */
2751 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2755 ** Do basic system initialization and set the sender
2758 initsys(&MainEnvelope);
2759 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2760 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2761 setsender(from, &MainEnvelope, NULL, '\0', false);
2762 if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2763 (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2764 strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2766 auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2767 RealUserName, from, warn_f_flag);
2776 /* set the initial sender for AUTH= to $f@$j */
2777 fv = macvalue('f', &MainEnvelope);
2778 if (fv == NULL || *fv == '\0')
2779 MainEnvelope.e_auth_param = NULL;
2782 if (strchr(fv, '@') == NULL)
2784 i = strlen(fv) + strlen(macvalue('j',
2785 &MainEnvelope)) + 2;
2787 (void) sm_strlcpyn(p, i, 3, fv, "@",
2792 p = sm_strdup_x(fv);
2793 MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2795 sm_free(p); /* XXX */
2798 if (macvalue('s', &MainEnvelope) == NULL)
2799 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2802 if (*av == NULL && !GrabTo)
2804 MainEnvelope.e_to = NULL;
2805 MainEnvelope.e_flags |= EF_GLOBALERRS;
2807 SuperSafe = SAFE_NO;
2808 usrerr("Recipient names must be specified");
2810 /* collect body for UUCP return */
2811 if (OpMode != MD_VERIFY)
2812 collect(InChannel, false, NULL, &MainEnvelope, true);
2813 finis(true, true, EX_USAGE);
2818 ** Scan argv and deliver the message to everyone.
2821 save_val = LogUsrErrs;
2823 sendtoargv(av, &MainEnvelope);
2824 LogUsrErrs = save_val;
2826 /* if we have had errors sofar, arrange a meaningful exit stat */
2827 if (Errors > 0 && ExitStat == EX_OK)
2828 ExitStat = EX_USAGE;
2832 ** If using -t, force not sending to argv recipients, even
2833 ** if they are mentioned in the headers.
2840 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2841 q->q_state = QS_REMOVED;
2843 #endif /* _FFR_FIX_DASHT */
2846 ** Read the input mail.
2849 MainEnvelope.e_to = NULL;
2850 if (OpMode != MD_VERIFY || GrabTo)
2853 unsigned long savedflags;
2856 ** workaround for compiler warning on Irix:
2857 ** do not initialize variable in the definition, but
2859 ** warning(1548): transfer of control bypasses
2860 ** initialization of:
2861 ** variable "savederrors" (declared at line 2570)
2862 ** variable "savedflags" (declared at line 2571)
2866 savederrors = Errors;
2867 savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2868 MainEnvelope.e_flags |= EF_GLOBALERRS;
2869 MainEnvelope.e_flags &= ~EF_FATALERRS;
2872 collect(InChannel, false, NULL, &MainEnvelope, true);
2874 /* header checks failed */
2880 /* Log who the mail would have gone to */
2881 logundelrcpts(&MainEnvelope,
2882 MainEnvelope.e_message,
2886 finis(true, true, ExitStat);
2891 /* bail out if message too large */
2892 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2894 finis(true, true, ExitStat != EX_OK ? ExitStat
2900 /* set message size */
2901 (void) sm_snprintf(buf, sizeof(buf), "%ld",
2902 PRT_NONNEGL(MainEnvelope.e_msgsize));
2903 macdefine(&MainEnvelope.e_macro, A_TEMP,
2904 macid("{msg_size}"), buf);
2906 Errors = savederrors;
2907 MainEnvelope.e_flags |= savedflags;
2912 sm_dprintf("From person = \"%s\"\n",
2913 MainEnvelope.e_from.q_paddr);
2915 /* Check if quarantining stats should be updated */
2916 if (MainEnvelope.e_quarmsg != NULL)
2917 markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2920 ** Actually send everything.
2921 ** If verifying, just ack.
2926 if (!split_by_recipient(&MainEnvelope) &&
2927 bitset(EF_FATALERRS, MainEnvelope.e_flags))
2931 /* make sure we deliver at least the first envelope */
2932 i = FastSplit > 0 ? 0 : -1;
2933 for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2937 e->e_from.q_state = QS_SENDER;
2940 sm_dprintf("main[%d]: QS_SENDER ", i);
2941 printaddr(sm_debug_file(), &e->e_from, false);
2947 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2948 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2950 next = e->e_sibling;
2951 e->e_sibling = NULL;
2953 /* after FastSplit envelopes: queue up */
2954 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2955 e->e_sibling = next;
2960 ** Don't send return error message if in VERIFY mode.
2963 finis(true, true, ExitStat);
2968 ** STOP_SENDMAIL -- Stop the running program
2983 /* reset uid for process accounting */
2985 (void) setuid(RealUid);
2989 ** FINIS -- Clean up and exit.
2992 ** drop -- whether or not to drop CurEnv envelope
2993 ** cleanup -- call exit() or _exit()?
2994 ** exitstat -- exit status to use for exit() call
3004 finis(drop, cleanup, exitstat)
3007 volatile int exitstat;
3009 char pidpath[MAXPATHLEN];
3012 /* Still want to process new timeouts added below */
3014 (void) sm_releasesignal(SIGALRM);
3016 #if RATECTL_DEBUG || _FFR_OCC
3017 /* do this only in "main" process */
3018 if (DaemonPid == getpid())
3022 fp = sm_debug_file();
3029 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
3031 CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
3032 printenvflags(CurEnv);
3035 printopenfds(false);
3039 ** Clean up. This might raise E:mta.quickabort
3042 /* clean up temp files */
3043 CurEnv->e_to = NULL;
3046 if (CurEnv->e_id != NULL)
3050 r = dropenvelope(CurEnv, true, false);
3051 if (exitstat == EX_OK)
3053 sm_rpool_free(CurEnv->e_rpool);
3054 CurEnv->e_rpool = NULL;
3056 /* these may have pointed to the rpool */
3057 CurEnv->e_to = NULL;
3058 CurEnv->e_message = NULL;
3059 CurEnv->e_statmsg = NULL;
3060 CurEnv->e_quarmsg = NULL;
3061 CurEnv->e_bodytype = NULL;
3062 CurEnv->e_id = NULL;
3063 CurEnv->e_envid = NULL;
3064 CurEnv->e_auth_param = NULL;
3067 poststats(StatFile);
3070 /* flush any cached connections */
3071 mci_flush(true, NULL);
3073 /* close maps belonging to this pid */
3077 /* close UserDatabase */
3086 /* clean up extended load average stuff */
3096 sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
3098 if (exitstat == EX_TEMPFAIL ||
3099 CurEnv->e_errormode == EM_BERKNET)
3102 /* XXX clean up queues and related data structures */
3106 cleanup_shm(DaemonPid == pid);
3109 /* close locked pid file */
3110 close_sendmail_pid();
3112 if (DaemonPid == pid || PidFilePid == pid)
3114 /* blow away the pid file */
3115 expand(PidFile, pidpath, sizeof(pidpath), CurEnv);
3116 (void) unlink(pidpath);
3119 /* reset uid for process accounting */
3121 sm_mbdb_terminate();
3123 (void) sm_memstat_close();
3125 (void) setuid(RealUid);
3127 /* dump the heap, if we are checking for memory leaks */
3128 if (sm_debug_active(&SmHeapCheck, 2))
3129 sm_heap_report(smioout,
3130 sm_debug_level(&SmHeapCheck) - 1);
3132 if (sm_debug_active(&SmXtrapReport, 1))
3133 sm_dprintf("xtrap count = %d\n", SmXtrapCount);
3141 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
3144 ** sig -- incoming signal.
3150 ** longjmps back to test mode loop.
3152 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3153 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3157 /* Type of an exception generated on SIGINT during address test mode. */
3158 static const SM_EXC_TYPE_T EtypeInterrupt =
3172 int save_errno = errno;
3174 FIX_SYSV_SIGNAL(sig, intindebug);
3176 CHECK_CRITICAL(sig);
3178 sm_exc_raisenew_x(&EtypeInterrupt);
3180 return SIGFUNC_RETURN;
3183 ** SIGTERM -- SIGTERM handler for the daemon
3186 ** sig -- signal number.
3192 ** Sets ShutdownRequest which will hopefully trigger
3193 ** the daemon to exit.
3195 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3196 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3205 int save_errno = errno;
3207 FIX_SYSV_SIGNAL(sig, sigterm);
3208 ShutdownRequest = "signal";
3210 return SIGFUNC_RETURN;
3213 ** SIGHUP -- handle a SIGHUP signal
3216 ** sig -- incoming signal.
3222 ** Sets RestartRequest which should cause the daemon
3225 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3226 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3235 int save_errno = errno;
3237 FIX_SYSV_SIGNAL(sig, sighup);
3238 RestartRequest = "signal";
3240 return SIGFUNC_RETURN;
3243 ** SIGPIPE -- signal handler for SIGPIPE
3246 ** sig -- incoming signal.
3252 ** Sets StopRequest which should cause the mailq/hoststatus
3255 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3256 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3265 int save_errno = errno;
3267 FIX_SYSV_SIGNAL(sig, sigpipe);
3270 return SIGFUNC_RETURN;
3273 ** INTSIG -- clean up on interrupt
3275 ** This just arranges to exit. It pessimizes in that it
3276 ** may resend a message.
3279 ** sig -- incoming signal.
3285 ** Unlocks the current job.
3287 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3288 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3298 int save_errno = errno;
3300 FIX_SYSV_SIGNAL(sig, intsig);
3302 CHECK_CRITICAL(sig);
3303 sm_allsignals(true);
3308 /* Clean-up on aborted stdin message submission */
3309 if (OpMode == MD_SMTP ||
3310 OpMode == MD_DELIVER ||
3311 OpMode == MD_ARPAFTP)
3313 if (CurEnv->e_id != NULL)
3317 fn = queuename(CurEnv, DATAFL_LETTER);
3320 fn = queuename(CurEnv, ANYQFL_LETTER);
3328 if (sig != 0 && LogLevel > 79)
3329 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3330 if (OpMode != MD_TEST)
3331 unlockqueue(CurEnv);
3333 finis(drop, false, EX_OK);
3337 ** DISCONNECT -- remove our connection with any foreground process
3340 ** droplev -- how "deeply" we should drop the line.
3341 ** 0 -- ignore signals, mail back errors, make sure
3342 ** output goes to stdout.
3343 ** 1 -- also, make stdout go to /dev/null.
3344 ** 2 -- also, disconnect from controlling terminal
3345 ** (only for daemon mode).
3346 ** e -- the current envelope.
3352 ** Trys to insure that we are immune to vagaries of
3353 ** the controlling tty.
3357 disconnect(droplev, e)
3359 register ENVELOPE *e;
3364 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3365 sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3366 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL),
3370 sm_dprintf("don't\n");
3374 sm_syslog(LOG_DEBUG, e->e_id,
3375 "disconnect level %d",
3378 /* be sure we don't get nasty signals */
3379 (void) sm_signal(SIGINT, SIG_IGN);
3380 (void) sm_signal(SIGQUIT, SIG_IGN);
3382 /* we can't communicate with our caller, so.... */
3384 CurEnv->e_errormode = EM_MAIL;
3386 DisConnected = true;
3388 /* all input from /dev/null */
3389 if (InChannel != smioin)
3391 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3394 if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3395 SM_IO_RDONLY, NULL, smioin) == NULL)
3396 sm_syslog(LOG_ERR, e->e_id,
3397 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3398 SM_PATH_DEVNULL, sm_errstring(errno));
3401 ** output to the transcript
3402 ** We also compare the fd numbers here since OutChannel
3403 ** might be a layer on top of smioout due to encryption
3407 if (OutChannel != smioout &&
3408 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3409 sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3411 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3412 OutChannel = smioout;
3416 ** Has smioout been closed? Reopen it.
3417 ** This shouldn't happen anymore, the code is here
3418 ** just as a reminder.
3421 if (smioout->sm_magic == NULL &&
3422 sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3423 SM_IO_WRONLY, NULL, smioout) == NULL)
3424 sm_syslog(LOG_ERR, e->e_id,
3425 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3426 SM_PATH_DEVNULL, sm_errstring(errno));
3431 fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3434 sm_syslog(LOG_ERR, e->e_id,
3435 "disconnect: open(\"%s\") failed: %s",
3436 SM_PATH_DEVNULL, sm_errstring(errno));
3438 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3441 (void) dup2(fd, STDOUT_FILENO);
3442 (void) dup2(fd, STDERR_FILENO);
3447 /* drop our controlling TTY completely if possible */
3455 checkfd012("disconnect");
3459 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3472 while ((ap = *++argv) != NULL)
3474 /* Return if "--" or not an option of any form. */
3475 if (ap[0] != '-' || ap[1] == '-')
3478 /* Don't allow users to use "-Q." or "-Q ." */
3479 if ((ap[1] == 'Q' && ap[2] == '.') ||
3480 (ap[1] == 'Q' && argv[1] != NULL &&
3481 argv[1][0] == '.' && argv[1][1] == '\0'))
3483 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3484 "Can not use -Q.\n");
3488 /* skip over options that do have a value */
3489 op = strchr(OPTIONS, ap[1]);
3490 if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3492 #if defined(sony_news)
3493 ap[1] != 'E' && ap[1] != 'J' &&
3495 argv[1] != NULL && argv[1][0] != '-')
3501 /* If -C doesn't have an argument, use sendmail.cf. */
3502 #define __DEFPATH "sendmail.cf"
3503 if (ap[1] == 'C' && ap[2] == '\0')
3505 *argv = xalloc(sizeof(__DEFPATH) + 2);
3506 (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3510 /* If -q doesn't have an argument, run it once. */
3511 if (ap[1] == 'q' && ap[2] == '\0')
3514 /* If -Q doesn't have an argument, disable quarantining */
3515 if (ap[1] == 'Q' && ap[2] == '\0')
3518 /* if -d doesn't have an argument, use 0-99.1 */
3519 if (ap[1] == 'd' && ap[2] == '\0')
3522 #if defined(sony_news)
3523 /* if -E doesn't have an argument, use -EC */
3524 if (ap[1] == 'E' && ap[2] == '\0')
3527 /* if -J doesn't have an argument, use -JJ */
3528 if (ap[1] == 'J' && ap[2] == '\0')
3530 #endif /* defined(sony_news) */
3534 ** AUTH_WARNING -- specify authorization warning
3537 ** e -- the current envelope.
3538 ** msg -- the text of the message.
3539 ** args -- arguments to the message.
3547 auth_warning(register ENVELOPE *e, const char *msg, ...)
3548 #else /* __STDC__ */
3549 auth_warning(e, msg, va_alist)
3550 register ENVELOPE *e;
3553 #endif /* __STDC__ */
3558 if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3561 static char hostbuf[48];
3563 if (hostbuf[0] == '\0')
3567 hp = myhostname(hostbuf, sizeof(hostbuf));
3574 #endif /* NETINET6 */
3577 (void) sm_strlcpyn(buf, sizeof(buf), 2, hostbuf, ": ");
3578 p = &buf[strlen(buf)];
3579 SM_VA_START(ap, msg);
3580 (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3582 addheader("X-Authentication-Warning", buf, 0, e, true);
3584 sm_syslog(LOG_INFO, e->e_id,
3585 "Authentication-Warning: %.400s",
3590 ** GETEXTENV -- get from external environment
3593 ** envar -- the name of the variable to retrieve
3596 ** The value, if any.
3607 for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3609 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3610 return &(*envp)[l + 1];
3615 ** SM_SETUSERENV -- set an environment variable in the propagated environment
3618 ** envar -- the name of the environment variable.
3619 ** value -- the value to which it should be set. If
3620 ** null, this is extracted from the incoming
3621 ** environment. If that is not set, the call
3622 ** to sm_setuserenv is ignored.
3629 sm_setuserenv(envar, value)
3634 char **evp = UserEnviron;
3639 value = getextenv(envar);
3644 /* XXX enforce reasonable size? */
3645 i = strlen(envar) + 1;
3646 l = strlen(value) + i + 1;
3647 p = (char *) xalloc(l);
3648 (void) sm_strlcpyn(p, l, 3, envar, "=", value);
3650 while (*evp != NULL && strncmp(*evp, p, i) != 0)
3656 else if (evp < &UserEnviron[MAXUSERENVIRON])
3662 /* make sure it is in our environment as well */
3664 syserr("sm_setuserenv: putenv(%s) failed", p);
3667 ** DUMPSTATE -- dump state
3676 register char *j = macvalue('j', CurEnv);
3678 extern int NextMacroId;
3680 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3681 "--- dumping state on %s: $j = %s ---",
3683 j == NULL ? "<NULL>" : j);
3686 if (!wordinclass(j, 'w'))
3687 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3688 "*** $j not in $=w ***");
3690 sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3691 sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3692 NextMacroId, MAXMACROID);
3693 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3695 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3696 mci_dump_all(smioout, true);
3697 rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3701 register char **pvp;
3702 char *pv[MAXATOM + 1];
3705 status = REWRITE(pv, rs, CurEnv);
3706 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3707 "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3709 for (pvp = pv; *pvp != NULL; pvp++)
3710 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3712 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3717 ** SIGUSR1 -- Signal a request to dump state.
3720 ** sig -- calling signal.
3725 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3726 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3729 ** XXX: More work is needed for this signal handler.
3737 int save_errno = errno;
3739 FIX_SYSV_SIGNAL(sig, sigusr1);
3741 CHECK_CRITICAL(sig);
3742 dumpstate("user signal");
3747 return SIGFUNC_RETURN;
3749 #endif /* SIGUSR1 */
3752 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3755 ** to_real_uid -- if set, drop to the real uid instead
3756 ** of the RunAsUser.
3759 ** EX_OSERR if the setuid failed.
3764 drop_privileges(to_real_uid)
3768 GIDSET_T emptygidset[1];
3771 sm_dprintf("drop_privileges(%d): Real[UG]id=%ld:%ld, get[ug]id=%ld:%ld, gete[ug]id=%ld:%ld, RunAs[UG]id=%ld:%ld\n",
3773 (long) RealUid, (long) RealGid,
3774 (long) getuid(), (long) getgid(),
3775 (long) geteuid(), (long) getegid(),
3776 (long) RunAsUid, (long) RunAsGid);
3780 RunAsUserName = RealUserName;
3786 /* make sure no one can grab open descriptors for secret files */
3788 sm_mbdb_terminate();
3790 /* reset group permissions; these can be set later */
3791 emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3794 ** Notice: on some OS (Linux...) the setgroups() call causes
3795 ** a logfile entry if sendmail is not run by root.
3796 ** However, it is unclear (no POSIX standard) whether
3797 ** setgroups() can only succeed if executed by root.
3798 ** So for now we keep it as it is; if you want to change it, use
3799 ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3802 if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3804 syserr("drop_privileges: setgroups(1, %d) failed",
3805 (int) emptygidset[0]);
3809 /* reset primary group id */
3813 ** Drop gid to real gid.
3814 ** On some OS we must reset the effective[/real[/saved]] gid,
3815 ** and then use setgid() to finally drop all group privileges.
3816 ** Later on we check whether we can get back the
3821 if (setegid(RunAsGid) < 0)
3823 syserr("drop_privileges: setegid(%d) failed",
3827 #else /* HASSETEGID */
3829 if (setregid(RunAsGid, RunAsGid) < 0)
3831 syserr("drop_privileges: setregid(%d, %d) failed",
3832 (int) RunAsGid, (int) RunAsGid);
3835 # else /* HASSETREGID */
3837 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3839 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3840 (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3843 # endif /* HASSETRESGID */
3844 # endif /* HASSETREGID */
3845 #endif /* HASSETEGID */
3847 if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3849 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3851 syserr("drop_privileges: setgid(%ld) failed",
3856 if (rval == EX_OK && getegid() != RunAsGid)
3858 syserr("drop_privileges: Unable to set effective gid=%ld to RunAsGid=%ld",
3859 (long) getegid(), (long) RunAsGid);
3864 /* fiddle with uid */
3865 if (to_real_uid || RunAsUid != 0)
3870 ** Try to setuid(RunAsUid).
3871 ** euid must be RunAsUid,
3872 ** ruid must be RunAsUid unless (e|r)uid wasn't 0
3873 ** and we didn't have to drop privileges to the real uid.
3876 if (setuid(RunAsUid) < 0 ||
3877 geteuid() != RunAsUid ||
3878 (getuid() != RunAsUid &&
3879 (to_real_uid || geteuid() == 0 || getuid() == 0)))
3883 ** if ruid != RunAsUid, euid == RunAsUid, then
3884 ** try resetting just the real uid, then using
3885 ** setuid() to drop the saved-uid as well.
3888 if (geteuid() == RunAsUid)
3890 if (setreuid(RunAsUid, -1) < 0)
3892 syserr("drop_privileges: setreuid(%d, -1) failed",
3896 if (setuid(RunAsUid) < 0)
3898 syserr("drop_privileges: second setuid(%d) attempt failed",
3904 #endif /* HASSETREUID */
3906 syserr("drop_privileges: setuid(%d) failed",
3912 if (RunAsUid != 0 && setuid(0) == 0)
3915 ** Believe it or not, the Linux capability model
3916 ** allows a non-root process to override setuid()
3917 ** on a process running as root and prevent that
3918 ** process from dropping privileges.
3921 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3924 else if (RunAsUid != euid && setuid(euid) == 0)
3927 ** Some operating systems will keep the saved-uid
3928 ** if a non-root effective-uid calls setuid(real-uid)
3929 ** making it possible to set it back again later.
3932 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3937 if ((to_real_uid || RunAsGid != 0) &&
3938 rval == EX_OK && RunAsGid != EffGid &&
3939 getuid() != 0 && geteuid() != 0)
3942 if (setgid(EffGid) == 0)
3944 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3952 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3953 (int) geteuid(), (int) getuid(),
3954 (int) getegid(), (int) getgid());
3955 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3956 (int) RunAsUid, (int) RunAsGid);
3958 sm_dprintf("drop_privileges: rval = %d\n", rval);
3963 ** FILL_FD -- make sure a file descriptor has been properly allocated
3965 ** Used to make sure that stdin/out/err are allocated on startup
3968 ** fd -- the file descriptor to be filled.
3969 ** where -- a string used for logging. If NULL, this is
3970 ** being called on startup, and logging should
3977 ** possibly changes MissingFds
3988 if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3992 syserr("fill_fd: %s: fd %d not open", where, fd);
3994 MissingFds |= 1 << fd;
3995 i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3998 syserr("!fill_fd: %s: cannot open %s",
3999 where == NULL ? "startup" : where, SM_PATH_DEVNULL);
4008 ** SM_PRINTOPTIONS -- print options
4011 ** options -- array of options.
4018 sm_printoptions(options)
4028 if (ll + strlen(*av) > 63)
4037 sm_dprintf("%s", *av);
4038 ll += strlen(*av++) + 1;
4044 ** TO8BIT -- convert \octal sequences in a test mode input line
4047 ** str -- the input line.
4053 ** replaces \0octal in str with octal value.
4056 static bool to8bit __P((char *));
4071 while ((c = (*str++ & 0377)) != '\0')
4077 (nxtc = (*str & 0377)) == '0')
4080 while ((nxtc = (*str & 0377)) != '\0' &&
4081 isascii(nxtc) && isdigit(nxtc))
4098 q = quote_internal_chars(in, in, &len);
4100 sm_strlcpy(in, q, len);
4106 ** TESTMODELINE -- process a test mode input line
4109 ** line -- the input line.
4110 ** e -- the current environment.
4113 ** .X process X as a configuration line
4114 ** =X dump a configuration item (such as mailers)
4115 ** $X dump a macro or class
4116 ** /X try an activity
4117 ** X normal process through rule set X
4121 testmodeline(line, e)
4127 auto char *delimptr;
4136 static int tryflags = RF_COPYNONE;
4137 char exbuf[MAXLINE];
4139 extern unsigned char TokTypeNoC[];
4142 /* skip leading spaces */
4143 while (*line == ' ')
4158 case '.': /* config-style settings */
4162 mid = macid_parse(&line[2], &delimptr);
4166 lbp = translate_dollars(delimptr, lbuf, &lbs);
4167 macdefine(&e->e_macro, A_TEMP, mid, lbp);
4173 if (line[2] == '\0') /* not to call syserr() */
4176 mid = macid_parse(&line[2], &delimptr);
4180 lbp = translate_dollars(delimptr, lbuf, &lbs);
4181 expand(lbp, exbuf, sizeof(exbuf), e);
4190 while (*p != '\0' && SM_ISSPACE(*p))
4193 while (*p != '\0' && !(SM_ISSPACE(*p)))
4204 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4205 "Usage: .[DC]macro value(s)\n");
4209 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4210 "Unknown \".\" command %s\n", line);
4215 case '=': /* config-style settings */
4218 case 'S': /* dump rule set */
4219 rs = strtorwset(&line[2], NULL, ST_FIND);
4222 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4223 "Undefined ruleset %s\n", &line[2]);
4226 rw = RewriteRules[rs];
4231 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4236 xputs(smioout, *s++);
4237 (void) sm_io_putc(smioout,
4238 SM_TIME_DEFAULT, ' ');
4240 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4242 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4247 xputs(smioout, *s++);
4248 (void) sm_io_putc(smioout,
4249 SM_TIME_DEFAULT, ' ');
4251 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4253 } while ((rw = rw->r_next) != NULL);
4257 for (i = 0; i < MAXMAILERS; i++)
4259 if (Mailer[i] != NULL)
4260 printmailer(smioout, Mailer[i]);
4265 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4266 "Usage: =Sruleset or =M\n");
4270 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4271 "Unknown \"=\" command %s\n", line);
4276 case '-': /* set command-line-like opts */
4284 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4285 "Usage: -d{debug arguments}\n");
4289 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4290 "Unknown \"-\" command %s\n", line);
4298 mid = macid(&line[2]);
4300 stabapply(dump_class, mid);
4303 mid = macid(&line[1]);
4306 p = macvalue(mid, e);
4308 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4313 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4318 case '/': /* miscellaneous commands */
4319 p = &line[strlen(line)];
4320 while (--p >= line && SM_ISSPACE(*p))
4322 p = strpbrk(line, " \t");
4325 while (SM_ISSPACE(*p))
4330 if (line[1] == '\0')
4332 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4333 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4336 if (sm_strcasecmp(&line[1], "quit") == 0)
4338 CurEnv->e_id = NULL;
4339 finis(true, true, ExitStat);
4342 if (sm_strcasecmp(&line[1], "mx") == 0)
4345 /* look up MX records */
4348 char *mxhosts[MAXMXHOSTS + 1];
4352 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4353 "Usage: /mx address\n");
4356 nmx = getmxrr(p, mxhosts, NULL, TRYFALLBACK, &rcode,
4359 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4360 "getmxrr(%s) returns null MX (See RFC7505)\n",
4363 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4364 "getmxrr(%s) returns %d value(s):\n",
4366 for (i = 0; i < nmx; i++)
4367 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4368 "\t%s\n", mxhosts[i]);
4369 #else /* NAMED_BIND */
4370 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4371 "No MX code compiled in\n");
4372 #endif /* NAMED_BIND */
4374 else if (sm_strcasecmp(&line[1], "canon") == 0)
4376 char host[MAXHOSTNAMELEN];
4380 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4381 "Usage: /canon address\n");
4384 else if (sm_strlcpy(host, p, sizeof(host)) >= sizeof(host))
4386 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4390 (void) getcanonname(host, sizeof(host), !HasWildcardMX,
4392 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4393 "getcanonname(%s) returns %s\n",
4396 else if (sm_strcasecmp(&line[1], "map") == 0)
4398 auto int rcode = EX_OK;
4403 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4404 "Usage: /map mapname key\n");
4407 for (q = p; *q != '\0' && !(SM_ISSPACE(*q)); q++)
4411 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4412 "No key specified\n");
4416 map = stab(p, ST_MAP, ST_FIND);
4419 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4420 "Map named \"%s\" not found\n", p);
4423 if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4424 !openmap(&(map->s_map)))
4426 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4427 "Map named \"%s\" not open\n", p);
4430 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4431 "map_lookup: %s (%s) ", p, q);
4434 p = (*map->s_map.map_class->map_lookup)
4435 (&map->s_map, q, av, &rcode);
4437 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4441 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4442 "returns %s (%d)\n", p,
4445 else if (sm_strcasecmp(&line[1], "try") == 0)
4449 auto int rcode = EX_OK;
4451 q = strpbrk(p, " \t");
4454 while (SM_ISSPACE(*q))
4457 if (q == NULL || *q == '\0')
4459 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4460 "Usage: /try mailer address\n");
4463 st = stab(p, ST_MAILER, ST_FIND);
4466 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4467 "Unknown mailer %s\n", p);
4471 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4472 "Trying %s %s address %s for mailer %s\n",
4473 bitset(RF_HEADERADDR, tryflags) ? "header"
4475 bitset(RF_SENDERADDR, tryflags) ? "sender"
4476 : "recipient", q, p);
4477 p = remotename(q, m, tryflags, &rcode, CurEnv);
4478 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4479 "Rcode = %d, addr = %s\n",
4480 rcode, p == NULL ? "<NULL>" : p);
4483 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4487 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4488 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4491 for (; *p != '\0'; p++)
4497 tryflags |= RF_HEADERADDR;
4502 tryflags &= ~RF_HEADERADDR;
4507 tryflags |= RF_SENDERADDR;
4512 tryflags &= ~RF_SENDERADDR;
4516 exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4518 exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4520 macdefine(&e->e_macro, A_TEMP,
4521 macid("{addr_type}"), exbuf);
4523 else if (sm_strcasecmp(&line[1], "parse") == 0)
4527 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4528 "Usage: /parse address\n");
4531 q = crackaddr(p, e);
4532 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4533 "Cracked address = ");
4535 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4536 "\nParsing %s %s address\n",
4537 bitset(RF_HEADERADDR, tryflags) ?
4538 "header" : "envelope",
4539 bitset(RF_SENDERADDR, tryflags) ?
4540 "sender" : "recipient");
4541 if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4543 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4545 else if (a.q_host != NULL && a.q_host[0] != '\0')
4546 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4547 "mailer %s, host %s, user %s\n",
4552 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4553 "mailer %s, user %s\n",
4558 else if (sm_strcasecmp(&line[1], "header") == 0)
4562 ul = chompheader(p, CHHDR_CHECK|CHHDR_USER, NULL, e);
4563 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4566 #if NETINET || NETINET6
4567 else if (sm_strcasecmp(&line[1], "gethostbyname") == 0)
4569 int family = AF_INET;
4571 q = strpbrk(p, " \t");
4574 while (SM_ISSPACE(*q))
4577 if (*q != '\0' && (strcmp(q, "inet6") == 0 ||
4578 strcmp(q, "AAAA") == 0))
4580 # endif /* NETINET6 */
4582 (void) sm_gethostbyname(p, family);
4584 #endif /* NETINET || NETINET6 */
4586 else if (sm_strcasecmp(&line[1], "dnslookup") == 0)
4589 int rr_type, family;
4595 q = strpbrk(p, " \t");
4600 while (SM_ISSPACE(*q))
4602 pflags = strpbrk(q, " \t");
4605 while (SM_ISSPACE(*pflags))
4608 rr_type = dns_string_to_type(q);
4612 if (rr_type == T_AAAA)
4615 while (pflags != NULL && *pflags != '\0' &&
4616 !SM_ISSPACE(*pflags))
4619 flags |= RR_NO_CNAME;
4620 else if (*pflags == 'o')
4621 flags |= RR_ONLY_CNAME;
4622 else if (*pflags == 'T')
4623 flags &= ~RR_AS_TEXT;
4627 r = dns_lookup_int(p, C_IN, rr_type,
4628 0, 0, 0, flags, NULL, NULL);
4629 if (r != NULL && family >= 0)
4631 (void) dns2he(r, family);
4639 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4640 "Unknown \"/\" command %s\n",
4643 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4647 for (p = line; SM_ISSPACE(*p); p++)
4650 while (*p != '\0' && !(SM_ISSPACE(*p)))
4654 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4660 eightbit = to8bit(p + 1);
4661 if (invalidaddr(p + 1, NULL, true))
4665 register char **pvp;
4666 char pvpbuf[PSBUFSIZE];
4668 pvp = prescan(++p, ',', pvpbuf, sizeof(pvpbuf), &delimptr,
4669 ConfigLevel >= 9 ? TokTypeNoC : ExtTokenTab, false);
4677 rs = strtorwset(p, NULL, ST_FIND);
4680 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4681 "Undefined ruleset %s\n",
4685 status = REWRITE(pvp, rs, e);
4686 if (status != EX_OK)
4687 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4688 "== Ruleset %s (%d) status %d\n",
4692 cataddr(pvp, NULL, exbuf, sizeof(exbuf), '\0',
4694 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4698 while (*p != '\0' && *p++ != ',')
4701 } while (*(p = delimptr) != '\0');
4702 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4710 if (s->s_symtype != ST_CLASS)
4712 if (bitnset(bitidx(id), s->s_class))
4713 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4718 ** An exception type used to create QuickAbort exceptions.
4719 ** This is my first cut at converting QuickAbort from longjmp to exceptions.
4720 ** These exceptions have a single integer argument, which is the argument
4721 ** to longjmp in the original code (either 1 or 2). I don't know the
4722 ** significance of 1 vs 2: the calls to setjmp don't care.
4725 const SM_EXC_TYPE_T EtypeQuickAbort =