2 * Copyright (c) 1998-2006, 2008 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.
16 #include <sm/sendmail.h>
18 #include <sm/signal.h>
21 SM_UNUSED(static char copyright[]) =
22 "@(#) Copyright (c) 1998-2003 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.967 2008/03/31 16:32:13 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 */
179 char *quarantining = NULL; /* quarantine queue items? */
182 bool queuepersistent = false; /* queue runner process runs forever */
183 bool foregroundqueue = false; /* queue run in foreground */
184 bool save_val; /* to save some bool var. */
185 int cftype; /* which cf file to use? */
187 static time_t starttime = 0; /* when was process started */
188 struct stat traf_st; /* for TrafficLog FIFO check */
190 char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */
191 static char rnamebuf[MAXNAME]; /* holds RealUserName */
192 char *emptyenviron[1];
195 #endif /* STARTTLS */
198 extern int DtableSize;
202 extern char **environ;
204 extern void sm_sasl_init __P((void));
209 #endif /* USE_ENVIRON */
211 /* turn off profiling */
214 /* install default exception handler */
215 sm_exc_newthread(fatal_error);
217 /* set the default in/out channel so errors reported to screen */
219 OutChannel = smioout;
222 ** Check to see if we reentered.
223 ** This would normally happen if e_putheader or e_putbody
224 ** were NULL when invoked.
229 syserr("main: reentered!");
232 starttime = curtime();
234 /* avoid null pointer dereferences */
235 TermEscape.te_rv_on = TermEscape.te_under_on = TermEscape.te_normal = "";
240 /* Check if sendmail is running with extra privs */
241 extraprivs = (RealUid != 0 &&
242 (geteuid() != getuid() || getegid() != getgid()));
244 CurrentPid = getpid();
246 /* get whatever .cf file is right for the opmode */
247 cftype = SM_GET_RIGHT_CF;
249 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
250 DtableSize = getdtsize();
251 if (DtableSize > 256)
255 ** Be sure we have enough file descriptors.
256 ** But also be sure that 0, 1, & 2 are open.
259 /* reset errno and fill_errno; the latter is used way down below */
260 errno = fill_errno = 0;
261 fill_fd(STDIN_FILENO, NULL);
264 fill_fd(STDOUT_FILENO, NULL);
267 fill_fd(STDERR_FILENO, NULL);
271 sm_closefrom(STDERR_FILENO + 1, DtableSize);
277 # define SM_LOG_STR "sendmail"
278 # endif /* ! SM_LOG_STR */
280 openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
281 # else /* LOG_MAIL */
282 openlog(SM_LOG_STR, LOG_PID);
283 # endif /* LOG_MAIL */
287 ** Seed the random number generator.
288 ** Used for queue file names, picking a queue directory, and
294 /* do machine-dependent initializations */
298 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
300 /* reset status from syserr() calls for missing file descriptors */
304 SubmitMode = SUBMIT_UNKNOWN;
305 #if _FFR_LOCAL_DAEMON
307 #endif /* _FFR_LOCAL_DAEMON */
309 checkfd012("after openlog");
312 tTsetup(tTdvect, sizeof(tTdvect), "0-99.1,*_trace_*.1");
315 /* save initial group set for future checks */
316 i = getgroups(NGROUPS_MAX, InitialGidSet);
319 InitialGidSet[0] = (GID_T) -1;
322 while (i < NGROUPS_MAX)
323 InitialGidSet[i++] = InitialGidSet[0];
324 #endif /* NGROUPS_MAX */
326 /* drop group id privileges (RunAsUser not yet set) */
327 dp = drop_privileges(false);
331 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
334 /* arrange to dump state on user-1 signal */
335 (void) sm_signal(SIGUSR1, sigusr1);
339 /* ignore user-1 signal */
340 (void) sm_signal(SIGUSR1, SIG_IGN);
344 /* initialize for setproctitle */
345 initsetproctitle(argc, argv, envp);
347 /* Handle any non-getoptable constructions. */
351 ** Do a quick prescan of the argument list.
355 /* find initial opMode */
358 p = strrchr(*av, '/');
361 if (strcmp(p, "newaliases") == 0)
362 OpMode = MD_INITALIAS;
363 else if (strcmp(p, "mailq") == 0)
365 else if (strcmp(p, "smtpd") == 0)
367 else if (strcmp(p, "hoststat") == 0)
368 OpMode = MD_HOSTSTAT;
369 else if (strcmp(p, "purgestat") == 0)
370 OpMode = MD_PURGESTAT;
372 #if defined(__osf__) || defined(_AIX3)
373 # 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"
374 #endif /* defined(__osf__) || defined(_AIX3) */
375 #if defined(sony_news)
376 # 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:"
377 #endif /* defined(sony_news) */
379 # define OPTIONS "A:B:b:C:cD:d:e:F:f:Gh:IiL:M:mN:nO:o:p:Q:q:R:r:sTtV:vX:"
380 #endif /* ! OPTIONS */
382 /* Set to 0 to allow -b; need to check optarg before using it! */
384 while ((j = getopt(argc, argv, OPTIONS)) != -1)
388 case 'b': /* operations mode */
389 j = (optarg == NULL) ? ' ' : *optarg;
407 #if _FFR_LOCAL_DAEMON
412 #endif /* _FFR_LOCAL_DAEMON */
415 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
416 "Frozen configurations unsupported\n");
420 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
421 "Invalid operation mode %c\n",
431 syserr("-D file must be before -d");
435 dp = drop_privileges(true);
437 smdebug = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
438 optarg, SM_IO_APPEND, NULL);
441 syserr("cannot open %s", optarg);
442 ExitStat = EX_CANTCREAT;
445 sm_debug_setfile(smdebug);
451 (void) sm_io_setvbuf(sm_debug_file(), SM_TIME_DEFAULT,
452 (char *) NULL, SM_IO_NBF,
456 case 'G': /* relay (gateway) submission */
457 SubmitMode = SUBMIT_MTA;
463 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
464 "option requires an argument -- '%c'",
468 j = SM_MIN(strlen(optarg), 32) + 1;
469 sysloglabel = xalloc(j);
470 (void) sm_strlcpy(sysloglabel, optarg, j);
471 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
477 /* just check if it is there */
484 /* Don't leak queue information via debug flags */
485 if (extraprivs && queuerun && debug)
487 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
488 "WARNING: Can not use -d with -q. Disabling debugging.\n");
490 sm_debug_setfile(NULL);
491 (void) memset(tTdvect, '\0', sizeof(tTdvect));
495 if (sysloglabel != NULL)
497 /* Sanitize the string */
498 for (p = sysloglabel; *p != '\0'; p++)
500 if (!isascii(*p) || !isprint(*p) || *p == '%')
505 openlog(sysloglabel, LOG_PID, LOG_MAIL);
506 # else /* LOG_MAIL */
507 openlog(sysloglabel, LOG_PID);
508 # endif /* LOG_MAIL */
512 /* set up the blank envelope */
513 BlankEnvelope.e_puthdr = putheader;
514 BlankEnvelope.e_putbody = putbody;
515 BlankEnvelope.e_xfp = NULL;
516 STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
517 CurEnv = &BlankEnvelope;
518 STRUCTCOPY(NullAddress, MainEnvelope.e_from);
521 ** Set default values for variables.
522 ** These cannot be in initialized data space.
525 setdefaults(&BlankEnvelope);
526 initmacros(&BlankEnvelope);
530 if (OpMode == MD_DAEMON)
531 DaemonPid = CurrentPid; /* needed for finis() to work */
533 pw = sm_getpwuid(RealUid);
535 (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof(rnamebuf));
537 (void) sm_snprintf(rnamebuf, sizeof(rnamebuf), "Unknown UID %d",
540 RealUserName = rnamebuf;
544 sm_dprintf("Version %s\n", Version);
545 finis(false, true, EX_OK);
550 ** if running non-set-user-ID binary as non-root, pretend
551 ** we are the RunAsUid
554 if (RealUid != 0 && geteuid() == RealUid)
557 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
561 else if (geteuid() != 0)
562 RunAsUid = geteuid();
565 if (RealUid != 0 && EffGid == RealGid)
570 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
571 (int) geteuid(), (int) getuid(),
572 (int) getegid(), (int) getgid());
573 sm_dprintf("main: RunAsUser = %d:%d\n",
574 (int) RunAsUid, (int) RunAsGid);
577 /* save command line arguments */
579 for (av = argv; *av != NULL; )
580 j += strlen(*av++) + 1;
581 SaveArgv = (char **) xalloc(sizeof(char *) * (argc + 1));
582 CommandLineArgs = xalloc(j);
584 for (av = argv, i = 0; *av != NULL; )
588 SaveArgv[i++] = newstr(*av);
591 (void) sm_strlcpy(p, *av++, j);
600 extern char *CompileOptions[];
602 sm_dprintf("Version %s\n Compiled with:", Version);
603 sm_printoptions(CompileOptions);
607 extern char *OsCompileOptions[];
609 sm_dprintf(" OS Defines:");
610 sm_printoptions(OsCompileOptions);
612 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
613 #endif /* _PATH_UNIX */
615 sm_dprintf(" Conf file:\t%s (default for MSP)\n",
616 getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
618 sm_dprintf(" Conf file:\t%s (default for MTA)\n",
619 getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
621 sm_dprintf(" Pid file:\t%s (default)\n", PidFile);
626 extern char *SmCompileOptions[];
628 sm_dprintf(" libsm Defines:");
629 sm_printoptions(SmCompileOptions);
634 extern char *FFRCompileOptions[];
636 sm_dprintf(" FFR Defines:");
637 sm_printoptions(FFRCompileOptions);
640 /* clear sendmail's environment */
641 ExternalEnviron = environ;
642 emptyenviron[0] = NULL;
643 environ = emptyenviron;
646 ** restore any original TZ setting until TimeZoneSpec has been
647 ** determined - or early log messages may get bogus time stamps
650 if ((p = getextenv("TZ")) != NULL)
655 /* XXX check for reasonable length? */
656 tzlen = strlen(p) + 4;
658 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
660 /* XXX check return code? */
664 /* prime the child environment */
665 sm_setuserenv("AGENT", "sendmail");
667 (void) sm_signal(SIGPIPE, SIG_IGN);
668 OldUmask = umask(022);
669 FullName = getextenv("NAME");
670 if (FullName != NULL)
671 FullName = newstr(FullName);
674 ** Initialize name server if it is going to be used.
678 if (!bitset(RES_INIT, _res.options))
681 _res.options |= RES_DEBUG;
683 _res.options &= ~RES_DEBUG;
684 # ifdef RES_NOALIASES
685 _res.options |= RES_NOALIASES;
686 # endif /* RES_NOALIASES */
687 TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
688 TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
689 TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
690 TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
691 TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
692 TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
693 #endif /* NAMED_BIND */
698 /* initialize some macros, etc. */
699 init_vendor_macros(&BlankEnvelope);
702 macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
705 hp = myhostname(jbuf, sizeof(jbuf));
708 struct utsname utsname;
711 sm_dprintf("Canonical name: %s\n", jbuf);
712 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
713 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
716 p = strchr(jbuf, '.');
717 if (p != NULL && p[1] != '\0')
718 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm', &p[1]);
720 if (uname(&utsname) >= 0)
721 p = utsname.nodename;
725 sm_dprintf("uname failed (%s)\n",
726 sm_errstring(errno));
731 sm_dprintf(" UUCP nodename: %s\n", p);
732 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
738 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
741 sm_dprintf("\ta.k.a.: %s\n", *av);
744 #if NETINET || NETINET6
745 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
749 char buf6[INET6_ADDRSTRLEN];
751 # endif /* NETINET6 */
754 # endif /* NETINET */
758 switch (hp->h_addrtype)
762 if (hp->h_length != INADDRSZ)
765 memmove(&ia, hp->h_addr_list[i], INADDRSZ);
766 (void) sm_snprintf(ipbuf, sizeof(ipbuf),
767 "[%.100s]", inet_ntoa(ia));
769 # endif /* NETINET */
773 if (hp->h_length != IN6ADDRSZ)
776 memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
777 addr = anynet_ntop(&ia6, buf6, sizeof(buf6));
779 (void) sm_snprintf(ipbuf, sizeof(ipbuf),
782 # endif /* NETINET6 */
784 if (ipbuf[0] == '\0')
788 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
789 setclass('w', ipbuf);
791 #endif /* NETINET || NETINET6 */
795 #endif /* NETINET6 */
799 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
801 /* current load average */
804 QueueLimitRecipient = (QUEUE_CHAR *) NULL;
805 QueueLimitSender = (QUEUE_CHAR *) NULL;
806 QueueLimitId = (QUEUE_CHAR *) NULL;
807 QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
814 while ((j = getopt(argc, argv, OPTIONS)) != -1)
818 case 'b': /* operations mode */
822 case 'A': /* use Alternate sendmail/submit.cf */
823 cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
824 : SM_GET_SENDMAIL_CF;
827 case 'B': /* body type */
828 CHECK_AGAINST_OPMODE(j);
829 BlankEnvelope.e_bodytype = newstr(optarg);
832 case 'C': /* select configuration file (already done) */
835 conffile = newstr(optarg);
836 dp = drop_privileges(true);
842 case 'd': /* debugging */
846 case 'f': /* from address */
847 case 'r': /* obsolete -f flag */
848 CHECK_AGAINST_OPMODE(j);
851 usrerr("More than one \"from\" person");
855 if (optarg[0] == '\0')
858 from = newstr(denlstring(optarg, true, true));
859 if (strcmp(RealUserName, from) != 0)
863 case 'F': /* set full name */
864 CHECK_AGAINST_OPMODE(j);
865 FullName = newstr(optarg);
868 case 'G': /* relay (gateway) submission */
870 CHECK_AGAINST_OPMODE(j);
873 case 'h': /* hop count */
874 CHECK_AGAINST_OPMODE(j);
875 BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
877 (void) sm_snprintf(buf, sizeof(buf), "%d",
878 BlankEnvelope.e_hopcount);
879 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
883 usrerr("Bad hop count (%s)", optarg);
888 case 'L': /* program label */
892 case 'n': /* don't alias */
893 CHECK_AGAINST_OPMODE(j);
897 case 'N': /* delivery status notifications */
898 CHECK_AGAINST_OPMODE(j);
899 DefaultNotify |= QHASNOTIFY;
900 macdefine(&BlankEnvelope.e_macro, A_TEMP,
901 macid("{dsn_notify}"), optarg);
902 if (sm_strcasecmp(optarg, "never") == 0)
904 for (p = optarg; p != NULL; optarg = p)
909 if (sm_strcasecmp(optarg, "success") == 0)
910 DefaultNotify |= QPINGONSUCCESS;
911 else if (sm_strcasecmp(optarg, "failure") == 0)
912 DefaultNotify |= QPINGONFAILURE;
913 else if (sm_strcasecmp(optarg, "delay") == 0)
914 DefaultNotify |= QPINGONDELAY;
917 usrerr("Invalid -N argument");
923 case 'o': /* set option */
924 setoption(*optarg, optarg + 1, false, true,
928 case 'O': /* set option (long form) */
929 setoption(' ', optarg, false, true, &BlankEnvelope);
932 case 'p': /* set protocol */
933 CHECK_AGAINST_OPMODE(j);
934 p = strchr(optarg, ':');
942 cleanstrcpy(ep, p, i);
943 macdefine(&BlankEnvelope.e_macro,
949 i = strlen(optarg) + 1;
951 cleanstrcpy(ep, optarg, i);
952 macdefine(&BlankEnvelope.e_macro, A_HEAP,
957 case 'Q': /* change quarantining on queued items */
959 if (OpMode != MD_DELIVER &&
960 OpMode != MD_QUEUERUN)
962 usrerr("Can not use -Q with -b%c", OpMode);
967 if (OpMode == MD_DELIVER)
968 set_op_mode(MD_QUEUERUN);
972 quarantining = newstr(optarg);
975 case 'q': /* run queue files at intervals */
977 if (OpMode != MD_DELIVER &&
978 OpMode != MD_DAEMON &&
979 OpMode != MD_FGDAEMON &&
980 OpMode != MD_PRINT &&
981 OpMode != MD_PRINTNQE &&
982 OpMode != MD_QUEUERUN)
984 usrerr("Can not use -q with -b%c", OpMode);
989 /* don't override -bd, -bD or -bp */
990 if (OpMode == MD_DELIVER)
991 set_op_mode(MD_QUEUERUN);
994 negate = optarg[0] == '!';
997 /* negate meaning of pattern match */
998 optarg++; /* skip '!' for next switch */
1003 case 'G': /* Limit by queue group name */
1006 usrerr("Can not use -q!G");
1007 ExitStat = EX_USAGE;
1010 if (queuegroup != NULL)
1012 usrerr("Can not use multiple -qG options");
1013 ExitStat = EX_USAGE;
1016 queuegroup = newstr(&optarg[1]);
1019 case 'I': /* Limit by ID */
1020 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1021 new->queue_match = newstr(&optarg[1]);
1022 new->queue_negate = negate;
1023 new->queue_next = QueueLimitId;
1027 case 'R': /* Limit by recipient */
1028 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1029 new->queue_match = newstr(&optarg[1]);
1030 new->queue_negate = negate;
1031 new->queue_next = QueueLimitRecipient;
1032 QueueLimitRecipient = new;
1035 case 'S': /* Limit by sender */
1036 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1037 new->queue_match = newstr(&optarg[1]);
1038 new->queue_negate = negate;
1039 new->queue_next = QueueLimitSender;
1040 QueueLimitSender = new;
1043 case 'f': /* foreground queue run */
1044 foregroundqueue = true;
1047 case 'Q': /* Limit by quarantine message */
1048 if (optarg[1] != '\0')
1050 new = (QUEUE_CHAR *) xalloc(sizeof(*new));
1051 new->queue_match = newstr(&optarg[1]);
1052 new->queue_negate = negate;
1053 new->queue_next = QueueLimitQuarantine;
1054 QueueLimitQuarantine = new;
1056 QueueMode = QM_QUARANTINE;
1059 case 'L': /* act on lost items */
1060 QueueMode = QM_LOST;
1063 case 'p': /* Persistent queue */
1064 queuepersistent = true;
1065 if (QueueIntvl == 0)
1067 if (optarg[1] == '\0')
1074 QueueIntvl = convtime(optarg, 'm');
1077 usrerr("Invalid -q value");
1078 ExitStat = EX_USAGE;
1081 /* check for bad conversion */
1083 ExitStat = EX_USAGE;
1088 case 'R': /* DSN RET: what to return */
1089 CHECK_AGAINST_OPMODE(j);
1090 if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1092 usrerr("Duplicate -R flag");
1093 ExitStat = EX_USAGE;
1096 BlankEnvelope.e_flags |= EF_RET_PARAM;
1097 if (sm_strcasecmp(optarg, "hdrs") == 0)
1098 BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1099 else if (sm_strcasecmp(optarg, "full") != 0)
1101 usrerr("Invalid -R value");
1102 ExitStat = EX_USAGE;
1104 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1105 macid("{dsn_ret}"), optarg);
1108 case 't': /* read recipients from message */
1109 CHECK_AGAINST_OPMODE(j);
1113 case 'V': /* DSN ENVID: set "original" envelope id */
1114 CHECK_AGAINST_OPMODE(j);
1115 if (!xtextok(optarg))
1117 usrerr("Invalid syntax in -V flag");
1118 ExitStat = EX_USAGE;
1122 BlankEnvelope.e_envid = newstr(optarg);
1123 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1124 macid("{dsn_envid}"), optarg);
1128 case 'X': /* traffic log file */
1129 dp = drop_privileges(true);
1131 if (stat(optarg, &traf_st) == 0 &&
1132 S_ISFIFO(traf_st.st_mode))
1133 TrafficLogFile = sm_io_open(SmFtStdio,
1136 SM_IO_WRONLY, NULL);
1138 TrafficLogFile = sm_io_open(SmFtStdio,
1141 SM_IO_APPEND, NULL);
1142 if (TrafficLogFile == NULL)
1144 syserr("cannot open %s", optarg);
1145 ExitStat = EX_CANTCREAT;
1148 (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1149 NULL, SM_IO_LBF, 0);
1152 /* compatibility flags */
1153 case 'c': /* connect to non-local mailers */
1154 case 'i': /* don't let dot stop me */
1155 case 'm': /* send to me too */
1156 case 'T': /* set timeout interval */
1157 case 'v': /* give blow-by-blow description */
1158 setoption(j, "T", false, true, &BlankEnvelope);
1161 case 'e': /* error message disposition */
1162 case 'M': /* define macro */
1163 setoption(j, optarg, false, true, &BlankEnvelope);
1166 case 's': /* save From lines in headers */
1167 setoption('f', "T", false, true, &BlankEnvelope);
1171 case 'I': /* initialize alias DBM file */
1172 set_op_mode(MD_INITALIAS);
1176 #if defined(__osf__) || defined(_AIX3)
1177 case 'x': /* random flag that OSF/1 & AIX mailx passes */
1179 #endif /* defined(__osf__) || defined(_AIX3) */
1180 #if defined(sony_news)
1182 case 'J': /* ignore flags for Japanese code conversion
1183 implemented on Sony NEWS */
1185 #endif /* defined(sony_news) */
1188 finis(true, true, EX_USAGE);
1194 /* if we've had errors so far, exit now */
1195 if ((ExitStat != EX_OK && OpMode != MD_TEST) ||
1196 ExitStat == EX_OSERR)
1198 finis(false, true, ExitStat);
1202 if (bitset(SUBMIT_MTA, SubmitMode))
1204 /* If set daemon_flags on command line, don't reset it */
1205 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1206 macdefine(&BlankEnvelope.e_macro, A_PERM,
1207 macid("{daemon_flags}"), "CC f");
1209 else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1211 SubmitMode = SUBMIT_MSA;
1213 /* If set daemon_flags on command line, don't reset it */
1214 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1215 macdefine(&BlankEnvelope.e_macro, A_PERM,
1216 macid("{daemon_flags}"), "c u");
1220 ** Do basic initialization.
1221 ** Read system control file.
1222 ** Extract special fields for local use.
1226 checkfd012("before readcf");
1228 vendor_pre_defaults(&BlankEnvelope);
1230 readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1231 safecf, &BlankEnvelope);
1232 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1233 ConfigFileRead = true;
1234 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1235 vendor_post_defaults(&BlankEnvelope);
1237 /* now we can complain about missing fds */
1238 if (MissingFds != 0 && LogLevel > 8)
1243 if (bitset(1 << STDIN_FILENO, MissingFds))
1244 (void) sm_strlcat(mbuf, ", stdin", sizeof(mbuf));
1245 if (bitset(1 << STDOUT_FILENO, MissingFds))
1246 (void) sm_strlcat(mbuf, ", stdout", sizeof(mbuf));
1247 if (bitset(1 << STDERR_FILENO, MissingFds))
1248 (void) sm_strlcat(mbuf, ", stderr", sizeof(mbuf));
1250 /* Notice: fill_errno is from high above: fill_fd() */
1251 sm_syslog(LOG_WARNING, NOQID,
1252 "File descriptors missing on startup: %s; %s",
1253 &mbuf[2], sm_errstring(fill_errno));
1256 /* Remove the ability for a normal user to send signals */
1257 if (RealUid != 0 && RealUid != geteuid())
1259 uid_t new_uid = geteuid();
1263 ** Since we can differentiate between uid and euid,
1264 ** make the uid a different user so the real user
1265 ** can't send signals. However, it doesn't need to be
1266 ** root (euid has root).
1272 sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1273 if (setreuid(new_uid, geteuid()) < 0)
1275 syserr("main: setreuid(%d, %d) failed",
1276 (int) new_uid, (int) geteuid());
1277 finis(false, true, EX_OSERR);
1281 sm_dprintf("Now running as e/ruid %d:%d\n",
1282 (int) geteuid(), (int) getuid());
1283 #else /* HASSETREUID */
1285 ** Have to change both effective and real so need to
1286 ** change them both to effective to keep privs.
1290 sm_dprintf("Changing uid to %d\n", (int) new_uid);
1291 if (setuid(new_uid) < 0)
1293 syserr("main: setuid(%d) failed", (int) new_uid);
1294 finis(false, true, EX_OSERR);
1298 sm_dprintf("Now running as e/ruid %d:%d\n",
1299 (int) geteuid(), (int) getuid());
1300 #endif /* HASSETREUID */
1304 if (FallbackMX != NULL)
1305 (void) getfallbackmxrr(FallbackMX);
1306 #endif /* NAMED_BIND */
1308 if (SuperSafe == SAFE_INTERACTIVE && CurEnv->e_sendmode != SM_DELIVER)
1310 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1311 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1314 if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1316 usrerr("Mail submission program cannot be used as daemon");
1317 finis(false, true, EX_USAGE);
1320 if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1321 OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1322 OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1325 /* set up the basic signal handlers */
1326 if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1327 (void) sm_signal(SIGINT, intsig);
1328 (void) sm_signal(SIGTERM, intsig);
1330 /* Enforce use of local time (null string overrides this) */
1331 if (TimeZoneSpec == NULL)
1333 else if (TimeZoneSpec[0] != '\0')
1334 sm_setuserenv("TZ", TimeZoneSpec);
1336 sm_setuserenv("TZ", NULL);
1339 /* initialize mailbox database */
1340 i = sm_mbdb_initialize(Mbdb);
1343 usrerr("Can't initialize mailbox database \"%s\": %s",
1344 Mbdb, sm_strexit(i));
1348 /* avoid denial-of-service attacks */
1351 if (OpMode == MD_TEST)
1353 /* can't be done after readcf if RunAs* is used */
1354 dp = drop_privileges(true);
1357 finis(false, true, dp);
1361 else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1363 /* drop privileges -- daemon mode done after socket/bind */
1364 dp = drop_privileges(false);
1366 if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1368 usrerr("Mail submission program must have RunAsUser set to non root user");
1369 finis(false, true, EX_CONFIG);
1375 _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1376 _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1377 #endif /* NAMED_BIND */
1380 ** Find our real host name for future logging.
1383 authinfo = getauthinfo(STDIN_FILENO, &forged);
1384 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1386 /* suppress error printing if errors mailed back or whatever */
1387 if (BlankEnvelope.e_errormode != EM_PRINT)
1390 /* set up the $=m class now, after .cf has a chance to redefine $m */
1391 expand("\201m", jbuf, sizeof(jbuf), &BlankEnvelope);
1392 if (jbuf[0] != '\0')
1393 setclass('m', jbuf);
1395 /* probe interfaces and locate any additional names */
1396 if (DontProbeInterfaces != DPI_PROBENONE)
1401 char pidpath[MAXPATHLEN];
1403 /* Now we know which .cf file we use */
1404 sm_dprintf(" Conf file:\t%s (selected)\n",
1405 getcfname(OpMode, SubmitMode, cftype, conffile));
1406 expand(PidFile, pidpath, sizeof(pidpath), &BlankEnvelope);
1407 sm_dprintf(" Pid file:\t%s (selected)\n", pidpath);
1412 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1413 sm_dprintf("\n (short domain name) $w = ");
1414 xputs(sm_debug_file(), macvalue('w', &BlankEnvelope));
1415 sm_dprintf("\n (canonical domain name) $j = ");
1416 xputs(sm_debug_file(), macvalue('j', &BlankEnvelope));
1417 sm_dprintf("\n (subdomain name) $m = ");
1418 xputs(sm_debug_file(), macvalue('m', &BlankEnvelope));
1419 sm_dprintf("\n (node name) $k = ");
1420 xputs(sm_debug_file(), macvalue('k', &BlankEnvelope));
1421 sm_dprintf("\n========================================================\n\n");
1425 ** Do more command line checking -- these are things that
1426 ** have to modify the results of reading the config file.
1429 /* process authorization warnings from command line */
1431 auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1432 RealUserName, conffile);
1433 if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1434 auth_warning(&BlankEnvelope, "Processed from queue %s",
1436 if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1437 RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1438 sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1441 /* check body type for legality */
1442 i = check_bodytype(BlankEnvelope.e_bodytype);
1443 if (i == BODYTYPE_ILLEGAL)
1445 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1446 BlankEnvelope.e_bodytype = NULL;
1448 else if (i != BODYTYPE_NONE)
1449 SevenBitInput = (i == BODYTYPE_7BIT);
1451 /* tweak default DSN notifications */
1452 if (DefaultNotify == 0)
1453 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1455 /* check for sane configuration level */
1456 if (ConfigLevel > MAXCONFIGLEVEL)
1458 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1459 ConfigLevel, Version, MAXCONFIGLEVEL);
1462 /* need MCI cache to have persistence */
1463 if (HostStatDir != NULL && MaxMciCache == 0)
1466 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1467 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1470 /* need HostStatusDir in order to have SingleThreadDelivery */
1471 if (SingleThreadDelivery && HostStatDir == NULL)
1473 SingleThreadDelivery = false;
1474 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1475 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1479 j = sm_memstat_open();
1480 if (j < 0 && (RefuseLowMem > 0 || QueueLowMem > 0) && LogLevel > 4)
1482 sm_syslog(LOG_WARNING, NOQID,
1483 "cannot get memory statistics, settings ignored, error=%d"
1486 #endif /* _FFR_MEMSTAT */
1488 /* check for permissions */
1490 RealUid != TrustedUid)
1492 char *action = NULL;
1497 if (quarantining != NULL)
1498 action = "quarantine jobs";
1501 /* Normal users can do a single queue run */
1502 if (QueueIntvl == 0)
1506 /* but not persistent queue runners */
1508 action = "start a queue runner daemon";
1513 action = "purge host status";
1519 action = "run daemon";
1522 sm_dprintf("Deny user %d attempt to %s\n",
1523 (int) RealUid, action);
1526 sm_syslog(LOG_ALERT, NOQID,
1527 "user %d attempted to %s",
1528 (int) RealUid, action);
1530 usrerr("Permission denied (real uid not trusted)");
1531 finis(false, true, EX_USAGE);
1536 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1539 ** If -bv and RestrictExpand,
1540 ** drop privs to prevent normal
1541 ** users from reading private
1542 ** aliases/forwards/:include:s
1546 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1549 dp = drop_privileges(true);
1551 /* Fake address safety */
1553 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1554 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1559 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1561 CurEnv->e_id = NULL;
1562 finis(true, true, dp);
1573 /* Nothing special to check */
1577 if (!wordinclass(RealUserName, 't'))
1580 sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1583 sm_syslog(LOG_ALERT, NOQID,
1584 "user %d attempted to rebuild the alias map",
1587 usrerr("Permission denied (real uid not trusted)");
1588 finis(false, true, EX_USAGE);
1594 usrerr("User %d cannot rebuild aliases in mail submission program",
1596 finis(false, true, EX_USAGE);
1602 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1606 ** If -v and RestrictExpand, reset
1607 ** Verbose to prevent normal users
1608 ** from seeing the expansion of
1609 ** aliases/forwards/:include:s
1613 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1622 BlankEnvelope.e_flags |= EF_METOO;
1627 /* don't have persistent host status in test mode */
1631 BlankEnvelope.e_errormode = EM_PRINT;
1636 BlankEnvelope.e_errormode = EM_PRINT;
1638 /* arrange to exit cleanly on hangup signal */
1639 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1640 (void) sm_signal(SIGHUP, intsig);
1642 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1643 "Notice: -bv may give misleading output for non-privileged user\n");
1647 run_in_foreground = true;
1648 set_op_mode(MD_DAEMON);
1652 vendor_daemon_setup(&BlankEnvelope);
1654 /* remove things that don't make sense in daemon mode */
1658 /* arrange to restart on hangup signal */
1659 if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1660 sm_syslog(LOG_WARNING, NOQID,
1661 "daemon invoked without full pathname; kill -1 won't work");
1666 BlankEnvelope.e_errormode = EM_PRINT;
1671 /* arrange to exit cleanly on hangup signal */
1672 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1673 (void) sm_signal(SIGHUP, intsig);
1677 /* special considerations for FullName */
1678 if (FullName != NULL)
1682 /* full names can't have newlines */
1683 if (strchr(FullName, '\n') != NULL)
1685 full = newstr(denlstring(FullName, true, true));
1689 /* check for characters that may have to be quoted */
1690 if (!rfc822_string(FullName))
1693 ** Quote a full name with special characters
1694 ** as a comment so crackaddr() doesn't destroy
1695 ** the name portion of the address.
1698 FullName = addquotes(FullName, NULL);
1700 sm_free(full); /* XXX */
1704 /* do heuristic mode adjustment */
1707 /* turn off noconnect option */
1708 setoption('c', "F", true, false, &BlankEnvelope);
1710 /* turn on interactive delivery */
1711 setoption('d', "", true, false, &BlankEnvelope);
1715 /* check for vendor mismatch */
1716 if (VendorCode != VENDOR_CODE)
1718 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1719 getvendor(VENDOR_CODE), getvendor(VendorCode));
1721 #endif /* VENDOR_CODE */
1723 /* check for out of date configuration level */
1724 if (ConfigLevel < MAXCONFIGLEVEL)
1726 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1727 Version, MAXCONFIGLEVEL, ConfigLevel);
1730 if (ConfigLevel < 3)
1733 /* set options that were previous macros */
1734 if (SmtpGreeting == NULL)
1736 if (ConfigLevel < 7 &&
1737 (p = macvalue('e', &BlankEnvelope)) != NULL)
1738 SmtpGreeting = newstr(p);
1740 SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1742 if (UnixFromLine == NULL)
1744 if (ConfigLevel < 7 &&
1745 (p = macvalue('l', &BlankEnvelope)) != NULL)
1746 UnixFromLine = newstr(p);
1748 UnixFromLine = "From \201g \201d";
1750 SmtpError[0] = '\0';
1752 /* our name for SMTP codes */
1753 expand("\201j", jbuf, sizeof(jbuf), &BlankEnvelope);
1754 if (jbuf[0] == '\0')
1755 PSTRSET(MyHostName, "localhost");
1757 PSTRSET(MyHostName, jbuf);
1758 if (strchr(MyHostName, '.') == NULL)
1759 message("WARNING: local host name (%s) is not qualified; see cf/README: WHO AM I?",
1762 /* make certain that this name is part of the $=w class */
1763 setclass('w', MyHostName);
1765 /* fill in the structure of the *default* queue */
1766 st = stab("mqueue", ST_QUEUE, ST_FIND);
1768 syserr("No default queue (mqueue) defined");
1770 set_def_queueval(st->s_quegrp, true);
1772 /* the indices of built-in mailers */
1773 st = stab("local", ST_MAILER, ST_FIND);
1775 LocalMailer = st->s_mailer;
1776 else if (OpMode != MD_TEST || !warn_C_flag)
1777 syserr("No local mailer defined");
1779 st = stab("prog", ST_MAILER, ST_FIND);
1781 syserr("No prog mailer defined");
1784 ProgMailer = st->s_mailer;
1785 clrbitn(M_MUSER, ProgMailer->m_flags);
1788 st = stab("*file*", ST_MAILER, ST_FIND);
1790 syserr("No *file* mailer defined");
1793 FileMailer = st->s_mailer;
1794 clrbitn(M_MUSER, FileMailer->m_flags);
1797 st = stab("*include*", ST_MAILER, ST_FIND);
1799 syserr("No *include* mailer defined");
1801 InclMailer = st->s_mailer;
1803 if (ConfigLevel < 6)
1805 /* heuristic tweaking of local mailer for back compat */
1806 if (LocalMailer != NULL)
1808 setbitn(M_ALIASABLE, LocalMailer->m_flags);
1809 setbitn(M_HASPWENT, LocalMailer->m_flags);
1810 setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1811 setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1812 setbitn(M_CHECKPROG, LocalMailer->m_flags);
1813 setbitn(M_CHECKFILE, LocalMailer->m_flags);
1814 setbitn(M_CHECKUDB, LocalMailer->m_flags);
1816 if (ProgMailer != NULL)
1817 setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1818 if (FileMailer != NULL)
1819 setbitn(M_RUNASRCPT, FileMailer->m_flags);
1821 if (ConfigLevel < 7)
1823 if (LocalMailer != NULL)
1824 setbitn(M_VRFY250, LocalMailer->m_flags);
1825 if (ProgMailer != NULL)
1826 setbitn(M_VRFY250, ProgMailer->m_flags);
1827 if (FileMailer != NULL)
1828 setbitn(M_VRFY250, FileMailer->m_flags);
1831 /* MIME Content-Types that cannot be transfer encoded */
1832 setclass('n', "multipart/signed");
1834 /* MIME message/xxx subtypes that can be treated as messages */
1835 setclass('s', "rfc822");
1837 /* MIME Content-Transfer-Encodings that can be encoded */
1838 setclass('e', "7bit");
1839 setclass('e', "8bit");
1840 setclass('e', "binary");
1843 /* MIME Content-Types that should be treated as binary */
1844 setclass('b', "image");
1845 setclass('b', "audio");
1846 setclass('b', "video");
1847 setclass('b', "application/octet-stream");
1848 #endif /* USE_B_CLASS */
1850 /* MIME headers which have fields to check for overflow */
1851 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1852 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1854 /* MIME headers to check for length overflow */
1855 setclass(macid("{checkMIMETextHeaders}"), "content-description");
1857 /* MIME headers to check for overflow and rebalance */
1858 setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1859 setclass(macid("{checkMIMEHeaders}"), "content-id");
1860 setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1861 setclass(macid("{checkMIMEHeaders}"), "content-type");
1862 setclass(macid("{checkMIMEHeaders}"), "mime-version");
1864 /* Macros to save in the queue file -- don't remove any */
1865 setclass(macid("{persistentMacros}"), "r");
1866 setclass(macid("{persistentMacros}"), "s");
1867 setclass(macid("{persistentMacros}"), "_");
1868 setclass(macid("{persistentMacros}"), "{if_addr}");
1869 setclass(macid("{persistentMacros}"), "{daemon_flags}");
1871 /* operate in queue directory */
1872 if (QueueDir == NULL || *QueueDir == '\0')
1874 if (OpMode != MD_TEST)
1876 syserr("QueueDirectory (Q) option must be set");
1877 ExitStat = EX_CONFIG;
1882 if (OpMode != MD_TEST)
1883 setup_queues(OpMode == MD_DAEMON);
1886 /* check host status directory for validity */
1887 if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1889 /* cannot use this value */
1890 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1891 "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1892 HostStatDir, sm_errstring(errno));
1896 if (OpMode == MD_QUEUERUN &&
1897 RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1901 /* check to see if we own the queue directory */
1902 if (stat(".", &stbuf) < 0)
1903 syserr("main: cannot stat %s", QueueDir);
1904 if (stbuf.st_uid != RealUid)
1906 /* nope, really a botch */
1908 usrerr("You do not have permission to process the queue");
1909 finis(false, true, EX_NOPERM);
1915 /* sanity checks on milter filters */
1916 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1918 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1919 setup_daemon_milters();
1923 /* Convert queuegroup string to qgrp number */
1924 if (queuegroup != NULL)
1926 qgrp = name2qid(queuegroup);
1930 usrerr("Queue group %s unknown", queuegroup);
1931 finis(false, true, ExitStat);
1936 /* if we've had errors so far, exit now */
1937 if (ExitStat != EX_OK && OpMode != MD_TEST)
1939 finis(false, true, ExitStat);
1944 /* sendmail specific SASL initialization */
1949 checkfd012("before main() initmaps");
1953 ** Do operation-mode-dependent initialization.
1959 /* print the queue */
1961 dropenvelope(&BlankEnvelope, true, false);
1962 (void) sm_signal(SIGPIPE, sigpipe);
1967 /* Selecting a particular queue group to run */
1968 for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1972 (void) print_single_queue(qgrp, j);
1974 finis(false, true, EX_OK);
1978 finis(false, true, EX_OK);
1983 /* print number of entries in queue */
1984 dropenvelope(&BlankEnvelope, true, false);
1985 (void) sm_signal(SIGPIPE, sigpipe);
1986 printnqe(smioout, NULL);
1987 finis(false, true, EX_OK);
1992 /* only handle quarantining here */
1993 if (quarantining == NULL)
1996 if (QueueMode != QM_QUARANTINE &&
1997 QueueMode != QM_NORMAL)
2000 usrerr("Can not use -Q with -q%c", QueueMode);
2001 ExitStat = EX_USAGE;
2002 finis(false, true, ExitStat);
2005 quarantine_queue(quarantining, qgrp);
2006 finis(false, true, EX_OK);
2010 (void) sm_signal(SIGPIPE, sigpipe);
2011 (void) mci_traverse_persistent(mci_print_persistent, NULL);
2012 finis(false, true, EX_OK);
2017 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2018 finis(false, true, EX_OK);
2023 /* initialize maps */
2025 finis(false, true, ExitStat);
2031 /* reset DSN parameters */
2032 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2033 macdefine(&BlankEnvelope.e_macro, A_PERM,
2034 macid("{dsn_notify}"), NULL);
2035 BlankEnvelope.e_envid = NULL;
2036 macdefine(&BlankEnvelope.e_macro, A_PERM,
2037 macid("{dsn_envid}"), NULL);
2038 BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2039 macdefine(&BlankEnvelope.e_macro, A_PERM,
2040 macid("{dsn_ret}"), NULL);
2042 /* don't open maps for daemon -- done below in child */
2048 /* print configuration table (or at least part of it) */
2051 for (i = 0; i < MAXMAILERS; i++)
2053 if (Mailer[i] != NULL)
2054 printmailer(sm_debug_file(), Mailer[i]);
2059 ** Switch to the main envelope.
2062 CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2063 sm_rpool_new_x(NULL));
2064 MainEnvelope.e_flags = BlankEnvelope.e_flags;
2067 ** If test mode, read addresses from stdin and process.
2070 if (OpMode == MD_TEST)
2072 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2077 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2078 "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2079 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2080 "Enter <ruleset> <address>\n");
2082 macdefine(&(MainEnvelope.e_macro), A_PERM,
2083 macid("{addr_type}"), "e r");
2088 (void) sm_signal(SIGINT, intindebug);
2089 (void) sm_releasesignal(SIGINT);
2091 (void) sm_io_fprintf(smioout,
2094 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2095 if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2096 sizeof(buf)) == NULL)
2097 testmodeline("/quit", &MainEnvelope);
2098 p = strchr(buf, '\n');
2102 (void) sm_io_fprintf(smioout,
2105 testmodeline(buf, &MainEnvelope);
2107 SM_EXCEPT(exc, "[!F]*")
2110 ** 8.10 just prints \n on interrupt.
2111 ** I'm printing the exception here in case
2112 ** sendmail is extended to raise additional
2113 ** exceptions in this context.
2116 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2118 sm_exc_print(exc, smioout);
2126 if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER ||
2127 OpMode == MD_ARPAFTP)
2129 /* check whether STARTTLS is turned off for the client */
2130 if (chkclientmodifiers(D_NOTLS))
2133 else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2136 /* check whether STARTTLS is turned off for the server */
2137 if (chkdaemonmodifiers(D_NOTLS))
2140 else /* other modes don't need STARTTLS */
2145 /* basic TLS initialization */
2146 tls_ok = init_tls_library();
2149 if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2151 /* disable TLS for client */
2154 #endif /* STARTTLS */
2157 ** If collecting stuff from the queue, go start doing that.
2160 if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2165 /* init TLS for client, ignore result for now */
2166 (void) initclttls(tls_ok);
2167 #endif /* STARTTLS */
2170 ** The parent process of the caller of runqueue() needs
2171 ** to stay around for a possible SIGTERM. The SIGTERM will
2172 ** tell this process that all of the queue runners children
2173 ** need to be sent SIGTERM as well. At the same time, we
2174 ** want to return control to the command line. So we do an
2178 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2181 ** If the fork() failed we should still try to do
2182 ** the queue run. If it succeeded then the child
2183 ** is going to start the run and wait for all
2184 ** of the children to finish.
2189 /* Reset global flags */
2190 RestartRequest = NULL;
2191 ShutdownRequest = NULL;
2194 /* disconnect from terminal */
2195 disconnect(2, CurEnv);
2198 CurrentPid = getpid();
2201 int rwgflags = RWG_NONE;
2204 ** To run a specific queue group mark it to
2205 ** be run, select the work group it's in and
2206 ** increment the work counter.
2209 for (i = 0; i < NumQueue && Queue[i] != NULL;
2211 Queue[i]->qg_nextrun = (time_t) -1;
2212 Queue[qgrp]->qg_nextrun = 0;
2214 rwgflags |= RWG_VERBOSE;
2215 if (queuepersistent)
2216 rwgflags |= RWG_PERSISTENT;
2217 rwgflags |= RWG_FORCE;
2218 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2222 (void) runqueue(false, Verbose,
2223 queuepersistent, true);
2225 /* set the title to make it easier to find */
2226 sm_setproctitle(true, CurEnv, "Queue control");
2227 (void) sm_signal(SIGCHLD, SIG_DFL);
2228 while (CurChildren > 0)
2234 while ((ret = sm_wait(&status)) <= 0)
2236 if (errno == ECHILD)
2239 ** Oops... something got messed
2240 ** up really bad. Waiting for
2241 ** non-existent children
2242 ** shouldn't happen. Let's get
2252 /* something is really really wrong */
2253 if (errno == ECHILD)
2255 sm_syslog(LOG_ERR, NOQID,
2256 "queue control process: lost all children: wait returned ECHILD");
2260 /* Only drop when a child gives status */
2261 if (WIFSTOPPED(status))
2264 proc_list_drop(ret, status, NULL);
2267 finis(true, true, ExitStat);
2272 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2274 /* check whether AUTH is turned off for the server */
2275 if (!chkdaemonmodifiers(D_NOAUTH) &&
2276 (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2277 syserr("!sasl_server_init failed! [%s]",
2278 sasl_errstring(i, NULL, NULL));
2282 if (OpMode == MD_SMTP)
2284 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2285 PROC_DAEMON, 0, -1, NULL);
2287 /* clean up background delivery children */
2288 (void) sm_signal(SIGCHLD, reapchild);
2292 ** If a daemon, wait for a request.
2293 ** getrequests will always return in a child.
2294 ** If we should also be processing the queue, start
2295 ** doing it in background.
2296 ** We check for any errors that might have happened
2300 if (OpMode == MD_DAEMON || QueueIntvl > 0)
2304 /* avoid cleanup in finis(), DaemonPid will be set below */
2306 if (!run_in_foreground && !tTd(99, 100))
2308 /* put us in background */
2311 syserr("daemon: cannot fork");
2314 finis(false, true, EX_OK);
2319 ** Initialize exception stack and default exception
2320 ** handler for child process.
2323 /* Reset global flags */
2324 RestartRequest = NULL;
2325 RestartWorkGroup = false;
2326 ShutdownRequest = NULL;
2328 CurrentPid = getpid();
2330 sm_exc_newthread(fatal_error);
2332 /* disconnect from our controlling tty */
2333 disconnect(2, &MainEnvelope);
2337 if (OpMode == MD_DAEMON)
2339 (void) sm_strlcat(dtype, "+SMTP", sizeof(dtype));
2340 DaemonPid = CurrentPid;
2344 (void) sm_strlcat2(dtype,
2346 ? "+persistent-queueing@"
2348 pintvl(QueueIntvl, true),
2352 (void) sm_strlcat(dtype, "+debugging", sizeof(dtype));
2354 sm_syslog(LOG_INFO, NOQID,
2355 "starting daemon (%s): %s", Version, dtype + 1);
2360 /* save daemon type in a macro for possible PidFile use */
2361 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2362 macid("{daemon_info}"), dtype + 1);
2364 /* save queue interval in a macro for possible PidFile use */
2365 macdefine(&MainEnvelope.e_macro, A_TEMP,
2366 macid("{queue_interval}"), pintvl(QueueIntvl, true));
2368 /* workaround: can't seem to release the signal in the parent */
2369 (void) sm_signal(SIGHUP, sighup);
2370 (void) sm_releasesignal(SIGHUP);
2371 (void) sm_signal(SIGTERM, sigterm);
2378 int rwgflags = RWG_NONE;
2381 ** To run a specific queue group mark it to
2382 ** be run, select the work group it's in and
2383 ** increment the work counter.
2386 for (i = 0; i < NumQueue && Queue[i] != NULL;
2388 Queue[i]->qg_nextrun = (time_t) -1;
2389 Queue[qgrp]->qg_nextrun = 0;
2391 rwgflags |= RWG_VERBOSE;
2392 if (queuepersistent)
2393 rwgflags |= RWG_PERSISTENT;
2394 rwgflags |= RWG_FORCE;
2395 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2399 #endif /* _FFR_RUNPQG */
2400 (void) runqueue(true, false, queuepersistent,
2404 ** If queuepersistent but not in daemon mode then
2405 ** we're going to do the queue runner monitoring here.
2406 ** If in daemon mode then the monitoring will happen
2410 if (OpMode != MD_DAEMON && queuepersistent)
2413 ** Write the pid to file
2414 ** XXX Overwrites sendmail.pid
2417 log_sendmail_pid(&MainEnvelope);
2419 /* set the title to make it easier to find */
2420 sm_setproctitle(true, CurEnv, "Queue control");
2421 (void) sm_signal(SIGCHLD, SIG_DFL);
2422 while (CurChildren > 0)
2430 while ((ret = sm_wait(&status)) <= 0)
2433 ** Waiting for non-existent
2434 ** children shouldn't happen.
2435 ** Let's get out of here if
2439 if (errno == ECHILD)
2447 /* something is really really wrong */
2448 if (errno == ECHILD)
2450 sm_syslog(LOG_ERR, NOQID,
2451 "persistent queue runner control process: lost all children: wait returned ECHILD");
2455 if (WIFSTOPPED(status))
2458 /* Probe only on a child status */
2459 proc_list_drop(ret, status, &group);
2461 if (WIFSIGNALED(status))
2463 if (WCOREDUMP(status))
2465 sm_syslog(LOG_ERR, NOQID,
2466 "persistent queue runner=%d core dumped, signal=%d",
2467 group, WTERMSIG(status));
2469 /* don't restart this */
2470 mark_work_group_restart(
2475 sm_syslog(LOG_ERR, NOQID,
2476 "persistent queue runner=%d died, pid=%ld, signal=%d",
2482 ** When debugging active, don't
2483 ** restart the persistent queues.
2484 ** But do log this as info.
2487 if (sm_debug_active(&DebugNoPRestart,
2490 sm_syslog(LOG_DEBUG, NOQID,
2491 "persistent queue runner=%d, exited",
2493 mark_work_group_restart(group,
2498 finis(true, true, ExitStat);
2502 if (OpMode != MD_DAEMON)
2507 ** Write the pid to file
2508 ** XXX Overwrites sendmail.pid
2511 log_sendmail_pid(&MainEnvelope);
2513 /* set the title to make it easier to find */
2515 (void) sm_strlcpyn(qtype, sizeof(qtype), 4,
2517 pintvl(QueueIntvl, true),
2520 sm_setproctitle(true, CurEnv, qtype);
2528 (void) runqueue(true, false,
2533 dropenvelope(&MainEnvelope, true, false);
2536 /* init TLS for server, ignore result for now */
2537 (void) initsrvtls(tls_ok);
2538 #endif /* STARTTLS */
2541 p_flags = getrequests(&MainEnvelope);
2543 /* drop privileges */
2544 (void) drop_privileges(false);
2547 ** Get authentication data
2548 ** Set _ macro in BlankEnvelope before calling newenvelope().
2551 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2553 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2555 /* at this point we are in a child: reset state */
2556 sm_rpool_free(MainEnvelope.e_rpool);
2557 (void) newenvelope(&MainEnvelope, &MainEnvelope,
2558 sm_rpool_new_x(NULL));
2563 /* log connection information */
2564 sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2568 ** If running SMTP protocol, start collecting and executing
2569 ** commands. This will never return.
2572 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2577 ** Save some macros for check_* rulesets.
2584 (void) sm_snprintf(ipbuf, sizeof(ipbuf), "[%.100s]",
2585 anynet_ntoa(&RealHostAddr));
2586 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2587 macid("{client_name}"), ipbuf);
2590 macdefine(&BlankEnvelope.e_macro, A_PERM,
2591 macid("{client_name}"), RealHostName);
2592 macdefine(&BlankEnvelope.e_macro, A_PERM,
2593 macid("{client_ptr}"), RealHostName);
2594 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2595 macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2598 switch (RealHostAddr.sa.sa_family)
2602 (void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2603 RealHostAddr.sin.sin_port);
2605 #endif /* NETINET */
2608 (void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2609 RealHostAddr.sin6.sin6_port);
2611 #endif /* NETINET6 */
2613 (void) sm_snprintf(pbuf, sizeof(pbuf), "0");
2616 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2617 macid("{client_port}"), pbuf);
2619 if (OpMode == MD_DAEMON)
2621 ENVELOPE *saved_env;
2623 /* validate the connection */
2626 CurEnv = &BlankEnvelope;
2627 nullserver = validate_connection(&RealHostAddr,
2628 macvalue(macid("{client_name}"),
2631 if (bitset(EF_DISCARD, BlankEnvelope.e_flags))
2632 MainEnvelope.e_flags |= EF_DISCARD;
2636 else if (p_flags == NULL)
2638 p_flags = (BITMAP256 *) xalloc(sizeof(*p_flags));
2642 if (OpMode == MD_SMTP)
2643 (void) initsrvtls(tls_ok);
2644 #endif /* STARTTLS */
2646 /* turn off profiling */
2648 smtp(nullserver, *p_flags, &MainEnvelope);
2652 /* turn off profiling */
2654 if (OpMode == MD_DAEMON)
2659 sm_rpool_free(MainEnvelope.e_rpool);
2660 clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2661 if (OpMode == MD_VERIFY)
2663 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2664 PostMasterCopy = NULL;
2668 /* interactive -- all errors are global */
2669 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2673 ** Do basic system initialization and set the sender
2676 initsys(&MainEnvelope);
2677 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2678 macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2679 setsender(from, &MainEnvelope, NULL, '\0', false);
2680 if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2681 (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2682 strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2684 auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2685 RealUserName, from, warn_f_flag);
2694 /* set the initial sender for AUTH= to $f@$j */
2695 fv = macvalue('f', &MainEnvelope);
2696 if (fv == NULL || *fv == '\0')
2697 MainEnvelope.e_auth_param = NULL;
2700 if (strchr(fv, '@') == NULL)
2702 i = strlen(fv) + strlen(macvalue('j',
2703 &MainEnvelope)) + 2;
2705 (void) sm_strlcpyn(p, i, 3, fv, "@",
2710 p = sm_strdup_x(fv);
2711 MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2713 sm_free(p); /* XXX */
2716 if (macvalue('s', &MainEnvelope) == NULL)
2717 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2720 if (*av == NULL && !GrabTo)
2722 MainEnvelope.e_to = NULL;
2723 MainEnvelope.e_flags |= EF_GLOBALERRS;
2725 SuperSafe = SAFE_NO;
2726 usrerr("Recipient names must be specified");
2728 /* collect body for UUCP return */
2729 if (OpMode != MD_VERIFY)
2730 collect(InChannel, false, NULL, &MainEnvelope, true);
2731 finis(true, true, EX_USAGE);
2736 ** Scan argv and deliver the message to everyone.
2739 save_val = LogUsrErrs;
2741 sendtoargv(av, &MainEnvelope);
2742 LogUsrErrs = save_val;
2744 /* if we have had errors sofar, arrange a meaningful exit stat */
2745 if (Errors > 0 && ExitStat == EX_OK)
2746 ExitStat = EX_USAGE;
2750 ** If using -t, force not sending to argv recipients, even
2751 ** if they are mentioned in the headers.
2758 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2759 q->q_state = QS_REMOVED;
2761 #endif /* _FFR_FIX_DASHT */
2764 ** Read the input mail.
2767 MainEnvelope.e_to = NULL;
2768 if (OpMode != MD_VERIFY || GrabTo)
2771 unsigned long savedflags;
2774 ** workaround for compiler warning on Irix:
2775 ** do not initialize variable in the definition, but
2777 ** warning(1548): transfer of control bypasses
2778 ** initialization of:
2779 ** variable "savederrors" (declared at line 2570)
2780 ** variable "savedflags" (declared at line 2571)
2784 savederrors = Errors;
2785 savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2786 MainEnvelope.e_flags |= EF_GLOBALERRS;
2787 MainEnvelope.e_flags &= ~EF_FATALERRS;
2790 collect(InChannel, false, NULL, &MainEnvelope, true);
2792 /* header checks failed */
2798 /* Log who the mail would have gone to */
2799 logundelrcpts(&MainEnvelope,
2800 MainEnvelope.e_message,
2804 finis(true, true, ExitStat);
2809 /* bail out if message too large */
2810 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2812 finis(true, true, ExitStat != EX_OK ? ExitStat
2818 /* set message size */
2819 (void) sm_snprintf(buf, sizeof(buf), "%ld",
2820 MainEnvelope.e_msgsize);
2821 macdefine(&MainEnvelope.e_macro, A_TEMP,
2822 macid("{msg_size}"), buf);
2824 Errors = savederrors;
2825 MainEnvelope.e_flags |= savedflags;
2830 sm_dprintf("From person = \"%s\"\n",
2831 MainEnvelope.e_from.q_paddr);
2833 /* Check if quarantining stats should be updated */
2834 if (MainEnvelope.e_quarmsg != NULL)
2835 markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2838 ** Actually send everything.
2839 ** If verifying, just ack.
2844 if (!split_by_recipient(&MainEnvelope) &&
2845 bitset(EF_FATALERRS, MainEnvelope.e_flags))
2849 /* make sure we deliver at least the first envelope */
2850 i = FastSplit > 0 ? 0 : -1;
2851 for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2855 e->e_from.q_state = QS_SENDER;
2858 sm_dprintf("main[%d]: QS_SENDER ", i);
2859 printaddr(sm_debug_file(), &e->e_from, false);
2865 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2866 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2867 #endif /* NAMED_BIND */
2868 next = e->e_sibling;
2869 e->e_sibling = NULL;
2871 /* after FastSplit envelopes: queue up */
2872 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2873 e->e_sibling = next;
2878 ** Don't send return error message if in VERIFY mode.
2881 finis(true, true, ExitStat);
2886 ** STOP_SENDMAIL -- Stop the running program
2901 /* reset uid for process accounting */
2903 (void) setuid(RealUid);
2907 ** FINIS -- Clean up and exit.
2910 ** drop -- whether or not to drop CurEnv envelope
2911 ** cleanup -- call exit() or _exit()?
2912 ** exitstat -- exit status to use for exit() call
2922 finis(drop, cleanup, exitstat)
2925 volatile int exitstat;
2927 char pidpath[MAXPATHLEN];
2930 /* Still want to process new timeouts added below */
2932 (void) sm_releasesignal(SIGALRM);
2936 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2938 CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2939 printenvflags(CurEnv);
2942 printopenfds(false);
2946 ** Clean up. This might raise E:mta.quickabort
2949 /* clean up temp files */
2950 CurEnv->e_to = NULL;
2953 if (CurEnv->e_id != NULL)
2955 dropenvelope(CurEnv, true, false);
2956 sm_rpool_free(CurEnv->e_rpool);
2957 CurEnv->e_rpool = NULL;
2959 /* these may have pointed to the rpool */
2960 CurEnv->e_to = NULL;
2961 CurEnv->e_message = NULL;
2962 CurEnv->e_statmsg = NULL;
2963 CurEnv->e_quarmsg = NULL;
2964 CurEnv->e_bodytype = NULL;
2965 CurEnv->e_id = NULL;
2966 CurEnv->e_envid = NULL;
2967 CurEnv->e_auth_param = NULL;
2970 poststats(StatFile);
2973 /* flush any cached connections */
2974 mci_flush(true, NULL);
2976 /* close maps belonging to this pid */
2980 /* close UserDatabase */
2989 /* clean up extended load average stuff */
2999 sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
3001 if (exitstat == EX_TEMPFAIL ||
3002 CurEnv->e_errormode == EM_BERKNET)
3005 /* XXX clean up queues and related data structures */
3009 cleanup_shm(DaemonPid == pid);
3010 #endif /* SM_CONF_SHM */
3012 /* close locked pid file */
3013 close_sendmail_pid();
3015 if (DaemonPid == pid || PidFilePid == pid)
3017 /* blow away the pid file */
3018 expand(PidFile, pidpath, sizeof(pidpath), CurEnv);
3019 (void) unlink(pidpath);
3022 /* reset uid for process accounting */
3024 sm_mbdb_terminate();
3026 (void) sm_memstat_close();
3027 #endif /* _FFR_MEMSTAT */
3028 (void) setuid(RealUid);
3030 /* dump the heap, if we are checking for memory leaks */
3031 if (sm_debug_active(&SmHeapCheck, 2))
3032 sm_heap_report(smioout,
3033 sm_debug_level(&SmHeapCheck) - 1);
3034 #endif /* SM_HEAP_CHECK */
3035 if (sm_debug_active(&SmXtrapReport, 1))
3036 sm_dprintf("xtrap count = %d\n", SmXtrapCount);
3044 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
3047 ** sig -- incoming signal.
3053 ** longjmps back to test mode loop.
3055 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3056 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3060 /* Type of an exception generated on SIGINT during address test mode. */
3061 static const SM_EXC_TYPE_T EtypeInterrupt =
3075 int save_errno = errno;
3077 FIX_SYSV_SIGNAL(sig, intindebug);
3079 CHECK_CRITICAL(sig);
3081 sm_exc_raisenew_x(&EtypeInterrupt);
3083 return SIGFUNC_RETURN;
3086 ** SIGTERM -- SIGTERM handler for the daemon
3089 ** sig -- signal number.
3095 ** Sets ShutdownRequest which will hopefully trigger
3096 ** the daemon to exit.
3098 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3099 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3108 int save_errno = errno;
3110 FIX_SYSV_SIGNAL(sig, sigterm);
3111 ShutdownRequest = "signal";
3113 return SIGFUNC_RETURN;
3116 ** SIGHUP -- handle a SIGHUP signal
3119 ** sig -- incoming signal.
3125 ** Sets RestartRequest which should cause the daemon
3128 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3129 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3138 int save_errno = errno;
3140 FIX_SYSV_SIGNAL(sig, sighup);
3141 RestartRequest = "signal";
3143 return SIGFUNC_RETURN;
3146 ** SIGPIPE -- signal handler for SIGPIPE
3149 ** sig -- incoming signal.
3155 ** Sets StopRequest which should cause the mailq/hoststatus
3158 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3159 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3168 int save_errno = errno;
3170 FIX_SYSV_SIGNAL(sig, sigpipe);
3173 return SIGFUNC_RETURN;
3176 ** INTSIG -- clean up on interrupt
3178 ** This just arranges to exit. It pessimizes in that it
3179 ** may resend a message.
3188 ** Unlocks the current job.
3190 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3191 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3194 ** XXX: More work is needed for this signal handler.
3203 int save_errno = errno;
3205 FIX_SYSV_SIGNAL(sig, intsig);
3207 CHECK_CRITICAL(sig);
3208 sm_allsignals(true);
3210 if (sig != 0 && LogLevel > 79)
3211 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3214 /* Clean-up on aborted stdin message submission */
3215 if (CurEnv->e_id != NULL &&
3216 (OpMode == MD_SMTP ||
3217 OpMode == MD_DELIVER ||
3218 OpMode == MD_ARPAFTP))
3220 register ADDRESS *q;
3222 /* don't return an error indication */
3223 CurEnv->e_to = NULL;
3224 CurEnv->e_flags &= ~EF_FATALERRS;
3225 CurEnv->e_flags |= EF_CLRQUEUE;
3228 ** Spin through the addresses and
3229 ** mark them dead to prevent bounces
3232 for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
3233 q->q_state = QS_DONTSEND;
3237 else if (OpMode != MD_TEST)
3239 unlockqueue(CurEnv);
3242 finis(drop, false, EX_OK);
3246 ** DISCONNECT -- remove our connection with any foreground process
3249 ** droplev -- how "deeply" we should drop the line.
3250 ** 0 -- ignore signals, mail back errors, make sure
3251 ** output goes to stdout.
3252 ** 1 -- also, make stdout go to /dev/null.
3253 ** 2 -- also, disconnect from controlling terminal
3254 ** (only for daemon mode).
3255 ** e -- the current envelope.
3261 ** Trys to insure that we are immune to vagaries of
3262 ** the controlling tty.
3266 disconnect(droplev, e)
3268 register ENVELOPE *e;
3273 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3274 sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3275 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3278 sm_dprintf("don't\n");
3282 sm_syslog(LOG_DEBUG, e->e_id,
3283 "disconnect level %d",
3286 /* be sure we don't get nasty signals */
3287 (void) sm_signal(SIGINT, SIG_IGN);
3288 (void) sm_signal(SIGQUIT, SIG_IGN);
3290 /* we can't communicate with our caller, so.... */
3292 CurEnv->e_errormode = EM_MAIL;
3294 DisConnected = true;
3296 /* all input from /dev/null */
3297 if (InChannel != smioin)
3299 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3302 if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3303 SM_IO_RDONLY, NULL, smioin) == NULL)
3304 sm_syslog(LOG_ERR, e->e_id,
3305 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3306 SM_PATH_DEVNULL, sm_errstring(errno));
3309 ** output to the transcript
3310 ** We also compare the fd numbers here since OutChannel
3311 ** might be a layer on top of smioout due to encryption
3315 if (OutChannel != smioout &&
3316 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3317 sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3319 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3320 OutChannel = smioout;
3324 ** Has smioout been closed? Reopen it.
3325 ** This shouldn't happen anymore, the code is here
3326 ** just as a reminder.
3329 if (smioout->sm_magic == NULL &&
3330 sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3331 SM_IO_WRONLY, NULL, smioout) == NULL)
3332 sm_syslog(LOG_ERR, e->e_id,
3333 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3334 SM_PATH_DEVNULL, sm_errstring(errno));
3339 fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3342 sm_syslog(LOG_ERR, e->e_id,
3343 "disconnect: open(\"%s\") failed: %s",
3344 SM_PATH_DEVNULL, sm_errstring(errno));
3346 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3349 (void) dup2(fd, STDOUT_FILENO);
3350 (void) dup2(fd, STDERR_FILENO);
3355 /* drop our controlling TTY completely if possible */
3363 checkfd012("disconnect");
3367 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3380 while ((ap = *++argv) != NULL)
3382 /* Return if "--" or not an option of any form. */
3383 if (ap[0] != '-' || ap[1] == '-')
3386 /* Don't allow users to use "-Q." or "-Q ." */
3387 if ((ap[1] == 'Q' && ap[2] == '.') ||
3388 (ap[1] == 'Q' && argv[1] != NULL &&
3389 argv[1][0] == '.' && argv[1][1] == '\0'))
3391 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3392 "Can not use -Q.\n");
3396 /* skip over options that do have a value */
3397 op = strchr(OPTIONS, ap[1]);
3398 if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3400 #if defined(sony_news)
3401 ap[1] != 'E' && ap[1] != 'J' &&
3402 #endif /* defined(sony_news) */
3403 argv[1] != NULL && argv[1][0] != '-')
3409 /* If -C doesn't have an argument, use sendmail.cf. */
3410 #define __DEFPATH "sendmail.cf"
3411 if (ap[1] == 'C' && ap[2] == '\0')
3413 *argv = xalloc(sizeof(__DEFPATH) + 2);
3414 (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3418 /* If -q doesn't have an argument, run it once. */
3419 if (ap[1] == 'q' && ap[2] == '\0')
3422 /* If -Q doesn't have an argument, disable quarantining */
3423 if (ap[1] == 'Q' && ap[2] == '\0')
3426 /* if -d doesn't have an argument, use 0-99.1 */
3427 if (ap[1] == 'd' && ap[2] == '\0')
3430 #if defined(sony_news)
3431 /* if -E doesn't have an argument, use -EC */
3432 if (ap[1] == 'E' && ap[2] == '\0')
3435 /* if -J doesn't have an argument, use -JJ */
3436 if (ap[1] == 'J' && ap[2] == '\0')
3438 #endif /* defined(sony_news) */
3442 ** AUTH_WARNING -- specify authorization warning
3445 ** e -- the current envelope.
3446 ** msg -- the text of the message.
3447 ** args -- arguments to the message.
3455 auth_warning(register ENVELOPE *e, const char *msg, ...)
3456 #else /* __STDC__ */
3457 auth_warning(e, msg, va_alist)
3458 register ENVELOPE *e;
3461 #endif /* __STDC__ */
3466 if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3469 static char hostbuf[48];
3471 if (hostbuf[0] == '\0')
3475 hp = myhostname(hostbuf, sizeof(hostbuf));
3482 #endif /* NETINET6 */
3485 (void) sm_strlcpyn(buf, sizeof(buf), 2, hostbuf, ": ");
3486 p = &buf[strlen(buf)];
3487 SM_VA_START(ap, msg);
3488 (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3490 addheader("X-Authentication-Warning", buf, 0, e, true);
3492 sm_syslog(LOG_INFO, e->e_id,
3493 "Authentication-Warning: %.400s",
3498 ** GETEXTENV -- get from external environment
3501 ** envar -- the name of the variable to retrieve
3504 ** The value, if any.
3515 for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3517 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3518 return &(*envp)[l + 1];
3523 ** SM_SETUSERENV -- set an environment variable in the propagated environment
3526 ** envar -- the name of the environment variable.
3527 ** value -- the value to which it should be set. If
3528 ** null, this is extracted from the incoming
3529 ** environment. If that is not set, the call
3530 ** to sm_setuserenv is ignored.
3537 sm_setuserenv(envar, value)
3542 char **evp = UserEnviron;
3547 value = getextenv(envar);
3552 /* XXX enforce reasonable size? */
3553 i = strlen(envar) + 1;
3554 l = strlen(value) + i + 1;
3555 p = (char *) xalloc(l);
3556 (void) sm_strlcpyn(p, l, 3, envar, "=", value);
3558 while (*evp != NULL && strncmp(*evp, p, i) != 0)
3564 else if (evp < &UserEnviron[MAXUSERENVIRON])
3570 /* make sure it is in our environment as well */
3572 syserr("sm_setuserenv: putenv(%s) failed", p);
3575 ** DUMPSTATE -- dump state
3584 register char *j = macvalue('j', CurEnv);
3586 extern int NextMacroId;
3588 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3589 "--- dumping state on %s: $j = %s ---",
3591 j == NULL ? "<NULL>" : j);
3594 if (!wordinclass(j, 'w'))
3595 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3596 "*** $j not in $=w ***");
3598 sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3599 sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3600 NextMacroId, MAXMACROID);
3601 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3603 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3604 mci_dump_all(smioout, true);
3605 rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3609 register char **pvp;
3610 char *pv[MAXATOM + 1];
3613 status = REWRITE(pv, rs, CurEnv);
3614 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3615 "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3617 for (pvp = pv; *pvp != NULL; pvp++)
3618 sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3620 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3625 ** SIGUSR1 -- Signal a request to dump state.
3628 ** sig -- calling signal.
3633 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3634 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3637 ** XXX: More work is needed for this signal handler.
3645 int save_errno = errno;
3647 FIX_SYSV_SIGNAL(sig, sigusr1);
3649 CHECK_CRITICAL(sig);
3650 dumpstate("user signal");
3653 # endif /* SM_HEAP_CHECK */
3655 return SIGFUNC_RETURN;
3657 #endif /* SIGUSR1 */
3660 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3663 ** to_real_uid -- if set, drop to the real uid instead
3664 ** of the RunAsUser.
3667 ** EX_OSERR if the setuid failed.
3672 drop_privileges(to_real_uid)
3676 GIDSET_T emptygidset[1];
3679 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",
3681 (int) RealUid, (int) RealGid,
3682 (int) getuid(), (int) getgid(),
3683 (int) geteuid(), (int) getegid(),
3684 (int) RunAsUid, (int) RunAsGid);
3688 RunAsUserName = RealUserName;
3694 /* make sure no one can grab open descriptors for secret files */
3696 sm_mbdb_terminate();
3698 /* reset group permissions; these can be set later */
3699 emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3702 ** Notice: on some OS (Linux...) the setgroups() call causes
3703 ** a logfile entry if sendmail is not run by root.
3704 ** However, it is unclear (no POSIX standard) whether
3705 ** setgroups() can only succeed if executed by root.
3706 ** So for now we keep it as it is; if you want to change it, use
3707 ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3710 if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3712 syserr("drop_privileges: setgroups(1, %d) failed",
3713 (int) emptygidset[0]);
3717 /* reset primary group id */
3721 ** Drop gid to real gid.
3722 ** On some OS we must reset the effective[/real[/saved]] gid,
3723 ** and then use setgid() to finally drop all group privileges.
3724 ** Later on we check whether we can get back the
3729 if (setegid(RunAsGid) < 0)
3731 syserr("drop_privileges: setegid(%d) failed",
3735 #else /* HASSETEGID */
3737 if (setregid(RunAsGid, RunAsGid) < 0)
3739 syserr("drop_privileges: setregid(%d, %d) failed",
3740 (int) RunAsGid, (int) RunAsGid);
3743 # else /* HASSETREGID */
3745 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3747 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3748 (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3751 # endif /* HASSETRESGID */
3752 # endif /* HASSETREGID */
3753 #endif /* HASSETEGID */
3755 if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3757 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3759 syserr("drop_privileges: setgid(%d) failed",
3764 if (rval == EX_OK && getegid() != RunAsGid)
3766 syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3767 (int) getegid(), (int) RunAsGid);
3772 /* fiddle with uid */
3773 if (to_real_uid || RunAsUid != 0)
3778 ** Try to setuid(RunAsUid).
3779 ** euid must be RunAsUid,
3780 ** ruid must be RunAsUid unless (e|r)uid wasn't 0
3781 ** and we didn't have to drop privileges to the real uid.
3784 if (setuid(RunAsUid) < 0 ||
3785 geteuid() != RunAsUid ||
3786 (getuid() != RunAsUid &&
3787 (to_real_uid || geteuid() == 0 || getuid() == 0)))
3791 ** if ruid != RunAsUid, euid == RunAsUid, then
3792 ** try resetting just the real uid, then using
3793 ** setuid() to drop the saved-uid as well.
3796 if (geteuid() == RunAsUid)
3798 if (setreuid(RunAsUid, -1) < 0)
3800 syserr("drop_privileges: setreuid(%d, -1) failed",
3804 if (setuid(RunAsUid) < 0)
3806 syserr("drop_privileges: second setuid(%d) attempt failed",
3812 #endif /* HASSETREUID */
3814 syserr("drop_privileges: setuid(%d) failed",
3820 if (RunAsUid != 0 && setuid(0) == 0)
3823 ** Believe it or not, the Linux capability model
3824 ** allows a non-root process to override setuid()
3825 ** on a process running as root and prevent that
3826 ** process from dropping privileges.
3829 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3832 else if (RunAsUid != euid && setuid(euid) == 0)
3835 ** Some operating systems will keep the saved-uid
3836 ** if a non-root effective-uid calls setuid(real-uid)
3837 ** making it possible to set it back again later.
3840 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3845 if ((to_real_uid || RunAsGid != 0) &&
3846 rval == EX_OK && RunAsGid != EffGid &&
3847 getuid() != 0 && geteuid() != 0)
3850 if (setgid(EffGid) == 0)
3852 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3860 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3861 (int) geteuid(), (int) getuid(),
3862 (int) getegid(), (int) getgid());
3863 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3864 (int) RunAsUid, (int) RunAsGid);
3866 sm_dprintf("drop_privileges: rval = %d\n", rval);
3871 ** FILL_FD -- make sure a file descriptor has been properly allocated
3873 ** Used to make sure that stdin/out/err are allocated on startup
3876 ** fd -- the file descriptor to be filled.
3877 ** where -- a string used for logging. If NULL, this is
3878 ** being called on startup, and logging should
3885 ** possibly changes MissingFds
3896 if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3900 syserr("fill_fd: %s: fd %d not open", where, fd);
3902 MissingFds |= 1 << fd;
3903 i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3906 syserr("!fill_fd: %s: cannot open %s",
3907 where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3916 ** SM_PRINTOPTIONS -- print options
3919 ** options -- array of options.
3926 sm_printoptions(options)
3936 if (ll + strlen(*av) > 63)
3945 sm_dprintf("%s", *av);
3946 ll += strlen(*av++) + 1;
3952 ** TO8BIT -- convert \octal sequences in a test mode input line
3955 ** str -- the input line.
3961 ** replaces \0octal in str with octal value.
3964 static bool to8bit __P((char *));
3979 while ((c = (*str++ & 0377)) != '\0')
3985 (nxtc = (*str & 0377)) == '0')
3988 while ((nxtc = (*str & 0377)) != '\0' &&
3989 isascii(nxtc) && isdigit(nxtc))
4006 q = quote_internal_chars(in, in, &len);
4008 sm_strlcpy(in, q, len);
4014 ** TESTMODELINE -- process a test mode input line
4017 ** line -- the input line.
4018 ** e -- the current environment.
4021 ** .X process X as a configuration line
4022 ** =X dump a configuration item (such as mailers)
4023 ** $X dump a macro or class
4024 ** /X try an activity
4025 ** X normal process through rule set X
4029 testmodeline(line, e)
4035 auto char *delimptr;
4044 static int tryflags = RF_COPYNONE;
4045 char exbuf[MAXLINE];
4047 extern unsigned char TokTypeNoC[];
4050 /* skip leading spaces */
4051 while (*line == ' ')
4066 case '.': /* config-style settings */
4070 mid = macid_parse(&line[2], &delimptr);
4074 lbp = translate_dollars(delimptr, lbuf, &lbs);
4075 macdefine(&e->e_macro, A_TEMP, mid, lbp);
4081 if (line[2] == '\0') /* not to call syserr() */
4084 mid = macid_parse(&line[2], &delimptr);
4088 lbp = translate_dollars(delimptr, lbuf, &lbs);
4089 expand(lbp, exbuf, sizeof(exbuf), e);
4098 while (*p != '\0' && isascii(*p) && isspace(*p))
4101 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4112 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4113 "Usage: .[DC]macro value(s)\n");
4117 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4118 "Unknown \".\" command %s\n", line);
4123 case '=': /* config-style settings */
4126 case 'S': /* dump rule set */
4127 rs = strtorwset(&line[2], NULL, ST_FIND);
4130 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4131 "Undefined ruleset %s\n", &line[2]);
4134 rw = RewriteRules[rs];
4139 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4144 xputs(smioout, *s++);
4145 (void) sm_io_putc(smioout,
4146 SM_TIME_DEFAULT, ' ');
4148 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4150 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4155 xputs(smioout, *s++);
4156 (void) sm_io_putc(smioout,
4157 SM_TIME_DEFAULT, ' ');
4159 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4161 } while ((rw = rw->r_next) != NULL);
4165 for (i = 0; i < MAXMAILERS; i++)
4167 if (Mailer[i] != NULL)
4168 printmailer(smioout, Mailer[i]);
4173 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4174 "Usage: =Sruleset or =M\n");
4178 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4179 "Unknown \"=\" command %s\n", line);
4184 case '-': /* set command-line-like opts */
4192 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4193 "Usage: -d{debug arguments}\n");
4197 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4198 "Unknown \"-\" command %s\n", line);
4206 mid = macid(&line[2]);
4208 stabapply(dump_class, mid);
4211 mid = macid(&line[1]);
4214 p = macvalue(mid, e);
4216 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4221 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4226 case '/': /* miscellaneous commands */
4227 p = &line[strlen(line)];
4228 while (--p >= line && isascii(*p) && isspace(*p))
4230 p = strpbrk(line, " \t");
4233 while (isascii(*p) && isspace(*p))
4238 if (line[1] == '\0')
4240 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4241 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4244 if (sm_strcasecmp(&line[1], "quit") == 0)
4246 CurEnv->e_id = NULL;
4247 finis(true, true, ExitStat);
4250 if (sm_strcasecmp(&line[1], "mx") == 0)
4253 /* look up MX records */
4256 char *mxhosts[MAXMXHOSTS + 1];
4260 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4261 "Usage: /mx address\n");
4264 nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4266 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4267 "getmxrr(%s) returns %d value(s):\n",
4269 for (i = 0; i < nmx; i++)
4270 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4271 "\t%s\n", mxhosts[i]);
4272 #else /* NAMED_BIND */
4273 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4274 "No MX code compiled in\n");
4275 #endif /* NAMED_BIND */
4277 else if (sm_strcasecmp(&line[1], "canon") == 0)
4279 char host[MAXHOSTNAMELEN];
4283 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4284 "Usage: /canon address\n");
4287 else if (sm_strlcpy(host, p, sizeof(host)) >= sizeof(host))
4289 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4293 (void) getcanonname(host, sizeof(host), !HasWildcardMX,
4295 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4296 "getcanonname(%s) returns %s\n",
4299 else if (sm_strcasecmp(&line[1], "map") == 0)
4301 auto int rcode = EX_OK;
4306 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4307 "Usage: /map mapname key\n");
4310 for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q)); q++)
4314 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4315 "No key specified\n");
4319 map = stab(p, ST_MAP, ST_FIND);
4322 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4323 "Map named \"%s\" not found\n", p);
4326 if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4327 !openmap(&(map->s_map)))
4329 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4330 "Map named \"%s\" not open\n", p);
4333 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4334 "map_lookup: %s (%s) ", p, q);
4337 p = (*map->s_map.map_class->map_lookup)
4338 (&map->s_map, q, av, &rcode);
4340 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4344 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4345 "returns %s (%d)\n", p,
4348 else if (sm_strcasecmp(&line[1], "try") == 0)
4352 auto int rcode = EX_OK;
4354 q = strpbrk(p, " \t");
4357 while (isascii(*q) && isspace(*q))
4360 if (q == NULL || *q == '\0')
4362 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4363 "Usage: /try mailer address\n");
4366 st = stab(p, ST_MAILER, ST_FIND);
4369 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4370 "Unknown mailer %s\n", p);
4374 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4375 "Trying %s %s address %s for mailer %s\n",
4376 bitset(RF_HEADERADDR, tryflags) ? "header"
4378 bitset(RF_SENDERADDR, tryflags) ? "sender"
4379 : "recipient", q, p);
4380 p = remotename(q, m, tryflags, &rcode, CurEnv);
4381 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4382 "Rcode = %d, addr = %s\n",
4383 rcode, p == NULL ? "<NULL>" : p);
4386 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4390 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4391 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4394 for (; *p != '\0'; p++)
4400 tryflags |= RF_HEADERADDR;
4405 tryflags &= ~RF_HEADERADDR;
4410 tryflags |= RF_SENDERADDR;
4415 tryflags &= ~RF_SENDERADDR;
4419 exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4421 exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4423 macdefine(&e->e_macro, A_TEMP,
4424 macid("{addr_type}"), exbuf);
4426 else if (sm_strcasecmp(&line[1], "parse") == 0)
4430 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4431 "Usage: /parse address\n");
4434 q = crackaddr(p, e);
4435 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4436 "Cracked address = ");
4438 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4439 "\nParsing %s %s address\n",
4440 bitset(RF_HEADERADDR, tryflags) ?
4441 "header" : "envelope",
4442 bitset(RF_SENDERADDR, tryflags) ?
4443 "sender" : "recipient");
4444 if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4446 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4448 else if (a.q_host != NULL && a.q_host[0] != '\0')
4449 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4450 "mailer %s, host %s, user %s\n",
4455 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4456 "mailer %s, user %s\n",
4461 else if (sm_strcasecmp(&line[1], "header") == 0)
4465 ul = chompheader(p, CHHDR_CHECK|CHHDR_USER, NULL, e);
4466 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4471 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4472 "Unknown \"/\" command %s\n",
4475 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4479 for (p = line; isascii(*p) && isspace(*p); p++)
4482 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4486 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4492 eightbit = to8bit(p + 1);
4493 if (invalidaddr(p + 1, NULL, true))
4497 register char **pvp;
4498 char pvpbuf[PSBUFSIZE];
4500 pvp = prescan(++p, ',', pvpbuf, sizeof(pvpbuf), &delimptr,
4501 ConfigLevel >= 9 ? TokTypeNoC : ExtTokenTab, false);
4509 rs = strtorwset(p, NULL, ST_FIND);
4512 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4513 "Undefined ruleset %s\n",
4517 status = REWRITE(pvp, rs, e);
4518 if (status != EX_OK)
4519 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4520 "== Ruleset %s (%d) status %d\n",
4524 cataddr(pvp, NULL, exbuf, sizeof(exbuf), '\0',
4526 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4530 while (*p != '\0' && *p++ != ',')
4533 } while (*(p = delimptr) != '\0');
4534 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4542 if (s->s_symtype != ST_CLASS)
4544 if (bitnset(bitidx(id), s->s_class))
4545 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4550 ** An exception type used to create QuickAbort exceptions.
4551 ** This is my first cut at converting QuickAbort from longjmp to exceptions.
4552 ** These exceptions have a single integer argument, which is the argument
4553 ** to longjmp in the original code (either 1 or 2). I don't know the
4554 ** significance of 1 vs 2: the calls to setjmp don't care.
4557 const SM_EXC_TYPE_T EtypeQuickAbort =