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.
12 * $DragonFly: src/contrib/sendmail/src/Attic/main.c,v 1.3 2003/12/22 04:04:23 drhodus Exp $
18 #include <sm/signal.h>
21 SM_UNUSED(static char copyright[]) =
22 "@(#) Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers.\n\
23 All rights reserved.\n\
24 Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.\n\
25 Copyright (c) 1988, 1993\n\
26 The Regents of the University of California. All rights reserved.\n";
29 SM_RCSID("@(#)$Id: main.c,v 8.887.2.27 2003/08/04 17:23:37 ca Exp $")
32 #if NETINET || NETINET6
33 # include <arpa/inet.h>
34 #endif /* NETINET || NETINET6 */
37 #include <sendmail/pathnames.h>
40 DebugNoPRestart = SM_DEBUG_INITIALIZER("no_persistent_restart",
41 "@(#)$Debug: no_persistent_restart - don't restart, log only $");
43 static void dump_class __P((STAB *, int));
44 static void obsolete __P((char **));
45 static void testmodeline __P((char *, ENVELOPE *));
46 static char *getextenv __P((const char *));
47 static void sm_printoptions __P((char **));
48 static SIGFUNC_DECL intindebug __P((int));
49 static SIGFUNC_DECL sighup __P((int));
50 static SIGFUNC_DECL sigpipe __P((int));
51 static SIGFUNC_DECL sigterm __P((int));
53 static SIGFUNC_DECL sigusr1 __P((int));
57 ** SENDMAIL -- Post mail to a set of destinations.
59 ** This is the basic mail router. All user mail programs should
60 ** call this routine to actually deliver mail. Sendmail in
61 ** turn calls a bunch of mail servers that do the real work of
62 ** delivering the mail.
64 ** Sendmail is driven by settings read in from /etc/mail/sendmail.cf
65 ** (read by readcf.c).
68 ** /usr/lib/sendmail [flags] addr ...
70 ** See the associated documentation for details.
73 ** Eric Allman, UCB/INGRES (until 10/81).
74 ** Britton-Lee, Inc., purveyors of fine
75 ** database computers (11/81 - 10/88).
76 ** International Computer Science Institute
78 ** UCB/Mammoth Project (10/89 - 7/95).
79 ** InReference, Inc. (8/95 - 1/97).
80 ** Sendmail, Inc. (1/98 - present).
81 ** The support of my employers is gratefully acknowledged.
82 ** Few of them (Britton-Lee in particular) have had
83 ** anything to gain from my involvement in this project.
85 ** Gregory Neil Shapiro,
86 ** Worcester Polytechnic Institute (until 3/98).
87 ** Sendmail, Inc. (3/98 - present).
90 ** Sendmail, Inc. (12/98 - present).
93 char *FullName; /* sender's full name */
94 ENVELOPE BlankEnvelope; /* a "blank" envelope */
95 static ENVELOPE MainEnvelope; /* the envelope around the basic letter */
96 ADDRESS NullAddress = /* a null address */
98 char *CommandLineArgs; /* command line args for pid file */
99 bool Warn_Q_option = false; /* warn about Q option use */
100 static int MissingFds = 0; /* bit map of fds missing on startup */
101 char *Mbdb = "pw"; /* mailbox database defaults to /etc/passwd */
104 GIDSET_T InitialGidSet[NGROUPS_MAX];
105 #endif /* NGROUPS_MAX */
107 #define MAXCONFIGLEVEL 10 /* highest config version level known */
110 static sasl_callback_t srvcallbacks[] =
112 { SASL_CB_VERIFYFILE, &safesaslfile, NULL },
113 { SASL_CB_PROXY_POLICY, &proxy_policy, NULL },
114 { SASL_CB_LIST_END, NULL, NULL }
118 unsigned int SubmitMode;
119 int SyslogPrefixLen; /* estimated length of syslog prefix */
120 #define PIDLEN 6 /* pid length for computing SyslogPrefixLen */
122 # define SL_FUDGE 10 /* fudge offset for SyslogPrefixLen */
123 #endif /* ! SL_FUDGE */
124 #define SLDLL 8 /* est. length of default syslog label */
127 /* Some options are dangerous to allow users to use in non-submit mode */
128 #define CHECK_AGAINST_OPMODE(cmd) \
131 OpMode != MD_DELIVER && OpMode != MD_SMTP && \
132 OpMode != MD_ARPAFTP && \
133 OpMode != MD_VERIFY && OpMode != MD_TEST) \
135 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
136 "WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \
140 if (extraprivs && queuerun) \
142 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
143 "WARNING: Ignoring submission mode -%c option with -q\n", \
150 main(argc, argv, envp)
157 extern char Version[];
164 int qgrp = NOQGRP; /* queue group to process */
166 BITMAP256 *p_flags = NULL; /* daemon flags */
167 bool warn_C_flag = false;
168 bool auth = true; /* whether to set e_auth_param */
169 char warn_f_flag = '\0';
170 bool run_in_foreground = false; /* -bD mode */
171 bool queuerun = false, debug = false;
174 char *nullserver = NULL;
175 char *authinfo = NULL;
176 char *sysloglabel = NULL; /* label for syslog */
177 char *conffile = NULL; /* name of .cf file */
178 char *queuegroup = NULL; /* queue group to process */
180 char *quarantining = NULL; /* quarantine queue items? */
181 #endif /* _FFR_QUARANTINE */
184 bool queuepersistent = false; /* queue runner process runs forever */
185 bool foregroundqueue = false; /* queue run in foreground */
186 bool save_val; /* to save some bool var. */
187 int cftype; /* which cf file to use? */
188 static time_t starttime = 0; /* when was process started */
189 struct stat traf_st; /* for TrafficLog FIFO check */
191 char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */
192 static char rnamebuf[MAXNAME]; /* holds RealUserName */
193 char *emptyenviron[1];
196 #endif /* STARTTLS */
199 extern int DtableSize;
203 extern char **environ;
205 extern void sm_sasl_init __P((void));
210 #endif /* USE_ENVIRON */
212 /* turn off profiling */
215 /* install default exception handler */
216 sm_exc_newthread(fatal_error);
218 /* set the default in/out channel so errors reported to screen */
220 OutChannel = smioout;
223 ** Check to see if we reentered.
224 ** This would normally happen if e_putheader or e_putbody
225 ** were NULL when invoked.
230 syserr("main: reentered!");
233 starttime = curtime();
235 /* avoid null pointer dereferences */
236 TermEscape.te_rv_on = TermEscape.te_rv_off = "";
241 /* Check if sendmail is running with extra privs */
242 extraprivs = (RealUid != 0 &&
243 (geteuid() != getuid() || getegid() != getgid()));
245 CurrentPid = getpid();
247 /* get whatever .cf file is right for the opmode */
248 cftype = SM_GET_RIGHT_CF;
250 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
251 DtableSize = getdtsize();
252 if (DtableSize > 256)
256 ** Be sure we have enough file descriptors.
257 ** But also be sure that 0, 1, & 2 are open.
260 /* reset errno and fill_errno; the latter is used way down below */
261 errno = fill_errno = 0;
262 fill_fd(STDIN_FILENO, NULL);
265 fill_fd(STDOUT_FILENO, NULL);
268 fill_fd(STDERR_FILENO, NULL);
275 if (i != STDIN_FILENO && i != STDOUT_FILENO &&
283 # define SM_LOG_STR "sendmail"
284 # endif /* ! SM_LOG_STR */
286 openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
287 # else /* LOG_MAIL */
288 openlog(SM_LOG_STR, LOG_PID);
289 # endif /* LOG_MAIL */
293 ** Seed the random number generator.
294 ** Used for queue file names, picking a queue directory, and
300 /* do machine-dependent initializations */
304 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
306 /* reset status from syserr() calls for missing file descriptors */
310 SubmitMode = SUBMIT_UNKNOWN;
312 checkfd012("after openlog");
315 tTsetup(tTdvect, sizeof tTdvect, "0-99.1,*_trace_*.1");
318 /* save initial group set for future checks */
319 i = getgroups(NGROUPS_MAX, InitialGidSet);
322 InitialGidSet[0] = (GID_T) -1;
325 while (i < NGROUPS_MAX)
326 InitialGidSet[i++] = InitialGidSet[0];
327 #endif /* NGROUPS_MAX */
329 /* drop group id privileges (RunAsUser not yet set) */
330 dp = drop_privileges(false);
334 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
337 /* arrange to dump state on user-1 signal */
338 (void) sm_signal(SIGUSR1, sigusr1);
342 /* ignore user-1 signal */
343 (void) sm_signal(SIGUSR1, SIG_IGN);
347 /* initialize for setproctitle */
348 initsetproctitle(argc, argv, envp);
350 /* Handle any non-getoptable constructions. */
354 ** Do a quick prescan of the argument list.
358 /* find initial opMode */
361 p = strrchr(*av, '/');
364 if (strcmp(p, "newaliases") == 0)
365 OpMode = MD_INITALIAS;
366 else if (strcmp(p, "mailq") == 0)
368 else if (strcmp(p, "smtpd") == 0)
370 else if (strcmp(p, "hoststat") == 0)
371 OpMode = MD_HOSTSTAT;
372 else if (strcmp(p, "purgestat") == 0)
373 OpMode = MD_PURGESTAT;
376 # if defined(__osf__) || defined(_AIX3)
377 # define OPTIONS "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:xQ:"
378 # endif /* defined(__osf__) || defined(_AIX3) */
379 # if defined(sony_news)
380 # 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:"
381 # endif /* defined(sony_news) */
383 # define OPTIONS "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:Q:"
384 # endif /* ! OPTIONS */
385 #else /* _FFR_QUARANTINE */
386 # if defined(__osf__) || defined(_AIX3)
387 # define OPTIONS "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:x"
388 # endif /* defined(__osf__) || defined(_AIX3) */
389 # if defined(sony_news)
390 # define OPTIONS "A:B:b:C:cd:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:q:R:r:sTtV:vX:"
391 # endif /* defined(sony_news) */
393 # define OPTIONS "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:"
394 # endif /* ! OPTIONS */
395 #endif /* _FFR_QUARANTINE */
397 /* Set to 0 to allow -b; need to check optarg before using it! */
399 while ((j = getopt(argc, argv, OPTIONS)) != -1)
403 case 'b': /* operations mode */
404 j = (optarg == NULL) ? ' ' : *optarg;
423 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
424 "Frozen configurations unsupported\n");
428 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
429 "Invalid operation mode %c\n",
438 (void) sm_io_setvbuf(smioout, SM_TIME_DEFAULT,
439 (char *) NULL, SM_IO_NBF,
443 case 'G': /* relay (gateway) submission */
444 SubmitMode = SUBMIT_MTA;
450 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
451 "option requires an argument -- '%c'",
455 j = SM_MIN(strlen(optarg), 24) + 1;
456 sysloglabel = xalloc(j);
457 (void) sm_strlcpy(sysloglabel, optarg, j);
458 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
464 #endif /* _FFR_QUARANTINE */
466 /* just check if it is there */
473 /* Don't leak queue information via debug flags */
474 if (extraprivs && queuerun && debug)
476 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
477 "WARNING: Can not use -d with -q. Disabling debugging.\n");
478 sm_debug_setfile(NULL);
479 (void) memset(tTdvect, '\0', sizeof tTdvect);
483 if (sysloglabel != NULL)
485 /* Sanitize the string */
486 for (p = sysloglabel; *p != '\0'; p++)
488 if (!isascii(*p) || !isprint(*p) || *p == '%')
493 openlog(sysloglabel, LOG_PID, LOG_MAIL);
494 # else /* LOG_MAIL */
495 openlog(sysloglabel, LOG_PID);
496 # endif /* LOG_MAIL */
500 /* set up the blank envelope */
501 BlankEnvelope.e_puthdr = putheader;
502 BlankEnvelope.e_putbody = putbody;
503 BlankEnvelope.e_xfp = NULL;
504 STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
505 CurEnv = &BlankEnvelope;
506 STRUCTCOPY(NullAddress, MainEnvelope.e_from);
509 ** Set default values for variables.
510 ** These cannot be in initialized data space.
513 setdefaults(&BlankEnvelope);
514 initmacros(&BlankEnvelope);
519 pw = sm_getpwuid(RealUid);
521 (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof rnamebuf);
523 (void) sm_snprintf(rnamebuf, sizeof rnamebuf, "Unknown UID %d",
526 RealUserName = rnamebuf;
530 sm_dprintf("Version %s\n", Version);
531 finis(false, true, EX_OK);
536 ** if running non-set-user-ID binary as non-root, pretend
537 ** we are the RunAsUid
540 if (RealUid != 0 && geteuid() == RealUid)
543 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
547 else if (geteuid() != 0)
548 RunAsUid = geteuid();
551 if (RealUid != 0 && EffGid == RealGid)
556 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
557 (int) geteuid(), (int) getuid(),
558 (int) getegid(), (int) getgid());
559 sm_dprintf("main: RunAsUser = %d:%d\n",
560 (int) RunAsUid, (int) RunAsGid);
563 /* save command line arguments */
565 for (av = argv; *av != NULL; )
566 j += strlen(*av++) + 1;
567 SaveArgv = (char **) xalloc(sizeof (char *) * (argc + 1));
568 CommandLineArgs = xalloc(j);
570 for (av = argv, i = 0; *av != NULL; )
574 SaveArgv[i++] = newstr(*av);
577 (void) sm_strlcpy(p, *av++, j);
586 extern char *CompileOptions[];
588 sm_dprintf("Version %s\n Compiled with:", Version);
589 sm_printoptions(CompileOptions);
593 extern char *OsCompileOptions[];
595 sm_dprintf(" OS Defines:");
596 sm_printoptions(OsCompileOptions);
598 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
599 #endif /* _PATH_UNIX */
601 sm_dprintf(" Conf file:\t%s (default for MSP)\n",
602 getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
604 sm_dprintf(" Conf file:\t%s (default for MTA)\n",
605 getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
607 sm_dprintf(" Pid file:\t%s (default)\n", PidFile);
612 extern char *SmCompileOptions[];
614 sm_dprintf(" libsm Defines:");
615 sm_printoptions(SmCompileOptions);
620 extern char *FFRCompileOptions[];
622 sm_dprintf(" FFR Defines:");
623 sm_printoptions(FFRCompileOptions);
626 /* clear sendmail's environment */
627 ExternalEnviron = environ;
628 emptyenviron[0] = NULL;
629 environ = emptyenviron;
632 ** restore any original TZ setting until TimeZoneSpec has been
633 ** determined - or early log messages may get bogus time stamps
636 if ((p = getextenv("TZ")) != NULL)
641 /* XXX check for reasonable length? */
642 tzlen = strlen(p) + 4;
644 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
646 /* XXX check return code? */
650 /* prime the child environment */
651 setuserenv("AGENT", "sendmail");
653 (void) sm_signal(SIGPIPE, SIG_IGN);
654 OldUmask = umask(022);
655 FullName = getextenv("NAME");
656 if (FullName != NULL)
657 FullName = newstr(FullName);
660 ** Initialize name server if it is going to be used.
664 if (!bitset(RES_INIT, _res.options))
667 _res.options |= RES_DEBUG;
669 _res.options &= ~RES_DEBUG;
670 # ifdef RES_NOALIASES
671 if (bitset(RES_NOALIASES, _res.options))
673 _res.options |= RES_NOALIASES;
674 # endif /* RES_NOALIASES */
675 TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
676 TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
677 TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
678 TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
679 TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
680 TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
681 #endif /* NAMED_BIND */
686 /* initialize some macros, etc. */
687 init_vendor_macros(&BlankEnvelope);
690 macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
693 hp = myhostname(jbuf, sizeof jbuf);
696 struct utsname utsname;
699 sm_dprintf("Canonical name: %s\n", jbuf);
700 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
701 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
704 p = strchr(jbuf, '.');
709 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm',
712 while (p != NULL && strchr(&p[1], '.') != NULL)
716 sm_dprintf("\ta.k.a.: %s\n", jbuf);
723 if (uname(&utsname) >= 0)
724 p = utsname.nodename;
728 sm_dprintf("uname failed (%s)\n",
729 sm_errstring(errno));
734 sm_dprintf(" UUCP nodename: %s\n", p);
735 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
741 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
744 sm_dprintf("\ta.k.a.: %s\n", *av);
747 #if NETINET || NETINET6
748 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
752 char buf6[INET6_ADDRSTRLEN];
754 # endif /* NETINET6 */
757 # endif /* NETINET */
761 switch (hp->h_addrtype)
765 if (hp->h_length != INADDRSZ)
768 memmove(&ia, hp->h_addr_list[i], INADDRSZ);
769 (void) sm_snprintf(ipbuf, sizeof ipbuf,
770 "[%.100s]", inet_ntoa(ia));
772 # endif /* NETINET */
776 if (hp->h_length != IN6ADDRSZ)
779 memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
780 addr = anynet_ntop(&ia6, buf6, sizeof buf6);
782 (void) sm_snprintf(ipbuf, sizeof ipbuf,
785 # endif /* NETINET6 */
787 if (ipbuf[0] == '\0')
791 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
792 setclass('w', ipbuf);
794 #endif /* NETINET || NETINET6 */
798 #endif /* NETINET6 */
802 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
804 /* current load average */
807 QueueLimitRecipient = (QUEUE_CHAR *) NULL;
808 QueueLimitSender = (QUEUE_CHAR *) NULL;
809 QueueLimitId = (QUEUE_CHAR *) NULL;
811 QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
812 #endif /* _FFR_QUARANTINE */
819 while ((j = getopt(argc, argv, OPTIONS)) != -1)
823 case 'b': /* operations mode */
827 case 'A': /* use Alternate sendmail/submit.cf */
828 cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
829 : SM_GET_SENDMAIL_CF;
832 case 'B': /* body type */
833 CHECK_AGAINST_OPMODE(j);
834 BlankEnvelope.e_bodytype = newstr(optarg);
837 case 'C': /* select configuration file (already done) */
840 conffile = newstr(optarg);
841 dp = drop_privileges(true);
846 case 'd': /* debugging */
850 case 'f': /* from address */
851 case 'r': /* obsolete -f flag */
852 CHECK_AGAINST_OPMODE(j);
855 usrerr("More than one \"from\" person");
859 if (optarg[0] == '\0')
862 from = newstr(denlstring(optarg, true, true));
863 if (strcmp(RealUserName, from) != 0)
867 case 'F': /* set full name */
868 CHECK_AGAINST_OPMODE(j);
869 FullName = newstr(optarg);
872 case 'G': /* relay (gateway) submission */
874 CHECK_AGAINST_OPMODE(j);
877 case 'h': /* hop count */
878 CHECK_AGAINST_OPMODE(j);
879 BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
881 (void) sm_snprintf(buf, sizeof buf, "%d",
882 BlankEnvelope.e_hopcount);
883 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
887 usrerr("Bad hop count (%s)", optarg);
892 case 'L': /* program label */
896 case 'n': /* don't alias */
897 CHECK_AGAINST_OPMODE(j);
901 case 'N': /* delivery status notifications */
902 CHECK_AGAINST_OPMODE(j);
903 DefaultNotify |= QHASNOTIFY;
904 macdefine(&BlankEnvelope.e_macro, A_TEMP,
905 macid("{dsn_notify}"), optarg);
906 if (sm_strcasecmp(optarg, "never") == 0)
908 for (p = optarg; p != NULL; optarg = p)
913 if (sm_strcasecmp(optarg, "success") == 0)
914 DefaultNotify |= QPINGONSUCCESS;
915 else if (sm_strcasecmp(optarg, "failure") == 0)
916 DefaultNotify |= QPINGONFAILURE;
917 else if (sm_strcasecmp(optarg, "delay") == 0)
918 DefaultNotify |= QPINGONDELAY;
921 usrerr("Invalid -N argument");
927 case 'o': /* set option */
928 setoption(*optarg, optarg + 1, false, true,
932 case 'O': /* set option (long form) */
933 setoption(' ', optarg, false, true, &BlankEnvelope);
936 case 'p': /* set protocol */
937 CHECK_AGAINST_OPMODE(j);
938 p = strchr(optarg, ':');
946 cleanstrcpy(ep, p, i);
947 macdefine(&BlankEnvelope.e_macro,
953 i = strlen(optarg) + 1;
955 cleanstrcpy(ep, optarg, i);
956 macdefine(&BlankEnvelope.e_macro, A_HEAP,
962 case 'Q': /* change quarantining on queued items */
964 if (OpMode != MD_DELIVER &&
965 OpMode != MD_QUEUERUN)
967 usrerr("Can not use -Q with -b%c", OpMode);
972 if (OpMode == MD_DELIVER)
973 set_op_mode(MD_QUEUERUN);
977 quarantining = newstr(optarg);
979 #endif /* _FFR_QUARANTINE */
981 case 'q': /* run queue files at intervals */
983 if (OpMode != MD_DELIVER &&
984 OpMode != MD_DAEMON &&
985 OpMode != MD_FGDAEMON &&
986 OpMode != MD_PRINT &&
987 OpMode != MD_PRINTNQE &&
988 OpMode != MD_QUEUERUN)
990 usrerr("Can not use -q with -b%c", OpMode);
995 /* don't override -bd, -bD or -bp */
996 if (OpMode == MD_DELIVER)
997 set_op_mode(MD_QUEUERUN);
1000 negate = optarg[0] == '!';
1003 /* negate meaning of pattern match */
1004 optarg++; /* skip '!' for next switch */
1009 case 'G': /* Limit by queue group name */
1012 usrerr("Can not use -q!G");
1013 ExitStat = EX_USAGE;
1016 if (queuegroup != NULL)
1018 usrerr("Can not use multiple -qG options");
1019 ExitStat = EX_USAGE;
1022 queuegroup = newstr(&optarg[1]);
1025 case 'I': /* Limit by ID */
1026 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1027 new->queue_match = newstr(&optarg[1]);
1028 new->queue_negate = negate;
1029 new->queue_next = QueueLimitId;
1033 case 'R': /* Limit by recipient */
1034 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1035 new->queue_match = newstr(&optarg[1]);
1036 new->queue_negate = negate;
1037 new->queue_next = QueueLimitRecipient;
1038 QueueLimitRecipient = new;
1041 case 'S': /* Limit by sender */
1042 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1043 new->queue_match = newstr(&optarg[1]);
1044 new->queue_negate = negate;
1045 new->queue_next = QueueLimitSender;
1046 QueueLimitSender = new;
1049 case 'f': /* foreground queue run */
1050 foregroundqueue = true;
1054 case 'Q': /* Limit by quarantine message */
1055 if (optarg[1] != '\0')
1057 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1058 new->queue_match = newstr(&optarg[1]);
1059 new->queue_negate = negate;
1060 new->queue_next = QueueLimitQuarantine;
1061 QueueLimitQuarantine = new;
1063 QueueMode = QM_QUARANTINE;
1066 case 'L': /* act on lost items */
1067 QueueMode = QM_LOST;
1069 #endif /* _FFR_QUARANTINE */
1071 case 'p': /* Persistent queue */
1072 queuepersistent = true;
1073 if (QueueIntvl == 0)
1075 if (optarg[1] == '\0')
1082 QueueIntvl = convtime(optarg, 'm');
1085 usrerr("Invalid -q value");
1086 ExitStat = EX_USAGE;
1089 /* check for bad conversion */
1091 ExitStat = EX_USAGE;
1096 case 'R': /* DSN RET: what to return */
1097 CHECK_AGAINST_OPMODE(j);
1098 if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1100 usrerr("Duplicate -R flag");
1101 ExitStat = EX_USAGE;
1104 BlankEnvelope.e_flags |= EF_RET_PARAM;
1105 if (sm_strcasecmp(optarg, "hdrs") == 0)
1106 BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1107 else if (sm_strcasecmp(optarg, "full") != 0)
1109 usrerr("Invalid -R value");
1110 ExitStat = EX_USAGE;
1112 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1113 macid("{dsn_ret}"), optarg);
1116 case 't': /* read recipients from message */
1117 CHECK_AGAINST_OPMODE(j);
1121 case 'V': /* DSN ENVID: set "original" envelope id */
1122 CHECK_AGAINST_OPMODE(j);
1123 if (!xtextok(optarg))
1125 usrerr("Invalid syntax in -V flag");
1126 ExitStat = EX_USAGE;
1130 BlankEnvelope.e_envid = newstr(optarg);
1131 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1132 macid("{dsn_envid}"), optarg);
1136 case 'X': /* traffic log file */
1137 dp = drop_privileges(true);
1139 if (stat(optarg, &traf_st) == 0 &&
1140 S_ISFIFO(traf_st.st_mode))
1141 TrafficLogFile = sm_io_open(SmFtStdio,
1144 SM_IO_WRONLY, NULL);
1146 TrafficLogFile = sm_io_open(SmFtStdio,
1149 SM_IO_APPEND, NULL);
1150 if (TrafficLogFile == NULL)
1152 syserr("cannot open %s", optarg);
1153 ExitStat = EX_CANTCREAT;
1156 (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1157 NULL, SM_IO_LBF, 0);
1160 /* compatibility flags */
1161 case 'c': /* connect to non-local mailers */
1162 case 'i': /* don't let dot stop me */
1163 case 'm': /* send to me too */
1164 case 'T': /* set timeout interval */
1165 case 'v': /* give blow-by-blow description */
1166 setoption(j, "T", false, true, &BlankEnvelope);
1169 case 'e': /* error message disposition */
1170 case 'M': /* define macro */
1171 setoption(j, optarg, false, true, &BlankEnvelope);
1174 case 's': /* save From lines in headers */
1175 setoption('f', "T", false, true, &BlankEnvelope);
1179 case 'I': /* initialize alias DBM file */
1180 set_op_mode(MD_INITALIAS);
1184 #if defined(__osf__) || defined(_AIX3)
1185 case 'x': /* random flag that OSF/1 & AIX mailx passes */
1187 #endif /* defined(__osf__) || defined(_AIX3) */
1188 #if defined(sony_news)
1190 case 'J': /* ignore flags for Japanese code conversion
1191 implemented on Sony NEWS */
1193 #endif /* defined(sony_news) */
1196 finis(true, true, EX_USAGE);
1202 /* if we've had errors so far, exit now */
1203 if ((ExitStat != EX_OK && OpMode != MD_TEST) ||
1204 ExitStat == EX_OSERR)
1206 finis(false, true, ExitStat);
1210 if (bitset(SUBMIT_MTA, SubmitMode))
1212 /* If set daemon_flags on command line, don't reset it */
1213 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1214 macdefine(&BlankEnvelope.e_macro, A_PERM,
1215 macid("{daemon_flags}"), "CC f");
1217 else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1219 SubmitMode = SUBMIT_MSA;
1221 /* If set daemon_flags on command line, don't reset it */
1222 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1223 macdefine(&BlankEnvelope.e_macro, A_PERM,
1224 macid("{daemon_flags}"), "c u");
1228 ** Do basic initialization.
1229 ** Read system control file.
1230 ** Extract special fields for local use.
1234 checkfd012("before readcf");
1236 vendor_pre_defaults(&BlankEnvelope);
1238 readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1239 safecf, &BlankEnvelope);
1240 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1241 ConfigFileRead = true;
1242 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1243 vendor_post_defaults(&BlankEnvelope);
1245 /* now we can complain about missing fds */
1246 if (MissingFds != 0 && LogLevel > 8)
1251 if (bitset(1 << STDIN_FILENO, MissingFds))
1252 (void) sm_strlcat(mbuf, ", stdin", sizeof mbuf);
1253 if (bitset(1 << STDOUT_FILENO, MissingFds))
1254 (void) sm_strlcat(mbuf, ", stdout", sizeof mbuf);
1255 if (bitset(1 << STDERR_FILENO, MissingFds))
1256 (void) sm_strlcat(mbuf, ", stderr", sizeof mbuf);
1258 /* Notice: fill_errno is from high above: fill_fd() */
1259 sm_syslog(LOG_WARNING, NOQID,
1260 "File descriptors missing on startup: %s; %s",
1261 &mbuf[2], sm_errstring(fill_errno));
1264 /* Remove the ability for a normal user to send signals */
1265 if (RealUid != 0 && RealUid != geteuid())
1267 uid_t new_uid = geteuid();
1271 ** Since we can differentiate between uid and euid,
1272 ** make the uid a different user so the real user
1273 ** can't send signals. However, it doesn't need to be
1274 ** root (euid has root).
1280 sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1281 if (setreuid(new_uid, geteuid()) < 0)
1283 syserr("main: setreuid(%d, %d) failed",
1284 (int) new_uid, (int) geteuid());
1285 finis(false, true, EX_OSERR);
1289 sm_dprintf("Now running as e/ruid %d:%d\n",
1290 (int) geteuid(), (int) getuid());
1291 #else /* HASSETREUID */
1293 ** Have to change both effective and real so need to
1294 ** change them both to effective to keep privs.
1298 sm_dprintf("Changing uid to %d\n", (int) new_uid);
1299 if (setuid(new_uid) < 0)
1301 syserr("main: setuid(%d) failed", (int) new_uid);
1302 finis(false, true, EX_OSERR);
1306 sm_dprintf("Now running as e/ruid %d:%d\n",
1307 (int) geteuid(), (int) getuid());
1308 #endif /* HASSETREUID */
1312 if (FallBackMX != NULL)
1313 (void) getfallbackmxrr(FallBackMX);
1314 #endif /* NAMED_BIND */
1316 if (SuperSafe == SAFE_INTERACTIVE && CurEnv->e_sendmode != SM_DELIVER)
1318 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1319 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1322 if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1324 usrerr("Mail submission program cannot be used as daemon");
1325 finis(false, true, EX_USAGE);
1328 if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1329 OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1330 OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1333 /* set up the basic signal handlers */
1334 if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1335 (void) sm_signal(SIGINT, intsig);
1336 (void) sm_signal(SIGTERM, intsig);
1338 /* Enforce use of local time (null string overrides this) */
1339 if (TimeZoneSpec == NULL)
1341 else if (TimeZoneSpec[0] != '\0')
1342 setuserenv("TZ", TimeZoneSpec);
1344 setuserenv("TZ", NULL);
1347 /* initialize mailbox database */
1348 i = sm_mbdb_initialize(Mbdb);
1351 usrerr("Can't initialize mailbox database \"%s\": %s",
1352 Mbdb, sm_strexit(i));
1356 /* avoid denial-of-service attacks */
1359 if (OpMode == MD_TEST)
1361 /* can't be done after readcf if RunAs* is used */
1362 dp = drop_privileges(true);
1365 finis(false, true, dp);
1369 else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1371 /* drop privileges -- daemon mode done after socket/bind */
1372 dp = drop_privileges(false);
1374 if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1376 usrerr("Mail submission program must have RunAsUser set to non root user");
1377 finis(false, true, EX_CONFIG);
1383 _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1384 _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1385 #endif /* NAMED_BIND */
1388 ** Find our real host name for future logging.
1391 authinfo = getauthinfo(STDIN_FILENO, &forged);
1392 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1394 /* suppress error printing if errors mailed back or whatever */
1395 if (BlankEnvelope.e_errormode != EM_PRINT)
1398 /* set up the $=m class now, after .cf has a chance to redefine $m */
1399 expand("\201m", jbuf, sizeof jbuf, &BlankEnvelope);
1400 if (jbuf[0] != '\0')
1401 setclass('m', jbuf);
1403 /* probe interfaces and locate any additional names */
1404 if (DontProbeInterfaces != DPI_PROBENONE)
1409 char pidpath[MAXPATHLEN];
1411 /* Now we know which .cf file we use */
1412 sm_dprintf(" Conf file:\t%s (selected)\n",
1413 getcfname(OpMode, SubmitMode, cftype, conffile));
1414 expand(PidFile, pidpath, sizeof pidpath, &BlankEnvelope);
1415 sm_dprintf(" Pid file:\t%s (selected)\n", pidpath);
1420 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1421 sm_dprintf("\n (short domain name) $w = ");
1422 xputs(macvalue('w', &BlankEnvelope));
1423 sm_dprintf("\n (canonical domain name) $j = ");
1424 xputs(macvalue('j', &BlankEnvelope));
1425 sm_dprintf("\n (subdomain name) $m = ");
1426 xputs(macvalue('m', &BlankEnvelope));
1427 sm_dprintf("\n (node name) $k = ");
1428 xputs(macvalue('k', &BlankEnvelope));
1429 sm_dprintf("\n========================================================\n\n");
1433 ** Do more command line checking -- these are things that
1434 ** have to modify the results of reading the config file.
1437 /* process authorization warnings from command line */
1439 auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1440 RealUserName, conffile);
1441 if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1442 auth_warning(&BlankEnvelope, "Processed from queue %s",
1444 if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1445 RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1446 sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1449 /* check body type for legality */
1450 i = check_bodytype(BlankEnvelope.e_bodytype);
1451 if (i == BODYTYPE_ILLEGAL)
1453 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1454 BlankEnvelope.e_bodytype = NULL;
1456 else if (i != BODYTYPE_NONE)
1457 SevenBitInput = (i == BODYTYPE_7BIT);
1459 /* tweak default DSN notifications */
1460 if (DefaultNotify == 0)
1461 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1463 /* be sure we don't pick up bogus HOSTALIASES environment variable */
1464 if (OpMode == MD_QUEUERUN && RealUid != 0)
1465 (void) unsetenv("HOSTALIASES");
1467 /* check for sane configuration level */
1468 if (ConfigLevel > MAXCONFIGLEVEL)
1470 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1471 ConfigLevel, Version, MAXCONFIGLEVEL);
1474 /* need MCI cache to have persistence */
1475 if (HostStatDir != NULL && MaxMciCache == 0)
1478 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1479 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1482 /* need HostStatusDir in order to have SingleThreadDelivery */
1483 if (SingleThreadDelivery && HostStatDir == NULL)
1485 SingleThreadDelivery = false;
1486 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1487 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1490 /* check for permissions */
1492 RealUid != TrustedUid)
1494 char *action = NULL;
1500 if (quarantining != NULL)
1501 action = "quarantine jobs";
1503 #endif /* _FFR_QUARANTINE */
1504 /* Normal users can do a single queue run */
1505 if (QueueIntvl == 0)
1508 /* but not persistent queue runners */
1510 action = "start a queue runner daemon";
1515 action = "purge host status";
1521 action = "run daemon";
1524 sm_dprintf("Deny user %d attempt to %s\n",
1525 (int) RealUid, action);
1528 sm_syslog(LOG_ALERT, NOQID,
1529 "user %d attempted to %s",
1530 (int) RealUid, action);
1532 usrerr("Permission denied (real uid not trusted)");
1533 finis(false, true, EX_USAGE);
1538 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1541 ** If -bv and RestrictExpand,
1542 ** drop privs to prevent normal
1543 ** users from reading private
1544 ** aliases/forwards/:include:s
1548 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1551 dp = drop_privileges(true);
1553 /* Fake address safety */
1555 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1556 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1561 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1563 CurEnv->e_id = NULL;
1564 finis(true, true, dp);
1575 /* Nothing special to check */
1579 if (!wordinclass(RealUserName, 't'))
1582 sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1585 sm_syslog(LOG_ALERT, NOQID,
1586 "user %d attempted to rebuild the alias map",
1589 usrerr("Permission denied (real uid not trusted)");
1590 finis(false, true, EX_USAGE);
1596 usrerr("User %d cannot rebuild aliases in mail submission program",
1598 finis(false, true, EX_USAGE);
1604 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1608 ** If -v and RestrictExpand, reset
1609 ** Verbose to prevent normal users
1610 ** from seeing the expansion of
1611 ** aliases/forwards/:include:s
1615 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1624 BlankEnvelope.e_flags |= EF_METOO;
1629 /* don't have persistent host status in test mode */
1633 BlankEnvelope.e_errormode = EM_PRINT;
1638 BlankEnvelope.e_errormode = EM_PRINT;
1640 /* arrange to exit cleanly on hangup signal */
1641 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1642 (void) sm_signal(SIGHUP, intsig);
1644 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1645 "Notice: -bv may give misleading output for non-privileged user\n");
1649 run_in_foreground = true;
1650 set_op_mode(MD_DAEMON);
1654 vendor_daemon_setup(&BlankEnvelope);
1656 /* remove things that don't make sense in daemon mode */
1660 /* arrange to restart on hangup signal */
1661 if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1662 sm_syslog(LOG_WARNING, NOQID,
1663 "daemon invoked without full pathname; kill -1 won't work");
1668 BlankEnvelope.e_errormode = EM_PRINT;
1673 /* arrange to exit cleanly on hangup signal */
1674 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1675 (void) sm_signal(SIGHUP, intsig);
1679 /* special considerations for FullName */
1680 if (FullName != NULL)
1684 /* full names can't have newlines */
1685 if (strchr(FullName, '\n') != NULL)
1687 full = newstr(denlstring(FullName, true, true));
1691 /* check for characters that may have to be quoted */
1692 if (!rfc822_string(FullName))
1695 ** Quote a full name with special characters
1696 ** as a comment so crackaddr() doesn't destroy
1697 ** the name portion of the address.
1700 FullName = addquotes(FullName, NULL);
1702 sm_free(full); /* XXX */
1706 /* do heuristic mode adjustment */
1709 /* turn off noconnect option */
1710 setoption('c', "F", true, false, &BlankEnvelope);
1712 /* turn on interactive delivery */
1713 setoption('d', "", true, false, &BlankEnvelope);
1717 /* check for vendor mismatch */
1718 if (VendorCode != VENDOR_CODE)
1720 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1721 getvendor(VENDOR_CODE), getvendor(VendorCode));
1723 #endif /* VENDOR_CODE */
1725 /* check for out of date configuration level */
1726 if (ConfigLevel < MAXCONFIGLEVEL)
1728 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1729 Version, MAXCONFIGLEVEL, ConfigLevel);
1732 if (ConfigLevel < 3)
1735 /* set options that were previous macros */
1736 if (SmtpGreeting == NULL)
1738 if (ConfigLevel < 7 &&
1739 (p = macvalue('e', &BlankEnvelope)) != NULL)
1740 SmtpGreeting = newstr(p);
1742 SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1744 if (UnixFromLine == NULL)
1746 if (ConfigLevel < 7 &&
1747 (p = macvalue('l', &BlankEnvelope)) != NULL)
1748 UnixFromLine = newstr(p);
1750 UnixFromLine = "From \201g \201d";
1752 SmtpError[0] = '\0';
1754 /* our name for SMTP codes */
1755 expand("\201j", jbuf, sizeof jbuf, &BlankEnvelope);
1756 if (jbuf[0] == '\0')
1757 PSTRSET(MyHostName, "localhost");
1759 PSTRSET(MyHostName, jbuf);
1760 if (strchr(MyHostName, '.') == NULL)
1761 message("WARNING: local host name (%s) is not qualified; fix $j in config file",
1764 /* make certain that this name is part of the $=w class */
1765 setclass('w', MyHostName);
1767 /* fill in the structure of the *default* queue */
1768 st = stab("mqueue", ST_QUEUE, ST_FIND);
1770 syserr("No default queue (mqueue) defined");
1772 set_def_queueval(st->s_quegrp, true);
1774 /* the indices of built-in mailers */
1775 st = stab("local", ST_MAILER, ST_FIND);
1777 LocalMailer = st->s_mailer;
1778 else if (OpMode != MD_TEST || !warn_C_flag)
1779 syserr("No local mailer defined");
1781 st = stab("prog", ST_MAILER, ST_FIND);
1783 syserr("No prog mailer defined");
1786 ProgMailer = st->s_mailer;
1787 clrbitn(M_MUSER, ProgMailer->m_flags);
1790 st = stab("*file*", ST_MAILER, ST_FIND);
1792 syserr("No *file* mailer defined");
1795 FileMailer = st->s_mailer;
1796 clrbitn(M_MUSER, FileMailer->m_flags);
1799 st = stab("*include*", ST_MAILER, ST_FIND);
1801 syserr("No *include* mailer defined");
1803 InclMailer = st->s_mailer;
1805 if (ConfigLevel < 6)
1807 /* heuristic tweaking of local mailer for back compat */
1808 if (LocalMailer != NULL)
1810 setbitn(M_ALIASABLE, LocalMailer->m_flags);
1811 setbitn(M_HASPWENT, LocalMailer->m_flags);
1812 setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1813 setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1814 setbitn(M_CHECKPROG, LocalMailer->m_flags);
1815 setbitn(M_CHECKFILE, LocalMailer->m_flags);
1816 setbitn(M_CHECKUDB, LocalMailer->m_flags);
1818 if (ProgMailer != NULL)
1819 setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1820 if (FileMailer != NULL)
1821 setbitn(M_RUNASRCPT, FileMailer->m_flags);
1823 if (ConfigLevel < 7)
1825 if (LocalMailer != NULL)
1826 setbitn(M_VRFY250, LocalMailer->m_flags);
1827 if (ProgMailer != NULL)
1828 setbitn(M_VRFY250, ProgMailer->m_flags);
1829 if (FileMailer != NULL)
1830 setbitn(M_VRFY250, FileMailer->m_flags);
1833 /* MIME Content-Types that cannot be transfer encoded */
1834 setclass('n', "multipart/signed");
1836 /* MIME message/xxx subtypes that can be treated as messages */
1837 setclass('s', "rfc822");
1839 /* MIME Content-Transfer-Encodings that can be encoded */
1840 setclass('e', "7bit");
1841 setclass('e', "8bit");
1842 setclass('e', "binary");
1845 /* MIME Content-Types that should be treated as binary */
1846 setclass('b', "image");
1847 setclass('b', "audio");
1848 setclass('b', "video");
1849 setclass('b', "application/octet-stream");
1850 #endif /* USE_B_CLASS */
1852 /* MIME headers which have fields to check for overflow */
1853 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1854 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1856 /* MIME headers to check for length overflow */
1857 setclass(macid("{checkMIMETextHeaders}"), "content-description");
1859 /* MIME headers to check for overflow and rebalance */
1860 setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1861 setclass(macid("{checkMIMEHeaders}"), "content-id");
1862 setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1863 setclass(macid("{checkMIMEHeaders}"), "content-type");
1864 setclass(macid("{checkMIMEHeaders}"), "mime-version");
1866 /* Macros to save in the queue file -- don't remove any */
1867 setclass(macid("{persistentMacros}"), "r");
1868 setclass(macid("{persistentMacros}"), "s");
1869 setclass(macid("{persistentMacros}"), "_");
1870 setclass(macid("{persistentMacros}"), "{if_addr}");
1871 setclass(macid("{persistentMacros}"), "{daemon_flags}");
1873 /* operate in queue directory */
1874 if (QueueDir == NULL || *QueueDir == '\0')
1876 if (OpMode != MD_TEST)
1878 syserr("QueueDirectory (Q) option must be set");
1879 ExitStat = EX_CONFIG;
1884 if (OpMode != MD_TEST)
1885 setup_queues(OpMode == MD_DAEMON);
1888 /* check host status directory for validity */
1889 if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1891 /* cannot use this value */
1892 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1893 "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1894 HostStatDir, sm_errstring(errno));
1898 if (OpMode == MD_QUEUERUN &&
1899 RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1903 /* check to see if we own the queue directory */
1904 if (stat(".", &stbuf) < 0)
1905 syserr("main: cannot stat %s", QueueDir);
1906 if (stbuf.st_uid != RealUid)
1908 /* nope, really a botch */
1910 usrerr("You do not have permission to process the queue");
1911 finis(false, true, EX_NOPERM);
1917 /* sanity checks on milter filters */
1918 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1920 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1921 # if _FFR_MILTER_PERDAEMON
1922 setup_daemon_milters();
1923 # endif /* _FFR_MILTER_PERDAEMON */
1927 /* Convert queuegroup string to qgrp number */
1928 if (queuegroup != NULL)
1930 qgrp = name2qid(queuegroup);
1934 usrerr("Queue group %s unknown", queuegroup);
1935 finis(false, true, ExitStat);
1940 /* if we've had errors so far, exit now */
1941 if (ExitStat != EX_OK && OpMode != MD_TEST)
1943 finis(false, true, ExitStat);
1948 /* sendmail specific SASL initialization */
1953 checkfd012("before main() initmaps");
1957 ** Do operation-mode-dependent initialization.
1963 /* print the queue */
1965 dropenvelope(&BlankEnvelope, true, false);
1966 (void) sm_signal(SIGPIPE, sigpipe);
1971 /* Selecting a particular queue group to run */
1972 for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1976 (void) print_single_queue(qgrp, j);
1978 finis(false, true, EX_OK);
1982 finis(false, true, EX_OK);
1987 /* print number of entries in queue */
1988 dropenvelope(&BlankEnvelope, true, false);
1989 (void) sm_signal(SIGPIPE, sigpipe);
1990 printnqe(smioout, NULL);
1991 finis(false, true, EX_OK);
1997 /* only handle quarantining here */
1998 if (quarantining == NULL)
2001 if (QueueMode != QM_QUARANTINE &&
2002 QueueMode != QM_NORMAL)
2005 usrerr("Can not use -Q with -q%c", QueueMode);
2006 ExitStat = EX_USAGE;
2007 finis(false, true, ExitStat);
2010 quarantine_queue(quarantining, qgrp);
2011 finis(false, true, EX_OK);
2013 #endif /* _FFR_QUARANTINE */
2016 (void) sm_signal(SIGPIPE, sigpipe);
2017 (void) mci_traverse_persistent(mci_print_persistent, NULL);
2018 finis(false, true, EX_OK);
2023 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2024 finis(false, true, EX_OK);
2029 /* initialize maps */
2031 finis(false, true, ExitStat);
2037 /* reset DSN parameters */
2038 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2039 macdefine(&BlankEnvelope.e_macro, A_PERM,
2040 macid("{dsn_notify}"), NULL);
2041 BlankEnvelope.e_envid = NULL;
2042 macdefine(&BlankEnvelope.e_macro, A_PERM,
2043 macid("{dsn_envid}"), NULL);
2044 BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2045 macdefine(&BlankEnvelope.e_macro, A_PERM,
2046 macid("{dsn_ret}"), NULL);
2048 /* don't open maps for daemon -- done below in child */
2054 /* print configuration table (or at least part of it) */
2057 for (i = 0; i < MAXMAILERS; i++)
2059 if (Mailer[i] != NULL)
2060 printmailer(Mailer[i]);
2065 ** Switch to the main envelope.
2068 CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2069 sm_rpool_new_x(NULL));
2070 MainEnvelope.e_flags = BlankEnvelope.e_flags;
2073 ** If test mode, read addresses from stdin and process.
2076 if (OpMode == MD_TEST)
2078 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2083 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2084 "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2085 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2086 "Enter <ruleset> <address>\n");
2088 macdefine(&(MainEnvelope.e_macro), A_PERM,
2089 macid("{addr_type}"), "e r");
2094 (void) sm_signal(SIGINT, intindebug);
2095 (void) sm_releasesignal(SIGINT);
2097 (void) sm_io_fprintf(smioout,
2100 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2101 if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2102 sizeof buf) == NULL)
2103 testmodeline("/quit", &MainEnvelope);
2104 p = strchr(buf, '\n');
2108 (void) sm_io_fprintf(smioout,
2111 testmodeline(buf, &MainEnvelope);
2113 SM_EXCEPT(exc, "[!F]*")
2116 ** 8.10 just prints \n on interrupt.
2117 ** I'm printing the exception here in case
2118 ** sendmail is extended to raise additional
2119 ** exceptions in this context.
2122 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2124 sm_exc_print(exc, smioout);
2132 if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER)
2134 /* check whether STARTTLS is turned off for the client */
2135 if (chkclientmodifiers(D_NOTLS))
2138 else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2141 /* check whether STARTTLS is turned off for the server */
2142 if (chkdaemonmodifiers(D_NOTLS))
2145 else /* other modes don't need STARTTLS */
2150 /* basic TLS initialization */
2151 tls_ok = init_tls_library();
2154 if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2156 /* disable TLS for client */
2159 #endif /* STARTTLS */
2162 ** If collecting stuff from the queue, go start doing that.
2165 if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2170 /* init TLS for client, ignore result for now */
2171 (void) initclttls(tls_ok);
2172 #endif /* STARTTLS */
2175 ** The parent process of the caller of runqueue() needs
2176 ** to stay around for a possible SIGTERM. The SIGTERM will
2177 ** tell this process that all of the queue runners children
2178 ** need to be sent SIGTERM as well. At the same time, we
2179 ** want to return control to the command line. So we do an
2183 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2186 ** If the fork() failed we should still try to do
2187 ** the queue run. If it succeeded then the child
2188 ** is going to start the run and wait for all
2189 ** of the children to finish.
2194 /* Reset global flags */
2195 RestartRequest = NULL;
2196 ShutdownRequest = NULL;
2199 /* disconnect from terminal */
2200 disconnect(2, CurEnv);
2203 CurrentPid = getpid();
2206 int rwgflags = RWG_NONE;
2209 ** To run a specific queue group mark it to
2210 ** be run, select the work group it's in and
2211 ** increment the work counter.
2214 for (i = 0; i < NumQueue && Queue[i] != NULL;
2216 Queue[i]->qg_nextrun = (time_t) -1;
2217 Queue[qgrp]->qg_nextrun = 0;
2219 rwgflags |= RWG_VERBOSE;
2220 if (queuepersistent)
2221 rwgflags |= RWG_PERSISTENT;
2222 rwgflags |= RWG_FORCE;
2223 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2227 (void) runqueue(false, Verbose,
2228 queuepersistent, true);
2230 /* set the title to make it easier to find */
2231 sm_setproctitle(true, CurEnv, "Queue control");
2232 (void) sm_signal(SIGCHLD, SIG_DFL);
2233 while (CurChildren > 0)
2238 while ((ret = sm_wait(&status)) <= 0)
2241 /* Only drop when a child gives status */
2242 if (WIFSTOPPED(status))
2245 proc_list_drop(ret, status, NULL);
2248 finis(true, true, ExitStat);
2253 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2255 /* check whether AUTH is turned off for the server */
2256 if (!chkdaemonmodifiers(D_NOAUTH) &&
2257 (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2258 syserr("!sasl_server_init failed! [%s]",
2259 sasl_errstring(i, NULL, NULL));
2263 if (OpMode == MD_SMTP)
2265 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2266 PROC_DAEMON, 0, -1);
2268 /* clean up background delivery children */
2269 (void) sm_signal(SIGCHLD, reapchild);
2273 ** If a daemon, wait for a request.
2274 ** getrequests will always return in a child.
2275 ** If we should also be processing the queue, start
2276 ** doing it in background.
2277 ** We check for any errors that might have happened
2281 if (OpMode == MD_DAEMON || QueueIntvl > 0)
2285 if (!run_in_foreground && !tTd(99, 100))
2287 /* put us in background */
2290 syserr("daemon: cannot fork");
2293 finis(false, true, EX_OK);
2298 ** Initialize exception stack and default exception
2299 ** handler for child process.
2302 /* Reset global flags */
2303 RestartRequest = NULL;
2304 RestartWorkGroup = false;
2305 ShutdownRequest = NULL;
2307 CurrentPid = getpid();
2309 sm_exc_newthread(fatal_error);
2311 /* disconnect from our controlling tty */
2312 disconnect(2, &MainEnvelope);
2316 if (OpMode == MD_DAEMON)
2318 (void) sm_strlcat(dtype, "+SMTP", sizeof dtype);
2319 DaemonPid = CurrentPid;
2323 (void) sm_strlcat2(dtype,
2325 ? "+persistent-queueing@"
2327 pintvl(QueueIntvl, true),
2331 (void) sm_strlcat(dtype, "+debugging", sizeof dtype);
2333 sm_syslog(LOG_INFO, NOQID,
2334 "starting daemon (%s): %s", Version, dtype + 1);
2339 /* save daemon type in a macro for possible PidFile use */
2340 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2341 macid("{daemon_info}"), dtype + 1);
2343 /* save queue interval in a macro for possible PidFile use */
2344 macdefine(&MainEnvelope.e_macro, A_TEMP,
2345 macid("{queue_interval}"), pintvl(QueueIntvl, true));
2347 /* workaround: can't seem to release the signal in the parent */
2348 (void) sm_signal(SIGHUP, sighup);
2349 (void) sm_releasesignal(SIGHUP);
2350 (void) sm_signal(SIGTERM, sigterm);
2354 (void) runqueue(true, false, queuepersistent, true);
2357 ** If queuepersistent but not in daemon mode then
2358 ** we're going to do the queue runner monitoring here.
2359 ** If in daemon mode then the monitoring will happen
2363 if (OpMode != MD_DAEMON && queuepersistent)
2365 /* set the title to make it easier to find */
2366 sm_setproctitle(true, CurEnv, "Queue control");
2367 (void) sm_signal(SIGCHLD, SIG_DFL);
2368 while (CurChildren > 0)
2375 while ((ret = sm_wait(&status)) <= 0)
2378 if (WIFSTOPPED(status))
2381 /* Probe only on a child status */
2382 proc_list_drop(ret, status, &group);
2384 if (WIFSIGNALED(status))
2386 if (WCOREDUMP(status))
2388 sm_syslog(LOG_ERR, NOQID,
2389 "persistent queue runner=%d core dumped, signal=%d",
2390 group, WTERMSIG(status));
2392 /* don't restart this */
2393 mark_work_group_restart(
2398 sm_syslog(LOG_ERR, NOQID,
2399 "persistent queue runner=%d died, signal=%d",
2400 group, WTERMSIG(status));
2404 ** When debugging active, don't
2405 ** restart the persistent queues.
2406 ** But do log this as info.
2409 if (sm_debug_active(&DebugNoPRestart,
2412 sm_syslog(LOG_DEBUG, NOQID,
2413 "persistent queue runner=%d, exited",
2415 mark_work_group_restart(group,
2419 finis(true, true, ExitStat);
2423 if (OpMode != MD_DAEMON)
2428 ** Write the pid to file
2429 ** XXX Overwrites sendmail.pid
2432 log_sendmail_pid(&MainEnvelope);
2434 /* set the title to make it easier to find */
2436 (void) sm_strlcpyn(qtype, sizeof qtype, 4,
2438 pintvl(QueueIntvl, true),
2441 sm_setproctitle(true, CurEnv, qtype);
2447 (void) runqueue(true, false,
2452 dropenvelope(&MainEnvelope, true, false);
2455 /* init TLS for server, ignore result for now */
2456 (void) initsrvtls(tls_ok);
2457 #endif /* STARTTLS */
2460 p_flags = getrequests(&MainEnvelope);
2462 /* drop privileges */
2463 (void) drop_privileges(false);
2466 ** Get authentication data
2467 ** Set _ macro in BlankEnvelope before calling newenvelope().
2470 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2472 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2474 /* at this point we are in a child: reset state */
2475 sm_rpool_free(MainEnvelope.e_rpool);
2476 (void) newenvelope(&MainEnvelope, &MainEnvelope,
2477 sm_rpool_new_x(NULL));
2482 /* log connection information */
2483 sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2487 ** If running SMTP protocol, start collecting and executing
2488 ** commands. This will never return.
2491 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2496 ** Save some macros for check_* rulesets.
2503 (void) sm_snprintf(ipbuf, sizeof ipbuf, "[%.100s]",
2504 anynet_ntoa(&RealHostAddr));
2505 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2506 macid("{client_name}"), ipbuf);
2509 macdefine(&BlankEnvelope.e_macro, A_PERM,
2510 macid("{client_name}"), RealHostName);
2511 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2512 macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2515 switch (RealHostAddr.sa.sa_family)
2519 (void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2520 RealHostAddr.sin.sin_port);
2522 #endif /* NETINET */
2525 (void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2526 RealHostAddr.sin6.sin6_port);
2528 #endif /* NETINET6 */
2530 (void) sm_snprintf(pbuf, sizeof pbuf, "0");
2533 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2534 macid("{client_port}"), pbuf);
2536 if (OpMode == MD_DAEMON)
2538 /* validate the connection */
2540 nullserver = validate_connection(&RealHostAddr,
2545 else if (p_flags == NULL)
2547 p_flags = (BITMAP256 *) xalloc(sizeof *p_flags);
2551 if (OpMode == MD_SMTP)
2552 (void) initsrvtls(tls_ok);
2553 #endif /* STARTTLS */
2555 /* turn off profiling */
2557 smtp(nullserver, *p_flags, &MainEnvelope);
2561 /* turn off profiling */
2563 if (OpMode == MD_DAEMON)
2568 sm_rpool_free(MainEnvelope.e_rpool);
2569 clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2570 if (OpMode == MD_VERIFY)
2572 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2573 PostMasterCopy = NULL;
2577 /* interactive -- all errors are global */
2578 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2582 ** Do basic system initialization and set the sender
2585 initsys(&MainEnvelope);
2586 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2587 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2588 setsender(from, &MainEnvelope, NULL, '\0', false);
2589 if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2590 (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2591 strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2593 auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2594 RealUserName, from, warn_f_flag);
2603 /* set the initial sender for AUTH= to $f@$j */
2604 fv = macvalue('f', &MainEnvelope);
2605 if (fv == NULL || *fv == '\0')
2606 MainEnvelope.e_auth_param = NULL;
2609 if (strchr(fv, '@') == NULL)
2611 i = strlen(fv) + strlen(macvalue('j',
2612 &MainEnvelope)) + 2;
2614 (void) sm_strlcpyn(p, i, 3, fv, "@",
2619 p = sm_strdup_x(fv);
2620 MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2622 sm_free(p); /* XXX */
2625 if (macvalue('s', &MainEnvelope) == NULL)
2626 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2629 if (*av == NULL && !GrabTo)
2631 MainEnvelope.e_to = NULL;
2632 MainEnvelope.e_flags |= EF_GLOBALERRS;
2634 SuperSafe = SAFE_NO;
2635 usrerr("Recipient names must be specified");
2637 /* collect body for UUCP return */
2638 if (OpMode != MD_VERIFY)
2639 collect(InChannel, false, NULL, &MainEnvelope, true);
2640 finis(true, true, EX_USAGE);
2645 ** Scan argv and deliver the message to everyone.
2648 save_val = LogUsrErrs;
2650 sendtoargv(av, &MainEnvelope);
2651 LogUsrErrs = save_val;
2653 /* if we have had errors sofar, arrange a meaningful exit stat */
2654 if (Errors > 0 && ExitStat == EX_OK)
2655 ExitStat = EX_USAGE;
2659 ** If using -t, force not sending to argv recipients, even
2660 ** if they are mentioned in the headers.
2667 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2668 q->q_state = QS_REMOVED;
2670 #endif /* _FFR_FIX_DASHT */
2673 ** Read the input mail.
2676 MainEnvelope.e_to = NULL;
2677 if (OpMode != MD_VERIFY || GrabTo)
2680 unsigned long savedflags;
2683 ** workaround for compiler warning on Irix:
2684 ** do not initialize variable in the definition, but
2686 ** warning(1548): transfer of control bypasses
2687 ** initialization of:
2688 ** variable "savederrors" (declared at line 2570)
2689 ** variable "savedflags" (declared at line 2571)
2693 savederrors = Errors;
2694 savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2695 MainEnvelope.e_flags |= EF_GLOBALERRS;
2696 MainEnvelope.e_flags &= ~EF_FATALERRS;
2699 collect(InChannel, false, NULL, &MainEnvelope, true);
2701 /* header checks failed */
2707 /* Log who the mail would have gone to */
2708 logundelrcpts(&MainEnvelope,
2709 MainEnvelope.e_message,
2713 finis(true, true, ExitStat);
2718 /* bail out if message too large */
2719 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2721 finis(true, true, ExitStat != EX_OK ? ExitStat
2727 /* set message size */
2728 (void) sm_snprintf(buf, sizeof buf, "%ld",
2729 MainEnvelope.e_msgsize);
2730 macdefine(&MainEnvelope.e_macro, A_TEMP,
2731 macid("{msg_size}"), buf);
2733 Errors = savederrors;
2734 MainEnvelope.e_flags |= savedflags;
2739 sm_dprintf("From person = \"%s\"\n",
2740 MainEnvelope.e_from.q_paddr);
2743 /* Check if quarantining stats should be updated */
2744 if (MainEnvelope.e_quarmsg != NULL)
2745 markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2746 #endif /* _FFR_QUARANTINE */
2749 ** Actually send everything.
2750 ** If verifying, just ack.
2755 if (!split_by_recipient(&MainEnvelope) &&
2756 bitset(EF_FATALERRS, MainEnvelope.e_flags))
2760 /* make sure we deliver at least the first envelope */
2761 i = FastSplit > 0 ? 0 : -1;
2762 for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2766 e->e_from.q_state = QS_SENDER;
2769 sm_dprintf("main[%d]: QS_SENDER ", i);
2770 printaddr(&e->e_from, false);
2776 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2777 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2778 #endif /* NAMED_BIND */
2779 next = e->e_sibling;
2780 e->e_sibling = NULL;
2782 /* after FastSplit envelopes: queue up */
2783 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2784 e->e_sibling = next;
2789 ** Don't send return error message if in VERIFY mode.
2792 finis(true, true, ExitStat);
2797 ** STOP_SENDMAIL -- Stop the running program
2812 /* reset uid for process accounting */
2814 (void) setuid(RealUid);
2818 ** FINIS -- Clean up and exit.
2821 ** drop -- whether or not to drop CurEnv envelope
2822 ** cleanup -- call exit() or _exit()?
2823 ** exitstat -- exit status to use for exit() call
2833 finis(drop, cleanup, exitstat)
2836 volatile int exitstat;
2839 /* Still want to process new timeouts added below */
2841 (void) sm_releasesignal(SIGALRM);
2845 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2847 CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2848 printenvflags(CurEnv);
2851 printopenfds(false);
2855 ** Clean up. This might raise E:mta.quickabort
2858 /* clean up temp files */
2859 CurEnv->e_to = NULL;
2862 if (CurEnv->e_id != NULL)
2864 dropenvelope(CurEnv, true, false);
2865 sm_rpool_free(CurEnv->e_rpool);
2866 CurEnv->e_rpool = NULL;
2869 poststats(StatFile);
2872 /* flush any cached connections */
2873 mci_flush(true, NULL);
2875 /* close maps belonging to this pid */
2879 /* close UserDatabase */
2888 /* clean up extended load average stuff */
2898 sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
2900 if (exitstat == EX_TEMPFAIL ||
2901 CurEnv->e_errormode == EM_BERKNET)
2904 /* XXX clean up queues and related data structures */
2907 cleanup_shm(DaemonPid == getpid());
2908 #endif /* SM_CONF_SHM */
2910 /* reset uid for process accounting */
2912 sm_mbdb_terminate();
2913 (void) setuid(RealUid);
2915 /* dump the heap, if we are checking for memory leaks */
2916 if (sm_debug_active(&SmHeapCheck, 2))
2917 sm_heap_report(smioout,
2918 sm_debug_level(&SmHeapCheck) - 1);
2919 #endif /* SM_HEAP_CHECK */
2920 if (sm_debug_active(&SmXtrapReport, 1))
2921 sm_dprintf("xtrap count = %d\n", SmXtrapCount);
2929 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
2932 ** sig -- incoming signal.
2938 ** longjmps back to test mode loop.
2940 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2941 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2945 /* Type of an exception generated on SIGINT during address test mode. */
2946 static const SM_EXC_TYPE_T EtypeInterrupt =
2960 int save_errno = errno;
2962 FIX_SYSV_SIGNAL(sig, intindebug);
2964 CHECK_CRITICAL(sig);
2966 sm_exc_raisenew_x(&EtypeInterrupt);
2968 return SIGFUNC_RETURN;
2971 ** SIGTERM -- SIGTERM handler for the daemon
2974 ** sig -- signal number.
2980 ** Sets ShutdownRequest which will hopefully trigger
2981 ** the daemon to exit.
2983 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2984 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2993 int save_errno = errno;
2995 FIX_SYSV_SIGNAL(sig, sigterm);
2996 ShutdownRequest = "signal";
2998 return SIGFUNC_RETURN;
3001 ** SIGHUP -- handle a SIGHUP signal
3004 ** sig -- incoming signal.
3010 ** Sets RestartRequest which should cause the daemon
3013 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3014 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3023 int save_errno = errno;
3025 FIX_SYSV_SIGNAL(sig, sighup);
3026 RestartRequest = "signal";
3028 return SIGFUNC_RETURN;
3031 ** SIGPIPE -- signal handler for SIGPIPE
3034 ** sig -- incoming signal.
3040 ** Sets StopRequest which should cause the mailq/hoststatus
3043 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3044 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3053 int save_errno = errno;
3055 FIX_SYSV_SIGNAL(sig, sigpipe);
3058 return SIGFUNC_RETURN;
3061 ** INTSIG -- clean up on interrupt
3063 ** This just arranges to exit. It pessimizes in that it
3064 ** may resend a message.
3073 ** Unlocks the current job.
3075 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3076 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3079 ** XXX: More work is needed for this signal handler.
3088 int save_errno = errno;
3090 FIX_SYSV_SIGNAL(sig, intsig);
3092 CHECK_CRITICAL(sig);
3093 sm_allsignals(true);
3095 if (sig != 0 && LogLevel > 79)
3096 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3099 /* Clean-up on aborted stdin message submission */
3100 if (CurEnv->e_id != NULL &&
3101 (OpMode == MD_SMTP ||
3102 OpMode == MD_DELIVER ||
3103 OpMode == MD_ARPAFTP))
3105 register ADDRESS *q;
3107 /* don't return an error indication */
3108 CurEnv->e_to = NULL;
3109 CurEnv->e_flags &= ~EF_FATALERRS;
3110 CurEnv->e_flags |= EF_CLRQUEUE;
3113 ** Spin through the addresses and
3114 ** mark them dead to prevent bounces
3117 for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
3118 q->q_state = QS_DONTSEND;
3122 else if (OpMode != MD_TEST)
3124 unlockqueue(CurEnv);
3127 finis(drop, false, EX_OK);
3131 ** DISCONNECT -- remove our connection with any foreground process
3134 ** droplev -- how "deeply" we should drop the line.
3135 ** 0 -- ignore signals, mail back errors, make sure
3136 ** output goes to stdout.
3137 ** 1 -- also, make stdout go to /dev/null.
3138 ** 2 -- also, disconnect from controlling terminal
3139 ** (only for daemon mode).
3140 ** e -- the current envelope.
3146 ** Trys to insure that we are immune to vagaries of
3147 ** the controlling tty.
3151 disconnect(droplev, e)
3153 register ENVELOPE *e;
3158 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3159 sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3160 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3163 sm_dprintf("don't\n");
3167 sm_syslog(LOG_DEBUG, e->e_id,
3168 "disconnect level %d",
3171 /* be sure we don't get nasty signals */
3172 (void) sm_signal(SIGINT, SIG_IGN);
3173 (void) sm_signal(SIGQUIT, SIG_IGN);
3175 /* we can't communicate with our caller, so.... */
3177 CurEnv->e_errormode = EM_MAIL;
3179 DisConnected = true;
3181 /* all input from /dev/null */
3182 if (InChannel != smioin)
3184 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3187 if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3188 SM_IO_RDONLY, NULL, smioin) == NULL)
3189 sm_syslog(LOG_ERR, e->e_id,
3190 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3191 SM_PATH_DEVNULL, sm_errstring(errno));
3194 ** output to the transcript
3195 ** We also compare the fd numbers here since OutChannel
3196 ** might be a layer on top of smioout due to encryption
3200 if (OutChannel != smioout &&
3201 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3202 sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3204 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3205 OutChannel = smioout;
3209 ** Has smioout been closed? Reopen it.
3210 ** This shouldn't happen anymore, the code is here
3211 ** just as a reminder.
3214 if (smioout->sm_magic == NULL &&
3215 sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3216 SM_IO_WRONLY, NULL, smioout) == NULL)
3217 sm_syslog(LOG_ERR, e->e_id,
3218 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3219 SM_PATH_DEVNULL, sm_errstring(errno));
3224 fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3226 sm_syslog(LOG_ERR, e->e_id,
3227 "disconnect: open(\"%s\") failed: %s",
3228 SM_PATH_DEVNULL, sm_errstring(errno));
3229 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3230 (void) dup2(fd, STDOUT_FILENO);
3231 (void) dup2(fd, STDERR_FILENO);
3235 /* drop our controlling TTY completely if possible */
3243 checkfd012("disconnect");
3247 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3260 while ((ap = *++argv) != NULL)
3262 /* Return if "--" or not an option of any form. */
3263 if (ap[0] != '-' || ap[1] == '-')
3267 /* Don't allow users to use "-Q." or "-Q ." */
3268 if ((ap[1] == 'Q' && ap[2] == '.') ||
3269 (ap[1] == 'Q' && argv[1] != NULL &&
3270 argv[1][0] == '.' && argv[1][1] == '\0'))
3272 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3273 "Can not use -Q.\n");
3276 #endif /* _FFR_QUARANTINE */
3278 /* skip over options that do have a value */
3279 op = strchr(OPTIONS, ap[1]);
3280 if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3282 #if defined(sony_news)
3283 ap[1] != 'E' && ap[1] != 'J' &&
3284 #endif /* defined(sony_news) */
3285 argv[1] != NULL && argv[1][0] != '-')
3291 /* If -C doesn't have an argument, use sendmail.cf. */
3292 #define __DEFPATH "sendmail.cf"
3293 if (ap[1] == 'C' && ap[2] == '\0')
3295 *argv = xalloc(sizeof(__DEFPATH) + 2);
3296 (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3300 /* If -q doesn't have an argument, run it once. */
3301 if (ap[1] == 'q' && ap[2] == '\0')
3305 /* If -Q doesn't have an argument, disable quarantining */
3306 if (ap[1] == 'Q' && ap[2] == '\0')
3308 #endif /* _FFR_QUARANTINE */
3310 /* if -d doesn't have an argument, use 0-99.1 */
3311 if (ap[1] == 'd' && ap[2] == '\0')
3314 #if defined(sony_news)
3315 /* if -E doesn't have an argument, use -EC */
3316 if (ap[1] == 'E' && ap[2] == '\0')
3319 /* if -J doesn't have an argument, use -JJ */
3320 if (ap[1] == 'J' && ap[2] == '\0')
3322 #endif /* defined(sony_news) */
3326 ** AUTH_WARNING -- specify authorization warning
3329 ** e -- the current envelope.
3330 ** msg -- the text of the message.
3331 ** args -- arguments to the message.
3339 auth_warning(register ENVELOPE *e, const char *msg, ...)
3340 #else /* __STDC__ */
3341 auth_warning(e, msg, va_alist)
3342 register ENVELOPE *e;
3345 #endif /* __STDC__ */
3350 if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3353 static char hostbuf[48];
3355 if (hostbuf[0] == '\0')
3359 hp = myhostname(hostbuf, sizeof hostbuf);
3366 #endif /* NETINET6 */
3369 (void) sm_strlcpyn(buf, sizeof buf, 2, hostbuf, ": ");
3370 p = &buf[strlen(buf)];
3371 SM_VA_START(ap, msg);
3372 (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3374 addheader("X-Authentication-Warning", buf, 0, e);
3376 sm_syslog(LOG_INFO, e->e_id,
3377 "Authentication-Warning: %.400s",
3382 ** GETEXTENV -- get from external environment
3385 ** envar -- the name of the variable to retrieve
3388 ** The value, if any.
3399 for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3401 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3402 return &(*envp)[l + 1];
3407 ** SETUSERENV -- set an environment in the propagated environment
3410 ** envar -- the name of the environment variable.
3411 ** value -- the value to which it should be set. If
3412 ** null, this is extracted from the incoming
3413 ** environment. If that is not set, the call
3414 ** to setuserenv is ignored.
3421 setuserenv(envar, value)
3426 char **evp = UserEnviron;
3431 value = getextenv(envar);
3436 /* XXX enforce reasonable size? */
3437 i = strlen(envar) + 1;
3438 l = strlen(value) + i + 1;
3439 p = (char *) xalloc(l);
3440 (void) sm_strlcpyn(p, l, 3, envar, "=", value);
3442 while (*evp != NULL && strncmp(*evp, p, i) != 0)
3448 else if (evp < &UserEnviron[MAXUSERENVIRON])
3454 /* make sure it is in our environment as well */
3456 syserr("setuserenv: putenv(%s) failed", p);
3459 ** DUMPSTATE -- dump state
3468 register char *j = macvalue('j', CurEnv);
3470 extern int NextMacroId;
3472 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3473 "--- dumping state on %s: $j = %s ---",
3475 j == NULL ? "<NULL>" : j);
3478 if (!wordinclass(j, 'w'))
3479 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3480 "*** $j not in $=w ***");
3482 sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3483 sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3484 NextMacroId, MAXMACROID);
3485 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3487 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3489 rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3493 register char **pvp;
3494 char *pv[MAXATOM + 1];
3497 status = REWRITE(pv, rs, CurEnv);
3498 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3499 "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3501 for (pvp = pv; *pvp != NULL; pvp++)
3502 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3504 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3509 ** SIGUSR1 -- Signal a request to dump state.
3512 ** sig -- calling signal.
3517 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3518 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3521 ** XXX: More work is needed for this signal handler.
3529 int save_errno = errno;
3531 extern void dumpstab __P((void));
3532 # endif /* SM_HEAP_CHECK */
3534 FIX_SYSV_SIGNAL(sig, sigusr1);
3536 CHECK_CRITICAL(sig);
3537 dumpstate("user signal");
3540 # endif /* SM_HEAP_CHECK */
3542 return SIGFUNC_RETURN;
3544 #endif /* SIGUSR1 */
3547 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3550 ** to_real_uid -- if set, drop to the real uid instead
3551 ** of the RunAsUser.
3554 ** EX_OSERR if the setuid failed.
3559 drop_privileges(to_real_uid)
3563 GIDSET_T emptygidset[1];
3566 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",
3568 (int) RealUid, (int) RealGid,
3569 (int) getuid(), (int) getgid(),
3570 (int) geteuid(), (int) getegid(),
3571 (int) RunAsUid, (int) RunAsGid);
3575 RunAsUserName = RealUserName;
3581 /* make sure no one can grab open descriptors for secret files */
3583 sm_mbdb_terminate();
3585 /* reset group permissions; these can be set later */
3586 emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3589 ** Notice: on some OS (Linux...) the setgroups() call causes
3590 ** a logfile entry if sendmail is not run by root.
3591 ** However, it is unclear (no POSIX standard) whether
3592 ** setgroups() can only succeed if executed by root.
3593 ** So for now we keep it as it is; if you want to change it, use
3594 ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3597 if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3599 syserr("drop_privileges: setgroups(1, %d) failed",
3600 (int) emptygidset[0]);
3604 /* reset primary group id */
3608 ** Drop gid to real gid.
3609 ** On some OS we must reset the effective[/real[/saved]] gid,
3610 ** and then use setgid() to finally drop all group privileges.
3611 ** Later on we check whether we can get back the
3616 if (setegid(RunAsGid) < 0)
3618 syserr("drop_privileges: setegid(%d) failed",
3622 #else /* HASSETEGID */
3624 if (setregid(RunAsGid, RunAsGid) < 0)
3626 syserr("drop_privileges: setregid(%d, %d) failed",
3627 (int) RunAsGid, (int) RunAsGid);
3630 # else /* HASSETREGID */
3632 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3634 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3635 (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3638 # endif /* HASSETRESGID */
3639 # endif /* HASSETREGID */
3640 #endif /* HASSETEGID */
3642 if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3644 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3646 syserr("drop_privileges: setgid(%d) failed",
3651 if (rval == EX_OK && getegid() != RunAsGid)
3653 syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3654 (int) getegid(), (int) RunAsGid);
3659 /* fiddle with uid */
3660 if (to_real_uid || RunAsUid != 0)
3665 ** Try to setuid(RunAsUid).
3666 ** euid must be RunAsUid,
3667 ** ruid must be RunAsUid unless (e|r)uid wasn't 0
3668 ** and we didn't have to drop privileges to the real uid.
3671 if (setuid(RunAsUid) < 0 ||
3672 geteuid() != RunAsUid ||
3673 (getuid() != RunAsUid &&
3674 (to_real_uid || geteuid() == 0 || getuid() == 0)))
3678 ** if ruid != RunAsUid, euid == RunAsUid, then
3679 ** try resetting just the real uid, then using
3680 ** setuid() to drop the saved-uid as well.
3683 if (geteuid() == RunAsUid)
3685 if (setreuid(RunAsUid, -1) < 0)
3687 syserr("drop_privileges: setreuid(%d, -1) failed",
3691 if (setuid(RunAsUid) < 0)
3693 syserr("drop_privileges: second setuid(%d) attempt failed",
3699 #endif /* HASSETREUID */
3701 syserr("drop_privileges: setuid(%d) failed",
3707 if (RunAsUid != 0 && setuid(0) == 0)
3710 ** Believe it or not, the Linux capability model
3711 ** allows a non-root process to override setuid()
3712 ** on a process running as root and prevent that
3713 ** process from dropping privileges.
3716 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3719 else if (RunAsUid != euid && setuid(euid) == 0)
3722 ** Some operating systems will keep the saved-uid
3723 ** if a non-root effective-uid calls setuid(real-uid)
3724 ** making it possible to set it back again later.
3727 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3732 if ((to_real_uid || RunAsGid != 0) &&
3733 rval == EX_OK && RunAsGid != EffGid &&
3734 getuid() != 0 && geteuid() != 0)
3737 if (setgid(EffGid) == 0)
3739 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3747 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3748 (int) geteuid(), (int) getuid(),
3749 (int) getegid(), (int) getgid());
3750 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3751 (int) RunAsUid, (int) RunAsGid);
3753 sm_dprintf("drop_privileges: rval = %d\n", rval);
3758 ** FILL_FD -- make sure a file descriptor has been properly allocated
3760 ** Used to make sure that stdin/out/err are allocated on startup
3763 ** fd -- the file descriptor to be filled.
3764 ** where -- a string used for logging. If NULL, this is
3765 ** being called on startup, and logging should
3772 ** possibly changes MissingFds
3783 if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3787 syserr("fill_fd: %s: fd %d not open", where, fd);
3789 MissingFds |= 1 << fd;
3790 i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3793 syserr("!fill_fd: %s: cannot open %s",
3794 where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3803 ** SM_PRINTOPTIONS -- print options
3806 ** options -- array of options.
3813 sm_printoptions(options)
3823 if (ll + strlen(*av) > 63)
3832 sm_dprintf("%s", *av);
3833 ll += strlen(*av++) + 1;
3838 ** TESTMODELINE -- process a test mode input line
3841 ** line -- the input line.
3842 ** e -- the current environment.
3845 ** .X process X as a configuration line
3846 ** =X dump a configuration item (such as mailers)
3847 ** $X dump a macro or class
3848 ** /X try an activity
3849 ** X normal process through rule set X
3853 testmodeline(line, e)
3859 auto char *delimptr;
3866 static int tryflags = RF_COPYNONE;
3867 char exbuf[MAXLINE];
3868 extern unsigned char TokTypeNoC[];
3870 /* skip leading spaces */
3871 while (*line == ' ')
3884 case '.': /* config-style settings */
3888 mid = macid_parse(&line[2], &delimptr);
3891 translate_dollars(delimptr);
3892 macdefine(&e->e_macro, A_TEMP, mid, delimptr);
3896 if (line[2] == '\0') /* not to call syserr() */
3899 mid = macid_parse(&line[2], &delimptr);
3902 translate_dollars(delimptr);
3903 expand(delimptr, exbuf, sizeof exbuf, e);
3910 while (*p != '\0' && isascii(*p) && isspace(*p))
3913 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
3924 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3925 "Usage: .[DC]macro value(s)\n");
3929 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3930 "Unknown \".\" command %s\n", line);
3935 case '=': /* config-style settings */
3938 case 'S': /* dump rule set */
3939 rs = strtorwset(&line[2], NULL, ST_FIND);
3942 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3943 "Undefined ruleset %s\n", &line[2]);
3946 rw = RewriteRules[rs];
3951 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3957 (void) sm_io_putc(smioout,
3958 SM_TIME_DEFAULT, ' ');
3960 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3962 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3968 (void) sm_io_putc(smioout,
3969 SM_TIME_DEFAULT, ' ');
3971 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3973 } while ((rw = rw->r_next) != NULL);
3977 for (i = 0; i < MAXMAILERS; i++)
3979 if (Mailer[i] != NULL)
3980 printmailer(Mailer[i]);
3985 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3986 "Usage: =Sruleset or =M\n");
3990 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3991 "Unknown \"=\" command %s\n", line);
3996 case '-': /* set command-line-like opts */
4004 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4005 "Usage: -d{debug arguments}\n");
4009 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4010 "Unknown \"-\" command %s\n", line);
4018 mid = macid(&line[2]);
4020 stabapply(dump_class, mid);
4023 mid = macid(&line[1]);
4026 p = macvalue(mid, e);
4028 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4033 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4038 case '/': /* miscellaneous commands */
4039 p = &line[strlen(line)];
4040 while (--p >= line && isascii(*p) && isspace(*p))
4042 p = strpbrk(line, " \t");
4045 while (isascii(*p) && isspace(*p))
4050 if (line[1] == '\0')
4052 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4053 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4056 if (sm_strcasecmp(&line[1], "quit") == 0)
4058 CurEnv->e_id = NULL;
4059 finis(true, true, ExitStat);
4062 if (sm_strcasecmp(&line[1], "mx") == 0)
4065 /* look up MX records */
4068 char *mxhosts[MAXMXHOSTS + 1];
4072 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4073 "Usage: /mx address\n");
4076 nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4078 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4079 "getmxrr(%s) returns %d value(s):\n",
4081 for (i = 0; i < nmx; i++)
4082 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4083 "\t%s\n", mxhosts[i]);
4084 #else /* NAMED_BIND */
4085 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4086 "No MX code compiled in\n");
4087 #endif /* NAMED_BIND */
4089 else if (sm_strcasecmp(&line[1], "canon") == 0)
4091 char host[MAXHOSTNAMELEN];
4095 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4096 "Usage: /canon address\n");
4099 else if (sm_strlcpy(host, p, sizeof host) >= sizeof host)
4101 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4105 (void) getcanonname(host, sizeof host, !HasWildcardMX,
4107 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4108 "getcanonname(%s) returns %s\n",
4111 else if (sm_strcasecmp(&line[1], "map") == 0)
4113 auto int rcode = EX_OK;
4118 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4119 "Usage: /map mapname key\n");
4122 for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q)); q++)
4126 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4127 "No key specified\n");
4131 map = stab(p, ST_MAP, ST_FIND);
4134 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4135 "Map named \"%s\" not found\n", p);
4138 if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4139 !openmap(&(map->s_map)))
4141 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4142 "Map named \"%s\" not open\n", p);
4145 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4146 "map_lookup: %s (%s) ", p, q);
4149 p = (*map->s_map.map_class->map_lookup)
4150 (&map->s_map, q, av, &rcode);
4152 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4156 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4157 "returns %s (%d)\n", p,
4160 else if (sm_strcasecmp(&line[1], "try") == 0)
4164 auto int rcode = EX_OK;
4166 q = strpbrk(p, " \t");
4169 while (isascii(*q) && isspace(*q))
4172 if (q == NULL || *q == '\0')
4174 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4175 "Usage: /try mailer address\n");
4178 st = stab(p, ST_MAILER, ST_FIND);
4181 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4182 "Unknown mailer %s\n", p);
4186 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4187 "Trying %s %s address %s for mailer %s\n",
4188 bitset(RF_HEADERADDR, tryflags) ? "header"
4190 bitset(RF_SENDERADDR, tryflags) ? "sender"
4191 : "recipient", q, p);
4192 p = remotename(q, m, tryflags, &rcode, CurEnv);
4193 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4194 "Rcode = %d, addr = %s\n",
4195 rcode, p == NULL ? "<NULL>" : p);
4198 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4202 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4203 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4206 for (; *p != '\0'; p++)
4212 tryflags |= RF_HEADERADDR;
4217 tryflags &= ~RF_HEADERADDR;
4222 tryflags |= RF_SENDERADDR;
4227 tryflags &= ~RF_SENDERADDR;
4231 exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4233 exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4235 macdefine(&e->e_macro, A_TEMP,
4236 macid("{addr_type}"), exbuf);
4238 else if (sm_strcasecmp(&line[1], "parse") == 0)
4242 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4243 "Usage: /parse address\n");
4246 q = crackaddr(p, e);
4247 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4248 "Cracked address = ");
4250 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4251 "\nParsing %s %s address\n",
4252 bitset(RF_HEADERADDR, tryflags) ?
4253 "header" : "envelope",
4254 bitset(RF_SENDERADDR, tryflags) ?
4255 "sender" : "recipient");
4256 if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4258 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4260 else if (a.q_host != NULL && a.q_host[0] != '\0')
4261 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4262 "mailer %s, host %s, user %s\n",
4267 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4268 "mailer %s, user %s\n",
4275 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4276 "Unknown \"/\" command %s\n",
4282 for (p = line; isascii(*p) && isspace(*p); p++)
4285 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4289 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4294 if (invalidaddr(p + 1, NULL, true))
4298 register char **pvp;
4299 char pvpbuf[PSBUFSIZE];
4301 pvp = prescan(++p, ',', pvpbuf, sizeof pvpbuf,
4302 &delimptr, ConfigLevel >= 9 ? TokTypeNoC : NULL);
4310 rs = strtorwset(p, NULL, ST_FIND);
4313 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4314 "Undefined ruleset %s\n",
4318 status = REWRITE(pvp, rs, e);
4319 if (status != EX_OK)
4320 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4321 "== Ruleset %s (%d) status %d\n",
4323 while (*p != '\0' && *p++ != ',')
4326 } while (*(p = delimptr) != '\0');
4334 if (s->s_symtype != ST_CLASS)
4336 if (bitnset(bitidx(id), s->s_class))
4337 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4342 ** An exception type used to create QuickAbort exceptions.
4343 ** This is my first cut at converting QuickAbort from longjmp to exceptions.
4344 ** These exceptions have a single integer argument, which is the argument
4345 ** to longjmp in the original code (either 1 or 2). I don't know the
4346 ** significance of 1 vs 2: the calls to setjmp don't care.
4349 const SM_EXC_TYPE_T EtypeQuickAbort =