2 * Copyright (c) 1998-2006 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-2003 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.944 2006/04/21 23:56:42 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 */
178 char *quarantining = NULL; /* quarantine queue items? */
181 bool queuepersistent = false; /* queue runner process runs forever */
182 bool foregroundqueue = false; /* queue run in foreground */
183 bool save_val; /* to save some bool var. */
184 int cftype; /* which cf file to use? */
186 static time_t starttime = 0; /* when was process started */
187 struct stat traf_st; /* for TrafficLog FIFO check */
189 char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */
190 static char rnamebuf[MAXNAME]; /* holds RealUserName */
191 char *emptyenviron[1];
194 #endif /* STARTTLS */
197 extern int DtableSize;
201 extern char **environ;
203 extern void sm_sasl_init __P((void));
208 #endif /* USE_ENVIRON */
210 /* turn off profiling */
213 /* install default exception handler */
214 sm_exc_newthread(fatal_error);
216 /* set the default in/out channel so errors reported to screen */
218 OutChannel = smioout;
221 ** Check to see if we reentered.
222 ** This would normally happen if e_putheader or e_putbody
223 ** were NULL when invoked.
228 syserr("main: reentered!");
231 starttime = curtime();
233 /* avoid null pointer dereferences */
234 TermEscape.te_rv_on = TermEscape.te_rv_off = "";
239 /* Check if sendmail is running with extra privs */
240 extraprivs = (RealUid != 0 &&
241 (geteuid() != getuid() || getegid() != getgid()));
243 CurrentPid = getpid();
245 /* get whatever .cf file is right for the opmode */
246 cftype = SM_GET_RIGHT_CF;
248 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
249 DtableSize = getdtsize();
250 if (DtableSize > 256)
254 ** Be sure we have enough file descriptors.
255 ** But also be sure that 0, 1, & 2 are open.
258 /* reset errno and fill_errno; the latter is used way down below */
259 errno = fill_errno = 0;
260 fill_fd(STDIN_FILENO, NULL);
263 fill_fd(STDOUT_FILENO, NULL);
266 fill_fd(STDERR_FILENO, NULL);
270 sm_closefrom(STDERR_FILENO + 1, DtableSize);
276 # define SM_LOG_STR "sendmail"
277 # endif /* ! SM_LOG_STR */
279 openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
280 # else /* LOG_MAIL */
281 openlog(SM_LOG_STR, LOG_PID);
282 # endif /* LOG_MAIL */
286 ** Seed the random number generator.
287 ** Used for queue file names, picking a queue directory, and
293 /* do machine-dependent initializations */
297 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
299 /* reset status from syserr() calls for missing file descriptors */
303 SubmitMode = SUBMIT_UNKNOWN;
305 checkfd012("after openlog");
308 tTsetup(tTdvect, sizeof tTdvect, "0-99.1,*_trace_*.1");
311 /* save initial group set for future checks */
312 i = getgroups(NGROUPS_MAX, InitialGidSet);
315 InitialGidSet[0] = (GID_T) -1;
318 while (i < NGROUPS_MAX)
319 InitialGidSet[i++] = InitialGidSet[0];
320 #endif /* NGROUPS_MAX */
322 /* drop group id privileges (RunAsUser not yet set) */
323 dp = drop_privileges(false);
327 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
330 /* arrange to dump state on user-1 signal */
331 (void) sm_signal(SIGUSR1, sigusr1);
335 /* ignore user-1 signal */
336 (void) sm_signal(SIGUSR1, SIG_IGN);
340 /* initialize for setproctitle */
341 initsetproctitle(argc, argv, envp);
343 /* Handle any non-getoptable constructions. */
347 ** Do a quick prescan of the argument list.
351 /* find initial opMode */
354 p = strrchr(*av, '/');
357 if (strcmp(p, "newaliases") == 0)
358 OpMode = MD_INITALIAS;
359 else if (strcmp(p, "mailq") == 0)
361 else if (strcmp(p, "smtpd") == 0)
363 else if (strcmp(p, "hoststat") == 0)
364 OpMode = MD_HOSTSTAT;
365 else if (strcmp(p, "purgestat") == 0)
366 OpMode = MD_PURGESTAT;
368 #if defined(__osf__) || defined(_AIX3)
369 # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:x"
370 #endif /* defined(__osf__) || defined(_AIX3) */
371 #if defined(sony_news)
372 # define OPTIONS "A:B:b:C:cD:d:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
373 #endif /* defined(sony_news) */
375 # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
376 #endif /* ! OPTIONS */
378 /* Set to 0 to allow -b; need to check optarg before using it! */
380 while ((j = getopt(argc, argv, OPTIONS)) != -1)
384 case 'b': /* operations mode */
385 j = (optarg == NULL) ? ' ' : *optarg;
404 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
405 "Frozen configurations unsupported\n");
409 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
410 "Invalid operation mode %c\n",
420 syserr("-D file must be before -d");
424 dp = drop_privileges(true);
426 smdebug = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
427 optarg, SM_IO_APPEND, NULL);
430 syserr("cannot open %s", optarg);
431 ExitStat = EX_CANTCREAT;
434 sm_debug_setfile(smdebug);
440 (void) sm_io_setvbuf(sm_debug_file(), SM_TIME_DEFAULT,
441 (char *) NULL, SM_IO_NBF,
445 case 'G': /* relay (gateway) submission */
446 SubmitMode = SUBMIT_MTA;
452 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
453 "option requires an argument -- '%c'",
457 j = SM_MIN(strlen(optarg), 32) + 1;
458 sysloglabel = xalloc(j);
459 (void) sm_strlcpy(sysloglabel, optarg, j);
460 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
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");
479 sm_debug_setfile(NULL);
480 (void) memset(tTdvect, '\0', sizeof tTdvect);
484 if (sysloglabel != NULL)
486 /* Sanitize the string */
487 for (p = sysloglabel; *p != '\0'; p++)
489 if (!isascii(*p) || !isprint(*p) || *p == '%')
494 openlog(sysloglabel, LOG_PID, LOG_MAIL);
495 # else /* LOG_MAIL */
496 openlog(sysloglabel, LOG_PID);
497 # endif /* LOG_MAIL */
501 /* set up the blank envelope */
502 BlankEnvelope.e_puthdr = putheader;
503 BlankEnvelope.e_putbody = putbody;
504 BlankEnvelope.e_xfp = NULL;
505 STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
506 CurEnv = &BlankEnvelope;
507 STRUCTCOPY(NullAddress, MainEnvelope.e_from);
510 ** Set default values for variables.
511 ** These cannot be in initialized data space.
514 setdefaults(&BlankEnvelope);
515 initmacros(&BlankEnvelope);
519 if (OpMode == MD_DAEMON)
520 DaemonPid = CurrentPid; /* needed for finis() to work */
522 pw = sm_getpwuid(RealUid);
524 (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof rnamebuf);
526 (void) sm_snprintf(rnamebuf, sizeof rnamebuf, "Unknown UID %d",
529 RealUserName = rnamebuf;
533 sm_dprintf("Version %s\n", Version);
534 finis(false, true, EX_OK);
539 ** if running non-set-user-ID binary as non-root, pretend
540 ** we are the RunAsUid
543 if (RealUid != 0 && geteuid() == RealUid)
546 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
550 else if (geteuid() != 0)
551 RunAsUid = geteuid();
554 if (RealUid != 0 && EffGid == RealGid)
559 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
560 (int) geteuid(), (int) getuid(),
561 (int) getegid(), (int) getgid());
562 sm_dprintf("main: RunAsUser = %d:%d\n",
563 (int) RunAsUid, (int) RunAsGid);
566 /* save command line arguments */
568 for (av = argv; *av != NULL; )
569 j += strlen(*av++) + 1;
570 SaveArgv = (char **) xalloc(sizeof (char *) * (argc + 1));
571 CommandLineArgs = xalloc(j);
573 for (av = argv, i = 0; *av != NULL; )
577 SaveArgv[i++] = newstr(*av);
580 (void) sm_strlcpy(p, *av++, j);
589 extern char *CompileOptions[];
591 sm_dprintf("Version %s\n Compiled with:", Version);
592 sm_printoptions(CompileOptions);
596 extern char *OsCompileOptions[];
598 sm_dprintf(" OS Defines:");
599 sm_printoptions(OsCompileOptions);
601 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
602 #endif /* _PATH_UNIX */
604 sm_dprintf(" Conf file:\t%s (default for MSP)\n",
605 getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
607 sm_dprintf(" Conf file:\t%s (default for MTA)\n",
608 getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
610 sm_dprintf(" Pid file:\t%s (default)\n", PidFile);
615 extern char *SmCompileOptions[];
617 sm_dprintf(" libsm Defines:");
618 sm_printoptions(SmCompileOptions);
623 extern char *FFRCompileOptions[];
625 sm_dprintf(" FFR Defines:");
626 sm_printoptions(FFRCompileOptions);
629 /* clear sendmail's environment */
630 ExternalEnviron = environ;
631 emptyenviron[0] = NULL;
632 environ = emptyenviron;
635 ** restore any original TZ setting until TimeZoneSpec has been
636 ** determined - or early log messages may get bogus time stamps
639 if ((p = getextenv("TZ")) != NULL)
644 /* XXX check for reasonable length? */
645 tzlen = strlen(p) + 4;
647 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
649 /* XXX check return code? */
653 /* prime the child environment */
654 sm_setuserenv("AGENT", "sendmail");
656 (void) sm_signal(SIGPIPE, SIG_IGN);
657 OldUmask = umask(022);
658 FullName = getextenv("NAME");
659 if (FullName != NULL)
660 FullName = newstr(FullName);
663 ** Initialize name server if it is going to be used.
667 if (!bitset(RES_INIT, _res.options))
670 _res.options |= RES_DEBUG;
672 _res.options &= ~RES_DEBUG;
673 # ifdef RES_NOALIASES
674 _res.options |= RES_NOALIASES;
675 # endif /* RES_NOALIASES */
676 TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
677 TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
678 TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
679 TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
680 TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
681 TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
682 #endif /* NAMED_BIND */
687 /* initialize some macros, etc. */
688 init_vendor_macros(&BlankEnvelope);
691 macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
694 hp = myhostname(jbuf, sizeof jbuf);
697 struct utsname utsname;
700 sm_dprintf("Canonical name: %s\n", jbuf);
701 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
702 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
705 p = strchr(jbuf, '.');
706 if (p != NULL && p[1] != '\0')
707 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm', &p[1]);
709 if (uname(&utsname) >= 0)
710 p = utsname.nodename;
714 sm_dprintf("uname failed (%s)\n",
715 sm_errstring(errno));
720 sm_dprintf(" UUCP nodename: %s\n", p);
721 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
727 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
730 sm_dprintf("\ta.k.a.: %s\n", *av);
733 #if NETINET || NETINET6
734 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
738 char buf6[INET6_ADDRSTRLEN];
740 # endif /* NETINET6 */
743 # endif /* NETINET */
747 switch (hp->h_addrtype)
751 if (hp->h_length != INADDRSZ)
754 memmove(&ia, hp->h_addr_list[i], INADDRSZ);
755 (void) sm_snprintf(ipbuf, sizeof ipbuf,
756 "[%.100s]", inet_ntoa(ia));
758 # endif /* NETINET */
762 if (hp->h_length != IN6ADDRSZ)
765 memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
766 addr = anynet_ntop(&ia6, buf6, sizeof buf6);
768 (void) sm_snprintf(ipbuf, sizeof ipbuf,
771 # endif /* NETINET6 */
773 if (ipbuf[0] == '\0')
777 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
778 setclass('w', ipbuf);
780 #endif /* NETINET || NETINET6 */
784 #endif /* NETINET6 */
788 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
790 /* current load average */
793 QueueLimitRecipient = (QUEUE_CHAR *) NULL;
794 QueueLimitSender = (QUEUE_CHAR *) NULL;
795 QueueLimitId = (QUEUE_CHAR *) NULL;
796 QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
803 while ((j = getopt(argc, argv, OPTIONS)) != -1)
807 case 'b': /* operations mode */
811 case 'A': /* use Alternate sendmail/submit.cf */
812 cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
813 : SM_GET_SENDMAIL_CF;
816 case 'B': /* body type */
817 CHECK_AGAINST_OPMODE(j);
818 BlankEnvelope.e_bodytype = newstr(optarg);
821 case 'C': /* select configuration file (already done) */
824 conffile = newstr(optarg);
825 dp = drop_privileges(true);
831 case 'd': /* debugging */
835 case 'f': /* from address */
836 case 'r': /* obsolete -f flag */
837 CHECK_AGAINST_OPMODE(j);
840 usrerr("More than one \"from\" person");
844 if (optarg[0] == '\0')
847 from = newstr(denlstring(optarg, true, true));
848 if (strcmp(RealUserName, from) != 0)
852 case 'F': /* set full name */
853 CHECK_AGAINST_OPMODE(j);
854 FullName = newstr(optarg);
857 case 'G': /* relay (gateway) submission */
859 CHECK_AGAINST_OPMODE(j);
862 case 'h': /* hop count */
863 CHECK_AGAINST_OPMODE(j);
864 BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
866 (void) sm_snprintf(buf, sizeof buf, "%d",
867 BlankEnvelope.e_hopcount);
868 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
872 usrerr("Bad hop count (%s)", optarg);
877 case 'L': /* program label */
881 case 'n': /* don't alias */
882 CHECK_AGAINST_OPMODE(j);
886 case 'N': /* delivery status notifications */
887 CHECK_AGAINST_OPMODE(j);
888 DefaultNotify |= QHASNOTIFY;
889 macdefine(&BlankEnvelope.e_macro, A_TEMP,
890 macid("{dsn_notify}"), optarg);
891 if (sm_strcasecmp(optarg, "never") == 0)
893 for (p = optarg; p != NULL; optarg = p)
898 if (sm_strcasecmp(optarg, "success") == 0)
899 DefaultNotify |= QPINGONSUCCESS;
900 else if (sm_strcasecmp(optarg, "failure") == 0)
901 DefaultNotify |= QPINGONFAILURE;
902 else if (sm_strcasecmp(optarg, "delay") == 0)
903 DefaultNotify |= QPINGONDELAY;
906 usrerr("Invalid -N argument");
912 case 'o': /* set option */
913 setoption(*optarg, optarg + 1, false, true,
917 case 'O': /* set option (long form) */
918 setoption(' ', optarg, false, true, &BlankEnvelope);
921 case 'p': /* set protocol */
922 CHECK_AGAINST_OPMODE(j);
923 p = strchr(optarg, ':');
931 cleanstrcpy(ep, p, i);
932 macdefine(&BlankEnvelope.e_macro,
938 i = strlen(optarg) + 1;
940 cleanstrcpy(ep, optarg, i);
941 macdefine(&BlankEnvelope.e_macro, A_HEAP,
946 case 'Q': /* change quarantining on queued items */
948 if (OpMode != MD_DELIVER &&
949 OpMode != MD_QUEUERUN)
951 usrerr("Can not use -Q with -b%c", OpMode);
956 if (OpMode == MD_DELIVER)
957 set_op_mode(MD_QUEUERUN);
961 quarantining = newstr(optarg);
964 case 'q': /* run queue files at intervals */
966 if (OpMode != MD_DELIVER &&
967 OpMode != MD_DAEMON &&
968 OpMode != MD_FGDAEMON &&
969 OpMode != MD_PRINT &&
970 OpMode != MD_PRINTNQE &&
971 OpMode != MD_QUEUERUN)
973 usrerr("Can not use -q with -b%c", OpMode);
978 /* don't override -bd, -bD or -bp */
979 if (OpMode == MD_DELIVER)
980 set_op_mode(MD_QUEUERUN);
983 negate = optarg[0] == '!';
986 /* negate meaning of pattern match */
987 optarg++; /* skip '!' for next switch */
992 case 'G': /* Limit by queue group name */
995 usrerr("Can not use -q!G");
999 if (queuegroup != NULL)
1001 usrerr("Can not use multiple -qG options");
1002 ExitStat = EX_USAGE;
1005 queuegroup = newstr(&optarg[1]);
1008 case 'I': /* Limit by ID */
1009 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1010 new->queue_match = newstr(&optarg[1]);
1011 new->queue_negate = negate;
1012 new->queue_next = QueueLimitId;
1016 case 'R': /* Limit by recipient */
1017 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1018 new->queue_match = newstr(&optarg[1]);
1019 new->queue_negate = negate;
1020 new->queue_next = QueueLimitRecipient;
1021 QueueLimitRecipient = new;
1024 case 'S': /* Limit by sender */
1025 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1026 new->queue_match = newstr(&optarg[1]);
1027 new->queue_negate = negate;
1028 new->queue_next = QueueLimitSender;
1029 QueueLimitSender = new;
1032 case 'f': /* foreground queue run */
1033 foregroundqueue = true;
1036 case 'Q': /* Limit by quarantine message */
1037 if (optarg[1] != '\0')
1039 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1040 new->queue_match = newstr(&optarg[1]);
1041 new->queue_negate = negate;
1042 new->queue_next = QueueLimitQuarantine;
1043 QueueLimitQuarantine = new;
1045 QueueMode = QM_QUARANTINE;
1048 case 'L': /* act on lost items */
1049 QueueMode = QM_LOST;
1052 case 'p': /* Persistent queue */
1053 queuepersistent = true;
1054 if (QueueIntvl == 0)
1056 if (optarg[1] == '\0')
1063 QueueIntvl = convtime(optarg, 'm');
1066 usrerr("Invalid -q value");
1067 ExitStat = EX_USAGE;
1070 /* check for bad conversion */
1072 ExitStat = EX_USAGE;
1077 case 'R': /* DSN RET: what to return */
1078 CHECK_AGAINST_OPMODE(j);
1079 if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1081 usrerr("Duplicate -R flag");
1082 ExitStat = EX_USAGE;
1085 BlankEnvelope.e_flags |= EF_RET_PARAM;
1086 if (sm_strcasecmp(optarg, "hdrs") == 0)
1087 BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1088 else if (sm_strcasecmp(optarg, "full") != 0)
1090 usrerr("Invalid -R value");
1091 ExitStat = EX_USAGE;
1093 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1094 macid("{dsn_ret}"), optarg);
1097 case 't': /* read recipients from message */
1098 CHECK_AGAINST_OPMODE(j);
1102 case 'V': /* DSN ENVID: set "original" envelope id */
1103 CHECK_AGAINST_OPMODE(j);
1104 if (!xtextok(optarg))
1106 usrerr("Invalid syntax in -V flag");
1107 ExitStat = EX_USAGE;
1111 BlankEnvelope.e_envid = newstr(optarg);
1112 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1113 macid("{dsn_envid}"), optarg);
1117 case 'X': /* traffic log file */
1118 dp = drop_privileges(true);
1120 if (stat(optarg, &traf_st) == 0 &&
1121 S_ISFIFO(traf_st.st_mode))
1122 TrafficLogFile = sm_io_open(SmFtStdio,
1125 SM_IO_WRONLY, NULL);
1127 TrafficLogFile = sm_io_open(SmFtStdio,
1130 SM_IO_APPEND, NULL);
1131 if (TrafficLogFile == NULL)
1133 syserr("cannot open %s", optarg);
1134 ExitStat = EX_CANTCREAT;
1137 (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1138 NULL, SM_IO_LBF, 0);
1141 /* compatibility flags */
1142 case 'c': /* connect to non-local mailers */
1143 case 'i': /* don't let dot stop me */
1144 case 'm': /* send to me too */
1145 case 'T': /* set timeout interval */
1146 case 'v': /* give blow-by-blow description */
1147 setoption(j, "T", false, true, &BlankEnvelope);
1150 case 'e': /* error message disposition */
1151 case 'M': /* define macro */
1152 setoption(j, optarg, false, true, &BlankEnvelope);
1155 case 's': /* save From lines in headers */
1156 setoption('f', "T", false, true, &BlankEnvelope);
1160 case 'I': /* initialize alias DBM file */
1161 set_op_mode(MD_INITALIAS);
1165 #if defined(__osf__) || defined(_AIX3)
1166 case 'x': /* random flag that OSF/1 & AIX mailx passes */
1168 #endif /* defined(__osf__) || defined(_AIX3) */
1169 #if defined(sony_news)
1171 case 'J': /* ignore flags for Japanese code conversion
1172 implemented on Sony NEWS */
1174 #endif /* defined(sony_news) */
1177 finis(true, true, EX_USAGE);
1183 /* if we've had errors so far, exit now */
1184 if ((ExitStat != EX_OK && OpMode != MD_TEST) ||
1185 ExitStat == EX_OSERR)
1187 finis(false, true, ExitStat);
1191 if (bitset(SUBMIT_MTA, SubmitMode))
1193 /* If set daemon_flags on command line, don't reset it */
1194 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1195 macdefine(&BlankEnvelope.e_macro, A_PERM,
1196 macid("{daemon_flags}"), "CC f");
1198 else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1200 SubmitMode = SUBMIT_MSA;
1202 /* If set daemon_flags on command line, don't reset it */
1203 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1204 macdefine(&BlankEnvelope.e_macro, A_PERM,
1205 macid("{daemon_flags}"), "c u");
1209 ** Do basic initialization.
1210 ** Read system control file.
1211 ** Extract special fields for local use.
1215 checkfd012("before readcf");
1217 vendor_pre_defaults(&BlankEnvelope);
1219 readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1220 safecf, &BlankEnvelope);
1221 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1222 ConfigFileRead = true;
1223 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1224 vendor_post_defaults(&BlankEnvelope);
1226 /* now we can complain about missing fds */
1227 if (MissingFds != 0 && LogLevel > 8)
1232 if (bitset(1 << STDIN_FILENO, MissingFds))
1233 (void) sm_strlcat(mbuf, ", stdin", sizeof mbuf);
1234 if (bitset(1 << STDOUT_FILENO, MissingFds))
1235 (void) sm_strlcat(mbuf, ", stdout", sizeof mbuf);
1236 if (bitset(1 << STDERR_FILENO, MissingFds))
1237 (void) sm_strlcat(mbuf, ", stderr", sizeof mbuf);
1239 /* Notice: fill_errno is from high above: fill_fd() */
1240 sm_syslog(LOG_WARNING, NOQID,
1241 "File descriptors missing on startup: %s; %s",
1242 &mbuf[2], sm_errstring(fill_errno));
1245 /* Remove the ability for a normal user to send signals */
1246 if (RealUid != 0 && RealUid != geteuid())
1248 uid_t new_uid = geteuid();
1252 ** Since we can differentiate between uid and euid,
1253 ** make the uid a different user so the real user
1254 ** can't send signals. However, it doesn't need to be
1255 ** root (euid has root).
1261 sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1262 if (setreuid(new_uid, geteuid()) < 0)
1264 syserr("main: setreuid(%d, %d) failed",
1265 (int) new_uid, (int) geteuid());
1266 finis(false, true, EX_OSERR);
1270 sm_dprintf("Now running as e/ruid %d:%d\n",
1271 (int) geteuid(), (int) getuid());
1272 #else /* HASSETREUID */
1274 ** Have to change both effective and real so need to
1275 ** change them both to effective to keep privs.
1279 sm_dprintf("Changing uid to %d\n", (int) new_uid);
1280 if (setuid(new_uid) < 0)
1282 syserr("main: setuid(%d) failed", (int) new_uid);
1283 finis(false, true, EX_OSERR);
1287 sm_dprintf("Now running as e/ruid %d:%d\n",
1288 (int) geteuid(), (int) getuid());
1289 #endif /* HASSETREUID */
1293 if (FallbackMX != NULL)
1294 (void) getfallbackmxrr(FallbackMX);
1295 #endif /* NAMED_BIND */
1297 if (SuperSafe == SAFE_INTERACTIVE && CurEnv->e_sendmode != SM_DELIVER)
1299 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1300 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1303 if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1305 usrerr("Mail submission program cannot be used as daemon");
1306 finis(false, true, EX_USAGE);
1309 if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1310 OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1311 OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1314 /* set up the basic signal handlers */
1315 if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1316 (void) sm_signal(SIGINT, intsig);
1317 (void) sm_signal(SIGTERM, intsig);
1319 /* Enforce use of local time (null string overrides this) */
1320 if (TimeZoneSpec == NULL)
1322 else if (TimeZoneSpec[0] != '\0')
1323 sm_setuserenv("TZ", TimeZoneSpec);
1325 sm_setuserenv("TZ", NULL);
1328 /* initialize mailbox database */
1329 i = sm_mbdb_initialize(Mbdb);
1332 usrerr("Can't initialize mailbox database \"%s\": %s",
1333 Mbdb, sm_strexit(i));
1337 /* avoid denial-of-service attacks */
1340 if (OpMode == MD_TEST)
1342 /* can't be done after readcf if RunAs* is used */
1343 dp = drop_privileges(true);
1346 finis(false, true, dp);
1350 else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1352 /* drop privileges -- daemon mode done after socket/bind */
1353 dp = drop_privileges(false);
1355 if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1357 usrerr("Mail submission program must have RunAsUser set to non root user");
1358 finis(false, true, EX_CONFIG);
1364 _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1365 _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1366 #endif /* NAMED_BIND */
1369 ** Find our real host name for future logging.
1372 authinfo = getauthinfo(STDIN_FILENO, &forged);
1373 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1375 /* suppress error printing if errors mailed back or whatever */
1376 if (BlankEnvelope.e_errormode != EM_PRINT)
1379 /* set up the $=m class now, after .cf has a chance to redefine $m */
1380 expand("\201m", jbuf, sizeof jbuf, &BlankEnvelope);
1381 if (jbuf[0] != '\0')
1382 setclass('m', jbuf);
1384 /* probe interfaces and locate any additional names */
1385 if (DontProbeInterfaces != DPI_PROBENONE)
1390 char pidpath[MAXPATHLEN];
1392 /* Now we know which .cf file we use */
1393 sm_dprintf(" Conf file:\t%s (selected)\n",
1394 getcfname(OpMode, SubmitMode, cftype, conffile));
1395 expand(PidFile, pidpath, sizeof pidpath, &BlankEnvelope);
1396 sm_dprintf(" Pid file:\t%s (selected)\n", pidpath);
1401 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1402 sm_dprintf("\n (short domain name) $w = ");
1403 xputs(sm_debug_file(), macvalue('w', &BlankEnvelope));
1404 sm_dprintf("\n (canonical domain name) $j = ");
1405 xputs(sm_debug_file(), macvalue('j', &BlankEnvelope));
1406 sm_dprintf("\n (subdomain name) $m = ");
1407 xputs(sm_debug_file(), macvalue('m', &BlankEnvelope));
1408 sm_dprintf("\n (node name) $k = ");
1409 xputs(sm_debug_file(), macvalue('k', &BlankEnvelope));
1410 sm_dprintf("\n========================================================\n\n");
1414 ** Do more command line checking -- these are things that
1415 ** have to modify the results of reading the config file.
1418 /* process authorization warnings from command line */
1420 auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1421 RealUserName, conffile);
1422 if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1423 auth_warning(&BlankEnvelope, "Processed from queue %s",
1425 if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1426 RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1427 sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1430 /* check body type for legality */
1431 i = check_bodytype(BlankEnvelope.e_bodytype);
1432 if (i == BODYTYPE_ILLEGAL)
1434 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1435 BlankEnvelope.e_bodytype = NULL;
1437 else if (i != BODYTYPE_NONE)
1438 SevenBitInput = (i == BODYTYPE_7BIT);
1440 /* tweak default DSN notifications */
1441 if (DefaultNotify == 0)
1442 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1444 /* check for sane configuration level */
1445 if (ConfigLevel > MAXCONFIGLEVEL)
1447 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1448 ConfigLevel, Version, MAXCONFIGLEVEL);
1451 /* need MCI cache to have persistence */
1452 if (HostStatDir != NULL && MaxMciCache == 0)
1455 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1456 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1459 /* need HostStatusDir in order to have SingleThreadDelivery */
1460 if (SingleThreadDelivery && HostStatDir == NULL)
1462 SingleThreadDelivery = false;
1463 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1464 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1468 j = sm_memstat_open();
1469 if (j < 0 && (RefuseLowMem > 0 || QueueLowMem > 0) && LogLevel > 4)
1471 sm_syslog(LOG_WARNING, NOQID,
1472 "cannot get memory statistics, settings ignored, error=%d"
1475 #endif /* _FFR_MEMSTAT */
1477 /* check for permissions */
1479 RealUid != TrustedUid)
1481 char *action = NULL;
1486 if (quarantining != NULL)
1487 action = "quarantine jobs";
1490 /* Normal users can do a single queue run */
1491 if (QueueIntvl == 0)
1495 /* but not persistent queue runners */
1497 action = "start a queue runner daemon";
1502 action = "purge host status";
1508 action = "run daemon";
1511 sm_dprintf("Deny user %d attempt to %s\n",
1512 (int) RealUid, action);
1515 sm_syslog(LOG_ALERT, NOQID,
1516 "user %d attempted to %s",
1517 (int) RealUid, action);
1519 usrerr("Permission denied (real uid not trusted)");
1520 finis(false, true, EX_USAGE);
1525 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1528 ** If -bv and RestrictExpand,
1529 ** drop privs to prevent normal
1530 ** users from reading private
1531 ** aliases/forwards/:include:s
1535 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1538 dp = drop_privileges(true);
1540 /* Fake address safety */
1542 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1543 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1548 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1550 CurEnv->e_id = NULL;
1551 finis(true, true, dp);
1562 /* Nothing special to check */
1566 if (!wordinclass(RealUserName, 't'))
1569 sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1572 sm_syslog(LOG_ALERT, NOQID,
1573 "user %d attempted to rebuild the alias map",
1576 usrerr("Permission denied (real uid not trusted)");
1577 finis(false, true, EX_USAGE);
1583 usrerr("User %d cannot rebuild aliases in mail submission program",
1585 finis(false, true, EX_USAGE);
1591 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1595 ** If -v and RestrictExpand, reset
1596 ** Verbose to prevent normal users
1597 ** from seeing the expansion of
1598 ** aliases/forwards/:include:s
1602 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1611 BlankEnvelope.e_flags |= EF_METOO;
1616 /* don't have persistent host status in test mode */
1620 BlankEnvelope.e_errormode = EM_PRINT;
1625 BlankEnvelope.e_errormode = EM_PRINT;
1627 /* arrange to exit cleanly on hangup signal */
1628 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1629 (void) sm_signal(SIGHUP, intsig);
1631 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1632 "Notice: -bv may give misleading output for non-privileged user\n");
1636 run_in_foreground = true;
1637 set_op_mode(MD_DAEMON);
1641 vendor_daemon_setup(&BlankEnvelope);
1643 /* remove things that don't make sense in daemon mode */
1647 /* arrange to restart on hangup signal */
1648 if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1649 sm_syslog(LOG_WARNING, NOQID,
1650 "daemon invoked without full pathname; kill -1 won't work");
1655 BlankEnvelope.e_errormode = EM_PRINT;
1660 /* arrange to exit cleanly on hangup signal */
1661 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1662 (void) sm_signal(SIGHUP, intsig);
1666 /* special considerations for FullName */
1667 if (FullName != NULL)
1671 /* full names can't have newlines */
1672 if (strchr(FullName, '\n') != NULL)
1674 full = newstr(denlstring(FullName, true, true));
1678 /* check for characters that may have to be quoted */
1679 if (!rfc822_string(FullName))
1682 ** Quote a full name with special characters
1683 ** as a comment so crackaddr() doesn't destroy
1684 ** the name portion of the address.
1687 FullName = addquotes(FullName, NULL);
1689 sm_free(full); /* XXX */
1693 /* do heuristic mode adjustment */
1696 /* turn off noconnect option */
1697 setoption('c', "F", true, false, &BlankEnvelope);
1699 /* turn on interactive delivery */
1700 setoption('d', "", true, false, &BlankEnvelope);
1704 /* check for vendor mismatch */
1705 if (VendorCode != VENDOR_CODE)
1707 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1708 getvendor(VENDOR_CODE), getvendor(VendorCode));
1710 #endif /* VENDOR_CODE */
1712 /* check for out of date configuration level */
1713 if (ConfigLevel < MAXCONFIGLEVEL)
1715 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1716 Version, MAXCONFIGLEVEL, ConfigLevel);
1719 if (ConfigLevel < 3)
1722 /* set options that were previous macros */
1723 if (SmtpGreeting == NULL)
1725 if (ConfigLevel < 7 &&
1726 (p = macvalue('e', &BlankEnvelope)) != NULL)
1727 SmtpGreeting = newstr(p);
1729 SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1731 if (UnixFromLine == NULL)
1733 if (ConfigLevel < 7 &&
1734 (p = macvalue('l', &BlankEnvelope)) != NULL)
1735 UnixFromLine = newstr(p);
1737 UnixFromLine = "From \201g \201d";
1739 SmtpError[0] = '\0';
1741 /* our name for SMTP codes */
1742 expand("\201j", jbuf, sizeof jbuf, &BlankEnvelope);
1743 if (jbuf[0] == '\0')
1744 PSTRSET(MyHostName, "localhost");
1746 PSTRSET(MyHostName, jbuf);
1747 if (strchr(MyHostName, '.') == NULL)
1748 message("WARNING: local host name (%s) is not qualified; see cf/README: WHO AM I?",
1751 /* make certain that this name is part of the $=w class */
1752 setclass('w', MyHostName);
1754 /* fill in the structure of the *default* queue */
1755 st = stab("mqueue", ST_QUEUE, ST_FIND);
1757 syserr("No default queue (mqueue) defined");
1759 set_def_queueval(st->s_quegrp, true);
1761 /* the indices of built-in mailers */
1762 st = stab("local", ST_MAILER, ST_FIND);
1764 LocalMailer = st->s_mailer;
1765 else if (OpMode != MD_TEST || !warn_C_flag)
1766 syserr("No local mailer defined");
1768 st = stab("prog", ST_MAILER, ST_FIND);
1770 syserr("No prog mailer defined");
1773 ProgMailer = st->s_mailer;
1774 clrbitn(M_MUSER, ProgMailer->m_flags);
1777 st = stab("*file*", ST_MAILER, ST_FIND);
1779 syserr("No *file* mailer defined");
1782 FileMailer = st->s_mailer;
1783 clrbitn(M_MUSER, FileMailer->m_flags);
1786 st = stab("*include*", ST_MAILER, ST_FIND);
1788 syserr("No *include* mailer defined");
1790 InclMailer = st->s_mailer;
1792 if (ConfigLevel < 6)
1794 /* heuristic tweaking of local mailer for back compat */
1795 if (LocalMailer != NULL)
1797 setbitn(M_ALIASABLE, LocalMailer->m_flags);
1798 setbitn(M_HASPWENT, LocalMailer->m_flags);
1799 setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1800 setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1801 setbitn(M_CHECKPROG, LocalMailer->m_flags);
1802 setbitn(M_CHECKFILE, LocalMailer->m_flags);
1803 setbitn(M_CHECKUDB, LocalMailer->m_flags);
1805 if (ProgMailer != NULL)
1806 setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1807 if (FileMailer != NULL)
1808 setbitn(M_RUNASRCPT, FileMailer->m_flags);
1810 if (ConfigLevel < 7)
1812 if (LocalMailer != NULL)
1813 setbitn(M_VRFY250, LocalMailer->m_flags);
1814 if (ProgMailer != NULL)
1815 setbitn(M_VRFY250, ProgMailer->m_flags);
1816 if (FileMailer != NULL)
1817 setbitn(M_VRFY250, FileMailer->m_flags);
1820 /* MIME Content-Types that cannot be transfer encoded */
1821 setclass('n', "multipart/signed");
1823 /* MIME message/xxx subtypes that can be treated as messages */
1824 setclass('s', "rfc822");
1826 /* MIME Content-Transfer-Encodings that can be encoded */
1827 setclass('e', "7bit");
1828 setclass('e', "8bit");
1829 setclass('e', "binary");
1832 /* MIME Content-Types that should be treated as binary */
1833 setclass('b', "image");
1834 setclass('b', "audio");
1835 setclass('b', "video");
1836 setclass('b', "application/octet-stream");
1837 #endif /* USE_B_CLASS */
1839 /* MIME headers which have fields to check for overflow */
1840 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1841 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1843 /* MIME headers to check for length overflow */
1844 setclass(macid("{checkMIMETextHeaders}"), "content-description");
1846 /* MIME headers to check for overflow and rebalance */
1847 setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1848 setclass(macid("{checkMIMEHeaders}"), "content-id");
1849 setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1850 setclass(macid("{checkMIMEHeaders}"), "content-type");
1851 setclass(macid("{checkMIMEHeaders}"), "mime-version");
1853 /* Macros to save in the queue file -- don't remove any */
1854 setclass(macid("{persistentMacros}"), "r");
1855 setclass(macid("{persistentMacros}"), "s");
1856 setclass(macid("{persistentMacros}"), "_");
1857 setclass(macid("{persistentMacros}"), "{if_addr}");
1858 setclass(macid("{persistentMacros}"), "{daemon_flags}");
1860 /* operate in queue directory */
1861 if (QueueDir == NULL || *QueueDir == '\0')
1863 if (OpMode != MD_TEST)
1865 syserr("QueueDirectory (Q) option must be set");
1866 ExitStat = EX_CONFIG;
1871 if (OpMode != MD_TEST)
1872 setup_queues(OpMode == MD_DAEMON);
1875 /* check host status directory for validity */
1876 if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1878 /* cannot use this value */
1879 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1880 "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1881 HostStatDir, sm_errstring(errno));
1885 if (OpMode == MD_QUEUERUN &&
1886 RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1890 /* check to see if we own the queue directory */
1891 if (stat(".", &stbuf) < 0)
1892 syserr("main: cannot stat %s", QueueDir);
1893 if (stbuf.st_uid != RealUid)
1895 /* nope, really a botch */
1897 usrerr("You do not have permission to process the queue");
1898 finis(false, true, EX_NOPERM);
1904 /* sanity checks on milter filters */
1905 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1907 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1908 setup_daemon_milters();
1912 /* Convert queuegroup string to qgrp number */
1913 if (queuegroup != NULL)
1915 qgrp = name2qid(queuegroup);
1919 usrerr("Queue group %s unknown", queuegroup);
1920 finis(false, true, ExitStat);
1925 /* if we've had errors so far, exit now */
1926 if (ExitStat != EX_OK && OpMode != MD_TEST)
1928 finis(false, true, ExitStat);
1933 /* sendmail specific SASL initialization */
1938 checkfd012("before main() initmaps");
1942 ** Do operation-mode-dependent initialization.
1948 /* print the queue */
1950 dropenvelope(&BlankEnvelope, true, false);
1951 (void) sm_signal(SIGPIPE, sigpipe);
1956 /* Selecting a particular queue group to run */
1957 for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1961 (void) print_single_queue(qgrp, j);
1963 finis(false, true, EX_OK);
1967 finis(false, true, EX_OK);
1972 /* print number of entries in queue */
1973 dropenvelope(&BlankEnvelope, true, false);
1974 (void) sm_signal(SIGPIPE, sigpipe);
1975 printnqe(smioout, NULL);
1976 finis(false, true, EX_OK);
1981 /* only handle quarantining here */
1982 if (quarantining == NULL)
1985 if (QueueMode != QM_QUARANTINE &&
1986 QueueMode != QM_NORMAL)
1989 usrerr("Can not use -Q with -q%c", QueueMode);
1990 ExitStat = EX_USAGE;
1991 finis(false, true, ExitStat);
1994 quarantine_queue(quarantining, qgrp);
1995 finis(false, true, EX_OK);
1999 (void) sm_signal(SIGPIPE, sigpipe);
2000 (void) mci_traverse_persistent(mci_print_persistent, NULL);
2001 finis(false, true, EX_OK);
2006 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2007 finis(false, true, EX_OK);
2012 /* initialize maps */
2014 finis(false, true, ExitStat);
2020 /* reset DSN parameters */
2021 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2022 macdefine(&BlankEnvelope.e_macro, A_PERM,
2023 macid("{dsn_notify}"), NULL);
2024 BlankEnvelope.e_envid = NULL;
2025 macdefine(&BlankEnvelope.e_macro, A_PERM,
2026 macid("{dsn_envid}"), NULL);
2027 BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2028 macdefine(&BlankEnvelope.e_macro, A_PERM,
2029 macid("{dsn_ret}"), NULL);
2031 /* don't open maps for daemon -- done below in child */
2037 /* print configuration table (or at least part of it) */
2040 for (i = 0; i < MAXMAILERS; i++)
2042 if (Mailer[i] != NULL)
2043 printmailer(sm_debug_file(), Mailer[i]);
2048 ** Switch to the main envelope.
2051 CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2052 sm_rpool_new_x(NULL));
2053 MainEnvelope.e_flags = BlankEnvelope.e_flags;
2056 ** If test mode, read addresses from stdin and process.
2059 if (OpMode == MD_TEST)
2061 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2066 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2067 "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2068 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2069 "Enter <ruleset> <address>\n");
2071 macdefine(&(MainEnvelope.e_macro), A_PERM,
2072 macid("{addr_type}"), "e r");
2077 (void) sm_signal(SIGINT, intindebug);
2078 (void) sm_releasesignal(SIGINT);
2080 (void) sm_io_fprintf(smioout,
2083 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2084 if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2085 sizeof buf) == NULL)
2086 testmodeline("/quit", &MainEnvelope);
2087 p = strchr(buf, '\n');
2091 (void) sm_io_fprintf(smioout,
2094 testmodeline(buf, &MainEnvelope);
2096 SM_EXCEPT(exc, "[!F]*")
2099 ** 8.10 just prints \n on interrupt.
2100 ** I'm printing the exception here in case
2101 ** sendmail is extended to raise additional
2102 ** exceptions in this context.
2105 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2107 sm_exc_print(exc, smioout);
2115 if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER)
2117 /* check whether STARTTLS is turned off for the client */
2118 if (chkclientmodifiers(D_NOTLS))
2121 else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2124 /* check whether STARTTLS is turned off for the server */
2125 if (chkdaemonmodifiers(D_NOTLS))
2128 else /* other modes don't need STARTTLS */
2133 /* basic TLS initialization */
2134 tls_ok = init_tls_library();
2137 if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2139 /* disable TLS for client */
2142 #endif /* STARTTLS */
2145 ** If collecting stuff from the queue, go start doing that.
2148 if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2153 /* init TLS for client, ignore result for now */
2154 (void) initclttls(tls_ok);
2155 #endif /* STARTTLS */
2158 ** The parent process of the caller of runqueue() needs
2159 ** to stay around for a possible SIGTERM. The SIGTERM will
2160 ** tell this process that all of the queue runners children
2161 ** need to be sent SIGTERM as well. At the same time, we
2162 ** want to return control to the command line. So we do an
2166 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2169 ** If the fork() failed we should still try to do
2170 ** the queue run. If it succeeded then the child
2171 ** is going to start the run and wait for all
2172 ** of the children to finish.
2177 /* Reset global flags */
2178 RestartRequest = NULL;
2179 ShutdownRequest = NULL;
2182 /* disconnect from terminal */
2183 disconnect(2, CurEnv);
2186 CurrentPid = getpid();
2189 int rwgflags = RWG_NONE;
2192 ** To run a specific queue group mark it to
2193 ** be run, select the work group it's in and
2194 ** increment the work counter.
2197 for (i = 0; i < NumQueue && Queue[i] != NULL;
2199 Queue[i]->qg_nextrun = (time_t) -1;
2200 Queue[qgrp]->qg_nextrun = 0;
2202 rwgflags |= RWG_VERBOSE;
2203 if (queuepersistent)
2204 rwgflags |= RWG_PERSISTENT;
2205 rwgflags |= RWG_FORCE;
2206 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2210 (void) runqueue(false, Verbose,
2211 queuepersistent, true);
2213 /* set the title to make it easier to find */
2214 sm_setproctitle(true, CurEnv, "Queue control");
2215 (void) sm_signal(SIGCHLD, SIG_DFL);
2216 while (CurChildren > 0)
2222 while ((ret = sm_wait(&status)) <= 0)
2224 if (errno == ECHILD)
2227 ** Oops... something got messed
2228 ** up really bad. Waiting for
2229 ** non-existent children
2230 ** shouldn't happen. Let's get
2240 /* something is really really wrong */
2241 if (errno == ECHILD)
2243 sm_syslog(LOG_ERR, NOQID,
2244 "queue control process: lost all children: wait returned ECHILD");
2248 /* Only drop when a child gives status */
2249 if (WIFSTOPPED(status))
2252 proc_list_drop(ret, status, NULL);
2255 finis(true, true, ExitStat);
2260 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2262 /* check whether AUTH is turned off for the server */
2263 if (!chkdaemonmodifiers(D_NOAUTH) &&
2264 (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2265 syserr("!sasl_server_init failed! [%s]",
2266 sasl_errstring(i, NULL, NULL));
2270 if (OpMode == MD_SMTP)
2272 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2273 PROC_DAEMON, 0, -1, NULL);
2275 /* clean up background delivery children */
2276 (void) sm_signal(SIGCHLD, reapchild);
2280 ** If a daemon, wait for a request.
2281 ** getrequests will always return in a child.
2282 ** If we should also be processing the queue, start
2283 ** doing it in background.
2284 ** We check for any errors that might have happened
2288 if (OpMode == MD_DAEMON || QueueIntvl > 0)
2292 if (!run_in_foreground && !tTd(99, 100))
2294 /* put us in background */
2297 syserr("daemon: cannot fork");
2300 finis(false, true, EX_OK);
2305 ** Initialize exception stack and default exception
2306 ** handler for child process.
2309 /* Reset global flags */
2310 RestartRequest = NULL;
2311 RestartWorkGroup = false;
2312 ShutdownRequest = NULL;
2314 CurrentPid = getpid();
2316 sm_exc_newthread(fatal_error);
2318 /* disconnect from our controlling tty */
2319 disconnect(2, &MainEnvelope);
2323 if (OpMode == MD_DAEMON)
2324 (void) sm_strlcat(dtype, "+SMTP", sizeof dtype);
2327 (void) sm_strlcat2(dtype,
2329 ? "+persistent-queueing@"
2331 pintvl(QueueIntvl, true),
2335 (void) sm_strlcat(dtype, "+debugging", sizeof dtype);
2337 sm_syslog(LOG_INFO, NOQID,
2338 "starting daemon (%s): %s", Version, dtype + 1);
2343 /* save daemon type in a macro for possible PidFile use */
2344 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2345 macid("{daemon_info}"), dtype + 1);
2347 /* save queue interval in a macro for possible PidFile use */
2348 macdefine(&MainEnvelope.e_macro, A_TEMP,
2349 macid("{queue_interval}"), pintvl(QueueIntvl, true));
2351 /* workaround: can't seem to release the signal in the parent */
2352 (void) sm_signal(SIGHUP, sighup);
2353 (void) sm_releasesignal(SIGHUP);
2354 (void) sm_signal(SIGTERM, sigterm);
2358 (void) runqueue(true, false, queuepersistent, true);
2361 ** If queuepersistent but not in daemon mode then
2362 ** we're going to do the queue runner monitoring here.
2363 ** If in daemon mode then the monitoring will happen
2367 if (OpMode != MD_DAEMON && queuepersistent)
2370 ** Write the pid to file
2371 ** XXX Overwrites sendmail.pid
2374 log_sendmail_pid(&MainEnvelope);
2376 /* set the title to make it easier to find */
2377 sm_setproctitle(true, CurEnv, "Queue control");
2378 (void) sm_signal(SIGCHLD, SIG_DFL);
2379 while (CurChildren > 0)
2387 while ((ret = sm_wait(&status)) <= 0)
2390 ** Waiting for non-existent
2391 ** children shouldn't happen.
2392 ** Let's get out of here if
2396 if (errno == ECHILD)
2404 /* something is really really wrong */
2405 if (errno == ECHILD)
2407 sm_syslog(LOG_ERR, NOQID,
2408 "persistent queue runner control process: lost all children: wait returned ECHILD");
2412 if (WIFSTOPPED(status))
2415 /* Probe only on a child status */
2416 proc_list_drop(ret, status, &group);
2418 if (WIFSIGNALED(status))
2420 if (WCOREDUMP(status))
2422 sm_syslog(LOG_ERR, NOQID,
2423 "persistent queue runner=%d core dumped, signal=%d",
2424 group, WTERMSIG(status));
2426 /* don't restart this */
2427 mark_work_group_restart(
2432 sm_syslog(LOG_ERR, NOQID,
2433 "persistent queue runner=%d died, signal=%d",
2434 group, WTERMSIG(status));
2438 ** When debugging active, don't
2439 ** restart the persistent queues.
2440 ** But do log this as info.
2443 if (sm_debug_active(&DebugNoPRestart,
2446 sm_syslog(LOG_DEBUG, NOQID,
2447 "persistent queue runner=%d, exited",
2449 mark_work_group_restart(group,
2453 finis(true, true, ExitStat);
2457 if (OpMode != MD_DAEMON)
2462 ** Write the pid to file
2463 ** XXX Overwrites sendmail.pid
2466 log_sendmail_pid(&MainEnvelope);
2468 /* set the title to make it easier to find */
2470 (void) sm_strlcpyn(qtype, sizeof qtype, 4,
2472 pintvl(QueueIntvl, true),
2475 sm_setproctitle(true, CurEnv, qtype);
2483 (void) runqueue(true, false,
2488 dropenvelope(&MainEnvelope, true, false);
2491 /* init TLS for server, ignore result for now */
2492 (void) initsrvtls(tls_ok);
2493 #endif /* STARTTLS */
2496 p_flags = getrequests(&MainEnvelope);
2498 /* drop privileges */
2499 (void) drop_privileges(false);
2502 ** Get authentication data
2503 ** Set _ macro in BlankEnvelope before calling newenvelope().
2506 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2508 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2510 /* at this point we are in a child: reset state */
2511 sm_rpool_free(MainEnvelope.e_rpool);
2512 (void) newenvelope(&MainEnvelope, &MainEnvelope,
2513 sm_rpool_new_x(NULL));
2518 /* log connection information */
2519 sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2523 ** If running SMTP protocol, start collecting and executing
2524 ** commands. This will never return.
2527 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2532 ** Save some macros for check_* rulesets.
2539 (void) sm_snprintf(ipbuf, sizeof ipbuf, "[%.100s]",
2540 anynet_ntoa(&RealHostAddr));
2541 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2542 macid("{client_name}"), ipbuf);
2545 macdefine(&BlankEnvelope.e_macro, A_PERM,
2546 macid("{client_name}"), RealHostName);
2547 macdefine(&BlankEnvelope.e_macro, A_PERM,
2548 macid("{client_ptr}"), RealHostName);
2549 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2550 macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2553 switch (RealHostAddr.sa.sa_family)
2557 (void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2558 RealHostAddr.sin.sin_port);
2560 #endif /* NETINET */
2563 (void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2564 RealHostAddr.sin6.sin6_port);
2566 #endif /* NETINET6 */
2568 (void) sm_snprintf(pbuf, sizeof pbuf, "0");
2571 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2572 macid("{client_port}"), pbuf);
2574 if (OpMode == MD_DAEMON)
2576 /* validate the connection */
2578 nullserver = validate_connection(&RealHostAddr,
2579 macvalue(macid("{client_name}"),
2584 else if (p_flags == NULL)
2586 p_flags = (BITMAP256 *) xalloc(sizeof *p_flags);
2590 if (OpMode == MD_SMTP)
2591 (void) initsrvtls(tls_ok);
2592 #endif /* STARTTLS */
2594 /* turn off profiling */
2596 smtp(nullserver, *p_flags, &MainEnvelope);
2600 /* turn off profiling */
2602 if (OpMode == MD_DAEMON)
2607 sm_rpool_free(MainEnvelope.e_rpool);
2608 clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2609 if (OpMode == MD_VERIFY)
2611 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2612 PostMasterCopy = NULL;
2616 /* interactive -- all errors are global */
2617 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2621 ** Do basic system initialization and set the sender
2624 initsys(&MainEnvelope);
2625 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2626 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2627 setsender(from, &MainEnvelope, NULL, '\0', false);
2628 if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2629 (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2630 strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2632 auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2633 RealUserName, from, warn_f_flag);
2642 /* set the initial sender for AUTH= to $f@$j */
2643 fv = macvalue('f', &MainEnvelope);
2644 if (fv == NULL || *fv == '\0')
2645 MainEnvelope.e_auth_param = NULL;
2648 if (strchr(fv, '@') == NULL)
2650 i = strlen(fv) + strlen(macvalue('j',
2651 &MainEnvelope)) + 2;
2653 (void) sm_strlcpyn(p, i, 3, fv, "@",
2658 p = sm_strdup_x(fv);
2659 MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2661 sm_free(p); /* XXX */
2664 if (macvalue('s', &MainEnvelope) == NULL)
2665 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2668 if (*av == NULL && !GrabTo)
2670 MainEnvelope.e_to = NULL;
2671 MainEnvelope.e_flags |= EF_GLOBALERRS;
2673 SuperSafe = SAFE_NO;
2674 usrerr("Recipient names must be specified");
2676 /* collect body for UUCP return */
2677 if (OpMode != MD_VERIFY)
2678 collect(InChannel, false, NULL, &MainEnvelope, true);
2679 finis(true, true, EX_USAGE);
2684 ** Scan argv and deliver the message to everyone.
2687 save_val = LogUsrErrs;
2689 sendtoargv(av, &MainEnvelope);
2690 LogUsrErrs = save_val;
2692 /* if we have had errors sofar, arrange a meaningful exit stat */
2693 if (Errors > 0 && ExitStat == EX_OK)
2694 ExitStat = EX_USAGE;
2698 ** If using -t, force not sending to argv recipients, even
2699 ** if they are mentioned in the headers.
2706 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2707 q->q_state = QS_REMOVED;
2709 #endif /* _FFR_FIX_DASHT */
2712 ** Read the input mail.
2715 MainEnvelope.e_to = NULL;
2716 if (OpMode != MD_VERIFY || GrabTo)
2719 unsigned long savedflags;
2722 ** workaround for compiler warning on Irix:
2723 ** do not initialize variable in the definition, but
2725 ** warning(1548): transfer of control bypasses
2726 ** initialization of:
2727 ** variable "savederrors" (declared at line 2570)
2728 ** variable "savedflags" (declared at line 2571)
2732 savederrors = Errors;
2733 savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2734 MainEnvelope.e_flags |= EF_GLOBALERRS;
2735 MainEnvelope.e_flags &= ~EF_FATALERRS;
2738 collect(InChannel, false, NULL, &MainEnvelope, true);
2740 /* header checks failed */
2746 /* Log who the mail would have gone to */
2747 logundelrcpts(&MainEnvelope,
2748 MainEnvelope.e_message,
2752 finis(true, true, ExitStat);
2757 /* bail out if message too large */
2758 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2760 finis(true, true, ExitStat != EX_OK ? ExitStat
2766 /* set message size */
2767 (void) sm_snprintf(buf, sizeof buf, "%ld",
2768 MainEnvelope.e_msgsize);
2769 macdefine(&MainEnvelope.e_macro, A_TEMP,
2770 macid("{msg_size}"), buf);
2772 Errors = savederrors;
2773 MainEnvelope.e_flags |= savedflags;
2778 sm_dprintf("From person = \"%s\"\n",
2779 MainEnvelope.e_from.q_paddr);
2781 /* Check if quarantining stats should be updated */
2782 if (MainEnvelope.e_quarmsg != NULL)
2783 markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2786 ** Actually send everything.
2787 ** If verifying, just ack.
2792 if (!split_by_recipient(&MainEnvelope) &&
2793 bitset(EF_FATALERRS, MainEnvelope.e_flags))
2797 /* make sure we deliver at least the first envelope */
2798 i = FastSplit > 0 ? 0 : -1;
2799 for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2803 e->e_from.q_state = QS_SENDER;
2806 sm_dprintf("main[%d]: QS_SENDER ", i);
2807 printaddr(sm_debug_file(), &e->e_from, false);
2813 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2814 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2815 #endif /* NAMED_BIND */
2816 next = e->e_sibling;
2817 e->e_sibling = NULL;
2819 /* after FastSplit envelopes: queue up */
2820 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2821 e->e_sibling = next;
2826 ** Don't send return error message if in VERIFY mode.
2829 finis(true, true, ExitStat);
2834 ** STOP_SENDMAIL -- Stop the running program
2849 /* reset uid for process accounting */
2851 (void) setuid(RealUid);
2855 ** FINIS -- Clean up and exit.
2858 ** drop -- whether or not to drop CurEnv envelope
2859 ** cleanup -- call exit() or _exit()?
2860 ** exitstat -- exit status to use for exit() call
2870 finis(drop, cleanup, exitstat)
2873 volatile int exitstat;
2875 char pidpath[MAXPATHLEN];
2878 /* Still want to process new timeouts added below */
2880 (void) sm_releasesignal(SIGALRM);
2884 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2886 CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2887 printenvflags(CurEnv);
2890 printopenfds(false);
2894 ** Clean up. This might raise E:mta.quickabort
2897 /* clean up temp files */
2898 CurEnv->e_to = NULL;
2901 if (CurEnv->e_id != NULL)
2903 dropenvelope(CurEnv, true, false);
2904 sm_rpool_free(CurEnv->e_rpool);
2905 CurEnv->e_rpool = NULL;
2908 poststats(StatFile);
2911 /* flush any cached connections */
2912 mci_flush(true, NULL);
2914 /* close maps belonging to this pid */
2918 /* close UserDatabase */
2927 /* clean up extended load average stuff */
2937 sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
2939 if (exitstat == EX_TEMPFAIL ||
2940 CurEnv->e_errormode == EM_BERKNET)
2943 /* XXX clean up queues and related data structures */
2947 cleanup_shm(DaemonPid == pid);
2948 #endif /* SM_CONF_SHM */
2950 /* close locked pid file */
2951 close_sendmail_pid();
2953 if (DaemonPid == pid || PidFilePid == pid)
2955 /* blow away the pid file */
2956 expand(PidFile, pidpath, sizeof pidpath, CurEnv);
2957 (void) unlink(pidpath);
2960 /* reset uid for process accounting */
2962 sm_mbdb_terminate();
2964 (void) sm_memstat_close();
2965 #endif /* _FFR_MEMSTAT */
2966 (void) setuid(RealUid);
2968 /* dump the heap, if we are checking for memory leaks */
2969 if (sm_debug_active(&SmHeapCheck, 2))
2970 sm_heap_report(smioout,
2971 sm_debug_level(&SmHeapCheck) - 1);
2972 #endif /* SM_HEAP_CHECK */
2973 if (sm_debug_active(&SmXtrapReport, 1))
2974 sm_dprintf("xtrap count = %d\n", SmXtrapCount);
2982 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
2985 ** sig -- incoming signal.
2991 ** longjmps back to test mode loop.
2993 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2994 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2998 /* Type of an exception generated on SIGINT during address test mode. */
2999 static const SM_EXC_TYPE_T EtypeInterrupt =
3013 int save_errno = errno;
3015 FIX_SYSV_SIGNAL(sig, intindebug);
3017 CHECK_CRITICAL(sig);
3019 sm_exc_raisenew_x(&EtypeInterrupt);
3021 return SIGFUNC_RETURN;
3024 ** SIGTERM -- SIGTERM handler for the daemon
3027 ** sig -- signal number.
3033 ** Sets ShutdownRequest which will hopefully trigger
3034 ** the daemon to exit.
3036 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3037 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3046 int save_errno = errno;
3048 FIX_SYSV_SIGNAL(sig, sigterm);
3049 ShutdownRequest = "signal";
3051 return SIGFUNC_RETURN;
3054 ** SIGHUP -- handle a SIGHUP signal
3057 ** sig -- incoming signal.
3063 ** Sets RestartRequest which should cause the daemon
3066 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3067 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3076 int save_errno = errno;
3078 FIX_SYSV_SIGNAL(sig, sighup);
3079 RestartRequest = "signal";
3081 return SIGFUNC_RETURN;
3084 ** SIGPIPE -- signal handler for SIGPIPE
3087 ** sig -- incoming signal.
3093 ** Sets StopRequest which should cause the mailq/hoststatus
3096 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3097 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3106 int save_errno = errno;
3108 FIX_SYSV_SIGNAL(sig, sigpipe);
3111 return SIGFUNC_RETURN;
3114 ** INTSIG -- clean up on interrupt
3116 ** This just arranges to exit. It pessimizes in that it
3117 ** may resend a message.
3126 ** Unlocks the current job.
3128 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3129 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3132 ** XXX: More work is needed for this signal handler.
3141 int save_errno = errno;
3143 FIX_SYSV_SIGNAL(sig, intsig);
3145 CHECK_CRITICAL(sig);
3146 sm_allsignals(true);
3148 if (sig != 0 && LogLevel > 79)
3149 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3152 /* Clean-up on aborted stdin message submission */
3153 if (CurEnv->e_id != NULL &&
3154 (OpMode == MD_SMTP ||
3155 OpMode == MD_DELIVER ||
3156 OpMode == MD_ARPAFTP))
3158 register ADDRESS *q;
3160 /* don't return an error indication */
3161 CurEnv->e_to = NULL;
3162 CurEnv->e_flags &= ~EF_FATALERRS;
3163 CurEnv->e_flags |= EF_CLRQUEUE;
3166 ** Spin through the addresses and
3167 ** mark them dead to prevent bounces
3170 for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
3171 q->q_state = QS_DONTSEND;
3175 else if (OpMode != MD_TEST)
3177 unlockqueue(CurEnv);
3180 finis(drop, false, EX_OK);
3184 ** DISCONNECT -- remove our connection with any foreground process
3187 ** droplev -- how "deeply" we should drop the line.
3188 ** 0 -- ignore signals, mail back errors, make sure
3189 ** output goes to stdout.
3190 ** 1 -- also, make stdout go to /dev/null.
3191 ** 2 -- also, disconnect from controlling terminal
3192 ** (only for daemon mode).
3193 ** e -- the current envelope.
3199 ** Trys to insure that we are immune to vagaries of
3200 ** the controlling tty.
3204 disconnect(droplev, e)
3206 register ENVELOPE *e;
3211 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3212 sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3213 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3216 sm_dprintf("don't\n");
3220 sm_syslog(LOG_DEBUG, e->e_id,
3221 "disconnect level %d",
3224 /* be sure we don't get nasty signals */
3225 (void) sm_signal(SIGINT, SIG_IGN);
3226 (void) sm_signal(SIGQUIT, SIG_IGN);
3228 /* we can't communicate with our caller, so.... */
3230 CurEnv->e_errormode = EM_MAIL;
3232 DisConnected = true;
3234 /* all input from /dev/null */
3235 if (InChannel != smioin)
3237 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3240 if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3241 SM_IO_RDONLY, NULL, smioin) == NULL)
3242 sm_syslog(LOG_ERR, e->e_id,
3243 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3244 SM_PATH_DEVNULL, sm_errstring(errno));
3247 ** output to the transcript
3248 ** We also compare the fd numbers here since OutChannel
3249 ** might be a layer on top of smioout due to encryption
3253 if (OutChannel != smioout &&
3254 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3255 sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3257 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3258 OutChannel = smioout;
3262 ** Has smioout been closed? Reopen it.
3263 ** This shouldn't happen anymore, the code is here
3264 ** just as a reminder.
3267 if (smioout->sm_magic == NULL &&
3268 sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3269 SM_IO_WRONLY, NULL, smioout) == NULL)
3270 sm_syslog(LOG_ERR, e->e_id,
3271 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3272 SM_PATH_DEVNULL, sm_errstring(errno));
3277 fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3280 sm_syslog(LOG_ERR, e->e_id,
3281 "disconnect: open(\"%s\") failed: %s",
3282 SM_PATH_DEVNULL, sm_errstring(errno));
3284 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3287 (void) dup2(fd, STDOUT_FILENO);
3288 (void) dup2(fd, STDERR_FILENO);
3293 /* drop our controlling TTY completely if possible */
3301 checkfd012("disconnect");
3305 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3318 while ((ap = *++argv) != NULL)
3320 /* Return if "--" or not an option of any form. */
3321 if (ap[0] != '-' || ap[1] == '-')
3324 /* Don't allow users to use "-Q." or "-Q ." */
3325 if ((ap[1] == 'Q' && ap[2] == '.') ||
3326 (ap[1] == 'Q' && argv[1] != NULL &&
3327 argv[1][0] == '.' && argv[1][1] == '\0'))
3329 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3330 "Can not use -Q.\n");
3334 /* skip over options that do have a value */
3335 op = strchr(OPTIONS, ap[1]);
3336 if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3338 #if defined(sony_news)
3339 ap[1] != 'E' && ap[1] != 'J' &&
3340 #endif /* defined(sony_news) */
3341 argv[1] != NULL && argv[1][0] != '-')
3347 /* If -C doesn't have an argument, use sendmail.cf. */
3348 #define __DEFPATH "sendmail.cf"
3349 if (ap[1] == 'C' && ap[2] == '\0')
3351 *argv = xalloc(sizeof(__DEFPATH) + 2);
3352 (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3356 /* If -q doesn't have an argument, run it once. */
3357 if (ap[1] == 'q' && ap[2] == '\0')
3360 /* If -Q doesn't have an argument, disable quarantining */
3361 if (ap[1] == 'Q' && ap[2] == '\0')
3364 /* if -d doesn't have an argument, use 0-99.1 */
3365 if (ap[1] == 'd' && ap[2] == '\0')
3368 #if defined(sony_news)
3369 /* if -E doesn't have an argument, use -EC */
3370 if (ap[1] == 'E' && ap[2] == '\0')
3373 /* if -J doesn't have an argument, use -JJ */
3374 if (ap[1] == 'J' && ap[2] == '\0')
3376 #endif /* defined(sony_news) */
3380 ** AUTH_WARNING -- specify authorization warning
3383 ** e -- the current envelope.
3384 ** msg -- the text of the message.
3385 ** args -- arguments to the message.
3393 auth_warning(register ENVELOPE *e, const char *msg, ...)
3394 #else /* __STDC__ */
3395 auth_warning(e, msg, va_alist)
3396 register ENVELOPE *e;
3399 #endif /* __STDC__ */
3404 if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3407 static char hostbuf[48];
3409 if (hostbuf[0] == '\0')
3413 hp = myhostname(hostbuf, sizeof hostbuf);
3420 #endif /* NETINET6 */
3423 (void) sm_strlcpyn(buf, sizeof buf, 2, hostbuf, ": ");
3424 p = &buf[strlen(buf)];
3425 SM_VA_START(ap, msg);
3426 (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3428 addheader("X-Authentication-Warning", buf, 0, e);
3430 sm_syslog(LOG_INFO, e->e_id,
3431 "Authentication-Warning: %.400s",
3436 ** GETEXTENV -- get from external environment
3439 ** envar -- the name of the variable to retrieve
3442 ** The value, if any.
3453 for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3455 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3456 return &(*envp)[l + 1];
3461 ** SM_SETUSERENV -- set an environment variable in the propagated environment
3464 ** envar -- the name of the environment variable.
3465 ** value -- the value to which it should be set. If
3466 ** null, this is extracted from the incoming
3467 ** environment. If that is not set, the call
3468 ** to sm_setuserenv is ignored.
3475 sm_setuserenv(envar, value)
3480 char **evp = UserEnviron;
3485 value = getextenv(envar);
3490 /* XXX enforce reasonable size? */
3491 i = strlen(envar) + 1;
3492 l = strlen(value) + i + 1;
3493 p = (char *) xalloc(l);
3494 (void) sm_strlcpyn(p, l, 3, envar, "=", value);
3496 while (*evp != NULL && strncmp(*evp, p, i) != 0)
3502 else if (evp < &UserEnviron[MAXUSERENVIRON])
3508 /* make sure it is in our environment as well */
3510 syserr("sm_setuserenv: putenv(%s) failed", p);
3513 ** DUMPSTATE -- dump state
3522 register char *j = macvalue('j', CurEnv);
3524 extern int NextMacroId;
3526 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3527 "--- dumping state on %s: $j = %s ---",
3529 j == NULL ? "<NULL>" : j);
3532 if (!wordinclass(j, 'w'))
3533 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3534 "*** $j not in $=w ***");
3536 sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3537 sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3538 NextMacroId, MAXMACROID);
3539 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3541 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3542 mci_dump_all(smioout, true);
3543 rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3547 register char **pvp;
3548 char *pv[MAXATOM + 1];
3551 status = REWRITE(pv, rs, CurEnv);
3552 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3553 "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3555 for (pvp = pv; *pvp != NULL; pvp++)
3556 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3558 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3563 ** SIGUSR1 -- Signal a request to dump state.
3566 ** sig -- calling signal.
3571 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3572 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3575 ** XXX: More work is needed for this signal handler.
3583 int save_errno = errno;
3585 extern void dumpstab __P((void));
3586 # endif /* SM_HEAP_CHECK */
3588 FIX_SYSV_SIGNAL(sig, sigusr1);
3590 CHECK_CRITICAL(sig);
3591 dumpstate("user signal");
3594 # endif /* SM_HEAP_CHECK */
3596 return SIGFUNC_RETURN;
3598 #endif /* SIGUSR1 */
3601 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3604 ** to_real_uid -- if set, drop to the real uid instead
3605 ** of the RunAsUser.
3608 ** EX_OSERR if the setuid failed.
3613 drop_privileges(to_real_uid)
3617 GIDSET_T emptygidset[1];
3620 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",
3622 (int) RealUid, (int) RealGid,
3623 (int) getuid(), (int) getgid(),
3624 (int) geteuid(), (int) getegid(),
3625 (int) RunAsUid, (int) RunAsGid);
3629 RunAsUserName = RealUserName;
3635 /* make sure no one can grab open descriptors for secret files */
3637 sm_mbdb_terminate();
3639 /* reset group permissions; these can be set later */
3640 emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3643 ** Notice: on some OS (Linux...) the setgroups() call causes
3644 ** a logfile entry if sendmail is not run by root.
3645 ** However, it is unclear (no POSIX standard) whether
3646 ** setgroups() can only succeed if executed by root.
3647 ** So for now we keep it as it is; if you want to change it, use
3648 ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3651 if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3653 syserr("drop_privileges: setgroups(1, %d) failed",
3654 (int) emptygidset[0]);
3658 /* reset primary group id */
3662 ** Drop gid to real gid.
3663 ** On some OS we must reset the effective[/real[/saved]] gid,
3664 ** and then use setgid() to finally drop all group privileges.
3665 ** Later on we check whether we can get back the
3670 if (setegid(RunAsGid) < 0)
3672 syserr("drop_privileges: setegid(%d) failed",
3676 #else /* HASSETEGID */
3678 if (setregid(RunAsGid, RunAsGid) < 0)
3680 syserr("drop_privileges: setregid(%d, %d) failed",
3681 (int) RunAsGid, (int) RunAsGid);
3684 # else /* HASSETREGID */
3686 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3688 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3689 (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3692 # endif /* HASSETRESGID */
3693 # endif /* HASSETREGID */
3694 #endif /* HASSETEGID */
3696 if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3698 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3700 syserr("drop_privileges: setgid(%d) failed",
3705 if (rval == EX_OK && getegid() != RunAsGid)
3707 syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3708 (int) getegid(), (int) RunAsGid);
3713 /* fiddle with uid */
3714 if (to_real_uid || RunAsUid != 0)
3719 ** Try to setuid(RunAsUid).
3720 ** euid must be RunAsUid,
3721 ** ruid must be RunAsUid unless (e|r)uid wasn't 0
3722 ** and we didn't have to drop privileges to the real uid.
3725 if (setuid(RunAsUid) < 0 ||
3726 geteuid() != RunAsUid ||
3727 (getuid() != RunAsUid &&
3728 (to_real_uid || geteuid() == 0 || getuid() == 0)))
3732 ** if ruid != RunAsUid, euid == RunAsUid, then
3733 ** try resetting just the real uid, then using
3734 ** setuid() to drop the saved-uid as well.
3737 if (geteuid() == RunAsUid)
3739 if (setreuid(RunAsUid, -1) < 0)
3741 syserr("drop_privileges: setreuid(%d, -1) failed",
3745 if (setuid(RunAsUid) < 0)
3747 syserr("drop_privileges: second setuid(%d) attempt failed",
3753 #endif /* HASSETREUID */
3755 syserr("drop_privileges: setuid(%d) failed",
3761 if (RunAsUid != 0 && setuid(0) == 0)
3764 ** Believe it or not, the Linux capability model
3765 ** allows a non-root process to override setuid()
3766 ** on a process running as root and prevent that
3767 ** process from dropping privileges.
3770 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3773 else if (RunAsUid != euid && setuid(euid) == 0)
3776 ** Some operating systems will keep the saved-uid
3777 ** if a non-root effective-uid calls setuid(real-uid)
3778 ** making it possible to set it back again later.
3781 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3786 if ((to_real_uid || RunAsGid != 0) &&
3787 rval == EX_OK && RunAsGid != EffGid &&
3788 getuid() != 0 && geteuid() != 0)
3791 if (setgid(EffGid) == 0)
3793 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3801 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3802 (int) geteuid(), (int) getuid(),
3803 (int) getegid(), (int) getgid());
3804 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3805 (int) RunAsUid, (int) RunAsGid);
3807 sm_dprintf("drop_privileges: rval = %d\n", rval);
3812 ** FILL_FD -- make sure a file descriptor has been properly allocated
3814 ** Used to make sure that stdin/out/err are allocated on startup
3817 ** fd -- the file descriptor to be filled.
3818 ** where -- a string used for logging. If NULL, this is
3819 ** being called on startup, and logging should
3826 ** possibly changes MissingFds
3837 if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3841 syserr("fill_fd: %s: fd %d not open", where, fd);
3843 MissingFds |= 1 << fd;
3844 i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3847 syserr("!fill_fd: %s: cannot open %s",
3848 where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3857 ** SM_PRINTOPTIONS -- print options
3860 ** options -- array of options.
3867 sm_printoptions(options)
3877 if (ll + strlen(*av) > 63)
3886 sm_dprintf("%s", *av);
3887 ll += strlen(*av++) + 1;
3892 ** TESTMODELINE -- process a test mode input line
3895 ** line -- the input line.
3896 ** e -- the current environment.
3899 ** .X process X as a configuration line
3900 ** =X dump a configuration item (such as mailers)
3901 ** $X dump a macro or class
3902 ** /X try an activity
3903 ** X normal process through rule set X
3907 testmodeline(line, e)
3913 auto char *delimptr;
3920 static int tryflags = RF_COPYNONE;
3921 char exbuf[MAXLINE];
3922 extern unsigned char TokTypeNoC[];
3924 /* skip leading spaces */
3925 while (*line == ' ')
3938 case '.': /* config-style settings */
3942 mid = macid_parse(&line[2], &delimptr);
3945 translate_dollars(delimptr);
3946 macdefine(&e->e_macro, A_TEMP, mid, delimptr);
3950 if (line[2] == '\0') /* not to call syserr() */
3953 mid = macid_parse(&line[2], &delimptr);
3956 translate_dollars(delimptr);
3957 expand(delimptr, exbuf, sizeof exbuf, e);
3964 while (*p != '\0' && isascii(*p) && isspace(*p))
3967 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
3978 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3979 "Usage: .[DC]macro value(s)\n");
3983 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3984 "Unknown \".\" command %s\n", line);
3989 case '=': /* config-style settings */
3992 case 'S': /* dump rule set */
3993 rs = strtorwset(&line[2], NULL, ST_FIND);
3996 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3997 "Undefined ruleset %s\n", &line[2]);
4000 rw = RewriteRules[rs];
4005 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4010 xputs(smioout, *s++);
4011 (void) sm_io_putc(smioout,
4012 SM_TIME_DEFAULT, ' ');
4014 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4016 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4021 xputs(smioout, *s++);
4022 (void) sm_io_putc(smioout,
4023 SM_TIME_DEFAULT, ' ');
4025 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4027 } while ((rw = rw->r_next) != NULL);
4031 for (i = 0; i < MAXMAILERS; i++)
4033 if (Mailer[i] != NULL)
4034 printmailer(smioout, Mailer[i]);
4039 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4040 "Usage: =Sruleset or =M\n");
4044 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4045 "Unknown \"=\" command %s\n", line);
4050 case '-': /* set command-line-like opts */
4058 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4059 "Usage: -d{debug arguments}\n");
4063 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4064 "Unknown \"-\" command %s\n", line);
4072 mid = macid(&line[2]);
4074 stabapply(dump_class, mid);
4077 mid = macid(&line[1]);
4080 p = macvalue(mid, e);
4082 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4087 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4092 case '/': /* miscellaneous commands */
4093 p = &line[strlen(line)];
4094 while (--p >= line && isascii(*p) && isspace(*p))
4096 p = strpbrk(line, " \t");
4099 while (isascii(*p) && isspace(*p))
4104 if (line[1] == '\0')
4106 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4107 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4110 if (sm_strcasecmp(&line[1], "quit") == 0)
4112 CurEnv->e_id = NULL;
4113 finis(true, true, ExitStat);
4116 if (sm_strcasecmp(&line[1], "mx") == 0)
4119 /* look up MX records */
4122 char *mxhosts[MAXMXHOSTS + 1];
4126 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4127 "Usage: /mx address\n");
4130 nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4132 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4133 "getmxrr(%s) returns %d value(s):\n",
4135 for (i = 0; i < nmx; i++)
4136 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4137 "\t%s\n", mxhosts[i]);
4138 #else /* NAMED_BIND */
4139 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4140 "No MX code compiled in\n");
4141 #endif /* NAMED_BIND */
4143 else if (sm_strcasecmp(&line[1], "canon") == 0)
4145 char host[MAXHOSTNAMELEN];
4149 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4150 "Usage: /canon address\n");
4153 else if (sm_strlcpy(host, p, sizeof host) >= sizeof host)
4155 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4159 (void) getcanonname(host, sizeof host, !HasWildcardMX,
4161 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4162 "getcanonname(%s) returns %s\n",
4165 else if (sm_strcasecmp(&line[1], "map") == 0)
4167 auto int rcode = EX_OK;
4172 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4173 "Usage: /map mapname key\n");
4176 for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q)); q++)
4180 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4181 "No key specified\n");
4185 map = stab(p, ST_MAP, ST_FIND);
4188 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4189 "Map named \"%s\" not found\n", p);
4192 if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4193 !openmap(&(map->s_map)))
4195 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4196 "Map named \"%s\" not open\n", p);
4199 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4200 "map_lookup: %s (%s) ", p, q);
4203 p = (*map->s_map.map_class->map_lookup)
4204 (&map->s_map, q, av, &rcode);
4206 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4210 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4211 "returns %s (%d)\n", p,
4214 else if (sm_strcasecmp(&line[1], "try") == 0)
4218 auto int rcode = EX_OK;
4220 q = strpbrk(p, " \t");
4223 while (isascii(*q) && isspace(*q))
4226 if (q == NULL || *q == '\0')
4228 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4229 "Usage: /try mailer address\n");
4232 st = stab(p, ST_MAILER, ST_FIND);
4235 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4236 "Unknown mailer %s\n", p);
4240 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4241 "Trying %s %s address %s for mailer %s\n",
4242 bitset(RF_HEADERADDR, tryflags) ? "header"
4244 bitset(RF_SENDERADDR, tryflags) ? "sender"
4245 : "recipient", q, p);
4246 p = remotename(q, m, tryflags, &rcode, CurEnv);
4247 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4248 "Rcode = %d, addr = %s\n",
4249 rcode, p == NULL ? "<NULL>" : p);
4252 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4256 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4257 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4260 for (; *p != '\0'; p++)
4266 tryflags |= RF_HEADERADDR;
4271 tryflags &= ~RF_HEADERADDR;
4276 tryflags |= RF_SENDERADDR;
4281 tryflags &= ~RF_SENDERADDR;
4285 exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4287 exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4289 macdefine(&e->e_macro, A_TEMP,
4290 macid("{addr_type}"), exbuf);
4292 else if (sm_strcasecmp(&line[1], "parse") == 0)
4296 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4297 "Usage: /parse address\n");
4300 q = crackaddr(p, e);
4301 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4302 "Cracked address = ");
4304 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4305 "\nParsing %s %s address\n",
4306 bitset(RF_HEADERADDR, tryflags) ?
4307 "header" : "envelope",
4308 bitset(RF_SENDERADDR, tryflags) ?
4309 "sender" : "recipient");
4310 if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4312 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4314 else if (a.q_host != NULL && a.q_host[0] != '\0')
4315 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4316 "mailer %s, host %s, user %s\n",
4321 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4322 "mailer %s, user %s\n",
4329 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4330 "Unknown \"/\" command %s\n",
4336 for (p = line; isascii(*p) && isspace(*p); p++)
4339 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4343 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4348 if (invalidaddr(p + 1, NULL, true))
4352 register char **pvp;
4353 char pvpbuf[PSBUFSIZE];
4355 pvp = prescan(++p, ',', pvpbuf, sizeof pvpbuf, &delimptr,
4356 ConfigLevel >= 9 ? TokTypeNoC : NULL, false);
4364 rs = strtorwset(p, NULL, ST_FIND);
4367 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4368 "Undefined ruleset %s\n",
4372 status = REWRITE(pvp, rs, e);
4373 if (status != EX_OK)
4374 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4375 "== Ruleset %s (%d) status %d\n",
4377 while (*p != '\0' && *p++ != ',')
4380 } while (*(p = delimptr) != '\0');
4388 if (s->s_symtype != ST_CLASS)
4390 if (bitnset(bitidx(id), s->s_class))
4391 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4396 ** An exception type used to create QuickAbort exceptions.
4397 ** This is my first cut at converting QuickAbort from longjmp to exceptions.
4398 ** These exceptions have a single integer argument, which is the argument
4399 ** to longjmp in the original code (either 1 or 2). I don't know the
4400 ** significance of 1 vs 2: the calls to setjmp don't care.
4403 const SM_EXC_TYPE_T EtypeQuickAbort =