2 * Copyright (c) 1998-2003 Sendmail, Inc. and its suppliers.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
17 #include <sm/signal.h>
20 SM_UNUSED(static char copyright[]) =
21 "@(#) Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers.\n\
22 All rights reserved.\n\
23 Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.\n\
24 Copyright (c) 1988, 1993\n\
25 The Regents of the University of California. All rights reserved.\n";
28 SM_RCSID("@(#)$Id: main.c,v 8.887.2.22 2003/03/06 18:38:08 ca Exp $")
31 #if NETINET || NETINET6
32 # include <arpa/inet.h>
33 #endif /* NETINET || NETINET6 */
36 #include <sendmail/pathnames.h>
39 DebugNoPRestart = SM_DEBUG_INITIALIZER("no_persistent_restart",
40 "@(#)$Debug: no_persistent_restart - don't restart, log only $");
42 static void dump_class __P((STAB *, int));
43 static void obsolete __P((char **));
44 static void testmodeline __P((char *, ENVELOPE *));
45 static char *getextenv __P((const char *));
46 static void sm_printoptions __P((char **));
47 static SIGFUNC_DECL intindebug __P((int));
48 static SIGFUNC_DECL sighup __P((int));
49 static SIGFUNC_DECL sigpipe __P((int));
50 static SIGFUNC_DECL sigterm __P((int));
52 static SIGFUNC_DECL sigusr1 __P((int));
56 ** SENDMAIL -- Post mail to a set of destinations.
58 ** This is the basic mail router. All user mail programs should
59 ** call this routine to actually deliver mail. Sendmail in
60 ** turn calls a bunch of mail servers that do the real work of
61 ** delivering the mail.
63 ** Sendmail is driven by settings read in from /etc/mail/sendmail.cf
64 ** (read by readcf.c).
67 ** /usr/lib/sendmail [flags] addr ...
69 ** See the associated documentation for details.
72 ** Eric Allman, UCB/INGRES (until 10/81).
73 ** Britton-Lee, Inc., purveyors of fine
74 ** database computers (11/81 - 10/88).
75 ** International Computer Science Institute
77 ** UCB/Mammoth Project (10/89 - 7/95).
78 ** InReference, Inc. (8/95 - 1/97).
79 ** Sendmail, Inc. (1/98 - present).
80 ** The support of my employers is gratefully acknowledged.
81 ** Few of them (Britton-Lee in particular) have had
82 ** anything to gain from my involvement in this project.
84 ** Gregory Neil Shapiro,
85 ** Worcester Polytechnic Institute (until 3/98).
86 ** Sendmail, Inc. (3/98 - present).
89 ** Sendmail, Inc. (12/98 - present).
92 char *FullName; /* sender's full name */
93 ENVELOPE BlankEnvelope; /* a "blank" envelope */
94 static ENVELOPE MainEnvelope; /* the envelope around the basic letter */
95 ADDRESS NullAddress = /* a null address */
97 char *CommandLineArgs; /* command line args for pid file */
98 bool Warn_Q_option = false; /* warn about Q option use */
99 static int MissingFds = 0; /* bit map of fds missing on startup */
100 char *Mbdb = "pw"; /* mailbox database defaults to /etc/passwd */
103 GIDSET_T InitialGidSet[NGROUPS_MAX];
104 #endif /* NGROUPS_MAX */
106 #define MAXCONFIGLEVEL 10 /* highest config version level known */
109 static sasl_callback_t srvcallbacks[] =
111 { SASL_CB_VERIFYFILE, &safesaslfile, NULL },
112 { SASL_CB_PROXY_POLICY, &proxy_policy, NULL },
113 { SASL_CB_LIST_END, NULL, NULL }
117 unsigned int SubmitMode;
118 int SyslogPrefixLen; /* estimated length of syslog prefix */
119 #define PIDLEN 6 /* pid length for computing SyslogPrefixLen */
121 # define SL_FUDGE 10 /* fudge offset for SyslogPrefixLen */
122 #endif /* ! SL_FUDGE */
123 #define SLDLL 8 /* est. length of default syslog label */
126 /* Some options are dangerous to allow users to use in non-submit mode */
127 #define CHECK_AGAINST_OPMODE(cmd) \
130 OpMode != MD_DELIVER && OpMode != MD_SMTP && \
131 OpMode != MD_ARPAFTP && \
132 OpMode != MD_VERIFY && OpMode != MD_TEST) \
134 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
135 "WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \
139 if (extraprivs && queuerun) \
141 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
142 "WARNING: Ignoring submission mode -%c option with -q\n", \
149 main(argc, argv, envp)
156 extern char Version[];
163 int qgrp = NOQGRP; /* queue group to process */
165 BITMAP256 *p_flags = NULL; /* daemon flags */
166 bool warn_C_flag = false;
167 bool auth = true; /* whether to set e_auth_param */
168 char warn_f_flag = '\0';
169 bool run_in_foreground = false; /* -bD mode */
170 bool queuerun = false, debug = false;
173 char *nullserver = NULL;
174 char *authinfo = NULL;
175 char *sysloglabel = NULL; /* label for syslog */
176 char *conffile = NULL; /* name of .cf file */
177 char *queuegroup = NULL; /* queue group to process */
179 char *quarantining = NULL; /* quarantine queue items? */
180 #endif /* _FFR_QUARANTINE */
183 bool queuepersistent = false; /* queue runner process runs forever */
184 bool foregroundqueue = false; /* queue run in foreground */
185 bool save_val; /* to save some bool var. */
186 int cftype; /* which cf file to use? */
187 static time_t starttime = 0; /* when was process started */
188 struct stat traf_st; /* for TrafficLog FIFO check */
190 char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */
191 static char rnamebuf[MAXNAME]; /* holds RealUserName */
192 char *emptyenviron[1];
195 #endif /* STARTTLS */
198 extern int DtableSize;
202 extern char **environ;
204 extern void sm_sasl_init __P((void));
209 #endif /* USE_ENVIRON */
211 /* turn off profiling */
214 /* install default exception handler */
215 sm_exc_newthread(fatal_error);
217 /* set the default in/out channel so errors reported to screen */
219 OutChannel = smioout;
222 ** Check to see if we reentered.
223 ** This would normally happen if e_putheader or e_putbody
224 ** were NULL when invoked.
229 syserr("main: reentered!");
232 starttime = curtime();
234 /* avoid null pointer dereferences */
235 TermEscape.te_rv_on = TermEscape.te_rv_off = "";
240 /* Check if sendmail is running with extra privs */
241 extraprivs = (RealUid != 0 &&
242 (geteuid() != getuid() || getegid() != getgid()));
244 CurrentPid = getpid();
246 /* get whatever .cf file is right for the opmode */
247 cftype = SM_GET_RIGHT_CF;
249 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
250 DtableSize = getdtsize();
251 if (DtableSize > 256)
255 ** Be sure we have enough file descriptors.
256 ** But also be sure that 0, 1, & 2 are open.
259 /* reset errno and fill_errno; the latter is used way down below */
260 errno = fill_errno = 0;
261 fill_fd(STDIN_FILENO, NULL);
264 fill_fd(STDOUT_FILENO, NULL);
267 fill_fd(STDERR_FILENO, NULL);
274 if (i != STDIN_FILENO && i != STDOUT_FILENO &&
282 # define SM_LOG_STR "sendmail"
283 # endif /* ! SM_LOG_STR */
285 openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
286 # else /* LOG_MAIL */
287 openlog(SM_LOG_STR, LOG_PID);
288 # endif /* LOG_MAIL */
292 ** Seed the random number generator.
293 ** Used for queue file names, picking a queue directory, and
299 /* do machine-dependent initializations */
303 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
305 /* reset status from syserr() calls for missing file descriptors */
309 SubmitMode = SUBMIT_UNKNOWN;
311 checkfd012("after openlog");
314 tTsetup(tTdvect, sizeof tTdvect, "0-99.1,*_trace_*.1");
317 /* save initial group set for future checks */
318 i = getgroups(NGROUPS_MAX, InitialGidSet);
321 InitialGidSet[0] = (GID_T) -1;
324 while (i < NGROUPS_MAX)
325 InitialGidSet[i++] = InitialGidSet[0];
326 #endif /* NGROUPS_MAX */
328 /* drop group id privileges (RunAsUser not yet set) */
329 dp = drop_privileges(false);
333 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
336 /* arrange to dump state on user-1 signal */
337 (void) sm_signal(SIGUSR1, sigusr1);
341 /* ignore user-1 signal */
342 (void) sm_signal(SIGUSR1, SIG_IGN);
346 /* initialize for setproctitle */
347 initsetproctitle(argc, argv, envp);
349 /* Handle any non-getoptable constructions. */
353 ** Do a quick prescan of the argument list.
357 /* find initial opMode */
360 p = strrchr(*av, '/');
363 if (strcmp(p, "newaliases") == 0)
364 OpMode = MD_INITALIAS;
365 else if (strcmp(p, "mailq") == 0)
367 else if (strcmp(p, "smtpd") == 0)
369 else if (strcmp(p, "hoststat") == 0)
370 OpMode = MD_HOSTSTAT;
371 else if (strcmp(p, "purgestat") == 0)
372 OpMode = MD_PURGESTAT;
375 # if defined(__osf__) || defined(_AIX3)
376 # define OPTIONS "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:xQ:"
377 # endif /* defined(__osf__) || defined(_AIX3) */
378 # if defined(sony_news)
379 # define OPTIONS "A:B:b:C:cd:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:q:R:r:sTtV:vX:Q:"
380 # endif /* defined(sony_news) */
382 # define OPTIONS "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:Q:"
383 # endif /* ! OPTIONS */
384 #else /* _FFR_QUARANTINE */
385 # if defined(__osf__) || defined(_AIX3)
386 # define OPTIONS "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:x"
387 # endif /* defined(__osf__) || defined(_AIX3) */
388 # if defined(sony_news)
389 # define OPTIONS "A:B:b:C:cd:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:q:R:r:sTtV:vX:"
390 # endif /* defined(sony_news) */
392 # define OPTIONS "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:"
393 # endif /* ! OPTIONS */
394 #endif /* _FFR_QUARANTINE */
396 /* Set to 0 to allow -b; need to check optarg before using it! */
398 while ((j = getopt(argc, argv, OPTIONS)) != -1)
402 case 'b': /* operations mode */
403 j = (optarg == NULL) ? ' ' : *optarg;
422 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
423 "Frozen configurations unsupported\n");
427 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
428 "Invalid operation mode %c\n",
437 (void) sm_io_setvbuf(smioout, SM_TIME_DEFAULT,
438 (char *) NULL, SM_IO_NBF,
442 case 'G': /* relay (gateway) submission */
443 SubmitMode = SUBMIT_MTA;
449 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
450 "option requires an argument -- '%c'",
454 j = SM_MIN(strlen(optarg), 24) + 1;
455 sysloglabel = xalloc(j);
456 (void) sm_strlcpy(sysloglabel, optarg, j);
457 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
463 #endif /* _FFR_QUARANTINE */
465 /* just check if it is there */
472 /* Don't leak queue information via debug flags */
473 if (extraprivs && queuerun && debug)
475 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
476 "WARNING: Can not use -d with -q. Disabling debugging.\n");
477 sm_debug_setfile(NULL);
478 (void) memset(tTdvect, '\0', sizeof tTdvect);
482 if (sysloglabel != NULL)
484 /* Sanitize the string */
485 for (p = sysloglabel; *p != '\0'; p++)
487 if (!isascii(*p) || !isprint(*p) || *p == '%')
492 openlog(sysloglabel, LOG_PID, LOG_MAIL);
493 # else /* LOG_MAIL */
494 openlog(sysloglabel, LOG_PID);
495 # endif /* LOG_MAIL */
499 /* set up the blank envelope */
500 BlankEnvelope.e_puthdr = putheader;
501 BlankEnvelope.e_putbody = putbody;
502 BlankEnvelope.e_xfp = NULL;
503 STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
504 CurEnv = &BlankEnvelope;
505 STRUCTCOPY(NullAddress, MainEnvelope.e_from);
508 ** Set default values for variables.
509 ** These cannot be in initialized data space.
512 setdefaults(&BlankEnvelope);
513 initmacros(&BlankEnvelope);
518 pw = sm_getpwuid(RealUid);
520 (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof rnamebuf);
522 (void) sm_snprintf(rnamebuf, sizeof rnamebuf, "Unknown UID %d",
525 RealUserName = rnamebuf;
529 sm_dprintf("Version %s\n", Version);
530 finis(false, true, EX_OK);
535 ** if running non-set-user-ID binary as non-root, pretend
536 ** we are the RunAsUid
539 if (RealUid != 0 && geteuid() == RealUid)
542 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
546 else if (geteuid() != 0)
547 RunAsUid = geteuid();
550 if (RealUid != 0 && EffGid == RealGid)
555 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
556 (int) geteuid(), (int) getuid(),
557 (int) getegid(), (int) getgid());
558 sm_dprintf("main: RunAsUser = %d:%d\n",
559 (int) RunAsUid, (int) RunAsGid);
562 /* save command line arguments */
564 for (av = argv; *av != NULL; )
565 j += strlen(*av++) + 1;
566 SaveArgv = (char **) xalloc(sizeof (char *) * (argc + 1));
567 CommandLineArgs = xalloc(j);
569 for (av = argv, i = 0; *av != NULL; )
573 SaveArgv[i++] = newstr(*av);
576 (void) sm_strlcpy(p, *av++, j);
585 extern char *CompileOptions[];
587 sm_dprintf("Version %s\n Compiled with:", Version);
588 sm_printoptions(CompileOptions);
592 extern char *OsCompileOptions[];
594 sm_dprintf(" OS Defines:");
595 sm_printoptions(OsCompileOptions);
597 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
598 #endif /* _PATH_UNIX */
600 sm_dprintf(" Conf file:\t%s (default for MSP)\n",
601 getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
603 sm_dprintf(" Conf file:\t%s (default for MTA)\n",
604 getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
606 sm_dprintf(" Pid file:\t%s (default)\n", PidFile);
611 extern char *SmCompileOptions[];
613 sm_dprintf(" libsm Defines:");
614 sm_printoptions(SmCompileOptions);
619 extern char *FFRCompileOptions[];
621 sm_dprintf(" FFR Defines:");
622 sm_printoptions(FFRCompileOptions);
625 /* clear sendmail's environment */
626 ExternalEnviron = environ;
627 emptyenviron[0] = NULL;
628 environ = emptyenviron;
631 ** restore any original TZ setting until TimeZoneSpec has been
632 ** determined - or early log messages may get bogus time stamps
635 if ((p = getextenv("TZ")) != NULL)
640 /* XXX check for reasonable length? */
641 tzlen = strlen(p) + 4;
643 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
645 /* XXX check return code? */
649 /* prime the child environment */
650 setuserenv("AGENT", "sendmail");
652 (void) sm_signal(SIGPIPE, SIG_IGN);
653 OldUmask = umask(022);
654 FullName = getextenv("NAME");
655 if (FullName != NULL)
656 FullName = newstr(FullName);
659 ** Initialize name server if it is going to be used.
663 if (!bitset(RES_INIT, _res.options))
666 _res.options |= RES_DEBUG;
668 _res.options &= ~RES_DEBUG;
669 # ifdef RES_NOALIASES
670 if (bitset(RES_NOALIASES, _res.options))
672 _res.options |= RES_NOALIASES;
673 # endif /* RES_NOALIASES */
674 TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
675 TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
676 TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
677 TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
678 TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
679 TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
680 #endif /* NAMED_BIND */
685 /* initialize some macros, etc. */
686 init_vendor_macros(&BlankEnvelope);
689 macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
692 hp = myhostname(jbuf, sizeof jbuf);
695 struct utsname utsname;
698 sm_dprintf("Canonical name: %s\n", jbuf);
699 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
700 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
703 p = strchr(jbuf, '.');
708 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm',
711 while (p != NULL && strchr(&p[1], '.') != NULL)
715 sm_dprintf("\ta.k.a.: %s\n", jbuf);
722 if (uname(&utsname) >= 0)
723 p = utsname.nodename;
727 sm_dprintf("uname failed (%s)\n",
728 sm_errstring(errno));
733 sm_dprintf(" UUCP nodename: %s\n", p);
734 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
740 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
743 sm_dprintf("\ta.k.a.: %s\n", *av);
746 #if NETINET || NETINET6
747 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
751 char buf6[INET6_ADDRSTRLEN];
753 # endif /* NETINET6 */
756 # endif /* NETINET */
760 switch (hp->h_addrtype)
764 if (hp->h_length != INADDRSZ)
767 memmove(&ia, hp->h_addr_list[i], INADDRSZ);
768 (void) sm_snprintf(ipbuf, sizeof ipbuf,
769 "[%.100s]", inet_ntoa(ia));
771 # endif /* NETINET */
775 if (hp->h_length != IN6ADDRSZ)
778 memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
779 addr = anynet_ntop(&ia6, buf6, sizeof buf6);
781 (void) sm_snprintf(ipbuf, sizeof ipbuf,
784 # endif /* NETINET6 */
786 if (ipbuf[0] == '\0')
790 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
791 setclass('w', ipbuf);
793 #endif /* NETINET || NETINET6 */
797 #endif /* NETINET6 */
801 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
803 /* current load average */
806 QueueLimitRecipient = (QUEUE_CHAR *) NULL;
807 QueueLimitSender = (QUEUE_CHAR *) NULL;
808 QueueLimitId = (QUEUE_CHAR *) NULL;
810 QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
811 #endif /* _FFR_QUARANTINE */
818 while ((j = getopt(argc, argv, OPTIONS)) != -1)
822 case 'b': /* operations mode */
826 case 'A': /* use Alternate sendmail/submit.cf */
827 cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
828 : SM_GET_SENDMAIL_CF;
831 case 'B': /* body type */
832 CHECK_AGAINST_OPMODE(j);
833 BlankEnvelope.e_bodytype = newstr(optarg);
836 case 'C': /* select configuration file (already done) */
839 conffile = newstr(optarg);
840 dp = drop_privileges(true);
845 case 'd': /* debugging */
849 case 'f': /* from address */
850 case 'r': /* obsolete -f flag */
851 CHECK_AGAINST_OPMODE(j);
854 usrerr("More than one \"from\" person");
858 if (optarg[0] == '\0')
861 from = newstr(denlstring(optarg, true, true));
862 if (strcmp(RealUserName, from) != 0)
866 case 'F': /* set full name */
867 CHECK_AGAINST_OPMODE(j);
868 FullName = newstr(optarg);
871 case 'G': /* relay (gateway) submission */
873 CHECK_AGAINST_OPMODE(j);
876 case 'h': /* hop count */
877 CHECK_AGAINST_OPMODE(j);
878 BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
880 (void) sm_snprintf(buf, sizeof buf, "%d",
881 BlankEnvelope.e_hopcount);
882 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
886 usrerr("Bad hop count (%s)", optarg);
891 case 'L': /* program label */
895 case 'n': /* don't alias */
896 CHECK_AGAINST_OPMODE(j);
900 case 'N': /* delivery status notifications */
901 CHECK_AGAINST_OPMODE(j);
902 DefaultNotify |= QHASNOTIFY;
903 macdefine(&BlankEnvelope.e_macro, A_TEMP,
904 macid("{dsn_notify}"), optarg);
905 if (sm_strcasecmp(optarg, "never") == 0)
907 for (p = optarg; p != NULL; optarg = p)
912 if (sm_strcasecmp(optarg, "success") == 0)
913 DefaultNotify |= QPINGONSUCCESS;
914 else if (sm_strcasecmp(optarg, "failure") == 0)
915 DefaultNotify |= QPINGONFAILURE;
916 else if (sm_strcasecmp(optarg, "delay") == 0)
917 DefaultNotify |= QPINGONDELAY;
920 usrerr("Invalid -N argument");
926 case 'o': /* set option */
927 setoption(*optarg, optarg + 1, false, true,
931 case 'O': /* set option (long form) */
932 setoption(' ', optarg, false, true, &BlankEnvelope);
935 case 'p': /* set protocol */
936 CHECK_AGAINST_OPMODE(j);
937 p = strchr(optarg, ':');
943 ep = sm_malloc_x(strlen(p) + 1);
944 cleanstrcpy(ep, p, MAXNAME);
945 macdefine(&BlankEnvelope.e_macro,
951 ep = sm_malloc_x(strlen(optarg) + 1);
952 cleanstrcpy(ep, optarg, MAXNAME);
953 macdefine(&BlankEnvelope.e_macro, A_HEAP,
959 case 'Q': /* change quarantining on queued items */
961 if (OpMode != MD_DELIVER &&
962 OpMode != MD_QUEUERUN)
964 usrerr("Can not use -Q with -b%c", OpMode);
969 if (OpMode == MD_DELIVER)
970 set_op_mode(MD_QUEUERUN);
974 quarantining = newstr(optarg);
976 #endif /* _FFR_QUARANTINE */
978 case 'q': /* run queue files at intervals */
980 if (OpMode != MD_DELIVER &&
981 OpMode != MD_DAEMON &&
982 OpMode != MD_FGDAEMON &&
983 OpMode != MD_PRINT &&
984 OpMode != MD_PRINTNQE &&
985 OpMode != MD_QUEUERUN)
987 usrerr("Can not use -q with -b%c", OpMode);
992 /* don't override -bd, -bD or -bp */
993 if (OpMode == MD_DELIVER)
994 set_op_mode(MD_QUEUERUN);
997 negate = optarg[0] == '!';
1000 /* negate meaning of pattern match */
1001 optarg++; /* skip '!' for next switch */
1006 case 'G': /* Limit by queue group name */
1009 usrerr("Can not use -q!G");
1010 ExitStat = EX_USAGE;
1013 if (queuegroup != NULL)
1015 usrerr("Can not use multiple -qG options");
1016 ExitStat = EX_USAGE;
1019 queuegroup = newstr(&optarg[1]);
1022 case 'I': /* Limit by ID */
1023 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1024 new->queue_match = newstr(&optarg[1]);
1025 new->queue_negate = negate;
1026 new->queue_next = QueueLimitId;
1030 case 'R': /* Limit by recipient */
1031 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1032 new->queue_match = newstr(&optarg[1]);
1033 new->queue_negate = negate;
1034 new->queue_next = QueueLimitRecipient;
1035 QueueLimitRecipient = new;
1038 case 'S': /* Limit by sender */
1039 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1040 new->queue_match = newstr(&optarg[1]);
1041 new->queue_negate = negate;
1042 new->queue_next = QueueLimitSender;
1043 QueueLimitSender = new;
1046 case 'f': /* foreground queue run */
1047 foregroundqueue = true;
1051 case 'Q': /* Limit by quarantine message */
1052 if (optarg[1] != '\0')
1054 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1055 new->queue_match = newstr(&optarg[1]);
1056 new->queue_negate = negate;
1057 new->queue_next = QueueLimitQuarantine;
1058 QueueLimitQuarantine = new;
1060 QueueMode = QM_QUARANTINE;
1063 case 'L': /* act on lost items */
1064 QueueMode = QM_LOST;
1066 #endif /* _FFR_QUARANTINE */
1068 case 'p': /* Persistent queue */
1069 queuepersistent = true;
1070 if (QueueIntvl == 0)
1072 if (optarg[1] == '\0')
1079 QueueIntvl = convtime(optarg, 'm');
1082 usrerr("Invalid -q value");
1083 ExitStat = EX_USAGE;
1086 /* check for bad conversion */
1088 ExitStat = EX_USAGE;
1093 case 'R': /* DSN RET: what to return */
1094 CHECK_AGAINST_OPMODE(j);
1095 if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1097 usrerr("Duplicate -R flag");
1098 ExitStat = EX_USAGE;
1101 BlankEnvelope.e_flags |= EF_RET_PARAM;
1102 if (sm_strcasecmp(optarg, "hdrs") == 0)
1103 BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1104 else if (sm_strcasecmp(optarg, "full") != 0)
1106 usrerr("Invalid -R value");
1107 ExitStat = EX_USAGE;
1109 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1110 macid("{dsn_ret}"), optarg);
1113 case 't': /* read recipients from message */
1114 CHECK_AGAINST_OPMODE(j);
1118 case 'V': /* DSN ENVID: set "original" envelope id */
1119 CHECK_AGAINST_OPMODE(j);
1120 if (!xtextok(optarg))
1122 usrerr("Invalid syntax in -V flag");
1123 ExitStat = EX_USAGE;
1127 BlankEnvelope.e_envid = newstr(optarg);
1128 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1129 macid("{dsn_envid}"), optarg);
1133 case 'X': /* traffic log file */
1134 dp = drop_privileges(true);
1136 if (stat(optarg, &traf_st) == 0 &&
1137 S_ISFIFO(traf_st.st_mode))
1138 TrafficLogFile = sm_io_open(SmFtStdio,
1141 SM_IO_WRONLY, NULL);
1143 TrafficLogFile = sm_io_open(SmFtStdio,
1146 SM_IO_APPEND, NULL);
1147 if (TrafficLogFile == NULL)
1149 syserr("cannot open %s", optarg);
1150 ExitStat = EX_CANTCREAT;
1153 (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1154 NULL, SM_IO_LBF, 0);
1157 /* compatibility flags */
1158 case 'c': /* connect to non-local mailers */
1159 case 'i': /* don't let dot stop me */
1160 case 'm': /* send to me too */
1161 case 'T': /* set timeout interval */
1162 case 'v': /* give blow-by-blow description */
1163 setoption(j, "T", false, true, &BlankEnvelope);
1166 case 'e': /* error message disposition */
1167 case 'M': /* define macro */
1168 setoption(j, optarg, false, true, &BlankEnvelope);
1171 case 's': /* save From lines in headers */
1172 setoption('f', "T", false, true, &BlankEnvelope);
1176 case 'I': /* initialize alias DBM file */
1177 set_op_mode(MD_INITALIAS);
1181 #if defined(__osf__) || defined(_AIX3)
1182 case 'x': /* random flag that OSF/1 & AIX mailx passes */
1184 #endif /* defined(__osf__) || defined(_AIX3) */
1185 #if defined(sony_news)
1187 case 'J': /* ignore flags for Japanese code conversion
1188 implemented on Sony NEWS */
1190 #endif /* defined(sony_news) */
1193 finis(true, true, EX_USAGE);
1199 /* if we've had errors so far, exit now */
1200 if ((ExitStat != EX_OK && OpMode != MD_TEST) ||
1201 ExitStat == EX_OSERR)
1203 finis(false, true, ExitStat);
1207 if (bitset(SUBMIT_MTA, SubmitMode))
1209 /* If set daemon_flags on command line, don't reset it */
1210 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1211 macdefine(&BlankEnvelope.e_macro, A_PERM,
1212 macid("{daemon_flags}"), "CC f");
1214 else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1216 SubmitMode = SUBMIT_MSA;
1218 /* If set daemon_flags on command line, don't reset it */
1219 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1220 macdefine(&BlankEnvelope.e_macro, A_PERM,
1221 macid("{daemon_flags}"), "c u");
1225 ** Do basic initialization.
1226 ** Read system control file.
1227 ** Extract special fields for local use.
1231 checkfd012("before readcf");
1233 vendor_pre_defaults(&BlankEnvelope);
1235 readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1236 safecf, &BlankEnvelope);
1237 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1238 ConfigFileRead = true;
1239 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1240 vendor_post_defaults(&BlankEnvelope);
1242 /* now we can complain about missing fds */
1243 if (MissingFds != 0 && LogLevel > 8)
1248 if (bitset(1 << STDIN_FILENO, MissingFds))
1249 (void) sm_strlcat(mbuf, ", stdin", sizeof mbuf);
1250 if (bitset(1 << STDOUT_FILENO, MissingFds))
1251 (void) sm_strlcat(mbuf, ", stdout", sizeof mbuf);
1252 if (bitset(1 << STDERR_FILENO, MissingFds))
1253 (void) sm_strlcat(mbuf, ", stderr", sizeof mbuf);
1255 /* Notice: fill_errno is from high above: fill_fd() */
1256 sm_syslog(LOG_WARNING, NOQID,
1257 "File descriptors missing on startup: %s; %s",
1258 &mbuf[2], sm_errstring(fill_errno));
1261 /* Remove the ability for a normal user to send signals */
1262 if (RealUid != 0 && RealUid != geteuid())
1264 uid_t new_uid = geteuid();
1268 ** Since we can differentiate between uid and euid,
1269 ** make the uid a different user so the real user
1270 ** can't send signals. However, it doesn't need to be
1271 ** root (euid has root).
1277 sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1278 if (setreuid(new_uid, geteuid()) < 0)
1280 syserr("main: setreuid(%d, %d) failed",
1281 (int) new_uid, (int) geteuid());
1282 finis(false, true, EX_OSERR);
1286 sm_dprintf("Now running as e/ruid %d:%d\n",
1287 (int) geteuid(), (int) getuid());
1288 #else /* HASSETREUID */
1290 ** Have to change both effective and real so need to
1291 ** change them both to effective to keep privs.
1295 sm_dprintf("Changing uid to %d\n", (int) new_uid);
1296 if (setuid(new_uid) < 0)
1298 syserr("main: setuid(%d) failed", (int) new_uid);
1299 finis(false, true, EX_OSERR);
1303 sm_dprintf("Now running as e/ruid %d:%d\n",
1304 (int) geteuid(), (int) getuid());
1305 #endif /* HASSETREUID */
1309 if (FallBackMX != NULL)
1310 (void) getfallbackmxrr(FallBackMX);
1311 #endif /* NAMED_BIND */
1313 if (SuperSafe == SAFE_INTERACTIVE && CurEnv->e_sendmode != SM_DELIVER)
1315 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1316 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1319 if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1321 usrerr("Mail submission program cannot be used as daemon");
1322 finis(false, true, EX_USAGE);
1325 if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1326 OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1327 OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1330 /* set up the basic signal handlers */
1331 if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1332 (void) sm_signal(SIGINT, intsig);
1333 (void) sm_signal(SIGTERM, intsig);
1335 /* Enforce use of local time (null string overrides this) */
1336 if (TimeZoneSpec == NULL)
1338 else if (TimeZoneSpec[0] != '\0')
1339 setuserenv("TZ", TimeZoneSpec);
1341 setuserenv("TZ", NULL);
1344 /* initialize mailbox database */
1345 i = sm_mbdb_initialize(Mbdb);
1348 usrerr("Can't initialize mailbox database \"%s\": %s",
1349 Mbdb, sm_strexit(i));
1353 /* avoid denial-of-service attacks */
1356 if (OpMode == MD_TEST)
1358 /* can't be done after readcf if RunAs* is used */
1359 dp = drop_privileges(true);
1362 finis(false, true, dp);
1366 else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1368 /* drop privileges -- daemon mode done after socket/bind */
1369 dp = drop_privileges(false);
1371 if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1373 usrerr("Mail submission program must have RunAsUser set to non root user");
1374 finis(false, true, EX_CONFIG);
1380 _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1381 _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1382 #endif /* NAMED_BIND */
1385 ** Find our real host name for future logging.
1388 authinfo = getauthinfo(STDIN_FILENO, &forged);
1389 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1391 /* suppress error printing if errors mailed back or whatever */
1392 if (BlankEnvelope.e_errormode != EM_PRINT)
1395 /* set up the $=m class now, after .cf has a chance to redefine $m */
1396 expand("\201m", jbuf, sizeof jbuf, &BlankEnvelope);
1397 if (jbuf[0] != '\0')
1398 setclass('m', jbuf);
1400 /* probe interfaces and locate any additional names */
1401 if (DontProbeInterfaces != DPI_PROBENONE)
1406 char pidpath[MAXPATHLEN];
1408 /* Now we know which .cf file we use */
1409 sm_dprintf(" Conf file:\t%s (selected)\n",
1410 getcfname(OpMode, SubmitMode, cftype, conffile));
1411 expand(PidFile, pidpath, sizeof pidpath, &BlankEnvelope);
1412 sm_dprintf(" Pid file:\t%s (selected)\n", pidpath);
1417 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1418 sm_dprintf("\n (short domain name) $w = ");
1419 xputs(macvalue('w', &BlankEnvelope));
1420 sm_dprintf("\n (canonical domain name) $j = ");
1421 xputs(macvalue('j', &BlankEnvelope));
1422 sm_dprintf("\n (subdomain name) $m = ");
1423 xputs(macvalue('m', &BlankEnvelope));
1424 sm_dprintf("\n (node name) $k = ");
1425 xputs(macvalue('k', &BlankEnvelope));
1426 sm_dprintf("\n========================================================\n\n");
1430 ** Do more command line checking -- these are things that
1431 ** have to modify the results of reading the config file.
1434 /* process authorization warnings from command line */
1436 auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1437 RealUserName, conffile);
1438 if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1439 auth_warning(&BlankEnvelope, "Processed from queue %s",
1441 if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1442 RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1443 sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1446 /* check body type for legality */
1447 i = check_bodytype(BlankEnvelope.e_bodytype);
1448 if (i == BODYTYPE_ILLEGAL)
1450 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1451 BlankEnvelope.e_bodytype = NULL;
1453 else if (i != BODYTYPE_NONE)
1454 SevenBitInput = (i == BODYTYPE_7BIT);
1456 /* tweak default DSN notifications */
1457 if (DefaultNotify == 0)
1458 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1460 /* be sure we don't pick up bogus HOSTALIASES environment variable */
1461 if (OpMode == MD_QUEUERUN && RealUid != 0)
1462 (void) unsetenv("HOSTALIASES");
1464 /* check for sane configuration level */
1465 if (ConfigLevel > MAXCONFIGLEVEL)
1467 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1468 ConfigLevel, Version, MAXCONFIGLEVEL);
1471 /* need MCI cache to have persistence */
1472 if (HostStatDir != NULL && MaxMciCache == 0)
1475 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1476 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1479 /* need HostStatusDir in order to have SingleThreadDelivery */
1480 if (SingleThreadDelivery && HostStatDir == NULL)
1482 SingleThreadDelivery = false;
1483 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1484 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1487 /* check for permissions */
1489 RealUid != TrustedUid)
1491 char *action = NULL;
1497 if (quarantining != NULL)
1498 action = "quarantine jobs";
1500 #endif /* _FFR_QUARANTINE */
1501 /* Normal users can do a single queue run */
1502 if (QueueIntvl == 0)
1505 /* but not persistent queue runners */
1507 action = "start a queue runner daemon";
1512 action = "purge host status";
1518 action = "run daemon";
1521 sm_dprintf("Deny user %d attempt to %s\n",
1522 (int) RealUid, action);
1525 sm_syslog(LOG_ALERT, NOQID,
1526 "user %d attempted to %s",
1527 (int) RealUid, action);
1529 usrerr("Permission denied (real uid not trusted)");
1530 finis(false, true, EX_USAGE);
1535 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1538 ** If -bv and RestrictExpand,
1539 ** drop privs to prevent normal
1540 ** users from reading private
1541 ** aliases/forwards/:include:s
1545 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1548 dp = drop_privileges(true);
1550 /* Fake address safety */
1552 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1553 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1558 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1560 CurEnv->e_id = NULL;
1561 finis(true, true, dp);
1572 /* Nothing special to check */
1576 if (!wordinclass(RealUserName, 't'))
1579 sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1582 sm_syslog(LOG_ALERT, NOQID,
1583 "user %d attempted to rebuild the alias map",
1586 usrerr("Permission denied (real uid not trusted)");
1587 finis(false, true, EX_USAGE);
1593 usrerr("User %d cannot rebuild aliases in mail submission program",
1595 finis(false, true, EX_USAGE);
1601 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1605 ** If -v and RestrictExpand, reset
1606 ** Verbose to prevent normal users
1607 ** from seeing the expansion of
1608 ** aliases/forwards/:include:s
1612 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1621 BlankEnvelope.e_flags |= EF_METOO;
1626 /* don't have persistent host status in test mode */
1630 BlankEnvelope.e_errormode = EM_PRINT;
1635 BlankEnvelope.e_errormode = EM_PRINT;
1637 /* arrange to exit cleanly on hangup signal */
1638 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1639 (void) sm_signal(SIGHUP, intsig);
1641 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1642 "Notice: -bv may give misleading output for non-privileged user\n");
1646 run_in_foreground = true;
1647 set_op_mode(MD_DAEMON);
1651 vendor_daemon_setup(&BlankEnvelope);
1653 /* remove things that don't make sense in daemon mode */
1657 /* arrange to restart on hangup signal */
1658 if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1659 sm_syslog(LOG_WARNING, NOQID,
1660 "daemon invoked without full pathname; kill -1 won't work");
1665 BlankEnvelope.e_errormode = EM_PRINT;
1670 /* arrange to exit cleanly on hangup signal */
1671 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1672 (void) sm_signal(SIGHUP, intsig);
1676 /* special considerations for FullName */
1677 if (FullName != NULL)
1681 /* full names can't have newlines */
1682 if (strchr(FullName, '\n') != NULL)
1684 full = newstr(denlstring(FullName, true, true));
1688 /* check for characters that may have to be quoted */
1689 if (!rfc822_string(FullName))
1692 ** Quote a full name with special characters
1693 ** as a comment so crackaddr() doesn't destroy
1694 ** the name portion of the address.
1697 FullName = addquotes(FullName, NULL);
1699 sm_free(full); /* XXX */
1703 /* do heuristic mode adjustment */
1706 /* turn off noconnect option */
1707 setoption('c', "F", true, false, &BlankEnvelope);
1709 /* turn on interactive delivery */
1710 setoption('d', "", true, false, &BlankEnvelope);
1714 /* check for vendor mismatch */
1715 if (VendorCode != VENDOR_CODE)
1717 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1718 getvendor(VENDOR_CODE), getvendor(VendorCode));
1720 #endif /* VENDOR_CODE */
1722 /* check for out of date configuration level */
1723 if (ConfigLevel < MAXCONFIGLEVEL)
1725 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1726 Version, MAXCONFIGLEVEL, ConfigLevel);
1729 if (ConfigLevel < 3)
1732 /* set options that were previous macros */
1733 if (SmtpGreeting == NULL)
1735 if (ConfigLevel < 7 &&
1736 (p = macvalue('e', &BlankEnvelope)) != NULL)
1737 SmtpGreeting = newstr(p);
1739 SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1741 if (UnixFromLine == NULL)
1743 if (ConfigLevel < 7 &&
1744 (p = macvalue('l', &BlankEnvelope)) != NULL)
1745 UnixFromLine = newstr(p);
1747 UnixFromLine = "From \201g \201d";
1749 SmtpError[0] = '\0';
1751 /* our name for SMTP codes */
1752 expand("\201j", jbuf, sizeof jbuf, &BlankEnvelope);
1753 if (jbuf[0] == '\0')
1754 PSTRSET(MyHostName, "localhost");
1756 PSTRSET(MyHostName, jbuf);
1757 if (strchr(MyHostName, '.') == NULL)
1758 message("WARNING: local host name (%s) is not qualified; fix $j in config file",
1761 /* make certain that this name is part of the $=w class */
1762 setclass('w', MyHostName);
1764 /* fill in the structure of the *default* queue */
1765 st = stab("mqueue", ST_QUEUE, ST_FIND);
1767 syserr("No default queue (mqueue) defined");
1769 set_def_queueval(st->s_quegrp, true);
1771 /* the indices of built-in mailers */
1772 st = stab("local", ST_MAILER, ST_FIND);
1774 LocalMailer = st->s_mailer;
1775 else if (OpMode != MD_TEST || !warn_C_flag)
1776 syserr("No local mailer defined");
1778 st = stab("prog", ST_MAILER, ST_FIND);
1780 syserr("No prog mailer defined");
1783 ProgMailer = st->s_mailer;
1784 clrbitn(M_MUSER, ProgMailer->m_flags);
1787 st = stab("*file*", ST_MAILER, ST_FIND);
1789 syserr("No *file* mailer defined");
1792 FileMailer = st->s_mailer;
1793 clrbitn(M_MUSER, FileMailer->m_flags);
1796 st = stab("*include*", ST_MAILER, ST_FIND);
1798 syserr("No *include* mailer defined");
1800 InclMailer = st->s_mailer;
1802 if (ConfigLevel < 6)
1804 /* heuristic tweaking of local mailer for back compat */
1805 if (LocalMailer != NULL)
1807 setbitn(M_ALIASABLE, LocalMailer->m_flags);
1808 setbitn(M_HASPWENT, LocalMailer->m_flags);
1809 setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1810 setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1811 setbitn(M_CHECKPROG, LocalMailer->m_flags);
1812 setbitn(M_CHECKFILE, LocalMailer->m_flags);
1813 setbitn(M_CHECKUDB, LocalMailer->m_flags);
1815 if (ProgMailer != NULL)
1816 setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1817 if (FileMailer != NULL)
1818 setbitn(M_RUNASRCPT, FileMailer->m_flags);
1820 if (ConfigLevel < 7)
1822 if (LocalMailer != NULL)
1823 setbitn(M_VRFY250, LocalMailer->m_flags);
1824 if (ProgMailer != NULL)
1825 setbitn(M_VRFY250, ProgMailer->m_flags);
1826 if (FileMailer != NULL)
1827 setbitn(M_VRFY250, FileMailer->m_flags);
1830 /* MIME Content-Types that cannot be transfer encoded */
1831 setclass('n', "multipart/signed");
1833 /* MIME message/xxx subtypes that can be treated as messages */
1834 setclass('s', "rfc822");
1836 /* MIME Content-Transfer-Encodings that can be encoded */
1837 setclass('e', "7bit");
1838 setclass('e', "8bit");
1839 setclass('e', "binary");
1842 /* MIME Content-Types that should be treated as binary */
1843 setclass('b', "image");
1844 setclass('b', "audio");
1845 setclass('b', "video");
1846 setclass('b', "application/octet-stream");
1847 #endif /* USE_B_CLASS */
1849 /* MIME headers which have fields to check for overflow */
1850 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1851 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1853 /* MIME headers to check for length overflow */
1854 setclass(macid("{checkMIMETextHeaders}"), "content-description");
1856 /* MIME headers to check for overflow and rebalance */
1857 setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1858 setclass(macid("{checkMIMEHeaders}"), "content-id");
1859 setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1860 setclass(macid("{checkMIMEHeaders}"), "content-type");
1861 setclass(macid("{checkMIMEHeaders}"), "mime-version");
1863 /* Macros to save in the queue file -- don't remove any */
1864 setclass(macid("{persistentMacros}"), "r");
1865 setclass(macid("{persistentMacros}"), "s");
1866 setclass(macid("{persistentMacros}"), "_");
1867 setclass(macid("{persistentMacros}"), "{if_addr}");
1868 setclass(macid("{persistentMacros}"), "{daemon_flags}");
1870 /* operate in queue directory */
1871 if (QueueDir == NULL || *QueueDir == '\0')
1873 if (OpMode != MD_TEST)
1875 syserr("QueueDirectory (Q) option must be set");
1876 ExitStat = EX_CONFIG;
1881 if (OpMode != MD_TEST)
1882 setup_queues(OpMode == MD_DAEMON);
1885 /* check host status directory for validity */
1886 if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1888 /* cannot use this value */
1889 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1890 "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1891 HostStatDir, sm_errstring(errno));
1895 if (OpMode == MD_QUEUERUN &&
1896 RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1900 /* check to see if we own the queue directory */
1901 if (stat(".", &stbuf) < 0)
1902 syserr("main: cannot stat %s", QueueDir);
1903 if (stbuf.st_uid != RealUid)
1905 /* nope, really a botch */
1907 usrerr("You do not have permission to process the queue");
1908 finis(false, true, EX_NOPERM);
1914 /* sanity checks on milter filters */
1915 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1917 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1918 # if _FFR_MILTER_PERDAEMON
1919 setup_daemon_milters();
1920 # endif /* _FFR_MILTER_PERDAEMON */
1924 /* Convert queuegroup string to qgrp number */
1925 if (queuegroup != NULL)
1927 qgrp = name2qid(queuegroup);
1931 usrerr("Queue group %s unknown", queuegroup);
1932 finis(false, true, ExitStat);
1937 /* if we've had errors so far, exit now */
1938 if (ExitStat != EX_OK && OpMode != MD_TEST)
1940 finis(false, true, ExitStat);
1945 /* sendmail specific SASL initialization */
1950 checkfd012("before main() initmaps");
1954 ** Do operation-mode-dependent initialization.
1960 /* print the queue */
1962 dropenvelope(&BlankEnvelope, true, false);
1963 (void) sm_signal(SIGPIPE, sigpipe);
1968 /* Selecting a particular queue group to run */
1969 for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1973 (void) print_single_queue(qgrp, j);
1975 finis(false, true, EX_OK);
1979 finis(false, true, EX_OK);
1984 /* print number of entries in queue */
1985 dropenvelope(&BlankEnvelope, true, false);
1986 (void) sm_signal(SIGPIPE, sigpipe);
1987 printnqe(smioout, NULL);
1988 finis(false, true, EX_OK);
1994 /* only handle quarantining here */
1995 if (quarantining == NULL)
1998 if (QueueMode != QM_QUARANTINE &&
1999 QueueMode != QM_NORMAL)
2002 usrerr("Can not use -Q with -q%c", QueueMode);
2003 ExitStat = EX_USAGE;
2004 finis(false, true, ExitStat);
2007 quarantine_queue(quarantining, qgrp);
2008 finis(false, true, EX_OK);
2010 #endif /* _FFR_QUARANTINE */
2013 (void) sm_signal(SIGPIPE, sigpipe);
2014 (void) mci_traverse_persistent(mci_print_persistent, NULL);
2015 finis(false, true, EX_OK);
2020 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2021 finis(false, true, EX_OK);
2026 /* initialize maps */
2028 finis(false, true, ExitStat);
2034 /* reset DSN parameters */
2035 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2036 macdefine(&BlankEnvelope.e_macro, A_PERM,
2037 macid("{dsn_notify}"), NULL);
2038 BlankEnvelope.e_envid = NULL;
2039 macdefine(&BlankEnvelope.e_macro, A_PERM,
2040 macid("{dsn_envid}"), NULL);
2041 BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2042 macdefine(&BlankEnvelope.e_macro, A_PERM,
2043 macid("{dsn_ret}"), NULL);
2045 /* don't open maps for daemon -- done below in child */
2051 /* print configuration table (or at least part of it) */
2054 for (i = 0; i < MAXMAILERS; i++)
2056 if (Mailer[i] != NULL)
2057 printmailer(Mailer[i]);
2062 ** Switch to the main envelope.
2065 CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2066 sm_rpool_new_x(NULL));
2067 MainEnvelope.e_flags = BlankEnvelope.e_flags;
2070 ** If test mode, read addresses from stdin and process.
2073 if (OpMode == MD_TEST)
2075 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2080 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2081 "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2082 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2083 "Enter <ruleset> <address>\n");
2085 macdefine(&(MainEnvelope.e_macro), A_PERM,
2086 macid("{addr_type}"), "e r");
2091 (void) sm_signal(SIGINT, intindebug);
2092 (void) sm_releasesignal(SIGINT);
2094 (void) sm_io_fprintf(smioout,
2097 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2098 if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2099 sizeof buf) == NULL)
2100 testmodeline("/quit", &MainEnvelope);
2101 p = strchr(buf, '\n');
2105 (void) sm_io_fprintf(smioout,
2108 testmodeline(buf, &MainEnvelope);
2110 SM_EXCEPT(exc, "[!F]*")
2113 ** 8.10 just prints \n on interrupt.
2114 ** I'm printing the exception here in case
2115 ** sendmail is extended to raise additional
2116 ** exceptions in this context.
2119 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2121 sm_exc_print(exc, smioout);
2129 if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER)
2131 /* check whether STARTTLS is turned off for the client */
2132 if (chkclientmodifiers(D_NOTLS))
2135 else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2138 /* check whether STARTTLS is turned off for the server */
2139 if (chkdaemonmodifiers(D_NOTLS))
2142 else /* other modes don't need STARTTLS */
2147 /* basic TLS initialization */
2148 tls_ok = init_tls_library();
2151 if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2153 /* disable TLS for client */
2156 #endif /* STARTTLS */
2159 ** If collecting stuff from the queue, go start doing that.
2162 if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2167 /* init TLS for client, ignore result for now */
2168 (void) initclttls(tls_ok);
2169 #endif /* STARTTLS */
2172 ** The parent process of the caller of runqueue() needs
2173 ** to stay around for a possible SIGTERM. The SIGTERM will
2174 ** tell this process that all of the queue runners children
2175 ** need to be sent SIGTERM as well. At the same time, we
2176 ** want to return control to the command line. So we do an
2180 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2183 ** If the fork() failed we should still try to do
2184 ** the queue run. If it succeeded then the child
2185 ** is going to start the run and wait for all
2186 ** of the children to finish.
2191 /* Reset global flags */
2192 RestartRequest = NULL;
2193 ShutdownRequest = NULL;
2196 /* disconnect from terminal */
2197 disconnect(2, CurEnv);
2200 CurrentPid = getpid();
2203 int rwgflags = RWG_NONE;
2206 ** To run a specific queue group mark it to
2207 ** be run, select the work group it's in and
2208 ** increment the work counter.
2211 for (i = 0; i < NumQueue && Queue[i] != NULL;
2213 Queue[i]->qg_nextrun = (time_t) -1;
2214 Queue[qgrp]->qg_nextrun = 0;
2216 rwgflags |= RWG_VERBOSE;
2217 if (queuepersistent)
2218 rwgflags |= RWG_PERSISTENT;
2219 rwgflags |= RWG_FORCE;
2220 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2224 (void) runqueue(false, Verbose,
2225 queuepersistent, true);
2227 /* set the title to make it easier to find */
2228 sm_setproctitle(true, CurEnv, "Queue control");
2229 (void) sm_signal(SIGCHLD, SIG_DFL);
2230 while (CurChildren > 0)
2235 while ((ret = sm_wait(&status)) <= 0)
2238 /* Only drop when a child gives status */
2239 if (WIFSTOPPED(status))
2242 proc_list_drop(ret, status, NULL);
2245 finis(true, true, ExitStat);
2250 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2252 /* check whether AUTH is turned off for the server */
2253 if (!chkdaemonmodifiers(D_NOAUTH) &&
2254 (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2255 syserr("!sasl_server_init failed! [%s]",
2256 sasl_errstring(i, NULL, NULL));
2260 if (OpMode == MD_SMTP)
2262 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2263 PROC_DAEMON, 0, -1);
2265 /* clean up background delivery children */
2266 (void) sm_signal(SIGCHLD, reapchild);
2270 ** If a daemon, wait for a request.
2271 ** getrequests will always return in a child.
2272 ** If we should also be processing the queue, start
2273 ** doing it in background.
2274 ** We check for any errors that might have happened
2278 if (OpMode == MD_DAEMON || QueueIntvl > 0)
2282 if (!run_in_foreground && !tTd(99, 100))
2284 /* put us in background */
2287 syserr("daemon: cannot fork");
2290 finis(false, true, EX_OK);
2295 ** Initialize exception stack and default exception
2296 ** handler for child process.
2299 /* Reset global flags */
2300 RestartRequest = NULL;
2301 RestartWorkGroup = false;
2302 ShutdownRequest = NULL;
2304 CurrentPid = getpid();
2306 sm_exc_newthread(fatal_error);
2308 /* disconnect from our controlling tty */
2309 disconnect(2, &MainEnvelope);
2313 if (OpMode == MD_DAEMON)
2315 (void) sm_strlcat(dtype, "+SMTP", sizeof dtype);
2316 DaemonPid = CurrentPid;
2320 (void) sm_strlcat2(dtype,
2322 ? "+persistent-queueing@"
2324 pintvl(QueueIntvl, true),
2328 (void) sm_strlcat(dtype, "+debugging", sizeof dtype);
2330 sm_syslog(LOG_INFO, NOQID,
2331 "starting daemon (%s): %s", Version, dtype + 1);
2336 /* save daemon type in a macro for possible PidFile use */
2337 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2338 macid("{daemon_info}"), dtype + 1);
2340 /* save queue interval in a macro for possible PidFile use */
2341 macdefine(&MainEnvelope.e_macro, A_TEMP,
2342 macid("{queue_interval}"), pintvl(QueueIntvl, true));
2344 /* workaround: can't seem to release the signal in the parent */
2345 (void) sm_signal(SIGHUP, sighup);
2346 (void) sm_releasesignal(SIGHUP);
2347 (void) sm_signal(SIGTERM, sigterm);
2351 (void) runqueue(true, false, queuepersistent, true);
2354 ** If queuepersistent but not in daemon mode then
2355 ** we're going to do the queue runner monitoring here.
2356 ** If in daemon mode then the monitoring will happen
2360 if (OpMode != MD_DAEMON && queuepersistent)
2362 /* set the title to make it easier to find */
2363 sm_setproctitle(true, CurEnv, "Queue control");
2364 (void) sm_signal(SIGCHLD, SIG_DFL);
2365 while (CurChildren > 0)
2371 if (ShutdownRequest != NULL)
2373 else if (RestartRequest != NULL)
2375 else if (RestartWorkGroup)
2376 restart_marked_work_groups();
2378 while ((ret = sm_wait(&status)) <= 0)
2381 if (WIFSTOPPED(status))
2384 /* Probe only on a child status */
2385 proc_list_drop(ret, status, &group);
2387 if (WIFSIGNALED(status))
2389 if (WCOREDUMP(status))
2391 sm_syslog(LOG_ERR, NOQID,
2392 "persistent queue runner=%d core dumped, signal=%d",
2393 group, WTERMSIG(status));
2395 /* don't restart this one */
2396 mark_work_group_restart(group, -1);
2400 sm_syslog(LOG_ERR, NOQID,
2401 "persistent queue runner=%d died, signal=%d",
2402 group, WTERMSIG(status));
2406 ** When debugging active, don't
2407 ** restart the persistent queues.
2408 ** But do log this as info.
2411 if (sm_debug_active(&DebugNoPRestart,
2414 sm_syslog(LOG_DEBUG, NOQID,
2415 "persistent queue runner=%d, exited",
2417 mark_work_group_restart(group, -1);
2420 finis(true, true, ExitStat);
2424 if (OpMode != MD_DAEMON)
2429 ** Write the pid to file
2430 ** XXX Overwrites sendmail.pid
2433 log_sendmail_pid(&MainEnvelope);
2435 /* set the title to make it easier to find */
2437 (void) sm_strlcpyn(qtype, sizeof qtype, 4,
2439 pintvl(QueueIntvl, true),
2442 sm_setproctitle(true, CurEnv, qtype);
2446 if (ShutdownRequest != NULL)
2448 else if (RestartRequest != NULL)
2450 else if (RestartWorkGroup)
2451 restart_marked_work_groups();
2454 (void) runqueue(true, false,
2459 dropenvelope(&MainEnvelope, true, false);
2462 /* init TLS for server, ignore result for now */
2463 (void) initsrvtls(tls_ok);
2464 #endif /* STARTTLS */
2467 p_flags = getrequests(&MainEnvelope);
2469 /* drop privileges */
2470 (void) drop_privileges(false);
2473 ** Get authentication data
2474 ** Set _ macro in BlankEnvelope before calling newenvelope().
2477 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2479 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2481 /* at this point we are in a child: reset state */
2482 sm_rpool_free(MainEnvelope.e_rpool);
2483 (void) newenvelope(&MainEnvelope, &MainEnvelope,
2484 sm_rpool_new_x(NULL));
2489 /* log connection information */
2490 sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2494 ** If running SMTP protocol, start collecting and executing
2495 ** commands. This will never return.
2498 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2503 ** Save some macros for check_* rulesets.
2510 (void) sm_snprintf(ipbuf, sizeof ipbuf, "[%.100s]",
2511 anynet_ntoa(&RealHostAddr));
2512 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2513 macid("{client_name}"), ipbuf);
2516 macdefine(&BlankEnvelope.e_macro, A_PERM,
2517 macid("{client_name}"), RealHostName);
2518 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2519 macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2522 switch (RealHostAddr.sa.sa_family)
2526 (void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2527 RealHostAddr.sin.sin_port);
2529 #endif /* NETINET */
2532 (void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2533 RealHostAddr.sin6.sin6_port);
2535 #endif /* NETINET6 */
2537 (void) sm_snprintf(pbuf, sizeof pbuf, "0");
2540 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2541 macid("{client_port}"), pbuf);
2543 if (OpMode == MD_DAEMON)
2545 /* validate the connection */
2547 nullserver = validate_connection(&RealHostAddr,
2552 else if (p_flags == NULL)
2554 p_flags = (BITMAP256 *) xalloc(sizeof *p_flags);
2558 if (OpMode == MD_SMTP)
2559 (void) initsrvtls(tls_ok);
2560 #endif /* STARTTLS */
2562 /* turn off profiling */
2564 smtp(nullserver, *p_flags, &MainEnvelope);
2568 /* turn off profiling */
2570 if (OpMode == MD_DAEMON)
2575 sm_rpool_free(MainEnvelope.e_rpool);
2576 clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2577 if (OpMode == MD_VERIFY)
2579 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2580 PostMasterCopy = NULL;
2584 /* interactive -- all errors are global */
2585 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2589 ** Do basic system initialization and set the sender
2592 initsys(&MainEnvelope);
2593 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2594 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2595 setsender(from, &MainEnvelope, NULL, '\0', false);
2596 if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2597 (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2598 strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2600 auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2601 RealUserName, from, warn_f_flag);
2610 /* set the initial sender for AUTH= to $f@$j */
2611 fv = macvalue('f', &MainEnvelope);
2612 if (fv == NULL || *fv == '\0')
2613 MainEnvelope.e_auth_param = NULL;
2616 if (strchr(fv, '@') == NULL)
2618 i = strlen(fv) + strlen(macvalue('j',
2619 &MainEnvelope)) + 2;
2621 (void) sm_strlcpyn(p, i, 3, fv, "@",
2626 p = sm_strdup_x(fv);
2627 MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2629 sm_free(p); /* XXX */
2632 if (macvalue('s', &MainEnvelope) == NULL)
2633 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2636 if (*av == NULL && !GrabTo)
2638 MainEnvelope.e_to = NULL;
2639 MainEnvelope.e_flags |= EF_GLOBALERRS;
2641 SuperSafe = SAFE_NO;
2642 usrerr("Recipient names must be specified");
2644 /* collect body for UUCP return */
2645 if (OpMode != MD_VERIFY)
2646 collect(InChannel, false, NULL, &MainEnvelope);
2647 finis(true, true, EX_USAGE);
2652 ** Scan argv and deliver the message to everyone.
2655 save_val = LogUsrErrs;
2657 sendtoargv(av, &MainEnvelope);
2658 LogUsrErrs = save_val;
2660 /* if we have had errors sofar, arrange a meaningful exit stat */
2661 if (Errors > 0 && ExitStat == EX_OK)
2662 ExitStat = EX_USAGE;
2666 ** If using -t, force not sending to argv recipients, even
2667 ** if they are mentioned in the headers.
2674 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2675 q->q_state = QS_REMOVED;
2677 #endif /* _FFR_FIX_DASHT */
2680 ** Read the input mail.
2683 MainEnvelope.e_to = NULL;
2684 if (OpMode != MD_VERIFY || GrabTo)
2687 unsigned long savedflags;
2690 ** workaround for compiler warning on Irix:
2691 ** do not initialize variable in the definition, but
2693 ** warning(1548): transfer of control bypasses
2694 ** initialization of:
2695 ** variable "savederrors" (declared at line 2570)
2696 ** variable "savedflags" (declared at line 2571)
2700 savederrors = Errors;
2701 savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2702 MainEnvelope.e_flags |= EF_GLOBALERRS;
2703 MainEnvelope.e_flags &= ~EF_FATALERRS;
2706 collect(InChannel, false, NULL, &MainEnvelope);
2708 /* header checks failed */
2714 /* Log who the mail would have gone to */
2715 logundelrcpts(&MainEnvelope,
2716 MainEnvelope.e_message,
2720 finis(true, true, ExitStat);
2725 /* bail out if message too large */
2726 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2728 finis(true, true, ExitStat != EX_OK ? ExitStat
2734 /* set message size */
2735 (void) sm_snprintf(buf, sizeof buf, "%ld",
2736 MainEnvelope.e_msgsize);
2737 macdefine(&MainEnvelope.e_macro, A_TEMP,
2738 macid("{msg_size}"), buf);
2740 Errors = savederrors;
2741 MainEnvelope.e_flags |= savedflags;
2746 sm_dprintf("From person = \"%s\"\n",
2747 MainEnvelope.e_from.q_paddr);
2750 /* Check if quarantining stats should be updated */
2751 if (MainEnvelope.e_quarmsg != NULL)
2752 markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2753 #endif /* _FFR_QUARANTINE */
2756 ** Actually send everything.
2757 ** If verifying, just ack.
2762 if (!split_by_recipient(&MainEnvelope) &&
2763 bitset(EF_FATALERRS, MainEnvelope.e_flags))
2767 /* make sure we deliver at least the first envelope */
2768 i = FastSplit > 0 ? 0 : -1;
2769 for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2773 e->e_from.q_state = QS_SENDER;
2776 sm_dprintf("main[%d]: QS_SENDER ", i);
2777 printaddr(&e->e_from, false);
2783 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2784 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2785 #endif /* NAMED_BIND */
2786 next = e->e_sibling;
2787 e->e_sibling = NULL;
2789 /* after FastSplit envelopes: queue up */
2790 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2791 e->e_sibling = next;
2796 ** Don't send return error message if in VERIFY mode.
2799 finis(true, true, ExitStat);
2804 ** STOP_SENDMAIL -- Stop the running program
2819 /* reset uid for process accounting */
2821 (void) setuid(RealUid);
2825 ** FINIS -- Clean up and exit.
2828 ** drop -- whether or not to drop CurEnv envelope
2829 ** cleanup -- call exit() or _exit()?
2830 ** exitstat -- exit status to use for exit() call
2840 finis(drop, cleanup, exitstat)
2843 volatile int exitstat;
2846 /* Still want to process new timeouts added below */
2848 (void) sm_releasesignal(SIGALRM);
2852 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2854 CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2855 printenvflags(CurEnv);
2858 printopenfds(false);
2862 ** Clean up. This might raise E:mta.quickabort
2865 /* clean up temp files */
2866 CurEnv->e_to = NULL;
2869 if (CurEnv->e_id != NULL)
2871 dropenvelope(CurEnv, true, false);
2872 sm_rpool_free(CurEnv->e_rpool);
2873 CurEnv->e_rpool = NULL;
2876 poststats(StatFile);
2879 /* flush any cached connections */
2880 mci_flush(true, NULL);
2882 /* close maps belonging to this pid */
2886 /* close UserDatabase */
2895 /* clean up extended load average stuff */
2905 sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
2907 if (exitstat == EX_TEMPFAIL ||
2908 CurEnv->e_errormode == EM_BERKNET)
2911 /* XXX clean up queues and related data structures */
2914 cleanup_shm(DaemonPid == getpid());
2915 #endif /* SM_CONF_SHM */
2917 /* reset uid for process accounting */
2919 sm_mbdb_terminate();
2920 (void) setuid(RealUid);
2922 /* dump the heap, if we are checking for memory leaks */
2923 if (sm_debug_active(&SmHeapCheck, 2))
2924 sm_heap_report(smioout,
2925 sm_debug_level(&SmHeapCheck) - 1);
2926 #endif /* SM_HEAP_CHECK */
2927 if (sm_debug_active(&SmXtrapReport, 1))
2928 sm_dprintf("xtrap count = %d\n", SmXtrapCount);
2936 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
2939 ** sig -- incoming signal.
2945 ** longjmps back to test mode loop.
2947 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2948 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2952 /* Type of an exception generated on SIGINT during address test mode. */
2953 static const SM_EXC_TYPE_T EtypeInterrupt =
2967 int save_errno = errno;
2969 FIX_SYSV_SIGNAL(sig, intindebug);
2971 CHECK_CRITICAL(sig);
2973 sm_exc_raisenew_x(&EtypeInterrupt);
2975 return SIGFUNC_RETURN;
2978 ** SIGTERM -- SIGTERM handler for the daemon
2981 ** sig -- signal number.
2987 ** Sets ShutdownRequest which will hopefully trigger
2988 ** the daemon to exit.
2990 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2991 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3000 int save_errno = errno;
3002 FIX_SYSV_SIGNAL(sig, sigterm);
3003 ShutdownRequest = "signal";
3005 return SIGFUNC_RETURN;
3008 ** SIGHUP -- handle a SIGHUP signal
3011 ** sig -- incoming signal.
3017 ** Sets RestartRequest which should cause the daemon
3020 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3021 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3030 int save_errno = errno;
3032 FIX_SYSV_SIGNAL(sig, sighup);
3033 RestartRequest = "signal";
3035 return SIGFUNC_RETURN;
3038 ** SIGPIPE -- signal handler for SIGPIPE
3041 ** sig -- incoming signal.
3047 ** Sets StopRequest which should cause the mailq/hoststatus
3050 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3051 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3060 int save_errno = errno;
3062 FIX_SYSV_SIGNAL(sig, sigpipe);
3065 return SIGFUNC_RETURN;
3068 ** INTSIG -- clean up on interrupt
3070 ** This just arranges to exit. It pessimizes in that it
3071 ** may resend a message.
3080 ** Unlocks the current job.
3082 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3083 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3086 ** XXX: More work is needed for this signal handler.
3095 int save_errno = errno;
3097 FIX_SYSV_SIGNAL(sig, intsig);
3099 CHECK_CRITICAL(sig);
3100 sm_allsignals(true);
3102 if (sig != 0 && LogLevel > 79)
3103 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3106 /* Clean-up on aborted stdin message submission */
3107 if (CurEnv->e_id != NULL &&
3108 (OpMode == MD_SMTP ||
3109 OpMode == MD_DELIVER ||
3110 OpMode == MD_ARPAFTP))
3112 register ADDRESS *q;
3114 /* don't return an error indication */
3115 CurEnv->e_to = NULL;
3116 CurEnv->e_flags &= ~EF_FATALERRS;
3117 CurEnv->e_flags |= EF_CLRQUEUE;
3120 ** Spin through the addresses and
3121 ** mark them dead to prevent bounces
3124 for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
3125 q->q_state = QS_DONTSEND;
3129 else if (OpMode != MD_TEST)
3131 unlockqueue(CurEnv);
3134 finis(drop, false, EX_OK);
3138 ** DISCONNECT -- remove our connection with any foreground process
3141 ** droplev -- how "deeply" we should drop the line.
3142 ** 0 -- ignore signals, mail back errors, make sure
3143 ** output goes to stdout.
3144 ** 1 -- also, make stdout go to /dev/null.
3145 ** 2 -- also, disconnect from controlling terminal
3146 ** (only for daemon mode).
3147 ** e -- the current envelope.
3153 ** Trys to insure that we are immune to vagaries of
3154 ** the controlling tty.
3158 disconnect(droplev, e)
3160 register ENVELOPE *e;
3165 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3166 sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3167 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3170 sm_dprintf("don't\n");
3174 sm_syslog(LOG_DEBUG, e->e_id,
3175 "disconnect level %d",
3178 /* be sure we don't get nasty signals */
3179 (void) sm_signal(SIGINT, SIG_IGN);
3180 (void) sm_signal(SIGQUIT, SIG_IGN);
3182 /* we can't communicate with our caller, so.... */
3184 CurEnv->e_errormode = EM_MAIL;
3186 DisConnected = true;
3188 /* all input from /dev/null */
3189 if (InChannel != smioin)
3191 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3194 if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3195 SM_IO_RDONLY, NULL, smioin) == NULL)
3196 sm_syslog(LOG_ERR, e->e_id,
3197 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3198 SM_PATH_DEVNULL, sm_errstring(errno));
3201 ** output to the transcript
3202 ** We also compare the fd numbers here since OutChannel
3203 ** might be a layer on top of smioout due to encryption
3207 if (OutChannel != smioout &&
3208 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3209 sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3211 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3212 OutChannel = smioout;
3216 ** Has smioout been closed? Reopen it.
3217 ** This shouldn't happen anymore, the code is here
3218 ** just as a reminder.
3221 if (smioout->sm_magic == NULL &&
3222 sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3223 SM_IO_WRONLY, NULL, smioout) == NULL)
3224 sm_syslog(LOG_ERR, e->e_id,
3225 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3226 SM_PATH_DEVNULL, sm_errstring(errno));
3231 fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3233 sm_syslog(LOG_ERR, e->e_id,
3234 "disconnect: open(\"%s\") failed: %s",
3235 SM_PATH_DEVNULL, sm_errstring(errno));
3236 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3237 (void) dup2(fd, STDOUT_FILENO);
3238 (void) dup2(fd, STDERR_FILENO);
3242 /* drop our controlling TTY completely if possible */
3250 checkfd012("disconnect");
3254 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3267 while ((ap = *++argv) != NULL)
3269 /* Return if "--" or not an option of any form. */
3270 if (ap[0] != '-' || ap[1] == '-')
3274 /* Don't allow users to use "-Q." or "-Q ." */
3275 if ((ap[1] == 'Q' && ap[2] == '.') ||
3276 (ap[1] == 'Q' && argv[1] != NULL &&
3277 argv[1][0] == '.' && argv[1][1] == '\0'))
3279 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3280 "Can not use -Q.\n");
3283 #endif /* _FFR_QUARANTINE */
3285 /* skip over options that do have a value */
3286 op = strchr(OPTIONS, ap[1]);
3287 if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3289 #if defined(sony_news)
3290 ap[1] != 'E' && ap[1] != 'J' &&
3291 #endif /* defined(sony_news) */
3292 argv[1] != NULL && argv[1][0] != '-')
3298 /* If -C doesn't have an argument, use sendmail.cf. */
3299 #define __DEFPATH "sendmail.cf"
3300 if (ap[1] == 'C' && ap[2] == '\0')
3302 *argv = xalloc(sizeof(__DEFPATH) + 2);
3303 (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3307 /* If -q doesn't have an argument, run it once. */
3308 if (ap[1] == 'q' && ap[2] == '\0')
3312 /* If -Q doesn't have an argument, disable quarantining */
3313 if (ap[1] == 'Q' && ap[2] == '\0')
3315 #endif /* _FFR_QUARANTINE */
3317 /* if -d doesn't have an argument, use 0-99.1 */
3318 if (ap[1] == 'd' && ap[2] == '\0')
3321 #if defined(sony_news)
3322 /* if -E doesn't have an argument, use -EC */
3323 if (ap[1] == 'E' && ap[2] == '\0')
3326 /* if -J doesn't have an argument, use -JJ */
3327 if (ap[1] == 'J' && ap[2] == '\0')
3329 #endif /* defined(sony_news) */
3333 ** AUTH_WARNING -- specify authorization warning
3336 ** e -- the current envelope.
3337 ** msg -- the text of the message.
3338 ** args -- arguments to the message.
3346 auth_warning(register ENVELOPE *e, const char *msg, ...)
3347 #else /* __STDC__ */
3348 auth_warning(e, msg, va_alist)
3349 register ENVELOPE *e;
3352 #endif /* __STDC__ */
3357 if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3360 static char hostbuf[48];
3362 if (hostbuf[0] == '\0')
3366 hp = myhostname(hostbuf, sizeof hostbuf);
3373 #endif /* NETINET6 */
3376 (void) sm_strlcpyn(buf, sizeof buf, 2, hostbuf, ": ");
3377 p = &buf[strlen(buf)];
3378 SM_VA_START(ap, msg);
3379 (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3381 addheader("X-Authentication-Warning", buf, 0, e);
3383 sm_syslog(LOG_INFO, e->e_id,
3384 "Authentication-Warning: %.400s",
3389 ** GETEXTENV -- get from external environment
3392 ** envar -- the name of the variable to retrieve
3395 ** The value, if any.
3406 for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3408 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3409 return &(*envp)[l + 1];
3414 ** SETUSERENV -- set an environment in the propagated environment
3417 ** envar -- the name of the environment variable.
3418 ** value -- the value to which it should be set. If
3419 ** null, this is extracted from the incoming
3420 ** environment. If that is not set, the call
3421 ** to setuserenv is ignored.
3428 setuserenv(envar, value)
3433 char **evp = UserEnviron;
3438 value = getextenv(envar);
3443 /* XXX enforce reasonable size? */
3444 i = strlen(envar) + 1;
3445 l = strlen(value) + i + 1;
3446 p = (char *) xalloc(l);
3447 (void) sm_strlcpyn(p, l, 3, envar, "=", value);
3449 while (*evp != NULL && strncmp(*evp, p, i) != 0)
3455 else if (evp < &UserEnviron[MAXUSERENVIRON])
3461 /* make sure it is in our environment as well */
3463 syserr("setuserenv: putenv(%s) failed", p);
3466 ** DUMPSTATE -- dump state
3475 register char *j = macvalue('j', CurEnv);
3477 extern int NextMacroId;
3479 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3480 "--- dumping state on %s: $j = %s ---",
3482 j == NULL ? "<NULL>" : j);
3485 if (!wordinclass(j, 'w'))
3486 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3487 "*** $j not in $=w ***");
3489 sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3490 sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3491 NextMacroId, MAXMACROID);
3492 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3494 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3496 rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3500 register char **pvp;
3501 char *pv[MAXATOM + 1];
3504 status = REWRITE(pv, rs, CurEnv);
3505 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3506 "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3508 for (pvp = pv; *pvp != NULL; pvp++)
3509 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3511 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3516 ** SIGUSR1 -- Signal a request to dump state.
3519 ** sig -- calling signal.
3524 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3525 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3528 ** XXX: More work is needed for this signal handler.
3536 int save_errno = errno;
3538 extern void dumpstab __P((void));
3539 # endif /* SM_HEAP_CHECK */
3541 FIX_SYSV_SIGNAL(sig, sigusr1);
3543 CHECK_CRITICAL(sig);
3544 dumpstate("user signal");
3547 # endif /* SM_HEAP_CHECK */
3549 return SIGFUNC_RETURN;
3551 #endif /* SIGUSR1 */
3554 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3557 ** to_real_uid -- if set, drop to the real uid instead
3558 ** of the RunAsUser.
3561 ** EX_OSERR if the setuid failed.
3566 drop_privileges(to_real_uid)
3570 GIDSET_T emptygidset[1];
3573 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",
3575 (int) RealUid, (int) RealGid,
3576 (int) getuid(), (int) getgid(),
3577 (int) geteuid(), (int) getegid(),
3578 (int) RunAsUid, (int) RunAsGid);
3582 RunAsUserName = RealUserName;
3588 /* make sure no one can grab open descriptors for secret files */
3590 sm_mbdb_terminate();
3592 /* reset group permissions; these can be set later */
3593 emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3596 ** Notice: on some OS (Linux...) the setgroups() call causes
3597 ** a logfile entry if sendmail is not run by root.
3598 ** However, it is unclear (no POSIX standard) whether
3599 ** setgroups() can only succeed if executed by root.
3600 ** So for now we keep it as it is; if you want to change it, use
3601 ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3604 if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3606 syserr("drop_privileges: setgroups(1, %d) failed",
3607 (int) emptygidset[0]);
3611 /* reset primary group id */
3615 ** Drop gid to real gid.
3616 ** On some OS we must reset the effective[/real[/saved]] gid,
3617 ** and then use setgid() to finally drop all group privileges.
3618 ** Later on we check whether we can get back the
3623 if (setegid(RunAsGid) < 0)
3625 syserr("drop_privileges: setegid(%d) failed",
3629 #else /* HASSETEGID */
3631 if (setregid(RunAsGid, RunAsGid) < 0)
3633 syserr("drop_privileges: setregid(%d, %d) failed",
3634 (int) RunAsGid, (int) RunAsGid);
3637 # else /* HASSETREGID */
3639 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3641 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3642 (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3645 # endif /* HASSETRESGID */
3646 # endif /* HASSETREGID */
3647 #endif /* HASSETEGID */
3649 if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3651 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3653 syserr("drop_privileges: setgid(%d) failed",
3658 if (rval == EX_OK && getegid() != RunAsGid)
3660 syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3661 (int) getegid(), (int) RunAsGid);
3666 /* fiddle with uid */
3667 if (to_real_uid || RunAsUid != 0)
3672 ** Try to setuid(RunAsUid).
3673 ** euid must be RunAsUid,
3674 ** ruid must be RunAsUid unless (e|r)uid wasn't 0
3675 ** and we didn't have to drop privileges to the real uid.
3678 if (setuid(RunAsUid) < 0 ||
3679 geteuid() != RunAsUid ||
3680 (getuid() != RunAsUid &&
3681 (to_real_uid || geteuid() == 0 || getuid() == 0)))
3685 ** if ruid != RunAsUid, euid == RunAsUid, then
3686 ** try resetting just the real uid, then using
3687 ** setuid() to drop the saved-uid as well.
3690 if (geteuid() == RunAsUid)
3692 if (setreuid(RunAsUid, -1) < 0)
3694 syserr("drop_privileges: setreuid(%d, -1) failed",
3698 if (setuid(RunAsUid) < 0)
3700 syserr("drop_privileges: second setuid(%d) attempt failed",
3706 #endif /* HASSETREUID */
3708 syserr("drop_privileges: setuid(%d) failed",
3714 if (RunAsUid != 0 && setuid(0) == 0)
3717 ** Believe it or not, the Linux capability model
3718 ** allows a non-root process to override setuid()
3719 ** on a process running as root and prevent that
3720 ** process from dropping privileges.
3723 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3726 else if (RunAsUid != euid && setuid(euid) == 0)
3729 ** Some operating systems will keep the saved-uid
3730 ** if a non-root effective-uid calls setuid(real-uid)
3731 ** making it possible to set it back again later.
3734 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3739 if ((to_real_uid || RunAsGid != 0) &&
3740 rval == EX_OK && RunAsGid != EffGid &&
3741 getuid() != 0 && geteuid() != 0)
3744 if (setgid(EffGid) == 0)
3746 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3754 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3755 (int) geteuid(), (int) getuid(),
3756 (int) getegid(), (int) getgid());
3757 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3758 (int) RunAsUid, (int) RunAsGid);
3760 sm_dprintf("drop_privileges: rval = %d\n", rval);
3765 ** FILL_FD -- make sure a file descriptor has been properly allocated
3767 ** Used to make sure that stdin/out/err are allocated on startup
3770 ** fd -- the file descriptor to be filled.
3771 ** where -- a string used for logging. If NULL, this is
3772 ** being called on startup, and logging should
3779 ** possibly changes MissingFds
3790 if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3794 syserr("fill_fd: %s: fd %d not open", where, fd);
3796 MissingFds |= 1 << fd;
3797 i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3800 syserr("!fill_fd: %s: cannot open %s",
3801 where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3810 ** SM_PRINTOPTIONS -- print options
3813 ** options -- array of options.
3820 sm_printoptions(options)
3830 if (ll + strlen(*av) > 63)
3839 sm_dprintf("%s", *av);
3840 ll += strlen(*av++) + 1;
3845 ** TESTMODELINE -- process a test mode input line
3848 ** line -- the input line.
3849 ** e -- the current environment.
3852 ** .X process X as a configuration line
3853 ** =X dump a configuration item (such as mailers)
3854 ** $X dump a macro or class
3855 ** /X try an activity
3856 ** X normal process through rule set X
3860 testmodeline(line, e)
3866 auto char *delimptr;
3873 static int tryflags = RF_COPYNONE;
3874 char exbuf[MAXLINE];
3875 extern unsigned char TokTypeNoC[];
3877 /* skip leading spaces */
3878 while (*line == ' ')
3891 case '.': /* config-style settings */
3895 mid = macid_parse(&line[2], &delimptr);
3898 translate_dollars(delimptr);
3899 macdefine(&e->e_macro, A_TEMP, mid, delimptr);
3903 if (line[2] == '\0') /* not to call syserr() */
3906 mid = macid_parse(&line[2], &delimptr);
3909 translate_dollars(delimptr);
3910 expand(delimptr, exbuf, sizeof exbuf, e);
3917 while (*p != '\0' && isascii(*p) && isspace(*p))
3920 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
3931 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3932 "Usage: .[DC]macro value(s)\n");
3936 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3937 "Unknown \".\" command %s\n", line);
3942 case '=': /* config-style settings */
3945 case 'S': /* dump rule set */
3946 rs = strtorwset(&line[2], NULL, ST_FIND);
3949 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3950 "Undefined ruleset %s\n", &line[2]);
3953 rw = RewriteRules[rs];
3958 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3964 (void) sm_io_putc(smioout,
3965 SM_TIME_DEFAULT, ' ');
3967 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3969 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3975 (void) sm_io_putc(smioout,
3976 SM_TIME_DEFAULT, ' ');
3978 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3980 } while ((rw = rw->r_next) != NULL);
3984 for (i = 0; i < MAXMAILERS; i++)
3986 if (Mailer[i] != NULL)
3987 printmailer(Mailer[i]);
3992 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3993 "Usage: =Sruleset or =M\n");
3997 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3998 "Unknown \"=\" command %s\n", line);
4003 case '-': /* set command-line-like opts */
4011 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4012 "Usage: -d{debug arguments}\n");
4016 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4017 "Unknown \"-\" command %s\n", line);
4025 mid = macid(&line[2]);
4027 stabapply(dump_class, mid);
4030 mid = macid(&line[1]);
4033 p = macvalue(mid, e);
4035 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4040 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4045 case '/': /* miscellaneous commands */
4046 p = &line[strlen(line)];
4047 while (--p >= line && isascii(*p) && isspace(*p))
4049 p = strpbrk(line, " \t");
4052 while (isascii(*p) && isspace(*p))
4057 if (line[1] == '\0')
4059 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4060 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4063 if (sm_strcasecmp(&line[1], "quit") == 0)
4065 CurEnv->e_id = NULL;
4066 finis(true, true, ExitStat);
4069 if (sm_strcasecmp(&line[1], "mx") == 0)
4072 /* look up MX records */
4075 char *mxhosts[MAXMXHOSTS + 1];
4079 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4080 "Usage: /mx address\n");
4083 nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4085 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4086 "getmxrr(%s) returns %d value(s):\n",
4088 for (i = 0; i < nmx; i++)
4089 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4090 "\t%s\n", mxhosts[i]);
4091 #else /* NAMED_BIND */
4092 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4093 "No MX code compiled in\n");
4094 #endif /* NAMED_BIND */
4096 else if (sm_strcasecmp(&line[1], "canon") == 0)
4098 char host[MAXHOSTNAMELEN];
4102 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4103 "Usage: /canon address\n");
4106 else if (sm_strlcpy(host, p, sizeof host) >= sizeof host)
4108 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4112 (void) getcanonname(host, sizeof host, !HasWildcardMX,
4114 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4115 "getcanonname(%s) returns %s\n",
4118 else if (sm_strcasecmp(&line[1], "map") == 0)
4120 auto int rcode = EX_OK;
4125 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4126 "Usage: /map mapname key\n");
4129 for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q)); q++)
4133 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4134 "No key specified\n");
4138 map = stab(p, ST_MAP, ST_FIND);
4141 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4142 "Map named \"%s\" not found\n", p);
4145 if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4146 !openmap(&(map->s_map)))
4148 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4149 "Map named \"%s\" not open\n", p);
4152 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4153 "map_lookup: %s (%s) ", p, q);
4156 p = (*map->s_map.map_class->map_lookup)
4157 (&map->s_map, q, av, &rcode);
4159 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4163 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4164 "returns %s (%d)\n", p,
4167 else if (sm_strcasecmp(&line[1], "try") == 0)
4171 auto int rcode = EX_OK;
4173 q = strpbrk(p, " \t");
4176 while (isascii(*q) && isspace(*q))
4179 if (q == NULL || *q == '\0')
4181 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4182 "Usage: /try mailer address\n");
4185 st = stab(p, ST_MAILER, ST_FIND);
4188 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4189 "Unknown mailer %s\n", p);
4193 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4194 "Trying %s %s address %s for mailer %s\n",
4195 bitset(RF_HEADERADDR, tryflags) ? "header"
4197 bitset(RF_SENDERADDR, tryflags) ? "sender"
4198 : "recipient", q, p);
4199 p = remotename(q, m, tryflags, &rcode, CurEnv);
4200 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4201 "Rcode = %d, addr = %s\n",
4202 rcode, p == NULL ? "<NULL>" : p);
4205 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4209 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4210 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4213 for (; *p != '\0'; p++)
4219 tryflags |= RF_HEADERADDR;
4224 tryflags &= ~RF_HEADERADDR;
4229 tryflags |= RF_SENDERADDR;
4234 tryflags &= ~RF_SENDERADDR;
4238 exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4240 exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4242 macdefine(&e->e_macro, A_TEMP,
4243 macid("{addr_type}"), exbuf);
4245 else if (sm_strcasecmp(&line[1], "parse") == 0)
4249 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4250 "Usage: /parse address\n");
4253 q = crackaddr(p, e);
4254 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4255 "Cracked address = ");
4257 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4258 "\nParsing %s %s address\n",
4259 bitset(RF_HEADERADDR, tryflags) ?
4260 "header" : "envelope",
4261 bitset(RF_SENDERADDR, tryflags) ?
4262 "sender" : "recipient");
4263 if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4265 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4267 else if (a.q_host != NULL && a.q_host[0] != '\0')
4268 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4269 "mailer %s, host %s, user %s\n",
4274 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4275 "mailer %s, user %s\n",
4282 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4283 "Unknown \"/\" command %s\n",
4289 for (p = line; isascii(*p) && isspace(*p); p++)
4292 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4296 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4301 if (invalidaddr(p + 1, NULL, true))
4305 register char **pvp;
4306 char pvpbuf[PSBUFSIZE];
4308 pvp = prescan(++p, ',', pvpbuf, sizeof pvpbuf,
4309 &delimptr, ConfigLevel >= 9 ? TokTypeNoC : NULL);
4317 rs = strtorwset(p, NULL, ST_FIND);
4320 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4321 "Undefined ruleset %s\n",
4325 status = REWRITE(pvp, rs, e);
4326 if (status != EX_OK)
4327 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4328 "== Ruleset %s (%d) status %d\n",
4330 while (*p != '\0' && *p++ != ',')
4333 } while (*(p = delimptr) != '\0');
4341 if (s->s_symtype != ST_CLASS)
4343 if (bitnset(bitidx(id), s->s_class))
4344 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4349 ** An exception type used to create QuickAbort exceptions.
4350 ** This is my first cut at converting QuickAbort from longjmp to exceptions.
4351 ** These exceptions have a single integer argument, which is the argument
4352 ** to longjmp in the original code (either 1 or 2). I don't know the
4353 ** significance of 1 vs 2: the calls to setjmp don't care.
4356 const SM_EXC_TYPE_T EtypeQuickAbort =