2 * Copyright (c) 1998-2006, 2008, 2009 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.971 2009/12/18 17:08:01 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 && OpMode != MD_CHECKCONFIG && \
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
;
406 #endif /* _FFR_CHECKCONFIG */
410 #if _FFR_LOCAL_DAEMON
415 #endif /* _FFR_LOCAL_DAEMON */
418 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
419 "Frozen configurations unsupported\n");
423 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
424 "Invalid operation mode %c\n",
434 syserr("-D file must be before -d");
438 dp
= drop_privileges(true);
440 smdebug
= sm_io_open(SmFtStdio
, SM_TIME_DEFAULT
,
441 optarg
, SM_IO_APPEND
, NULL
);
444 syserr("cannot open %s", optarg
);
445 ExitStat
= EX_CANTCREAT
;
448 sm_debug_setfile(smdebug
);
454 (void) sm_io_setvbuf(sm_debug_file(), SM_TIME_DEFAULT
,
455 (char *) NULL
, SM_IO_NBF
,
459 case 'G': /* relay (gateway) submission */
460 SubmitMode
= SUBMIT_MTA
;
466 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
467 "option requires an argument -- '%c'",
471 j
= SM_MIN(strlen(optarg
), 32) + 1;
472 sysloglabel
= xalloc(j
);
473 (void) sm_strlcpy(sysloglabel
, optarg
, j
);
474 SyslogPrefixLen
= PIDLEN
+ (MAXQFNAME
- 3) +
480 /* just check if it is there */
487 /* Don't leak queue information via debug flags */
488 if (extraprivs
&& queuerun
&& debug
)
490 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
491 "WARNING: Can not use -d with -q. Disabling debugging.\n");
493 sm_debug_setfile(NULL
);
494 (void) memset(tTdvect
, '\0', sizeof(tTdvect
));
498 if (sysloglabel
!= NULL
)
500 /* Sanitize the string */
501 for (p
= sysloglabel
; *p
!= '\0'; p
++)
503 if (!isascii(*p
) || !isprint(*p
) || *p
== '%')
508 openlog(sysloglabel
, LOG_PID
, LOG_MAIL
);
509 # else /* LOG_MAIL */
510 openlog(sysloglabel
, LOG_PID
);
511 # endif /* LOG_MAIL */
515 /* set up the blank envelope */
516 BlankEnvelope
.e_puthdr
= putheader
;
517 BlankEnvelope
.e_putbody
= putbody
;
518 BlankEnvelope
.e_xfp
= NULL
;
519 STRUCTCOPY(NullAddress
, BlankEnvelope
.e_from
);
520 CurEnv
= &BlankEnvelope
;
521 STRUCTCOPY(NullAddress
, MainEnvelope
.e_from
);
524 ** Set default values for variables.
525 ** These cannot be in initialized data space.
528 setdefaults(&BlankEnvelope
);
529 initmacros(&BlankEnvelope
);
533 if (OpMode
== MD_DAEMON
)
534 DaemonPid
= CurrentPid
; /* needed for finis() to work */
536 pw
= sm_getpwuid(RealUid
);
538 (void) sm_strlcpy(rnamebuf
, pw
->pw_name
, sizeof(rnamebuf
));
540 (void) sm_snprintf(rnamebuf
, sizeof(rnamebuf
), "Unknown UID %d",
543 RealUserName
= rnamebuf
;
547 sm_dprintf("Version %s\n", Version
);
548 finis(false, true, EX_OK
);
553 ** if running non-set-user-ID binary as non-root, pretend
554 ** we are the RunAsUid
557 if (RealUid
!= 0 && geteuid() == RealUid
)
560 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
564 else if (geteuid() != 0)
565 RunAsUid
= geteuid();
568 if (RealUid
!= 0 && EffGid
== RealGid
)
573 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
574 (int) geteuid(), (int) getuid(),
575 (int) getegid(), (int) getgid());
576 sm_dprintf("main: RunAsUser = %d:%d\n",
577 (int) RunAsUid
, (int) RunAsGid
);
580 /* save command line arguments */
582 for (av
= argv
; *av
!= NULL
; )
583 j
+= strlen(*av
++) + 1;
584 SaveArgv
= (char **) xalloc(sizeof(char *) * (argc
+ 1));
585 CommandLineArgs
= xalloc(j
);
587 for (av
= argv
, i
= 0; *av
!= NULL
; )
591 SaveArgv
[i
++] = newstr(*av
);
594 (void) sm_strlcpy(p
, *av
++, j
);
603 extern char *CompileOptions
[];
605 sm_dprintf("Version %s\n Compiled with:", Version
);
606 sm_printoptions(CompileOptions
);
610 extern char *OsCompileOptions
[];
612 sm_dprintf(" OS Defines:");
613 sm_printoptions(OsCompileOptions
);
615 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX
);
616 #endif /* _PATH_UNIX */
618 sm_dprintf(" Conf file:\t%s (default for MSP)\n",
619 getcfname(OpMode
, SubmitMode
, SM_GET_SUBMIT_CF
,
621 sm_dprintf(" Conf file:\t%s (default for MTA)\n",
622 getcfname(OpMode
, SubmitMode
, SM_GET_SENDMAIL_CF
,
624 sm_dprintf(" Pid file:\t%s (default)\n", PidFile
);
629 extern char *SmCompileOptions
[];
631 sm_dprintf(" libsm Defines:");
632 sm_printoptions(SmCompileOptions
);
637 extern char *FFRCompileOptions
[];
639 sm_dprintf(" FFR Defines:");
640 sm_printoptions(FFRCompileOptions
);
643 /* clear sendmail's environment */
644 ExternalEnviron
= environ
;
645 emptyenviron
[0] = NULL
;
646 environ
= emptyenviron
;
649 ** restore any original TZ setting until TimeZoneSpec has been
650 ** determined - or early log messages may get bogus time stamps
653 if ((p
= getextenv("TZ")) != NULL
)
658 /* XXX check for reasonable length? */
659 tzlen
= strlen(p
) + 4;
661 (void) sm_strlcpyn(tz
, tzlen
, 2, "TZ=", p
);
663 /* XXX check return code? */
667 /* prime the child environment */
668 sm_setuserenv("AGENT", "sendmail");
670 (void) sm_signal(SIGPIPE
, SIG_IGN
);
671 OldUmask
= umask(022);
672 FullName
= getextenv("NAME");
673 if (FullName
!= NULL
)
674 FullName
= newstr(FullName
);
677 ** Initialize name server if it is going to be used.
681 if (!bitset(RES_INIT
, _res
.options
))
684 _res
.options
|= RES_DEBUG
;
686 _res
.options
&= ~RES_DEBUG
;
687 # ifdef RES_NOALIASES
688 _res
.options
|= RES_NOALIASES
;
689 # endif /* RES_NOALIASES */
690 TimeOuts
.res_retry
[RES_TO_DEFAULT
] = _res
.retry
;
691 TimeOuts
.res_retry
[RES_TO_FIRST
] = _res
.retry
;
692 TimeOuts
.res_retry
[RES_TO_NORMAL
] = _res
.retry
;
693 TimeOuts
.res_retrans
[RES_TO_DEFAULT
] = _res
.retrans
;
694 TimeOuts
.res_retrans
[RES_TO_FIRST
] = _res
.retrans
;
695 TimeOuts
.res_retrans
[RES_TO_NORMAL
] = _res
.retrans
;
696 #endif /* NAMED_BIND */
701 /* initialize some macros, etc. */
702 init_vendor_macros(&BlankEnvelope
);
705 macdefine(&BlankEnvelope
.e_macro
, A_PERM
, 'v', Version
);
708 hp
= myhostname(jbuf
, sizeof(jbuf
));
711 struct utsname utsname
;
714 sm_dprintf("Canonical name: %s\n", jbuf
);
715 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
, 'w', jbuf
);
716 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
, 'j', jbuf
);
719 p
= strchr(jbuf
, '.');
720 if (p
!= NULL
&& p
[1] != '\0')
721 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
, 'm', &p
[1]);
723 if (uname(&utsname
) >= 0)
724 p
= utsname
.nodename
;
728 sm_dprintf("uname failed (%s)\n",
729 sm_errstring(errno
));
734 sm_dprintf(" UUCP nodename: %s\n", p
);
735 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
, 'k', p
);
741 for (av
= hp
->h_aliases
; av
!= NULL
&& *av
!= NULL
; av
++)
744 sm_dprintf("\ta.k.a.: %s\n", *av
);
747 #if NETINET || NETINET6
748 for (i
= 0; i
>= 0 && hp
->h_addr_list
[i
] != NULL
; i
++)
752 char buf6
[INET6_ADDRSTRLEN
];
754 # endif /* NETINET6 */
757 # endif /* NETINET */
761 switch (hp
->h_addrtype
)
765 if (hp
->h_length
!= INADDRSZ
)
768 memmove(&ia
, hp
->h_addr_list
[i
], INADDRSZ
);
769 (void) sm_snprintf(ipbuf
, sizeof(ipbuf
),
770 "[%.100s]", inet_ntoa(ia
));
772 # endif /* NETINET */
776 if (hp
->h_length
!= IN6ADDRSZ
)
779 memmove(&ia6
, hp
->h_addr_list
[i
], IN6ADDRSZ
);
780 addr
= anynet_ntop(&ia6
, buf6
, sizeof(buf6
));
782 (void) sm_snprintf(ipbuf
, sizeof(ipbuf
),
785 # endif /* NETINET6 */
787 if (ipbuf
[0] == '\0')
791 sm_dprintf("\ta.k.a.: %s\n", ipbuf
);
792 setclass('w', ipbuf
);
794 #endif /* NETINET || NETINET6 */
798 #endif /* NETINET6 */
802 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
, 'b', arpadate((char *) NULL
));
804 /* current load average */
807 QueueLimitRecipient
= (QUEUE_CHAR
*) NULL
;
808 QueueLimitSender
= (QUEUE_CHAR
*) NULL
;
809 QueueLimitId
= (QUEUE_CHAR
*) NULL
;
810 QueueLimitQuarantine
= (QUEUE_CHAR
*) NULL
;
817 while ((j
= getopt(argc
, argv
, OPTIONS
)) != -1)
821 case 'b': /* operations mode */
825 case 'A': /* use Alternate sendmail/submit.cf */
826 cftype
= optarg
[0] == 'c' ? SM_GET_SUBMIT_CF
827 : SM_GET_SENDMAIL_CF
;
830 case 'B': /* body type */
831 CHECK_AGAINST_OPMODE(j
);
832 BlankEnvelope
.e_bodytype
= newstr(optarg
);
835 case 'C': /* select configuration file (already done) */
838 conffile
= newstr(optarg
);
839 dp
= drop_privileges(true);
845 case 'd': /* debugging */
849 case 'f': /* from address */
850 case 'r': /* obsolete -f flag */
851 CHECK_AGAINST_OPMODE(j
);
854 usrerr("More than one \"from\" person");
858 if (optarg
[0] == '\0')
861 from
= newstr(denlstring(optarg
, true, true));
862 if (strcmp(RealUserName
, from
) != 0)
866 case 'F': /* set full name */
867 CHECK_AGAINST_OPMODE(j
);
868 FullName
= newstr(optarg
);
871 case 'G': /* relay (gateway) submission */
873 CHECK_AGAINST_OPMODE(j
);
876 case 'h': /* hop count */
877 CHECK_AGAINST_OPMODE(j
);
878 BlankEnvelope
.e_hopcount
= (short) strtol(optarg
, &ep
,
880 (void) sm_snprintf(buf
, sizeof(buf
), "%d",
881 BlankEnvelope
.e_hopcount
);
882 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
, 'c', buf
);
886 usrerr("Bad hop count (%s)", optarg
);
891 case 'L': /* program label */
895 case 'n': /* don't alias */
896 CHECK_AGAINST_OPMODE(j
);
900 case 'N': /* delivery status notifications */
901 CHECK_AGAINST_OPMODE(j
);
902 DefaultNotify
|= QHASNOTIFY
;
903 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
,
904 macid("{dsn_notify}"), optarg
);
905 if (sm_strcasecmp(optarg
, "never") == 0)
907 for (p
= optarg
; p
!= NULL
; optarg
= p
)
912 if (sm_strcasecmp(optarg
, "success") == 0)
913 DefaultNotify
|= QPINGONSUCCESS
;
914 else if (sm_strcasecmp(optarg
, "failure") == 0)
915 DefaultNotify
|= QPINGONFAILURE
;
916 else if (sm_strcasecmp(optarg
, "delay") == 0)
917 DefaultNotify
|= QPINGONDELAY
;
920 usrerr("Invalid -N argument");
926 case 'o': /* set option */
927 setoption(*optarg
, optarg
+ 1, false, true,
931 case 'O': /* set option (long form) */
932 setoption(' ', optarg
, false, true, &BlankEnvelope
);
935 case 'p': /* set protocol */
936 CHECK_AGAINST_OPMODE(j
);
937 p
= strchr(optarg
, ':');
945 cleanstrcpy(ep
, p
, i
);
946 macdefine(&BlankEnvelope
.e_macro
,
952 i
= strlen(optarg
) + 1;
954 cleanstrcpy(ep
, optarg
, i
);
955 macdefine(&BlankEnvelope
.e_macro
, A_HEAP
,
960 case 'Q': /* change quarantining on queued items */
962 if (OpMode
!= MD_DELIVER
&&
963 OpMode
!= MD_QUEUERUN
)
965 usrerr("Can not use -Q with -b%c", OpMode
);
970 if (OpMode
== MD_DELIVER
)
971 set_op_mode(MD_QUEUERUN
);
975 quarantining
= newstr(optarg
);
978 case 'q': /* run queue files at intervals */
980 if (OpMode
!= MD_DELIVER
&&
981 OpMode
!= MD_DAEMON
&&
982 OpMode
!= MD_FGDAEMON
&&
983 OpMode
!= MD_PRINT
&&
984 OpMode
!= MD_PRINTNQE
&&
985 OpMode
!= MD_QUEUERUN
)
987 usrerr("Can not use -q with -b%c", OpMode
);
992 /* don't override -bd, -bD or -bp */
993 if (OpMode
== MD_DELIVER
)
994 set_op_mode(MD_QUEUERUN
);
997 negate
= optarg
[0] == '!';
1000 /* negate meaning of pattern match */
1001 optarg
++; /* skip '!' for next switch */
1006 case 'G': /* Limit by queue group name */
1009 usrerr("Can not use -q!G");
1010 ExitStat
= EX_USAGE
;
1013 if (queuegroup
!= NULL
)
1015 usrerr("Can not use multiple -qG options");
1016 ExitStat
= EX_USAGE
;
1019 queuegroup
= newstr(&optarg
[1]);
1022 case 'I': /* Limit by ID */
1023 new = (QUEUE_CHAR
*) xalloc(sizeof(*new));
1024 new->queue_match
= newstr(&optarg
[1]);
1025 new->queue_negate
= negate
;
1026 new->queue_next
= QueueLimitId
;
1030 case 'R': /* Limit by recipient */
1031 new = (QUEUE_CHAR
*) xalloc(sizeof(*new));
1032 new->queue_match
= newstr(&optarg
[1]);
1033 new->queue_negate
= negate
;
1034 new->queue_next
= QueueLimitRecipient
;
1035 QueueLimitRecipient
= new;
1038 case 'S': /* Limit by sender */
1039 new = (QUEUE_CHAR
*) xalloc(sizeof(*new));
1040 new->queue_match
= newstr(&optarg
[1]);
1041 new->queue_negate
= negate
;
1042 new->queue_next
= QueueLimitSender
;
1043 QueueLimitSender
= new;
1046 case 'f': /* foreground queue run */
1047 foregroundqueue
= true;
1050 case 'Q': /* Limit by quarantine message */
1051 if (optarg
[1] != '\0')
1053 new = (QUEUE_CHAR
*) xalloc(sizeof(*new));
1054 new->queue_match
= newstr(&optarg
[1]);
1055 new->queue_negate
= negate
;
1056 new->queue_next
= QueueLimitQuarantine
;
1057 QueueLimitQuarantine
= new;
1059 QueueMode
= QM_QUARANTINE
;
1062 case 'L': /* act on lost items */
1063 QueueMode
= QM_LOST
;
1066 case 'p': /* Persistent queue */
1067 queuepersistent
= true;
1068 if (QueueIntvl
== 0)
1070 if (optarg
[1] == '\0')
1077 QueueIntvl
= convtime(optarg
, 'm');
1080 usrerr("Invalid -q value");
1081 ExitStat
= EX_USAGE
;
1084 /* check for bad conversion */
1086 ExitStat
= EX_USAGE
;
1091 case 'R': /* DSN RET: what to return */
1092 CHECK_AGAINST_OPMODE(j
);
1093 if (bitset(EF_RET_PARAM
, BlankEnvelope
.e_flags
))
1095 usrerr("Duplicate -R flag");
1096 ExitStat
= EX_USAGE
;
1099 BlankEnvelope
.e_flags
|= EF_RET_PARAM
;
1100 if (sm_strcasecmp(optarg
, "hdrs") == 0)
1101 BlankEnvelope
.e_flags
|= EF_NO_BODY_RETN
;
1102 else if (sm_strcasecmp(optarg
, "full") != 0)
1104 usrerr("Invalid -R value");
1105 ExitStat
= EX_USAGE
;
1107 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
,
1108 macid("{dsn_ret}"), optarg
);
1111 case 't': /* read recipients from message */
1112 CHECK_AGAINST_OPMODE(j
);
1116 case 'V': /* DSN ENVID: set "original" envelope id */
1117 CHECK_AGAINST_OPMODE(j
);
1118 if (!xtextok(optarg
))
1120 usrerr("Invalid syntax in -V flag");
1121 ExitStat
= EX_USAGE
;
1125 BlankEnvelope
.e_envid
= newstr(optarg
);
1126 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
,
1127 macid("{dsn_envid}"), optarg
);
1131 case 'X': /* traffic log file */
1132 dp
= drop_privileges(true);
1134 if (stat(optarg
, &traf_st
) == 0 &&
1135 S_ISFIFO(traf_st
.st_mode
))
1136 TrafficLogFile
= sm_io_open(SmFtStdio
,
1139 SM_IO_WRONLY
, NULL
);
1141 TrafficLogFile
= sm_io_open(SmFtStdio
,
1144 SM_IO_APPEND
, NULL
);
1145 if (TrafficLogFile
== NULL
)
1147 syserr("cannot open %s", optarg
);
1148 ExitStat
= EX_CANTCREAT
;
1151 (void) sm_io_setvbuf(TrafficLogFile
, SM_TIME_DEFAULT
,
1152 NULL
, SM_IO_LBF
, 0);
1155 /* compatibility flags */
1156 case 'c': /* connect to non-local mailers */
1157 case 'i': /* don't let dot stop me */
1158 case 'm': /* send to me too */
1159 case 'T': /* set timeout interval */
1160 case 'v': /* give blow-by-blow description */
1161 setoption(j
, "T", false, true, &BlankEnvelope
);
1164 case 'e': /* error message disposition */
1165 case 'M': /* define macro */
1166 setoption(j
, optarg
, false, true, &BlankEnvelope
);
1169 case 's': /* save From lines in headers */
1170 setoption('f', "T", false, true, &BlankEnvelope
);
1174 case 'I': /* initialize alias DBM file */
1175 set_op_mode(MD_INITALIAS
);
1179 #if defined(__osf__) || defined(_AIX3)
1180 case 'x': /* random flag that OSF/1 & AIX mailx passes */
1182 #endif /* defined(__osf__) || defined(_AIX3) */
1183 #if defined(sony_news)
1185 case 'J': /* ignore flags for Japanese code conversion
1186 implemented on Sony NEWS */
1188 #endif /* defined(sony_news) */
1191 finis(true, true, EX_USAGE
);
1197 /* if we've had errors so far, exit now */
1198 if ((ExitStat
!= EX_OK
&& OpMode
!= MD_TEST
&& OpMode
!= MD_CHECKCONFIG
) ||
1199 ExitStat
== EX_OSERR
)
1201 finis(false, true, ExitStat
);
1205 if (bitset(SUBMIT_MTA
, SubmitMode
))
1207 /* If set daemon_flags on command line, don't reset it */
1208 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope
) == NULL
)
1209 macdefine(&BlankEnvelope
.e_macro
, A_PERM
,
1210 macid("{daemon_flags}"), "CC f");
1212 else if (OpMode
== MD_DELIVER
|| OpMode
== MD_SMTP
)
1214 SubmitMode
= SUBMIT_MSA
;
1216 /* If set daemon_flags on command line, don't reset it */
1217 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope
) == NULL
)
1218 macdefine(&BlankEnvelope
.e_macro
, A_PERM
,
1219 macid("{daemon_flags}"), "c u");
1223 ** Do basic initialization.
1224 ** Read system control file.
1225 ** Extract special fields for local use.
1229 checkfd012("before readcf");
1231 vendor_pre_defaults(&BlankEnvelope
);
1233 readcf(getcfname(OpMode
, SubmitMode
, cftype
, conffile
),
1234 safecf
, &BlankEnvelope
);
1235 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1236 ConfigFileRead
= true;
1237 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1238 vendor_post_defaults(&BlankEnvelope
);
1240 /* now we can complain about missing fds */
1241 if (MissingFds
!= 0 && LogLevel
> 8)
1246 if (bitset(1 << STDIN_FILENO
, MissingFds
))
1247 (void) sm_strlcat(mbuf
, ", stdin", sizeof(mbuf
));
1248 if (bitset(1 << STDOUT_FILENO
, MissingFds
))
1249 (void) sm_strlcat(mbuf
, ", stdout", sizeof(mbuf
));
1250 if (bitset(1 << STDERR_FILENO
, MissingFds
))
1251 (void) sm_strlcat(mbuf
, ", stderr", sizeof(mbuf
));
1253 /* Notice: fill_errno is from high above: fill_fd() */
1254 sm_syslog(LOG_WARNING
, NOQID
,
1255 "File descriptors missing on startup: %s; %s",
1256 &mbuf
[2], sm_errstring(fill_errno
));
1259 /* Remove the ability for a normal user to send signals */
1260 if (RealUid
!= 0 && RealUid
!= geteuid())
1262 uid_t new_uid
= geteuid();
1266 ** Since we can differentiate between uid and euid,
1267 ** make the uid a different user so the real user
1268 ** can't send signals. However, it doesn't need to be
1269 ** root (euid has root).
1275 sm_dprintf("Changing real uid to %d\n", (int) new_uid
);
1276 if (setreuid(new_uid
, geteuid()) < 0)
1278 syserr("main: setreuid(%d, %d) failed",
1279 (int) new_uid
, (int) geteuid());
1280 finis(false, true, EX_OSERR
);
1284 sm_dprintf("Now running as e/ruid %d:%d\n",
1285 (int) geteuid(), (int) getuid());
1286 #else /* HASSETREUID */
1288 ** Have to change both effective and real so need to
1289 ** change them both to effective to keep privs.
1293 sm_dprintf("Changing uid to %d\n", (int) new_uid
);
1294 if (setuid(new_uid
) < 0)
1296 syserr("main: setuid(%d) failed", (int) new_uid
);
1297 finis(false, true, EX_OSERR
);
1301 sm_dprintf("Now running as e/ruid %d:%d\n",
1302 (int) geteuid(), (int) getuid());
1303 #endif /* HASSETREUID */
1307 if (FallbackMX
!= NULL
)
1308 (void) getfallbackmxrr(FallbackMX
);
1309 #endif /* NAMED_BIND */
1311 if (SuperSafe
== SAFE_INTERACTIVE
&& CurEnv
->e_sendmode
!= SM_DELIVER
)
1313 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
1314 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1317 if (UseMSP
&& (OpMode
== MD_DAEMON
|| OpMode
== MD_FGDAEMON
))
1319 usrerr("Mail submission program cannot be used as daemon");
1320 finis(false, true, EX_USAGE
);
1323 if (OpMode
== MD_DELIVER
|| OpMode
== MD_SMTP
||
1324 OpMode
== MD_QUEUERUN
|| OpMode
== MD_ARPAFTP
||
1325 OpMode
== MD_DAEMON
|| OpMode
== MD_FGDAEMON
)
1328 /* set up the basic signal handlers */
1329 if (sm_signal(SIGINT
, SIG_IGN
) != SIG_IGN
)
1330 (void) sm_signal(SIGINT
, intsig
);
1331 (void) sm_signal(SIGTERM
, intsig
);
1333 /* Enforce use of local time (null string overrides this) */
1334 if (TimeZoneSpec
== NULL
)
1336 else if (TimeZoneSpec
[0] != '\0')
1337 sm_setuserenv("TZ", TimeZoneSpec
);
1339 sm_setuserenv("TZ", NULL
);
1342 /* initialize mailbox database */
1343 i
= sm_mbdb_initialize(Mbdb
);
1346 usrerr("Can't initialize mailbox database \"%s\": %s",
1347 Mbdb
, sm_strexit(i
));
1351 /* avoid denial-of-service attacks */
1354 if (OpMode
== MD_TEST
)
1356 /* can't be done after readcf if RunAs* is used */
1357 dp
= drop_privileges(true);
1360 finis(false, true, dp
);
1364 else if (OpMode
!= MD_DAEMON
&& OpMode
!= MD_FGDAEMON
)
1366 /* drop privileges -- daemon mode done after socket/bind */
1367 dp
= drop_privileges(false);
1369 if (dp
== EX_OK
&& UseMSP
&& (geteuid() == 0 || getuid() == 0))
1371 usrerr("Mail submission program must have RunAsUser set to non root user");
1372 finis(false, true, EX_CONFIG
);
1378 _res
.retry
= TimeOuts
.res_retry
[RES_TO_DEFAULT
];
1379 _res
.retrans
= TimeOuts
.res_retrans
[RES_TO_DEFAULT
];
1380 #endif /* NAMED_BIND */
1383 ** Find our real host name for future logging.
1386 authinfo
= getauthinfo(STDIN_FILENO
, &forged
);
1387 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
, '_', authinfo
);
1389 /* suppress error printing if errors mailed back or whatever */
1390 if (BlankEnvelope
.e_errormode
!= EM_PRINT
)
1393 /* set up the $=m class now, after .cf has a chance to redefine $m */
1394 expand("\201m", jbuf
, sizeof(jbuf
), &BlankEnvelope
);
1395 if (jbuf
[0] != '\0')
1396 setclass('m', jbuf
);
1398 /* probe interfaces and locate any additional names */
1399 if (DontProbeInterfaces
!= DPI_PROBENONE
)
1404 char pidpath
[MAXPATHLEN
];
1406 /* Now we know which .cf file we use */
1407 sm_dprintf(" Conf file:\t%s (selected)\n",
1408 getcfname(OpMode
, SubmitMode
, cftype
, conffile
));
1409 expand(PidFile
, pidpath
, sizeof(pidpath
), &BlankEnvelope
);
1410 sm_dprintf(" Pid file:\t%s (selected)\n", pidpath
);
1415 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1416 sm_dprintf("\n (short domain name) $w = ");
1417 xputs(sm_debug_file(), macvalue('w', &BlankEnvelope
));
1418 sm_dprintf("\n (canonical domain name) $j = ");
1419 xputs(sm_debug_file(), macvalue('j', &BlankEnvelope
));
1420 sm_dprintf("\n (subdomain name) $m = ");
1421 xputs(sm_debug_file(), macvalue('m', &BlankEnvelope
));
1422 sm_dprintf("\n (node name) $k = ");
1423 xputs(sm_debug_file(), macvalue('k', &BlankEnvelope
));
1424 sm_dprintf("\n========================================================\n\n");
1428 ** Do more command line checking -- these are things that
1429 ** have to modify the results of reading the config file.
1432 /* process authorization warnings from command line */
1434 auth_warning(&BlankEnvelope
, "Processed by %s with -C %s",
1435 RealUserName
, conffile
);
1436 if (Warn_Q_option
&& !wordinclass(RealUserName
, 't'))
1437 auth_warning(&BlankEnvelope
, "Processed from queue %s",
1439 if (sysloglabel
!= NULL
&& !wordinclass(RealUserName
, 't') &&
1440 RealUid
!= 0 && RealUid
!= TrustedUid
&& LogLevel
> 1)
1441 sm_syslog(LOG_WARNING
, NOQID
, "user %d changed syslog label",
1444 /* check body type for legality */
1445 i
= check_bodytype(BlankEnvelope
.e_bodytype
);
1446 if (i
== BODYTYPE_ILLEGAL
)
1448 usrerr("Illegal body type %s", BlankEnvelope
.e_bodytype
);
1449 BlankEnvelope
.e_bodytype
= NULL
;
1451 else if (i
!= BODYTYPE_NONE
)
1452 SevenBitInput
= (i
== BODYTYPE_7BIT
);
1454 /* tweak default DSN notifications */
1455 if (DefaultNotify
== 0)
1456 DefaultNotify
= QPINGONFAILURE
|QPINGONDELAY
;
1458 /* check for sane configuration level */
1459 if (ConfigLevel
> MAXCONFIGLEVEL
)
1461 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1462 ConfigLevel
, Version
, MAXCONFIGLEVEL
);
1465 /* need MCI cache to have persistence */
1466 if (HostStatDir
!= NULL
&& MaxMciCache
== 0)
1469 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
1470 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1473 /* need HostStatusDir in order to have SingleThreadDelivery */
1474 if (SingleThreadDelivery
&& HostStatDir
== NULL
)
1476 SingleThreadDelivery
= false;
1477 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
1478 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1482 j
= sm_memstat_open();
1483 if (j
< 0 && (RefuseLowMem
> 0 || QueueLowMem
> 0) && LogLevel
> 4)
1485 sm_syslog(LOG_WARNING
, NOQID
,
1486 "cannot get memory statistics, settings ignored, error=%d"
1489 #endif /* _FFR_MEMSTAT */
1491 /* check for permissions */
1493 RealUid
!= TrustedUid
)
1495 char *action
= NULL
;
1500 if (quarantining
!= NULL
)
1501 action
= "quarantine jobs";
1504 /* Normal users can do a single queue run */
1505 if (QueueIntvl
== 0)
1509 /* but not persistent queue runners */
1511 action
= "start a queue runner daemon";
1516 action
= "purge host status";
1522 action
= "run daemon";
1525 sm_dprintf("Deny user %d attempt to %s\n",
1526 (int) RealUid
, action
);
1529 sm_syslog(LOG_ALERT
, NOQID
,
1530 "user %d attempted to %s",
1531 (int) RealUid
, action
);
1533 usrerr("Permission denied (real uid not trusted)");
1534 finis(false, true, EX_USAGE
);
1539 if (bitset(PRIV_RESTRICTEXPAND
, PrivacyFlags
))
1542 ** If -bv and RestrictExpand,
1543 ** drop privs to prevent normal
1544 ** users from reading private
1545 ** aliases/forwards/:include:s
1549 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1552 dp
= drop_privileges(true);
1554 /* Fake address safety */
1556 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1557 setbitn(DBS_NONROOTSAFEADDR
, DontBlameSendmail
);
1562 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1564 CurEnv
->e_id
= NULL
;
1565 finis(true, true, dp
);
1572 case MD_CHECKCONFIG
:
1577 /* Nothing special to check */
1581 if (!wordinclass(RealUserName
, 't'))
1584 sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1587 sm_syslog(LOG_ALERT
, NOQID
,
1588 "user %d attempted to rebuild the alias map",
1591 usrerr("Permission denied (real uid not trusted)");
1592 finis(false, true, EX_USAGE
);
1598 usrerr("User %d cannot rebuild aliases in mail submission program",
1600 finis(false, true, EX_USAGE
);
1606 if (bitset(PRIV_RESTRICTEXPAND
, PrivacyFlags
) &&
1610 ** If -v and RestrictExpand, reset
1611 ** Verbose to prevent normal users
1612 ** from seeing the expansion of
1613 ** aliases/forwards/:include:s
1617 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1626 BlankEnvelope
.e_flags
|= EF_METOO
;
1631 /* don't have persistent host status in test mode */
1635 case MD_CHECKCONFIG
:
1638 BlankEnvelope
.e_errormode
= EM_PRINT
;
1643 BlankEnvelope
.e_errormode
= EM_PRINT
;
1645 /* arrange to exit cleanly on hangup signal */
1646 if (sm_signal(SIGHUP
, SIG_IGN
) == (sigfunc_t
) SIG_DFL
)
1647 (void) sm_signal(SIGHUP
, intsig
);
1649 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
1650 "Notice: -bv may give misleading output for non-privileged user\n");
1654 run_in_foreground
= true;
1655 set_op_mode(MD_DAEMON
);
1659 vendor_daemon_setup(&BlankEnvelope
);
1661 /* remove things that don't make sense in daemon mode */
1665 /* arrange to restart on hangup signal */
1666 if (SaveArgv
[0] == NULL
|| SaveArgv
[0][0] != '/')
1667 sm_syslog(LOG_WARNING
, NOQID
,
1668 "daemon invoked without full pathname; kill -1 won't work");
1673 BlankEnvelope
.e_errormode
= EM_PRINT
;
1678 /* arrange to exit cleanly on hangup signal */
1679 if (sm_signal(SIGHUP
, SIG_IGN
) == (sigfunc_t
) SIG_DFL
)
1680 (void) sm_signal(SIGHUP
, intsig
);
1684 /* special considerations for FullName */
1685 if (FullName
!= NULL
)
1689 /* full names can't have newlines */
1690 if (strchr(FullName
, '\n') != NULL
)
1692 full
= newstr(denlstring(FullName
, true, true));
1696 /* check for characters that may have to be quoted */
1697 if (!rfc822_string(FullName
))
1700 ** Quote a full name with special characters
1701 ** as a comment so crackaddr() doesn't destroy
1702 ** the name portion of the address.
1705 FullName
= addquotes(FullName
, NULL
);
1707 sm_free(full
); /* XXX */
1711 /* do heuristic mode adjustment */
1714 /* turn off noconnect option */
1715 setoption('c', "F", true, false, &BlankEnvelope
);
1717 /* turn on interactive delivery */
1718 setoption('d', "", true, false, &BlankEnvelope
);
1722 /* check for vendor mismatch */
1723 if (VendorCode
!= VENDOR_CODE
)
1725 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1726 getvendor(VENDOR_CODE
), getvendor(VendorCode
));
1728 #endif /* VENDOR_CODE */
1730 /* check for out of date configuration level */
1731 if (ConfigLevel
< MAXCONFIGLEVEL
)
1733 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1734 Version
, MAXCONFIGLEVEL
, ConfigLevel
);
1737 if (ConfigLevel
< 3)
1740 /* set options that were previous macros */
1741 if (SmtpGreeting
== NULL
)
1743 if (ConfigLevel
< 7 &&
1744 (p
= macvalue('e', &BlankEnvelope
)) != NULL
)
1745 SmtpGreeting
= newstr(p
);
1747 SmtpGreeting
= "\201j Sendmail \201v ready at \201b";
1749 if (UnixFromLine
== NULL
)
1751 if (ConfigLevel
< 7 &&
1752 (p
= macvalue('l', &BlankEnvelope
)) != NULL
)
1753 UnixFromLine
= newstr(p
);
1755 UnixFromLine
= "From \201g \201d";
1757 SmtpError
[0] = '\0';
1759 /* our name for SMTP codes */
1760 expand("\201j", jbuf
, sizeof(jbuf
), &BlankEnvelope
);
1761 if (jbuf
[0] == '\0')
1762 PSTRSET(MyHostName
, "localhost");
1764 PSTRSET(MyHostName
, jbuf
);
1765 if (strchr(MyHostName
, '.') == NULL
)
1766 message("WARNING: local host name (%s) is not qualified; see cf/README: WHO AM I?",
1769 /* make certain that this name is part of the $=w class */
1770 setclass('w', MyHostName
);
1772 /* fill in the structure of the *default* queue */
1773 st
= stab("mqueue", ST_QUEUE
, ST_FIND
);
1775 syserr("No default queue (mqueue) defined");
1777 set_def_queueval(st
->s_quegrp
, true);
1779 /* the indices of built-in mailers */
1780 st
= stab("local", ST_MAILER
, ST_FIND
);
1782 LocalMailer
= st
->s_mailer
;
1783 else if (OpMode
!= MD_TEST
|| !warn_C_flag
)
1784 syserr("No local mailer defined");
1786 st
= stab("prog", ST_MAILER
, ST_FIND
);
1788 syserr("No prog mailer defined");
1791 ProgMailer
= st
->s_mailer
;
1792 clrbitn(M_MUSER
, ProgMailer
->m_flags
);
1795 st
= stab("*file*", ST_MAILER
, ST_FIND
);
1797 syserr("No *file* mailer defined");
1800 FileMailer
= st
->s_mailer
;
1801 clrbitn(M_MUSER
, FileMailer
->m_flags
);
1804 st
= stab("*include*", ST_MAILER
, ST_FIND
);
1806 syserr("No *include* mailer defined");
1808 InclMailer
= st
->s_mailer
;
1810 if (ConfigLevel
< 6)
1812 /* heuristic tweaking of local mailer for back compat */
1813 if (LocalMailer
!= NULL
)
1815 setbitn(M_ALIASABLE
, LocalMailer
->m_flags
);
1816 setbitn(M_HASPWENT
, LocalMailer
->m_flags
);
1817 setbitn(M_TRYRULESET5
, LocalMailer
->m_flags
);
1818 setbitn(M_CHECKINCLUDE
, LocalMailer
->m_flags
);
1819 setbitn(M_CHECKPROG
, LocalMailer
->m_flags
);
1820 setbitn(M_CHECKFILE
, LocalMailer
->m_flags
);
1821 setbitn(M_CHECKUDB
, LocalMailer
->m_flags
);
1823 if (ProgMailer
!= NULL
)
1824 setbitn(M_RUNASRCPT
, ProgMailer
->m_flags
);
1825 if (FileMailer
!= NULL
)
1826 setbitn(M_RUNASRCPT
, FileMailer
->m_flags
);
1828 if (ConfigLevel
< 7)
1830 if (LocalMailer
!= NULL
)
1831 setbitn(M_VRFY250
, LocalMailer
->m_flags
);
1832 if (ProgMailer
!= NULL
)
1833 setbitn(M_VRFY250
, ProgMailer
->m_flags
);
1834 if (FileMailer
!= NULL
)
1835 setbitn(M_VRFY250
, FileMailer
->m_flags
);
1838 /* MIME Content-Types that cannot be transfer encoded */
1839 setclass('n', "multipart/signed");
1841 /* MIME message/xxx subtypes that can be treated as messages */
1842 setclass('s', "rfc822");
1844 /* MIME Content-Transfer-Encodings that can be encoded */
1845 setclass('e', "7bit");
1846 setclass('e', "8bit");
1847 setclass('e', "binary");
1850 /* MIME Content-Types that should be treated as binary */
1851 setclass('b', "image");
1852 setclass('b', "audio");
1853 setclass('b', "video");
1854 setclass('b', "application/octet-stream");
1855 #endif /* USE_B_CLASS */
1857 /* MIME headers which have fields to check for overflow */
1858 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1859 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1861 /* MIME headers to check for length overflow */
1862 setclass(macid("{checkMIMETextHeaders}"), "content-description");
1864 /* MIME headers to check for overflow and rebalance */
1865 setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1866 setclass(macid("{checkMIMEHeaders}"), "content-id");
1867 setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1868 setclass(macid("{checkMIMEHeaders}"), "content-type");
1869 setclass(macid("{checkMIMEHeaders}"), "mime-version");
1871 /* Macros to save in the queue file -- don't remove any */
1872 setclass(macid("{persistentMacros}"), "r");
1873 setclass(macid("{persistentMacros}"), "s");
1874 setclass(macid("{persistentMacros}"), "_");
1875 setclass(macid("{persistentMacros}"), "{if_addr}");
1876 setclass(macid("{persistentMacros}"), "{daemon_flags}");
1878 /* operate in queue directory */
1879 if (QueueDir
== NULL
|| *QueueDir
== '\0')
1881 if (OpMode
!= MD_TEST
)
1883 syserr("QueueDirectory (Q) option must be set");
1884 ExitStat
= EX_CONFIG
;
1889 if (OpMode
!= MD_TEST
)
1890 setup_queues(OpMode
== MD_DAEMON
);
1893 /* check host status directory for validity */
1894 if (HostStatDir
!= NULL
&& !path_is_dir(HostStatDir
, false))
1896 /* cannot use this value */
1897 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
1898 "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1899 HostStatDir
, sm_errstring(errno
));
1903 if (OpMode
== MD_QUEUERUN
&&
1904 RealUid
!= 0 && bitset(PRIV_RESTRICTQRUN
, PrivacyFlags
))
1908 /* check to see if we own the queue directory */
1909 if (stat(".", &stbuf
) < 0)
1910 syserr("main: cannot stat %s", QueueDir
);
1911 if (stbuf
.st_uid
!= RealUid
)
1913 /* nope, really a botch */
1915 usrerr("You do not have permission to process the queue");
1916 finis(false, true, EX_NOPERM
);
1922 /* sanity checks on milter filters */
1923 if (OpMode
== MD_DAEMON
|| OpMode
== MD_SMTP
)
1925 milter_config(InputFilterList
, InputFilters
, MAXFILTERS
);
1926 setup_daemon_milters();
1930 /* Convert queuegroup string to qgrp number */
1931 if (queuegroup
!= NULL
)
1933 qgrp
= name2qid(queuegroup
);
1937 usrerr("Queue group %s unknown", queuegroup
);
1938 finis(false, true, ExitStat
);
1943 /* if checking config or have had errors so far, exit now */
1944 if (OpMode
== MD_CHECKCONFIG
|| (ExitStat
!= EX_OK
&& OpMode
!= MD_TEST
))
1946 finis(false, true, ExitStat
);
1951 /* sendmail specific SASL initialization */
1956 checkfd012("before main() initmaps");
1960 ** Do operation-mode-dependent initialization.
1966 /* print the queue */
1968 (void) dropenvelope(&BlankEnvelope
, true, false);
1969 (void) sm_signal(SIGPIPE
, sigpipe
);
1974 /* Selecting a particular queue group to run */
1975 for (j
= 0; j
< Queue
[qgrp
]->qg_numqueues
; j
++)
1979 (void) print_single_queue(qgrp
, j
);
1981 finis(false, true, EX_OK
);
1985 finis(false, true, EX_OK
);
1990 /* print number of entries in queue */
1991 (void) dropenvelope(&BlankEnvelope
, true, false);
1992 (void) sm_signal(SIGPIPE
, sigpipe
);
1993 printnqe(smioout
, NULL
);
1994 finis(false, true, EX_OK
);
1999 /* only handle quarantining here */
2000 if (quarantining
== NULL
)
2003 if (QueueMode
!= QM_QUARANTINE
&&
2004 QueueMode
!= QM_NORMAL
)
2007 usrerr("Can not use -Q with -q%c", QueueMode
);
2008 ExitStat
= EX_USAGE
;
2009 finis(false, true, ExitStat
);
2012 quarantine_queue(quarantining
, qgrp
);
2013 finis(false, true, EX_OK
);
2017 (void) sm_signal(SIGPIPE
, sigpipe
);
2018 (void) mci_traverse_persistent(mci_print_persistent
, NULL
);
2019 finis(false, true, EX_OK
);
2024 (void) mci_traverse_persistent(mci_purge_persistent
, NULL
);
2025 finis(false, true, EX_OK
);
2030 /* initialize maps */
2032 finis(false, true, ExitStat
);
2038 /* reset DSN parameters */
2039 DefaultNotify
= QPINGONFAILURE
|QPINGONDELAY
;
2040 macdefine(&BlankEnvelope
.e_macro
, A_PERM
,
2041 macid("{dsn_notify}"), NULL
);
2042 BlankEnvelope
.e_envid
= NULL
;
2043 macdefine(&BlankEnvelope
.e_macro
, A_PERM
,
2044 macid("{dsn_envid}"), NULL
);
2045 BlankEnvelope
.e_flags
&= ~(EF_RET_PARAM
|EF_NO_BODY_RETN
);
2046 macdefine(&BlankEnvelope
.e_macro
, A_PERM
,
2047 macid("{dsn_ret}"), NULL
);
2049 /* don't open maps for daemon -- done below in child */
2055 /* print configuration table (or at least part of it) */
2058 for (i
= 0; i
< MAXMAILERS
; i
++)
2060 if (Mailer
[i
] != NULL
)
2061 printmailer(sm_debug_file(), Mailer
[i
]);
2066 ** Switch to the main envelope.
2069 CurEnv
= newenvelope(&MainEnvelope
, &BlankEnvelope
,
2070 sm_rpool_new_x(NULL
));
2071 MainEnvelope
.e_flags
= BlankEnvelope
.e_flags
;
2074 ** If test mode, read addresses from stdin and process.
2077 if (OpMode
== MD_TEST
)
2079 if (isatty(sm_io_getinfo(smioin
, SM_IO_WHAT_FD
, NULL
)))
2084 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
2085 "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2086 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
2087 "Enter <ruleset> <address>\n");
2089 macdefine(&(MainEnvelope
.e_macro
), A_PERM
,
2090 macid("{addr_type}"), "e r");
2095 (void) sm_signal(SIGINT
, intindebug
);
2096 (void) sm_releasesignal(SIGINT
);
2098 (void) sm_io_fprintf(smioout
,
2101 (void) sm_io_flush(smioout
, SM_TIME_DEFAULT
);
2102 if (sm_io_fgets(smioin
, SM_TIME_DEFAULT
, buf
,
2103 sizeof(buf
)) == NULL
)
2104 testmodeline("/quit", &MainEnvelope
);
2105 p
= strchr(buf
, '\n');
2109 (void) sm_io_fprintf(smioout
,
2112 testmodeline(buf
, &MainEnvelope
);
2114 SM_EXCEPT(exc
, "[!F]*")
2117 ** 8.10 just prints \n on interrupt.
2118 ** I'm printing the exception here in case
2119 ** sendmail is extended to raise additional
2120 ** exceptions in this context.
2123 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
2125 sm_exc_print(exc
, smioout
);
2133 if (OpMode
== MD_QUEUERUN
|| OpMode
== MD_DELIVER
||
2134 OpMode
== MD_ARPAFTP
)
2136 /* check whether STARTTLS is turned off for the client */
2137 if (chkclientmodifiers(D_NOTLS
))
2140 else if (OpMode
== MD_DAEMON
|| OpMode
== MD_FGDAEMON
||
2143 /* check whether STARTTLS is turned off */
2144 if (chkdaemonmodifiers(D_NOTLS
) && chkclientmodifiers(D_NOTLS
))
2147 else /* other modes don't need STARTTLS */
2152 /* basic TLS initialization */
2153 tls_ok
= init_tls_library();
2156 if (!tls_ok
&& (OpMode
== MD_QUEUERUN
|| OpMode
== MD_DELIVER
))
2158 /* disable TLS for client */
2161 #endif /* STARTTLS */
2164 ** If collecting stuff from the queue, go start doing that.
2167 if (OpMode
== MD_QUEUERUN
&& QueueIntvl
== 0)
2172 /* init TLS for client, ignore result for now */
2173 (void) initclttls(tls_ok
);
2174 #endif /* STARTTLS */
2177 ** The parent process of the caller of runqueue() needs
2178 ** to stay around for a possible SIGTERM. The SIGTERM will
2179 ** tell this process that all of the queue runners children
2180 ** need to be sent SIGTERM as well. At the same time, we
2181 ** want to return control to the command line. So we do an
2185 if (Verbose
|| foregroundqueue
|| (pid
= fork()) <= 0)
2188 ** If the fork() failed we should still try to do
2189 ** the queue run. If it succeeded then the child
2190 ** is going to start the run and wait for all
2191 ** of the children to finish.
2196 /* Reset global flags */
2197 RestartRequest
= NULL
;
2198 ShutdownRequest
= NULL
;
2201 /* disconnect from terminal */
2202 disconnect(2, CurEnv
);
2205 CurrentPid
= getpid();
2208 int rwgflags
= RWG_NONE
;
2211 ** To run a specific queue group mark it to
2212 ** be run, select the work group it's in and
2213 ** increment the work counter.
2216 for (i
= 0; i
< NumQueue
&& Queue
[i
] != NULL
;
2218 Queue
[i
]->qg_nextrun
= (time_t) -1;
2219 Queue
[qgrp
]->qg_nextrun
= 0;
2221 rwgflags
|= RWG_VERBOSE
;
2222 if (queuepersistent
)
2223 rwgflags
|= RWG_PERSISTENT
;
2224 rwgflags
|= RWG_FORCE
;
2225 (void) run_work_group(Queue
[qgrp
]->qg_wgrp
,
2229 (void) runqueue(false, Verbose
,
2230 queuepersistent
, true);
2232 /* set the title to make it easier to find */
2233 sm_setproctitle(true, CurEnv
, "Queue control");
2234 (void) sm_signal(SIGCHLD
, SIG_DFL
);
2235 while (CurChildren
> 0)
2241 while ((ret
= sm_wait(&status
)) <= 0)
2243 if (errno
== ECHILD
)
2246 ** Oops... something got messed
2247 ** up really bad. Waiting for
2248 ** non-existent children
2249 ** shouldn't happen. Let's get
2259 /* something is really really wrong */
2260 if (errno
== ECHILD
)
2262 sm_syslog(LOG_ERR
, NOQID
,
2263 "queue control process: lost all children: wait returned ECHILD");
2267 /* Only drop when a child gives status */
2268 if (WIFSTOPPED(status
))
2271 proc_list_drop(ret
, status
, NULL
);
2274 finis(true, true, ExitStat
);
2279 if (OpMode
== MD_SMTP
|| OpMode
== MD_DAEMON
)
2281 /* check whether AUTH is turned off for the server */
2282 if (!chkdaemonmodifiers(D_NOAUTH
) &&
2283 (i
= sasl_server_init(srvcallbacks
, "Sendmail")) != SASL_OK
)
2284 syserr("!sasl_server_init failed! [%s]",
2285 sasl_errstring(i
, NULL
, NULL
));
2289 if (OpMode
== MD_SMTP
)
2291 proc_list_add(CurrentPid
, "Sendmail SMTP Agent",
2292 PROC_DAEMON
, 0, -1, NULL
);
2294 /* clean up background delivery children */
2295 (void) sm_signal(SIGCHLD
, reapchild
);
2299 ** If a daemon, wait for a request.
2300 ** getrequests will always return in a child.
2301 ** If we should also be processing the queue, start
2302 ** doing it in background.
2303 ** We check for any errors that might have happened
2307 if (OpMode
== MD_DAEMON
|| QueueIntvl
> 0)
2311 /* avoid cleanup in finis(), DaemonPid will be set below */
2313 if (!run_in_foreground
&& !tTd(99, 100))
2315 /* put us in background */
2318 syserr("daemon: cannot fork");
2321 finis(false, true, EX_OK
);
2326 ** Initialize exception stack and default exception
2327 ** handler for child process.
2330 /* Reset global flags */
2331 RestartRequest
= NULL
;
2332 RestartWorkGroup
= false;
2333 ShutdownRequest
= NULL
;
2335 CurrentPid
= getpid();
2337 sm_exc_newthread(fatal_error
);
2339 /* disconnect from our controlling tty */
2340 disconnect(2, &MainEnvelope
);
2344 if (OpMode
== MD_DAEMON
)
2346 (void) sm_strlcat(dtype
, "+SMTP", sizeof(dtype
));
2347 DaemonPid
= CurrentPid
;
2351 (void) sm_strlcat2(dtype
,
2353 ? "+persistent-queueing@"
2355 pintvl(QueueIntvl
, true),
2359 (void) sm_strlcat(dtype
, "+debugging", sizeof(dtype
));
2361 sm_syslog(LOG_INFO
, NOQID
,
2362 "starting daemon (%s): %s", Version
, dtype
+ 1);
2367 /* save daemon type in a macro for possible PidFile use */
2368 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
,
2369 macid("{daemon_info}"), dtype
+ 1);
2371 /* save queue interval in a macro for possible PidFile use */
2372 macdefine(&MainEnvelope
.e_macro
, A_TEMP
,
2373 macid("{queue_interval}"), pintvl(QueueIntvl
, true));
2375 /* workaround: can't seem to release the signal in the parent */
2376 (void) sm_signal(SIGHUP
, sighup
);
2377 (void) sm_releasesignal(SIGHUP
);
2378 (void) sm_signal(SIGTERM
, sigterm
);
2385 int rwgflags
= RWG_NONE
;
2388 ** To run a specific queue group mark it to
2389 ** be run, select the work group it's in and
2390 ** increment the work counter.
2393 for (i
= 0; i
< NumQueue
&& Queue
[i
] != NULL
;
2395 Queue
[i
]->qg_nextrun
= (time_t) -1;
2396 Queue
[qgrp
]->qg_nextrun
= 0;
2398 rwgflags
|= RWG_VERBOSE
;
2399 if (queuepersistent
)
2400 rwgflags
|= RWG_PERSISTENT
;
2401 rwgflags
|= RWG_FORCE
;
2402 (void) run_work_group(Queue
[qgrp
]->qg_wgrp
,
2406 #endif /* _FFR_RUNPQG */
2407 (void) runqueue(true, false, queuepersistent
,
2411 ** If queuepersistent but not in daemon mode then
2412 ** we're going to do the queue runner monitoring here.
2413 ** If in daemon mode then the monitoring will happen
2417 if (OpMode
!= MD_DAEMON
&& queuepersistent
)
2420 ** Write the pid to file
2421 ** XXX Overwrites sendmail.pid
2424 log_sendmail_pid(&MainEnvelope
);
2426 /* set the title to make it easier to find */
2427 sm_setproctitle(true, CurEnv
, "Queue control");
2428 (void) sm_signal(SIGCHLD
, SIG_DFL
);
2429 while (CurChildren
> 0)
2437 while ((ret
= sm_wait(&status
)) <= 0)
2440 ** Waiting for non-existent
2441 ** children shouldn't happen.
2442 ** Let's get out of here if
2446 if (errno
== ECHILD
)
2454 /* something is really really wrong */
2455 if (errno
== ECHILD
)
2457 sm_syslog(LOG_ERR
, NOQID
,
2458 "persistent queue runner control process: lost all children: wait returned ECHILD");
2462 if (WIFSTOPPED(status
))
2465 /* Probe only on a child status */
2466 proc_list_drop(ret
, status
, &group
);
2468 if (WIFSIGNALED(status
))
2470 if (WCOREDUMP(status
))
2472 sm_syslog(LOG_ERR
, NOQID
,
2473 "persistent queue runner=%d core dumped, signal=%d",
2474 group
, WTERMSIG(status
));
2476 /* don't restart this */
2477 mark_work_group_restart(
2482 sm_syslog(LOG_ERR
, NOQID
,
2483 "persistent queue runner=%d died, pid=%ld, signal=%d",
2489 ** When debugging active, don't
2490 ** restart the persistent queues.
2491 ** But do log this as info.
2494 if (sm_debug_active(&DebugNoPRestart
,
2497 sm_syslog(LOG_DEBUG
, NOQID
,
2498 "persistent queue runner=%d, exited",
2500 mark_work_group_restart(group
,
2505 finis(true, true, ExitStat
);
2509 if (OpMode
!= MD_DAEMON
)
2514 ** Write the pid to file
2515 ** XXX Overwrites sendmail.pid
2518 log_sendmail_pid(&MainEnvelope
);
2520 /* set the title to make it easier to find */
2522 (void) sm_strlcpyn(qtype
, sizeof(qtype
), 4,
2524 pintvl(QueueIntvl
, true),
2527 sm_setproctitle(true, CurEnv
, qtype
);
2535 (void) runqueue(true, false,
2540 (void) dropenvelope(&MainEnvelope
, true, false);
2543 /* init TLS for server, ignore result for now */
2544 (void) initsrvtls(tls_ok
);
2545 #endif /* STARTTLS */
2548 p_flags
= getrequests(&MainEnvelope
);
2550 /* drop privileges */
2551 (void) drop_privileges(false);
2554 ** Get authentication data
2555 ** Set _ macro in BlankEnvelope before calling newenvelope().
2558 authinfo
= getauthinfo(sm_io_getinfo(InChannel
, SM_IO_WHAT_FD
,
2560 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
, '_', authinfo
);
2562 /* at this point we are in a child: reset state */
2563 sm_rpool_free(MainEnvelope
.e_rpool
);
2564 (void) newenvelope(&MainEnvelope
, &MainEnvelope
,
2565 sm_rpool_new_x(NULL
));
2570 /* log connection information */
2571 sm_syslog(LOG_INFO
, NULL
, "connect from %s", authinfo
);
2575 ** If running SMTP protocol, start collecting and executing
2576 ** commands. This will never return.
2579 if (OpMode
== MD_SMTP
|| OpMode
== MD_DAEMON
)
2584 ** Save some macros for check_* rulesets.
2591 (void) sm_snprintf(ipbuf
, sizeof(ipbuf
), "[%.100s]",
2592 anynet_ntoa(&RealHostAddr
));
2593 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
,
2594 macid("{client_name}"), ipbuf
);
2597 macdefine(&BlankEnvelope
.e_macro
, A_PERM
,
2598 macid("{client_name}"), RealHostName
);
2599 macdefine(&BlankEnvelope
.e_macro
, A_PERM
,
2600 macid("{client_ptr}"), RealHostName
);
2601 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
,
2602 macid("{client_addr}"), anynet_ntoa(&RealHostAddr
));
2605 switch (RealHostAddr
.sa
.sa_family
)
2609 (void) sm_snprintf(pbuf
, sizeof(pbuf
), "%d",
2610 RealHostAddr
.sin
.sin_port
);
2612 #endif /* NETINET */
2615 (void) sm_snprintf(pbuf
, sizeof(pbuf
), "%d",
2616 RealHostAddr
.sin6
.sin6_port
);
2618 #endif /* NETINET6 */
2620 (void) sm_snprintf(pbuf
, sizeof(pbuf
), "0");
2623 macdefine(&BlankEnvelope
.e_macro
, A_TEMP
,
2624 macid("{client_port}"), pbuf
);
2626 if (OpMode
== MD_DAEMON
)
2628 ENVELOPE
*saved_env
;
2630 /* validate the connection */
2633 CurEnv
= &BlankEnvelope
;
2634 nullserver
= validate_connection(&RealHostAddr
,
2635 macvalue(macid("{client_name}"),
2638 if (bitset(EF_DISCARD
, BlankEnvelope
.e_flags
))
2639 MainEnvelope
.e_flags
|= EF_DISCARD
;
2643 else if (p_flags
== NULL
)
2645 p_flags
= (BITMAP256
*) xalloc(sizeof(*p_flags
));
2649 if (OpMode
== MD_SMTP
)
2650 (void) initsrvtls(tls_ok
);
2651 #endif /* STARTTLS */
2653 /* turn off profiling */
2655 smtp(nullserver
, *p_flags
, &MainEnvelope
);
2659 /* turn off profiling */
2661 if (OpMode
== MD_DAEMON
)
2666 sm_rpool_free(MainEnvelope
.e_rpool
);
2667 clearenvelope(&MainEnvelope
, false, sm_rpool_new_x(NULL
));
2668 if (OpMode
== MD_VERIFY
)
2670 set_delivery_mode(SM_VERIFY
, &MainEnvelope
);
2671 PostMasterCopy
= NULL
;
2675 /* interactive -- all errors are global */
2676 MainEnvelope
.e_flags
|= EF_GLOBALERRS
|EF_LOGSENDER
;
2680 ** Do basic system initialization and set the sender
2683 initsys(&MainEnvelope
);
2684 macdefine(&MainEnvelope
.e_macro
, A_PERM
, macid("{ntries}"), "0");
2685 macdefine(&MainEnvelope
.e_macro
, A_PERM
, macid("{nrcpts}"), "0");
2686 setsender(from
, &MainEnvelope
, NULL
, '\0', false);
2687 if (warn_f_flag
!= '\0' && !wordinclass(RealUserName
, 't') &&
2688 (!bitnset(M_LOCALMAILER
, MainEnvelope
.e_from
.q_mailer
->m_flags
) ||
2689 strcmp(MainEnvelope
.e_from
.q_user
, RealUserName
) != 0))
2691 auth_warning(&MainEnvelope
, "%s set sender to %s using -%c",
2692 RealUserName
, from
, warn_f_flag
);
2701 /* set the initial sender for AUTH= to $f@$j */
2702 fv
= macvalue('f', &MainEnvelope
);
2703 if (fv
== NULL
|| *fv
== '\0')
2704 MainEnvelope
.e_auth_param
= NULL
;
2707 if (strchr(fv
, '@') == NULL
)
2709 i
= strlen(fv
) + strlen(macvalue('j',
2710 &MainEnvelope
)) + 2;
2712 (void) sm_strlcpyn(p
, i
, 3, fv
, "@",
2717 p
= sm_strdup_x(fv
);
2718 MainEnvelope
.e_auth_param
= sm_rpool_strdup_x(MainEnvelope
.e_rpool
,
2720 sm_free(p
); /* XXX */
2723 if (macvalue('s', &MainEnvelope
) == NULL
)
2724 macdefine(&MainEnvelope
.e_macro
, A_PERM
, 's', RealHostName
);
2727 if (*av
== NULL
&& !GrabTo
)
2729 MainEnvelope
.e_to
= NULL
;
2730 MainEnvelope
.e_flags
|= EF_GLOBALERRS
;
2732 SuperSafe
= SAFE_NO
;
2733 usrerr("Recipient names must be specified");
2735 /* collect body for UUCP return */
2736 if (OpMode
!= MD_VERIFY
)
2737 collect(InChannel
, false, NULL
, &MainEnvelope
, true);
2738 finis(true, true, EX_USAGE
);
2743 ** Scan argv and deliver the message to everyone.
2746 save_val
= LogUsrErrs
;
2748 sendtoargv(av
, &MainEnvelope
);
2749 LogUsrErrs
= save_val
;
2751 /* if we have had errors sofar, arrange a meaningful exit stat */
2752 if (Errors
> 0 && ExitStat
== EX_OK
)
2753 ExitStat
= EX_USAGE
;
2757 ** If using -t, force not sending to argv recipients, even
2758 ** if they are mentioned in the headers.
2765 for (q
= MainEnvelope
.e_sendqueue
; q
!= NULL
; q
= q
->q_next
)
2766 q
->q_state
= QS_REMOVED
;
2768 #endif /* _FFR_FIX_DASHT */
2771 ** Read the input mail.
2774 MainEnvelope
.e_to
= NULL
;
2775 if (OpMode
!= MD_VERIFY
|| GrabTo
)
2778 unsigned long savedflags
;
2781 ** workaround for compiler warning on Irix:
2782 ** do not initialize variable in the definition, but
2784 ** warning(1548): transfer of control bypasses
2785 ** initialization of:
2786 ** variable "savederrors" (declared at line 2570)
2787 ** variable "savedflags" (declared at line 2571)
2791 savederrors
= Errors
;
2792 savedflags
= MainEnvelope
.e_flags
& EF_FATALERRS
;
2793 MainEnvelope
.e_flags
|= EF_GLOBALERRS
;
2794 MainEnvelope
.e_flags
&= ~EF_FATALERRS
;
2797 collect(InChannel
, false, NULL
, &MainEnvelope
, true);
2799 /* header checks failed */
2805 /* Log who the mail would have gone to */
2806 logundelrcpts(&MainEnvelope
,
2807 MainEnvelope
.e_message
,
2811 finis(true, true, ExitStat
);
2816 /* bail out if message too large */
2817 if (bitset(EF_CLRQUEUE
, MainEnvelope
.e_flags
))
2819 finis(true, true, ExitStat
!= EX_OK
? ExitStat
2825 /* set message size */
2826 (void) sm_snprintf(buf
, sizeof(buf
), "%ld",
2827 MainEnvelope
.e_msgsize
);
2828 macdefine(&MainEnvelope
.e_macro
, A_TEMP
,
2829 macid("{msg_size}"), buf
);
2831 Errors
= savederrors
;
2832 MainEnvelope
.e_flags
|= savedflags
;
2837 sm_dprintf("From person = \"%s\"\n",
2838 MainEnvelope
.e_from
.q_paddr
);
2840 /* Check if quarantining stats should be updated */
2841 if (MainEnvelope
.e_quarmsg
!= NULL
)
2842 markstats(&MainEnvelope
, NULL
, STATS_QUARANTINE
);
2845 ** Actually send everything.
2846 ** If verifying, just ack.
2851 if (!split_by_recipient(&MainEnvelope
) &&
2852 bitset(EF_FATALERRS
, MainEnvelope
.e_flags
))
2856 /* make sure we deliver at least the first envelope */
2857 i
= FastSplit
> 0 ? 0 : -1;
2858 for (e
= &MainEnvelope
; e
!= NULL
; e
= e
->e_sibling
, i
++)
2862 e
->e_from
.q_state
= QS_SENDER
;
2865 sm_dprintf("main[%d]: QS_SENDER ", i
);
2866 printaddr(sm_debug_file(), &e
->e_from
, false);
2872 _res
.retry
= TimeOuts
.res_retry
[RES_TO_FIRST
];
2873 _res
.retrans
= TimeOuts
.res_retrans
[RES_TO_FIRST
];
2874 #endif /* NAMED_BIND */
2875 next
= e
->e_sibling
;
2876 e
->e_sibling
= NULL
;
2878 /* after FastSplit envelopes: queue up */
2879 sendall(e
, i
>= FastSplit
? SM_QUEUE
: SM_DEFAULT
);
2880 e
->e_sibling
= next
;
2885 ** Don't send return error message if in VERIFY mode.
2888 finis(true, true, ExitStat
);
2893 ** STOP_SENDMAIL -- Stop the running program
2908 /* reset uid for process accounting */
2910 (void) setuid(RealUid
);
2914 ** FINIS -- Clean up and exit.
2917 ** drop -- whether or not to drop CurEnv envelope
2918 ** cleanup -- call exit() or _exit()?
2919 ** exitstat -- exit status to use for exit() call
2929 finis(drop
, cleanup
, exitstat
)
2932 volatile int exitstat
;
2934 char pidpath
[MAXPATHLEN
];
2937 /* Still want to process new timeouts added below */
2939 (void) sm_releasesignal(SIGALRM
);
2943 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2945 CurEnv
->e_id
== NULL
? "NOQUEUE" : CurEnv
->e_id
);
2946 printenvflags(CurEnv
);
2949 printopenfds(false);
2953 ** Clean up. This might raise E:mta.quickabort
2956 /* clean up temp files */
2957 CurEnv
->e_to
= NULL
;
2960 if (CurEnv
->e_id
!= NULL
)
2964 r
= dropenvelope(CurEnv
, true, false);
2965 if (exitstat
== EX_OK
)
2967 sm_rpool_free(CurEnv
->e_rpool
);
2968 CurEnv
->e_rpool
= NULL
;
2970 /* these may have pointed to the rpool */
2971 CurEnv
->e_to
= NULL
;
2972 CurEnv
->e_message
= NULL
;
2973 CurEnv
->e_statmsg
= NULL
;
2974 CurEnv
->e_quarmsg
= NULL
;
2975 CurEnv
->e_bodytype
= NULL
;
2976 CurEnv
->e_id
= NULL
;
2977 CurEnv
->e_envid
= NULL
;
2978 CurEnv
->e_auth_param
= NULL
;
2981 poststats(StatFile
);
2984 /* flush any cached connections */
2985 mci_flush(true, NULL
);
2987 /* close maps belonging to this pid */
2991 /* close UserDatabase */
3000 /* clean up extended load average stuff */
3010 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
, "finis, pid=%d",
3012 if (exitstat
== EX_TEMPFAIL
||
3013 CurEnv
->e_errormode
== EM_BERKNET
)
3016 /* XXX clean up queues and related data structures */
3020 cleanup_shm(DaemonPid
== pid
);
3021 #endif /* SM_CONF_SHM */
3023 /* close locked pid file */
3024 close_sendmail_pid();
3026 if (DaemonPid
== pid
|| PidFilePid
== pid
)
3028 /* blow away the pid file */
3029 expand(PidFile
, pidpath
, sizeof(pidpath
), CurEnv
);
3030 (void) unlink(pidpath
);
3033 /* reset uid for process accounting */
3035 sm_mbdb_terminate();
3037 (void) sm_memstat_close();
3038 #endif /* _FFR_MEMSTAT */
3039 (void) setuid(RealUid
);
3041 /* dump the heap, if we are checking for memory leaks */
3042 if (sm_debug_active(&SmHeapCheck
, 2))
3043 sm_heap_report(smioout
,
3044 sm_debug_level(&SmHeapCheck
) - 1);
3045 #endif /* SM_HEAP_CHECK */
3046 if (sm_debug_active(&SmXtrapReport
, 1))
3047 sm_dprintf("xtrap count = %d\n", SmXtrapCount
);
3055 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
3058 ** sig -- incoming signal.
3064 ** longjmps back to test mode loop.
3066 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3067 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3071 /* Type of an exception generated on SIGINT during address test mode. */
3072 static const SM_EXC_TYPE_T EtypeInterrupt
=
3086 int save_errno
= errno
;
3088 FIX_SYSV_SIGNAL(sig
, intindebug
);
3090 CHECK_CRITICAL(sig
);
3092 sm_exc_raisenew_x(&EtypeInterrupt
);
3094 return SIGFUNC_RETURN
;
3097 ** SIGTERM -- SIGTERM handler for the daemon
3100 ** sig -- signal number.
3106 ** Sets ShutdownRequest which will hopefully trigger
3107 ** the daemon to exit.
3109 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3110 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3119 int save_errno
= errno
;
3121 FIX_SYSV_SIGNAL(sig
, sigterm
);
3122 ShutdownRequest
= "signal";
3124 return SIGFUNC_RETURN
;
3127 ** SIGHUP -- handle a SIGHUP signal
3130 ** sig -- incoming signal.
3136 ** Sets RestartRequest which should cause the daemon
3139 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3140 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3149 int save_errno
= errno
;
3151 FIX_SYSV_SIGNAL(sig
, sighup
);
3152 RestartRequest
= "signal";
3154 return SIGFUNC_RETURN
;
3157 ** SIGPIPE -- signal handler for SIGPIPE
3160 ** sig -- incoming signal.
3166 ** Sets StopRequest which should cause the mailq/hoststatus
3169 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3170 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3179 int save_errno
= errno
;
3181 FIX_SYSV_SIGNAL(sig
, sigpipe
);
3184 return SIGFUNC_RETURN
;
3187 ** INTSIG -- clean up on interrupt
3189 ** This just arranges to exit. It pessimizes in that it
3190 ** may resend a message.
3199 ** Unlocks the current job.
3201 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3202 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3205 ** XXX: More work is needed for this signal handler.
3214 int save_errno
= errno
;
3216 FIX_SYSV_SIGNAL(sig
, intsig
);
3218 CHECK_CRITICAL(sig
);
3219 sm_allsignals(true);
3221 if (sig
!= 0 && LogLevel
> 79)
3222 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
, "interrupt");
3225 /* Clean-up on aborted stdin message submission */
3226 if (CurEnv
->e_id
!= NULL
&&
3227 (OpMode
== MD_SMTP
||
3228 OpMode
== MD_DELIVER
||
3229 OpMode
== MD_ARPAFTP
))
3231 register ADDRESS
*q
;
3233 /* don't return an error indication */
3234 CurEnv
->e_to
= NULL
;
3235 CurEnv
->e_flags
&= ~EF_FATALERRS
;
3236 CurEnv
->e_flags
|= EF_CLRQUEUE
;
3239 ** Spin through the addresses and
3240 ** mark them dead to prevent bounces
3243 for (q
= CurEnv
->e_sendqueue
; q
!= NULL
; q
= q
->q_next
)
3244 q
->q_state
= QS_DONTSEND
;
3248 else if (OpMode
!= MD_TEST
)
3250 unlockqueue(CurEnv
);
3253 finis(drop
, false, EX_OK
);
3257 ** DISCONNECT -- remove our connection with any foreground process
3260 ** droplev -- how "deeply" we should drop the line.
3261 ** 0 -- ignore signals, mail back errors, make sure
3262 ** output goes to stdout.
3263 ** 1 -- also, make stdout go to /dev/null.
3264 ** 2 -- also, disconnect from controlling terminal
3265 ** (only for daemon mode).
3266 ** e -- the current envelope.
3272 ** Trys to insure that we are immune to vagaries of
3273 ** the controlling tty.
3277 disconnect(droplev
, e
)
3279 register ENVELOPE
*e
;
3284 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3285 sm_io_getinfo(InChannel
, SM_IO_WHAT_FD
, NULL
),
3286 sm_io_getinfo(OutChannel
, SM_IO_WHAT_FD
, NULL
), e
);
3289 sm_dprintf("don't\n");
3293 sm_syslog(LOG_DEBUG
, e
->e_id
,
3294 "disconnect level %d",
3297 /* be sure we don't get nasty signals */
3298 (void) sm_signal(SIGINT
, SIG_IGN
);
3299 (void) sm_signal(SIGQUIT
, SIG_IGN
);
3301 /* we can't communicate with our caller, so.... */
3303 CurEnv
->e_errormode
= EM_MAIL
;
3305 DisConnected
= true;
3307 /* all input from /dev/null */
3308 if (InChannel
!= smioin
)
3310 (void) sm_io_close(InChannel
, SM_TIME_DEFAULT
);
3313 if (sm_io_reopen(SmFtStdio
, SM_TIME_DEFAULT
, SM_PATH_DEVNULL
,
3314 SM_IO_RDONLY
, NULL
, smioin
) == NULL
)
3315 sm_syslog(LOG_ERR
, e
->e_id
,
3316 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3317 SM_PATH_DEVNULL
, sm_errstring(errno
));
3320 ** output to the transcript
3321 ** We also compare the fd numbers here since OutChannel
3322 ** might be a layer on top of smioout due to encryption
3326 if (OutChannel
!= smioout
&&
3327 sm_io_getinfo(OutChannel
, SM_IO_WHAT_FD
, NULL
) !=
3328 sm_io_getinfo(smioout
, SM_IO_WHAT_FD
, NULL
))
3330 (void) sm_io_close(OutChannel
, SM_TIME_DEFAULT
);
3331 OutChannel
= smioout
;
3335 ** Has smioout been closed? Reopen it.
3336 ** This shouldn't happen anymore, the code is here
3337 ** just as a reminder.
3340 if (smioout
->sm_magic
== NULL
&&
3341 sm_io_reopen(SmFtStdio
, SM_TIME_DEFAULT
, SM_PATH_DEVNULL
,
3342 SM_IO_WRONLY
, NULL
, smioout
) == NULL
)
3343 sm_syslog(LOG_ERR
, e
->e_id
,
3344 "disconnect: sm_io_reopen(\"%s\") failed: %s",
3345 SM_PATH_DEVNULL
, sm_errstring(errno
));
3350 fd
= open(SM_PATH_DEVNULL
, O_WRONLY
, 0666);
3353 sm_syslog(LOG_ERR
, e
->e_id
,
3354 "disconnect: open(\"%s\") failed: %s",
3355 SM_PATH_DEVNULL
, sm_errstring(errno
));
3357 (void) sm_io_flush(smioout
, SM_TIME_DEFAULT
);
3360 (void) dup2(fd
, STDOUT_FILENO
);
3361 (void) dup2(fd
, STDERR_FILENO
);
3366 /* drop our controlling TTY completely if possible */
3374 checkfd012("disconnect");
3378 sm_syslog(LOG_DEBUG
, e
->e_id
, "in background, pid=%d",
3391 while ((ap
= *++argv
) != NULL
)
3393 /* Return if "--" or not an option of any form. */
3394 if (ap
[0] != '-' || ap
[1] == '-')
3397 /* Don't allow users to use "-Q." or "-Q ." */
3398 if ((ap
[1] == 'Q' && ap
[2] == '.') ||
3399 (ap
[1] == 'Q' && argv
[1] != NULL
&&
3400 argv
[1][0] == '.' && argv
[1][1] == '\0'))
3402 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
3403 "Can not use -Q.\n");
3407 /* skip over options that do have a value */
3408 op
= strchr(OPTIONS
, ap
[1]);
3409 if (op
!= NULL
&& *++op
== ':' && ap
[2] == '\0' &&
3411 #if defined(sony_news)
3412 ap
[1] != 'E' && ap
[1] != 'J' &&
3413 #endif /* defined(sony_news) */
3414 argv
[1] != NULL
&& argv
[1][0] != '-')
3420 /* If -C doesn't have an argument, use sendmail.cf. */
3421 #define __DEFPATH "sendmail.cf"
3422 if (ap
[1] == 'C' && ap
[2] == '\0')
3424 *argv
= xalloc(sizeof(__DEFPATH
) + 2);
3425 (void) sm_strlcpyn(argv
[0], sizeof(__DEFPATH
) + 2, 2,
3429 /* If -q doesn't have an argument, run it once. */
3430 if (ap
[1] == 'q' && ap
[2] == '\0')
3433 /* If -Q doesn't have an argument, disable quarantining */
3434 if (ap
[1] == 'Q' && ap
[2] == '\0')
3437 /* if -d doesn't have an argument, use 0-99.1 */
3438 if (ap
[1] == 'd' && ap
[2] == '\0')
3441 #if defined(sony_news)
3442 /* if -E doesn't have an argument, use -EC */
3443 if (ap
[1] == 'E' && ap
[2] == '\0')
3446 /* if -J doesn't have an argument, use -JJ */
3447 if (ap
[1] == 'J' && ap
[2] == '\0')
3449 #endif /* defined(sony_news) */
3453 ** AUTH_WARNING -- specify authorization warning
3456 ** e -- the current envelope.
3457 ** msg -- the text of the message.
3458 ** args -- arguments to the message.
3466 auth_warning(register ENVELOPE
*e
, const char *msg
, ...)
3467 #else /* __STDC__ */
3468 auth_warning(e
, msg
, va_alist
)
3469 register ENVELOPE
*e
;
3472 #endif /* __STDC__ */
3477 if (bitset(PRIV_AUTHWARNINGS
, PrivacyFlags
))
3480 static char hostbuf
[48];
3482 if (hostbuf
[0] == '\0')
3486 hp
= myhostname(hostbuf
, sizeof(hostbuf
));
3493 #endif /* NETINET6 */
3496 (void) sm_strlcpyn(buf
, sizeof(buf
), 2, hostbuf
, ": ");
3497 p
= &buf
[strlen(buf
)];
3498 SM_VA_START(ap
, msg
);
3499 (void) sm_vsnprintf(p
, SPACELEFT(buf
, p
), msg
, ap
);
3501 addheader("X-Authentication-Warning", buf
, 0, e
, true);
3503 sm_syslog(LOG_INFO
, e
->e_id
,
3504 "Authentication-Warning: %.400s",
3509 ** GETEXTENV -- get from external environment
3512 ** envar -- the name of the variable to retrieve
3515 ** The value, if any.
3526 for (envp
= ExternalEnviron
; envp
!= NULL
&& *envp
!= NULL
; envp
++)
3528 if (strncmp(*envp
, envar
, l
) == 0 && (*envp
)[l
] == '=')
3529 return &(*envp
)[l
+ 1];
3534 ** SM_SETUSERENV -- set an environment variable in the propagated environment
3537 ** envar -- the name of the environment variable.
3538 ** value -- the value to which it should be set. If
3539 ** null, this is extracted from the incoming
3540 ** environment. If that is not set, the call
3541 ** to sm_setuserenv is ignored.
3548 sm_setuserenv(envar
, value
)
3553 char **evp
= UserEnviron
;
3558 value
= getextenv(envar
);
3563 /* XXX enforce reasonable size? */
3564 i
= strlen(envar
) + 1;
3565 l
= strlen(value
) + i
+ 1;
3566 p
= (char *) xalloc(l
);
3567 (void) sm_strlcpyn(p
, l
, 3, envar
, "=", value
);
3569 while (*evp
!= NULL
&& strncmp(*evp
, p
, i
) != 0)
3575 else if (evp
< &UserEnviron
[MAXUSERENVIRON
])
3581 /* make sure it is in our environment as well */
3583 syserr("sm_setuserenv: putenv(%s) failed", p
);
3586 ** DUMPSTATE -- dump state
3595 register char *j
= macvalue('j', CurEnv
);
3597 extern int NextMacroId
;
3599 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
,
3600 "--- dumping state on %s: $j = %s ---",
3602 j
== NULL
? "<NULL>" : j
);
3605 if (!wordinclass(j
, 'w'))
3606 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
,
3607 "*** $j not in $=w ***");
3609 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
, "CurChildren = %d", CurChildren
);
3610 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
, "NextMacroId = %d (Max %d)",
3611 NextMacroId
, MAXMACROID
);
3612 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
, "--- open file descriptors: ---");
3614 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
, "--- connection cache: ---");
3615 mci_dump_all(smioout
, true);
3616 rs
= strtorwset("debug_dumpstate", NULL
, ST_FIND
);
3620 register char **pvp
;
3621 char *pv
[MAXATOM
+ 1];
3624 status
= REWRITE(pv
, rs
, CurEnv
);
3625 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
,
3626 "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3628 for (pvp
= pv
; *pvp
!= NULL
; pvp
++)
3629 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
, "%s", *pvp
);
3631 sm_syslog(LOG_DEBUG
, CurEnv
->e_id
, "--- end of state dump ---");
3636 ** SIGUSR1 -- Signal a request to dump state.
3639 ** sig -- calling signal.
3644 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3645 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3648 ** XXX: More work is needed for this signal handler.
3656 int save_errno
= errno
;
3658 FIX_SYSV_SIGNAL(sig
, sigusr1
);
3660 CHECK_CRITICAL(sig
);
3661 dumpstate("user signal");
3664 # endif /* SM_HEAP_CHECK */
3666 return SIGFUNC_RETURN
;
3668 #endif /* SIGUSR1 */
3671 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3674 ** to_real_uid -- if set, drop to the real uid instead
3675 ** of the RunAsUser.
3678 ** EX_OSERR if the setuid failed.
3683 drop_privileges(to_real_uid
)
3687 GIDSET_T emptygidset
[1];
3690 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",
3692 (int) RealUid
, (int) RealGid
,
3693 (int) getuid(), (int) getgid(),
3694 (int) geteuid(), (int) getegid(),
3695 (int) RunAsUid
, (int) RunAsGid
);
3699 RunAsUserName
= RealUserName
;
3705 /* make sure no one can grab open descriptors for secret files */
3707 sm_mbdb_terminate();
3709 /* reset group permissions; these can be set later */
3710 emptygidset
[0] = (to_real_uid
|| RunAsGid
!= 0) ? RunAsGid
: getegid();
3713 ** Notice: on some OS (Linux...) the setgroups() call causes
3714 ** a logfile entry if sendmail is not run by root.
3715 ** However, it is unclear (no POSIX standard) whether
3716 ** setgroups() can only succeed if executed by root.
3717 ** So for now we keep it as it is; if you want to change it, use
3718 ** if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3721 if (setgroups(1, emptygidset
) == -1 && geteuid() == 0)
3723 syserr("drop_privileges: setgroups(1, %d) failed",
3724 (int) emptygidset
[0]);
3728 /* reset primary group id */
3732 ** Drop gid to real gid.
3733 ** On some OS we must reset the effective[/real[/saved]] gid,
3734 ** and then use setgid() to finally drop all group privileges.
3735 ** Later on we check whether we can get back the
3740 if (setegid(RunAsGid
) < 0)
3742 syserr("drop_privileges: setegid(%d) failed",
3746 #else /* HASSETEGID */
3748 if (setregid(RunAsGid
, RunAsGid
) < 0)
3750 syserr("drop_privileges: setregid(%d, %d) failed",
3751 (int) RunAsGid
, (int) RunAsGid
);
3754 # else /* HASSETREGID */
3756 if (setresgid(RunAsGid
, RunAsGid
, RunAsGid
) < 0)
3758 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3759 (int) RunAsGid
, (int) RunAsGid
, (int) RunAsGid
);
3762 # endif /* HASSETRESGID */
3763 # endif /* HASSETREGID */
3764 #endif /* HASSETEGID */
3766 if (rval
== EX_OK
&& (to_real_uid
|| RunAsGid
!= 0))
3768 if (setgid(RunAsGid
) < 0 && (!UseMSP
|| getegid() != RunAsGid
))
3770 syserr("drop_privileges: setgid(%d) failed",
3775 if (rval
== EX_OK
&& getegid() != RunAsGid
)
3777 syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3778 (int) getegid(), (int) RunAsGid
);
3783 /* fiddle with uid */
3784 if (to_real_uid
|| RunAsUid
!= 0)
3789 ** Try to setuid(RunAsUid).
3790 ** euid must be RunAsUid,
3791 ** ruid must be RunAsUid unless (e|r)uid wasn't 0
3792 ** and we didn't have to drop privileges to the real uid.
3795 if (setuid(RunAsUid
) < 0 ||
3796 geteuid() != RunAsUid
||
3797 (getuid() != RunAsUid
&&
3798 (to_real_uid
|| geteuid() == 0 || getuid() == 0)))
3802 ** if ruid != RunAsUid, euid == RunAsUid, then
3803 ** try resetting just the real uid, then using
3804 ** setuid() to drop the saved-uid as well.
3807 if (geteuid() == RunAsUid
)
3809 if (setreuid(RunAsUid
, -1) < 0)
3811 syserr("drop_privileges: setreuid(%d, -1) failed",
3815 if (setuid(RunAsUid
) < 0)
3817 syserr("drop_privileges: second setuid(%d) attempt failed",
3823 #endif /* HASSETREUID */
3825 syserr("drop_privileges: setuid(%d) failed",
3831 if (RunAsUid
!= 0 && setuid(0) == 0)
3834 ** Believe it or not, the Linux capability model
3835 ** allows a non-root process to override setuid()
3836 ** on a process running as root and prevent that
3837 ** process from dropping privileges.
3840 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3843 else if (RunAsUid
!= euid
&& setuid(euid
) == 0)
3846 ** Some operating systems will keep the saved-uid
3847 ** if a non-root effective-uid calls setuid(real-uid)
3848 ** making it possible to set it back again later.
3851 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3856 if ((to_real_uid
|| RunAsGid
!= 0) &&
3857 rval
== EX_OK
&& RunAsGid
!= EffGid
&&
3858 getuid() != 0 && geteuid() != 0)
3861 if (setgid(EffGid
) == 0)
3863 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3871 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3872 (int) geteuid(), (int) getuid(),
3873 (int) getegid(), (int) getgid());
3874 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3875 (int) RunAsUid
, (int) RunAsGid
);
3877 sm_dprintf("drop_privileges: rval = %d\n", rval
);
3882 ** FILL_FD -- make sure a file descriptor has been properly allocated
3884 ** Used to make sure that stdin/out/err are allocated on startup
3887 ** fd -- the file descriptor to be filled.
3888 ** where -- a string used for logging. If NULL, this is
3889 ** being called on startup, and logging should
3896 ** possibly changes MissingFds
3907 if (fstat(fd
, &stbuf
) >= 0 || errno
!= EBADF
)
3911 syserr("fill_fd: %s: fd %d not open", where
, fd
);
3913 MissingFds
|= 1 << fd
;
3914 i
= open(SM_PATH_DEVNULL
, fd
== 0 ? O_RDONLY
: O_WRONLY
, 0666);
3917 syserr("!fill_fd: %s: cannot open %s",
3918 where
== NULL
? "startup" : where
, SM_PATH_DEVNULL
);
3927 ** SM_PRINTOPTIONS -- print options
3930 ** options -- array of options.
3937 sm_printoptions(options
)
3947 if (ll
+ strlen(*av
) > 63)
3956 sm_dprintf("%s", *av
);
3957 ll
+= strlen(*av
++) + 1;
3963 ** TO8BIT -- convert \octal sequences in a test mode input line
3966 ** str -- the input line.
3972 ** replaces \0octal in str with octal value.
3975 static bool to8bit
__P((char *));
3990 while ((c
= (*str
++ & 0377)) != '\0')
3996 (nxtc
= (*str
& 0377)) == '0')
3999 while ((nxtc
= (*str
& 0377)) != '\0' &&
4000 isascii(nxtc
) && isdigit(nxtc
))
4017 q
= quote_internal_chars(in
, in
, &len
);
4019 sm_strlcpy(in
, q
, len
);
4025 ** TESTMODELINE -- process a test mode input line
4028 ** line -- the input line.
4029 ** e -- the current environment.
4032 ** .X process X as a configuration line
4033 ** =X dump a configuration item (such as mailers)
4034 ** $X dump a macro or class
4035 ** /X try an activity
4036 ** X normal process through rule set X
4040 testmodeline(line
, e
)
4046 auto char *delimptr
;
4055 static int tryflags
= RF_COPYNONE
;
4056 char exbuf
[MAXLINE
];
4058 extern unsigned char TokTypeNoC
[];
4061 /* skip leading spaces */
4062 while (*line
== ' ')
4077 case '.': /* config-style settings */
4081 mid
= macid_parse(&line
[2], &delimptr
);
4085 lbp
= translate_dollars(delimptr
, lbuf
, &lbs
);
4086 macdefine(&e
->e_macro
, A_TEMP
, mid
, lbp
);
4092 if (line
[2] == '\0') /* not to call syserr() */
4095 mid
= macid_parse(&line
[2], &delimptr
);
4099 lbp
= translate_dollars(delimptr
, lbuf
, &lbs
);
4100 expand(lbp
, exbuf
, sizeof(exbuf
), e
);
4109 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
4112 while (*p
!= '\0' && !(isascii(*p
) && isspace(*p
)))
4123 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4124 "Usage: .[DC]macro value(s)\n");
4128 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4129 "Unknown \".\" command %s\n", line
);
4134 case '=': /* config-style settings */
4137 case 'S': /* dump rule set */
4138 rs
= strtorwset(&line
[2], NULL
, ST_FIND
);
4141 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4142 "Undefined ruleset %s\n", &line
[2]);
4145 rw
= RewriteRules
[rs
];
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 (void) sm_io_putc(smioout
, SM_TIME_DEFAULT
,
4166 xputs(smioout
, *s
++);
4167 (void) sm_io_putc(smioout
,
4168 SM_TIME_DEFAULT
, ' ');
4170 (void) sm_io_putc(smioout
, SM_TIME_DEFAULT
,
4172 } while ((rw
= rw
->r_next
) != NULL
);
4176 for (i
= 0; i
< MAXMAILERS
; i
++)
4178 if (Mailer
[i
] != NULL
)
4179 printmailer(smioout
, Mailer
[i
]);
4184 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4185 "Usage: =Sruleset or =M\n");
4189 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4190 "Unknown \"=\" command %s\n", line
);
4195 case '-': /* set command-line-like opts */
4203 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4204 "Usage: -d{debug arguments}\n");
4208 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4209 "Unknown \"-\" command %s\n", line
);
4217 mid
= macid(&line
[2]);
4219 stabapply(dump_class
, mid
);
4222 mid
= macid(&line
[1]);
4225 p
= macvalue(mid
, e
);
4227 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4232 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4237 case '/': /* miscellaneous commands */
4238 p
= &line
[strlen(line
)];
4239 while (--p
>= line
&& isascii(*p
) && isspace(*p
))
4241 p
= strpbrk(line
, " \t");
4244 while (isascii(*p
) && isspace(*p
))
4249 if (line
[1] == '\0')
4251 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4252 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4255 if (sm_strcasecmp(&line
[1], "quit") == 0)
4257 CurEnv
->e_id
= NULL
;
4258 finis(true, true, ExitStat
);
4261 if (sm_strcasecmp(&line
[1], "mx") == 0)
4264 /* look up MX records */
4267 char *mxhosts
[MAXMXHOSTS
+ 1];
4271 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4272 "Usage: /mx address\n");
4275 nmx
= getmxrr(p
, mxhosts
, NULL
, false, &rcode
, true,
4277 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4278 "getmxrr(%s) returns %d value(s):\n",
4280 for (i
= 0; i
< nmx
; i
++)
4281 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4282 "\t%s\n", mxhosts
[i
]);
4283 #else /* NAMED_BIND */
4284 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4285 "No MX code compiled in\n");
4286 #endif /* NAMED_BIND */
4288 else if (sm_strcasecmp(&line
[1], "canon") == 0)
4290 char host
[MAXHOSTNAMELEN
];
4294 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4295 "Usage: /canon address\n");
4298 else if (sm_strlcpy(host
, p
, sizeof(host
)) >= sizeof(host
))
4300 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4304 (void) getcanonname(host
, sizeof(host
), !HasWildcardMX
,
4306 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4307 "getcanonname(%s) returns %s\n",
4310 else if (sm_strcasecmp(&line
[1], "map") == 0)
4312 auto int rcode
= EX_OK
;
4317 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4318 "Usage: /map mapname key\n");
4321 for (q
= p
; *q
!= '\0' && !(isascii(*q
) && isspace(*q
)); q
++)
4325 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4326 "No key specified\n");
4330 map
= stab(p
, ST_MAP
, ST_FIND
);
4333 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4334 "Map named \"%s\" not found\n", p
);
4337 if (!bitset(MF_OPEN
, map
->s_map
.map_mflags
) &&
4338 !openmap(&(map
->s_map
)))
4340 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4341 "Map named \"%s\" not open\n", p
);
4344 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4345 "map_lookup: %s (%s) ", p
, q
);
4348 p
= (*map
->s_map
.map_class
->map_lookup
)
4349 (&map
->s_map
, q
, av
, &rcode
);
4351 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4355 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4356 "returns %s (%d)\n", p
,
4359 else if (sm_strcasecmp(&line
[1], "try") == 0)
4363 auto int rcode
= EX_OK
;
4365 q
= strpbrk(p
, " \t");
4368 while (isascii(*q
) && isspace(*q
))
4371 if (q
== NULL
|| *q
== '\0')
4373 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4374 "Usage: /try mailer address\n");
4377 st
= stab(p
, ST_MAILER
, ST_FIND
);
4380 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4381 "Unknown mailer %s\n", p
);
4385 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4386 "Trying %s %s address %s for mailer %s\n",
4387 bitset(RF_HEADERADDR
, tryflags
) ? "header"
4389 bitset(RF_SENDERADDR
, tryflags
) ? "sender"
4390 : "recipient", q
, p
);
4391 p
= remotename(q
, m
, tryflags
, &rcode
, CurEnv
);
4392 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4393 "Rcode = %d, addr = %s\n",
4394 rcode
, p
== NULL
? "<NULL>" : p
);
4397 else if (sm_strcasecmp(&line
[1], "tryflags") == 0)
4401 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4402 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4405 for (; *p
!= '\0'; p
++)
4411 tryflags
|= RF_HEADERADDR
;
4416 tryflags
&= ~RF_HEADERADDR
;
4421 tryflags
|= RF_SENDERADDR
;
4426 tryflags
&= ~RF_SENDERADDR
;
4430 exbuf
[0] = bitset(RF_HEADERADDR
, tryflags
) ? 'h' : 'e';
4432 exbuf
[2] = bitset(RF_SENDERADDR
, tryflags
) ? 's' : 'r';
4434 macdefine(&e
->e_macro
, A_TEMP
,
4435 macid("{addr_type}"), exbuf
);
4437 else if (sm_strcasecmp(&line
[1], "parse") == 0)
4441 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4442 "Usage: /parse address\n");
4445 q
= crackaddr(p
, e
);
4446 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4447 "Cracked address = ");
4449 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4450 "\nParsing %s %s address\n",
4451 bitset(RF_HEADERADDR
, tryflags
) ?
4452 "header" : "envelope",
4453 bitset(RF_SENDERADDR
, tryflags
) ?
4454 "sender" : "recipient");
4455 if (parseaddr(p
, &a
, tryflags
, '\0', NULL
, e
, true)
4457 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4459 else if (a
.q_host
!= NULL
&& a
.q_host
[0] != '\0')
4460 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4461 "mailer %s, host %s, user %s\n",
4466 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4467 "mailer %s, user %s\n",
4472 else if (sm_strcasecmp(&line
[1], "header") == 0)
4476 ul
= chompheader(p
, CHHDR_CHECK
|CHHDR_USER
, NULL
, e
);
4477 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4482 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4483 "Unknown \"/\" command %s\n",
4486 (void) sm_io_flush(smioout
, SM_TIME_DEFAULT
);
4490 for (p
= line
; isascii(*p
) && isspace(*p
); p
++)
4493 while (*p
!= '\0' && !(isascii(*p
) && isspace(*p
)))
4497 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4503 eightbit
= to8bit(p
+ 1);
4504 if (invalidaddr(p
+ 1, NULL
, true))
4508 register char **pvp
;
4509 char pvpbuf
[PSBUFSIZE
];
4511 pvp
= prescan(++p
, ',', pvpbuf
, sizeof(pvpbuf
), &delimptr
,
4512 ConfigLevel
>= 9 ? TokTypeNoC
: ExtTokenTab
, false);
4520 rs
= strtorwset(p
, NULL
, ST_FIND
);
4523 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4524 "Undefined ruleset %s\n",
4528 status
= REWRITE(pvp
, rs
, e
);
4529 if (status
!= EX_OK
)
4530 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4531 "== Ruleset %s (%d) status %d\n",
4535 cataddr(pvp
, NULL
, exbuf
, sizeof(exbuf
), '\0',
4537 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4541 while (*p
!= '\0' && *p
++ != ',')
4544 } while (*(p
= delimptr
) != '\0');
4545 (void) sm_io_flush(smioout
, SM_TIME_DEFAULT
);
4553 if (s
->s_symtype
!= ST_CLASS
)
4555 if (bitnset(bitidx(id
), s
->s_class
))
4556 (void) sm_io_fprintf(smioout
, SM_TIME_DEFAULT
,
4561 ** An exception type used to create QuickAbort exceptions.
4562 ** This is my first cut at converting QuickAbort from longjmp to exceptions.
4563 ** These exceptions have a single integer argument, which is the argument
4564 ** to longjmp in the original code (either 1 or 2). I don't know the
4565 ** significance of 1 vs 2: the calls to setjmp don't care.
4568 const SM_EXC_TYPE_T EtypeQuickAbort
=