main.c revision 95154
1/*
2 * Copyright (c) 1998-2002 Sendmail, Inc. and its suppliers.
3 *	All rights reserved.
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.
7 *
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.
11 *
12 */
13
14#define _DEFINE
15#include <sendmail.h>
16#include <sm/xtrap.h>
17#include <sm/signal.h>
18
19#ifndef lint
20SM_UNUSED(static char copyright[]) =
21"@(#) Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers.\n\
22	All rights reserved.\n\
23     Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.\n\
24     Copyright (c) 1988, 1993\n\
25	The Regents of the University of California.  All rights reserved.\n";
26#endif /* ! lint */
27
28SM_RCSID("@(#)$Id: main.c,v 1.1.1.11 2002/04/10 03:04:49 gshapiro Exp $")
29
30
31#if NETINET || NETINET6
32# include <arpa/inet.h>
33#endif /* NETINET || NETINET6 */
34
35/* for getcfname() */
36#include <sendmail/pathnames.h>
37
38static SM_DEBUG_T
39DebugNoPRestart = SM_DEBUG_INITIALIZER("no_persistent_restart",
40	"@(#)$Debug: no_persistent_restart - don't restart, log only $");
41
42static void	dump_class __P((STAB *, int));
43static void	obsolete __P((char **));
44static void	testmodeline __P((char *, ENVELOPE *));
45static char	*getextenv __P((const char *));
46static void	sm_printoptions __P((char **));
47static SIGFUNC_DECL	intindebug __P((int));
48static SIGFUNC_DECL	sighup __P((int));
49static SIGFUNC_DECL	sigpipe __P((int));
50static SIGFUNC_DECL	sigterm __P((int));
51#ifdef SIGUSR1
52static SIGFUNC_DECL	sigusr1 __P((int));
53#endif /* SIGUSR1 */
54
55/*
56**  SENDMAIL -- Post mail to a set of destinations.
57**
58**	This is the basic mail router.  All user mail programs should
59**	call this routine to actually deliver mail.  Sendmail in
60**	turn calls a bunch of mail servers that do the real work of
61**	delivering the mail.
62**
63**	Sendmail is driven by settings read in from /etc/mail/sendmail.cf
64**	(read by readcf.c).
65**
66**	Usage:
67**		/usr/lib/sendmail [flags] addr ...
68**
69**		See the associated documentation for details.
70**
71**	Authors:
72**		Eric Allman, UCB/INGRES (until 10/81).
73**			     Britton-Lee, Inc., purveyors of fine
74**				database computers (11/81 - 10/88).
75**			     International Computer Science Institute
76**				(11/88 - 9/89).
77**			     UCB/Mammoth Project (10/89 - 7/95).
78**			     InReference, Inc. (8/95 - 1/97).
79**			     Sendmail, Inc. (1/98 - present).
80**		The support of the my employers is gratefully acknowledged.
81**			Few of them (Britton-Lee in particular) have had
82**			anything to gain from my involvement in this project.
83**
84**		Gregory Neil Shapiro,
85**			Worcester Polytechnic Institute	(until 3/98).
86**			Sendmail, Inc. (3/98 - present).
87**
88**		Claus Assmann,
89**			Sendmail, Inc. (12/98 - present).
90*/
91
92char		*FullName;	/* sender's full name */
93ENVELOPE	BlankEnvelope;	/* a "blank" envelope */
94static ENVELOPE	MainEnvelope;	/* the envelope around the basic letter */
95ADDRESS		NullAddress =	/* a null address */
96		{ "", "", NULL, "" };
97char		*CommandLineArgs;	/* command line args for pid file */
98bool		Warn_Q_option = false;	/* warn about Q option use */
99static int	MissingFds = 0;	/* bit map of fds missing on startup */
100char		*Mbdb = "pw";	/* mailbox database defaults to /etc/passwd */
101
102#ifdef NGROUPS_MAX
103GIDSET_T	InitialGidSet[NGROUPS_MAX];
104#endif /* NGROUPS_MAX */
105
106#define MAXCONFIGLEVEL	10	/* highest config version level known */
107
108#if SASL
109static sasl_callback_t srvcallbacks[] =
110{
111	{	SASL_CB_VERIFYFILE,	&safesaslfile,	NULL	},
112	{	SASL_CB_PROXY_POLICY,	&proxy_policy,	NULL	},
113	{	SASL_CB_LIST_END,	NULL,		NULL	}
114};
115#endif /* SASL */
116
117unsigned int	SubmitMode;
118int		SyslogPrefixLen; /* estimated length of syslog prefix */
119#define PIDLEN		6	/* pid length for computing SyslogPrefixLen */
120#ifndef SL_FUDGE
121# define SL_FUDGE	10	/* fudge offset for SyslogPrefixLen */
122#endif /* ! SL_FUDGE */
123#define SLDLL		8	/* est. length of default syslog label */
124
125
126/* Some options are dangerous to allow users to use in non-submit mode */
127#define CHECK_AGAINST_OPMODE(cmd)					\
128{									\
129	if (extraprivs &&						\
130	    OpMode != MD_DELIVER && OpMode != MD_SMTP &&		\
131	    OpMode != MD_VERIFY && OpMode != MD_TEST)			\
132	{								\
133		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,		\
134				     "WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \
135		       (cmd));						\
136		break;							\
137	}								\
138	if (extraprivs && queuerun)					\
139	{								\
140		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,		\
141				     "WARNING: Ignoring submission mode -%c option with -q\n", \
142		       (cmd));						\
143		break;							\
144	}								\
145}
146
147int
148main(argc, argv, envp)
149	int argc;
150	char **argv;
151	char **envp;
152{
153	register char *p;
154	char **av;
155	extern char Version[];
156	char *ep, *from;
157	STAB *st;
158	register int i;
159	int j;
160	int dp;
161	int fill_errno;
162	int qgrp = NOQGRP;		/* queue group to process */
163	bool safecf = true;
164	BITMAP256 *p_flags = NULL;	/* daemon flags */
165	bool warn_C_flag = false;
166	bool auth = true;		/* whether to set e_auth_param */
167	char warn_f_flag = '\0';
168	bool run_in_foreground = false;	/* -bD mode */
169	bool queuerun = false, debug = false;
170	struct passwd *pw;
171	struct hostent *hp;
172	char *nullserver = NULL;
173	char *authinfo = NULL;
174	char *sysloglabel = NULL;	/* label for syslog */
175	char *conffile = NULL;		/* name of .cf file */
176	char *queuegroup = NULL;	/* queue group to process */
177#if _FFR_QUARANTINE
178	char *quarantining = NULL;	/* quarantine queue items? */
179#endif /* _FFR_QUARANTINE */
180	bool extraprivs;
181	bool forged, negate;
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? */
186	static time_t starttime = 0;	/* when was process started */
187	struct stat traf_st;		/* for TrafficLog FIFO check */
188	char buf[MAXLINE];
189	char jbuf[MAXHOSTNAMELEN];	/* holds MyHostName */
190	static char rnamebuf[MAXNAME];	/* holds RealUserName */
191	char *emptyenviron[1];
192#if STARTTLS
193	bool tls_ok;
194#endif /* STARTTLS */
195	QUEUE_CHAR *new;
196	ENVELOPE *e;
197	extern int DtableSize;
198	extern int optind;
199	extern int opterr;
200	extern char *optarg;
201	extern char **environ;
202#if SASL
203	extern void sm_sasl_init __P((void));
204#endif /* SASL */
205
206#if USE_ENVIRON
207	envp = environ;
208#endif /* USE_ENVIRON */
209
210	/* turn off profiling */
211	SM_PROF(0);
212
213	/* install default exception handler */
214	sm_exc_newthread(fatal_error);
215
216	/*
217	**  Check to see if we reentered.
218	**	This would normally happen if e_putheader or e_putbody
219	**	were NULL when invoked.
220	*/
221
222	if (starttime != 0)
223	{
224		syserr("main: reentered!");
225		abort();
226	}
227	starttime = curtime();
228
229	/* avoid null pointer dereferences */
230	TermEscape.te_rv_on = TermEscape.te_rv_off = "";
231
232	RealUid = getuid();
233	RealGid = getgid();
234
235	/* Check if sendmail is running with extra privs */
236	extraprivs = (RealUid != 0 &&
237		      (geteuid() != getuid() || getegid() != getgid()));
238
239	CurrentPid = getpid();
240
241	/* get whatever .cf file is right for the opmode */
242	cftype = SM_GET_RIGHT_CF;
243
244	/* in 4.4BSD, the table can be huge; impose a reasonable limit */
245	DtableSize = getdtsize();
246	if (DtableSize > 256)
247		DtableSize = 256;
248
249	/*
250	**  Be sure we have enough file descriptors.
251	**	But also be sure that 0, 1, & 2 are open.
252	*/
253
254	/* reset errno and fill_errno; the latter is used way down below */
255	errno = fill_errno = 0;
256	fill_fd(STDIN_FILENO, NULL);
257	if (errno != 0)
258		fill_errno = errno;
259	fill_fd(STDOUT_FILENO, NULL);
260	if (errno != 0)
261		fill_errno = errno;
262	fill_fd(STDERR_FILENO, NULL);
263	if (errno != 0)
264		fill_errno = errno;
265
266	i = DtableSize;
267	while (--i > 0)
268	{
269		if (i != STDIN_FILENO && i != STDOUT_FILENO &&
270		    i != STDERR_FILENO)
271			(void) close(i);
272	}
273	errno = 0;
274
275#if LOG
276# ifndef SM_LOG_STR
277#  define SM_LOG_STR	"sendmail"
278# endif /* ! SM_LOG_STR */
279#  ifdef LOG_MAIL
280	openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
281#  else /* LOG_MAIL */
282	openlog(SM_LOG_STR, LOG_PID);
283#  endif /* LOG_MAIL */
284#endif /* LOG */
285
286	/*
287	**  Seed the random number generator.
288	**  Used for queue file names, picking a queue directory, and
289	**  MX randomization.
290	*/
291
292	seed_random();
293
294	/* do machine-dependent initializations */
295	init_md(argc, argv);
296
297
298	SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
299
300	/* reset status from syserr() calls for missing file descriptors */
301	Errors = 0;
302	ExitStat = EX_OK;
303
304	SubmitMode = SUBMIT_UNKNOWN;
305#if XDEBUG
306	checkfd012("after openlog");
307#endif /* XDEBUG */
308
309	tTsetup(tTdvect, sizeof tTdvect, "0-99.1,*_trace_*.1");
310
311#ifdef NGROUPS_MAX
312	/* save initial group set for future checks */
313	i = getgroups(NGROUPS_MAX, InitialGidSet);
314	if (i <= 0)
315	{
316		InitialGidSet[0] = (GID_T) -1;
317		i = 0;
318	}
319	while (i < NGROUPS_MAX)
320		InitialGidSet[i++] = InitialGidSet[0];
321#endif /* NGROUPS_MAX */
322
323	/* drop group id privileges (RunAsUser not yet set) */
324	dp = drop_privileges(false);
325	setstat(dp);
326
327#ifdef SIGUSR1
328	/* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
329	if (!extraprivs)
330	{
331		/* arrange to dump state on user-1 signal */
332		(void) sm_signal(SIGUSR1, sigusr1);
333	}
334	else
335	{
336		/* ignore user-1 signal */
337		(void) sm_signal(SIGUSR1, SIG_IGN);
338	}
339#endif /* SIGUSR1 */
340
341	/* initialize for setproctitle */
342	initsetproctitle(argc, argv, envp);
343
344	/* Handle any non-getoptable constructions. */
345	obsolete(argv);
346
347	/*
348	**  Do a quick prescan of the argument list.
349	*/
350
351
352	/* find initial opMode */
353	OpMode = MD_DELIVER;
354	av = argv;
355	p = strrchr(*av, '/');
356	if (p++ == NULL)
357		p = *av;
358	if (strcmp(p, "newaliases") == 0)
359		OpMode = MD_INITALIAS;
360	else if (strcmp(p, "mailq") == 0)
361		OpMode = MD_PRINT;
362	else if (strcmp(p, "smtpd") == 0)
363		OpMode = MD_DAEMON;
364	else if (strcmp(p, "hoststat") == 0)
365		OpMode = MD_HOSTSTAT;
366	else if (strcmp(p, "purgestat") == 0)
367		OpMode = MD_PURGESTAT;
368
369#if _FFR_QUARANTINE
370# if defined(__osf__) || defined(_AIX3)
371#  define OPTIONS	"A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:xQ:"
372# endif /* defined(__osf__) || defined(_AIX3) */
373# if defined(sony_news)
374#  define OPTIONS	"A:B:b:C:cd:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:q:R:r:sTtV:vX:Q:"
375# endif /* defined(sony_news) */
376# ifndef OPTIONS
377#  define OPTIONS	"A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:Q:"
378# endif /* ! OPTIONS */
379#else /* _FFR_QUARANTINE */
380# if defined(__osf__) || defined(_AIX3)
381#  define OPTIONS	"A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:x"
382# endif /* defined(__osf__) || defined(_AIX3) */
383# if defined(sony_news)
384#  define OPTIONS	"A:B:b:C:cd:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:q:R:r:sTtV:vX:"
385# endif /* defined(sony_news) */
386# ifndef OPTIONS
387#  define OPTIONS	"A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:"
388# endif /* ! OPTIONS */
389#endif /* _FFR_QUARANTINE */
390
391	opterr = 0;
392	while ((j = getopt(argc, argv, OPTIONS)) != -1)
393	{
394		switch (j)
395		{
396		  case 'b':	/* operations mode */
397			j = (optarg == NULL) ? ' ' : *optarg;
398			switch (j)
399			{
400			  case MD_DAEMON:
401			  case MD_FGDAEMON:
402			  case MD_SMTP:
403			  case MD_INITALIAS:
404			  case MD_DELIVER:
405			  case MD_VERIFY:
406			  case MD_TEST:
407			  case MD_PRINT:
408			  case MD_PRINTNQE:
409			  case MD_HOSTSTAT:
410			  case MD_PURGESTAT:
411			  case MD_ARPAFTP:
412				OpMode = j;
413				break;
414
415			  case MD_FREEZE:
416				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
417						     "Frozen configurations unsupported\n");
418				return EX_USAGE;
419
420			  default:
421				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
422						     "Invalid operation mode %c\n",
423						     j);
424				return EX_USAGE;
425			}
426			break;
427
428		  case 'd':
429			debug = true;
430			tTflag(optarg);
431			(void) sm_io_setvbuf(smioout, SM_TIME_DEFAULT,
432					     (char *) NULL, SM_IO_NBF,
433					     SM_IO_BUFSIZ);
434			break;
435
436		  case 'G':	/* relay (gateway) submission */
437			SubmitMode = SUBMIT_MTA;
438			break;
439
440		  case 'L':
441			j = SM_MIN(strlen(optarg), 24) + 1;
442			sysloglabel = xalloc(j);
443			(void) sm_strlcpy(sysloglabel, optarg, j);
444			SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
445					  SL_FUDGE + j;
446			break;
447
448#if _FFR_QUARANTINE
449		  case 'Q':
450#endif /* _FFR_QUARANTINE */
451		  case 'q':
452			/* just check if it is there */
453			queuerun = true;
454			break;
455		}
456	}
457	opterr = 1;
458
459	/* Don't leak queue information via debug flags */
460	if (extraprivs && queuerun && debug)
461	{
462		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
463				     "WARNING: Can not use -d with -q.  Disabling debugging.\n");
464		sm_debug_setfile(NULL);
465		(void) memset(tTdvect, '\0', sizeof tTdvect);
466	}
467
468#if LOG
469	if (sysloglabel != NULL)
470	{
471		/* Sanitize the string */
472		for (p = sysloglabel; *p != '\0'; p++)
473		{
474			if (!isascii(*p) || !isprint(*p) || *p == '%')
475				*p = '*';
476		}
477		closelog();
478#  ifdef LOG_MAIL
479		openlog(sysloglabel, LOG_PID, LOG_MAIL);
480#  else /* LOG_MAIL */
481		openlog(sysloglabel, LOG_PID);
482#  endif /* LOG_MAIL */
483	}
484#endif /* LOG */
485
486	/* set up the blank envelope */
487	BlankEnvelope.e_puthdr = putheader;
488	BlankEnvelope.e_putbody = putbody;
489	BlankEnvelope.e_xfp = NULL;
490	STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
491	CurEnv = &BlankEnvelope;
492	STRUCTCOPY(NullAddress, MainEnvelope.e_from);
493
494	/*
495	**  Set default values for variables.
496	**	These cannot be in initialized data space.
497	*/
498
499	setdefaults(&BlankEnvelope);
500	initmacros(&BlankEnvelope);
501
502	/* reset macro */
503	set_op_mode(OpMode);
504
505	pw = sm_getpwuid(RealUid);
506	if (pw != NULL)
507		(void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof rnamebuf);
508	else
509		(void) sm_snprintf(rnamebuf, sizeof rnamebuf, "Unknown UID %d",
510				   (int) RealUid);
511
512	RealUserName = rnamebuf;
513
514	if (tTd(0, 101))
515	{
516		sm_dprintf("Version %s\n", Version);
517		finis(false, true, EX_OK);
518		/* NOTREACHED */
519	}
520
521	/*
522	**  if running non-set-user-ID binary as non-root, pretend
523	**  we are the RunAsUid
524	*/
525
526	if (RealUid != 0 && geteuid() == RealUid)
527	{
528		if (tTd(47, 1))
529			sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
530				   (int) RealUid);
531		RunAsUid = RealUid;
532	}
533	else if (geteuid() != 0)
534		RunAsUid = geteuid();
535
536	EffGid = getegid();
537	if (RealUid != 0 && EffGid == RealGid)
538		RunAsGid = RealGid;
539
540	if (tTd(47, 5))
541	{
542		sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
543			   (int) geteuid(), (int) getuid(),
544			   (int) getegid(), (int) getgid());
545		sm_dprintf("main: RunAsUser = %d:%d\n",
546			   (int) RunAsUid, (int) RunAsGid);
547	}
548
549	/* save command line arguments */
550	j = 0;
551	for (av = argv; *av != NULL; )
552		j += strlen(*av++) + 1;
553	SaveArgv = (char **) xalloc(sizeof (char *) * (argc + 1));
554	CommandLineArgs = xalloc(j);
555	p = CommandLineArgs;
556	for (av = argv, i = 0; *av != NULL; )
557	{
558		int h;
559
560		SaveArgv[i++] = newstr(*av);
561		if (av != argv)
562			*p++ = ' ';
563		(void) sm_strlcpy(p, *av++, j);
564		h = strlen(p);
565		p += h;
566		j -= h + 1;
567	}
568	SaveArgv[i] = NULL;
569
570	if (tTd(0, 1))
571	{
572		extern char *CompileOptions[];
573
574		sm_dprintf("Version %s\n Compiled with:", Version);
575		sm_printoptions(CompileOptions);
576	}
577	if (tTd(0, 10))
578	{
579		extern char *OsCompileOptions[];
580
581		sm_dprintf("    OS Defines:");
582		sm_printoptions(OsCompileOptions);
583#ifdef _PATH_UNIX
584		sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
585#endif /* _PATH_UNIX */
586
587		sm_dprintf("     Conf file:\t%s (default for MSP)\n",
588			   getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
589				     conffile));
590		sm_dprintf("     Conf file:\t%s (default for MTA)\n",
591			   getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
592				     conffile));
593		sm_dprintf("      Pid file:\t%s (default)\n", PidFile);
594	}
595
596	if (tTd(0, 12))
597	{
598		extern char *SmCompileOptions[];
599
600		sm_dprintf(" libsm Defines:");
601		sm_printoptions(SmCompileOptions);
602	}
603
604	if (tTd(0, 13))
605	{
606		extern char *FFRCompileOptions[];
607
608		sm_dprintf("   FFR Defines:");
609		sm_printoptions(FFRCompileOptions);
610	}
611
612	InChannel = smioin;
613	OutChannel = smioout;
614
615	/* clear sendmail's environment */
616	ExternalEnviron = environ;
617	emptyenviron[0] = NULL;
618	environ = emptyenviron;
619
620	/*
621	**  restore any original TZ setting until TimeZoneSpec has been
622	**  determined - or early log messages may get bogus time stamps
623	*/
624
625	if ((p = getextenv("TZ")) != NULL)
626	{
627		char *tz;
628		int tzlen;
629
630		/* XXX check for reasonable length? */
631		tzlen = strlen(p) + 4;
632		tz = xalloc(tzlen);
633		(void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
634
635		/* XXX check return code? */
636		(void) putenv(tz);
637	}
638
639	/* prime the child environment */
640	setuserenv("AGENT", "sendmail");
641
642	(void) sm_signal(SIGPIPE, SIG_IGN);
643	OldUmask = umask(022);
644	FullName = getextenv("NAME");
645	if (FullName != NULL)
646		FullName = newstr(FullName);
647
648	/*
649	**  Initialize name server if it is going to be used.
650	*/
651
652#if NAMED_BIND
653	if (!bitset(RES_INIT, _res.options))
654		(void) res_init();
655	if (tTd(8, 8))
656		_res.options |= RES_DEBUG;
657	else
658		_res.options &= ~RES_DEBUG;
659# ifdef RES_NOALIASES
660	if (bitset(RES_NOALIASES, _res.options))
661		ResNoAliases = true;
662	_res.options |= RES_NOALIASES;
663# endif /* RES_NOALIASES */
664	TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
665	TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
666	TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
667	TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
668	TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
669	TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
670#endif /* NAMED_BIND */
671
672	errno = 0;
673	from = NULL;
674
675	/* initialize some macros, etc. */
676	init_vendor_macros(&BlankEnvelope);
677
678	/* version */
679	macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
680
681	/* hostname */
682	hp = myhostname(jbuf, sizeof jbuf);
683	if (jbuf[0] != '\0')
684	{
685		struct utsname utsname;
686
687		if (tTd(0, 4))
688			sm_dprintf("Canonical name: %s\n", jbuf);
689		macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
690		macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
691		setclass('w', jbuf);
692
693		p = strchr(jbuf, '.');
694		if (p != NULL)
695		{
696			if (p[1] != '\0')
697			{
698				macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm',
699					  &p[1]);
700			}
701			while (p != NULL && strchr(&p[1], '.') != NULL)
702			{
703				*p = '\0';
704				if (tTd(0, 4))
705					sm_dprintf("\ta.k.a.: %s\n", jbuf);
706				setclass('w', jbuf);
707				*p++ = '.';
708				p = strchr(p, '.');
709			}
710		}
711
712		if (uname(&utsname) >= 0)
713			p = utsname.nodename;
714		else
715		{
716			if (tTd(0, 22))
717				sm_dprintf("uname failed (%s)\n",
718					   sm_errstring(errno));
719			makelower(jbuf);
720			p = jbuf;
721		}
722		if (tTd(0, 4))
723			sm_dprintf(" UUCP nodename: %s\n", p);
724		macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
725		setclass('k', p);
726		setclass('w', p);
727	}
728	if (hp != NULL)
729	{
730		for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
731		{
732			if (tTd(0, 4))
733				sm_dprintf("\ta.k.a.: %s\n", *av);
734			setclass('w', *av);
735		}
736#if NETINET || NETINET6
737		for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
738		{
739# if NETINET6
740			char *addr;
741			char buf6[INET6_ADDRSTRLEN];
742			struct in6_addr ia6;
743# endif /* NETINET6 */
744# if NETINET
745			struct in_addr ia;
746# endif /* NETINET */
747			char ipbuf[103];
748
749			ipbuf[0] = '\0';
750			switch (hp->h_addrtype)
751			{
752# if NETINET
753			  case AF_INET:
754				if (hp->h_length != INADDRSZ)
755					break;
756
757				memmove(&ia, hp->h_addr_list[i], INADDRSZ);
758				(void) sm_snprintf(ipbuf, sizeof ipbuf,
759						   "[%.100s]", inet_ntoa(ia));
760				break;
761# endif /* NETINET */
762
763# if NETINET6
764			  case AF_INET6:
765				if (hp->h_length != IN6ADDRSZ)
766					break;
767
768				memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
769				addr = anynet_ntop(&ia6, buf6, sizeof buf6);
770				if (addr != NULL)
771					(void) sm_snprintf(ipbuf, sizeof ipbuf,
772							   "[%.100s]", addr);
773				break;
774# endif /* NETINET6 */
775			}
776			if (ipbuf[0] == '\0')
777				break;
778
779			if (tTd(0, 4))
780				sm_dprintf("\ta.k.a.: %s\n", ipbuf);
781			setclass('w', ipbuf);
782		}
783#endif /* NETINET || NETINET6 */
784#if NETINET6
785		freehostent(hp);
786		hp = NULL;
787#endif /* NETINET6 */
788	}
789
790	/* current time */
791	macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
792
793	/* current load average */
794	sm_getla();
795
796	QueueLimitRecipient = (QUEUE_CHAR *) NULL;
797	QueueLimitSender = (QUEUE_CHAR *) NULL;
798	QueueLimitId = (QUEUE_CHAR *) NULL;
799#if _FFR_QUARANTINE
800	QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
801#endif /* _FFR_QUARANTINE */
802
803	/*
804	**  Crack argv.
805	*/
806
807	optind = 1;
808	while ((j = getopt(argc, argv, OPTIONS)) != -1)
809	{
810		switch (j)
811		{
812		  case 'b':	/* operations mode */
813			/* already done */
814			break;
815
816		  case 'A':	/* use Alternate sendmail/submit.cf */
817			cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
818						  : SM_GET_SENDMAIL_CF;
819			break;
820
821		  case 'B':	/* body type */
822			CHECK_AGAINST_OPMODE(j);
823			BlankEnvelope.e_bodytype = newstr(optarg);
824			break;
825
826		  case 'C':	/* select configuration file (already done) */
827			if (RealUid != 0)
828				warn_C_flag = true;
829			conffile = newstr(optarg);
830			dp = drop_privileges(true);
831			setstat(dp);
832			safecf = false;
833			break;
834
835		  case 'd':	/* debugging */
836			/* already done */
837			break;
838
839		  case 'f':	/* from address */
840		  case 'r':	/* obsolete -f flag */
841			CHECK_AGAINST_OPMODE(j);
842			if (from != NULL)
843			{
844				usrerr("More than one \"from\" person");
845				ExitStat = EX_USAGE;
846				break;
847			}
848			from = newstr(denlstring(optarg, true, true));
849			if (strcmp(RealUserName, from) != 0)
850				warn_f_flag = j;
851			break;
852
853		  case 'F':	/* set full name */
854			CHECK_AGAINST_OPMODE(j);
855			FullName = newstr(optarg);
856			break;
857
858		  case 'G':	/* relay (gateway) submission */
859			/* already set */
860			CHECK_AGAINST_OPMODE(j);
861			break;
862
863		  case 'h':	/* hop count */
864			CHECK_AGAINST_OPMODE(j);
865			BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
866								  10);
867			(void) sm_snprintf(buf, sizeof buf, "%d",
868					   BlankEnvelope.e_hopcount);
869			macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
870
871			if (*ep)
872			{
873				usrerr("Bad hop count (%s)", optarg);
874				ExitStat = EX_USAGE;
875			}
876			break;
877
878		  case 'L':	/* program label */
879			/* already set */
880			break;
881
882		  case 'n':	/* don't alias */
883			CHECK_AGAINST_OPMODE(j);
884			NoAlias = true;
885			break;
886
887		  case 'N':	/* delivery status notifications */
888			CHECK_AGAINST_OPMODE(j);
889			DefaultNotify |= QHASNOTIFY;
890			macdefine(&BlankEnvelope.e_macro, A_TEMP,
891				macid("{dsn_notify}"), optarg);
892			if (sm_strcasecmp(optarg, "never") == 0)
893				break;
894			for (p = optarg; p != NULL; optarg = p)
895			{
896				p = strchr(p, ',');
897				if (p != NULL)
898					*p++ = '\0';
899				if (sm_strcasecmp(optarg, "success") == 0)
900					DefaultNotify |= QPINGONSUCCESS;
901				else if (sm_strcasecmp(optarg, "failure") == 0)
902					DefaultNotify |= QPINGONFAILURE;
903				else if (sm_strcasecmp(optarg, "delay") == 0)
904					DefaultNotify |= QPINGONDELAY;
905				else
906				{
907					usrerr("Invalid -N argument");
908					ExitStat = EX_USAGE;
909				}
910			}
911			break;
912
913		  case 'o':	/* set option */
914			setoption(*optarg, optarg + 1, false, true,
915				  &BlankEnvelope);
916			break;
917
918		  case 'O':	/* set option (long form) */
919			setoption(' ', optarg, false, true, &BlankEnvelope);
920			break;
921
922		  case 'p':	/* set protocol */
923			CHECK_AGAINST_OPMODE(j);
924			p = strchr(optarg, ':');
925			if (p != NULL)
926			{
927				*p++ = '\0';
928				if (*p != '\0')
929				{
930					ep = sm_malloc_x(strlen(p) + 1);
931					cleanstrcpy(ep, p, MAXNAME);
932					macdefine(&BlankEnvelope.e_macro,
933						  A_HEAP, 's', ep);
934				}
935			}
936			if (*optarg != '\0')
937			{
938				ep = sm_malloc_x(strlen(optarg) + 1);
939				cleanstrcpy(ep, optarg, MAXNAME);
940				macdefine(&BlankEnvelope.e_macro, A_HEAP,
941					  'r', ep);
942			}
943			break;
944
945#if _FFR_QUARANTINE
946		  case 'Q':	/* change quarantining on queued items */
947			/* sanity check */
948			if (OpMode != MD_DELIVER &&
949			    OpMode != MD_QUEUERUN)
950			{
951				usrerr("Can not use -Q with -b%c", OpMode);
952				ExitStat = EX_USAGE;
953				break;
954			}
955
956			if (OpMode == MD_DELIVER)
957				set_op_mode(MD_QUEUERUN);
958
959			FullName = NULL;
960
961			quarantining = newstr(optarg);
962			break;
963#endif /* _FFR_QUARANTINE */
964
965		  case 'q':	/* run queue files at intervals */
966			/* sanity check */
967			if (OpMode != MD_DELIVER &&
968			    OpMode != MD_DAEMON &&
969			    OpMode != MD_FGDAEMON &&
970			    OpMode != MD_PRINT &&
971			    OpMode != MD_PRINTNQE &&
972			    OpMode != MD_QUEUERUN)
973			{
974				usrerr("Can not use -q with -b%c", OpMode);
975				ExitStat = EX_USAGE;
976				break;
977			}
978
979			/* don't override -bd, -bD or -bp */
980			if (OpMode == MD_DELIVER)
981				set_op_mode(MD_QUEUERUN);
982
983			FullName = NULL;
984			negate = optarg[0] == '!';
985			if (negate)
986			{
987				/* negate meaning of pattern match */
988				optarg++; /* skip '!' for next switch */
989			}
990
991			switch (optarg[0])
992			{
993			  case 'G': /* Limit by queue group name */
994				if (negate)
995				{
996					usrerr("Can not use -q!G");
997					ExitStat = EX_USAGE;
998					break;
999				}
1000				if (queuegroup != NULL)
1001				{
1002					usrerr("Can not use multiple -qG options");
1003					ExitStat = EX_USAGE;
1004					break;
1005				}
1006				queuegroup = newstr(&optarg[1]);
1007				break;
1008
1009			  case 'I': /* Limit by ID */
1010				new = (QUEUE_CHAR *) xalloc(sizeof *new);
1011				new->queue_match = newstr(&optarg[1]);
1012				new->queue_negate = negate;
1013				new->queue_next = QueueLimitId;
1014				QueueLimitId = new;
1015				break;
1016
1017			  case 'R': /* Limit by recipient */
1018				new = (QUEUE_CHAR *) xalloc(sizeof *new);
1019				new->queue_match = newstr(&optarg[1]);
1020				new->queue_negate = negate;
1021				new->queue_next = QueueLimitRecipient;
1022				QueueLimitRecipient = new;
1023				break;
1024
1025			  case 'S': /* Limit by sender */
1026				new = (QUEUE_CHAR *) xalloc(sizeof *new);
1027				new->queue_match = newstr(&optarg[1]);
1028				new->queue_negate = negate;
1029				new->queue_next = QueueLimitSender;
1030				QueueLimitSender = new;
1031				break;
1032
1033			  case 'f': /* foreground queue run */
1034				foregroundqueue  = true;
1035				break;
1036
1037#if _FFR_QUARANTINE
1038			  case 'Q': /* Limit by quarantine message */
1039				if (optarg[1] != '\0')
1040				{
1041					new = (QUEUE_CHAR *) xalloc(sizeof *new);
1042					new->queue_match = newstr(&optarg[1]);
1043					new->queue_negate = negate;
1044					new->queue_next = QueueLimitQuarantine;
1045					QueueLimitQuarantine = new;
1046				}
1047				QueueMode = QM_QUARANTINE;
1048				break;
1049
1050			  case 'L': /* act on lost items */
1051				QueueMode = QM_LOST;
1052				break;
1053#endif /* _FFR_QUARANTINE */
1054
1055			  case 'p': /* Persistent queue */
1056				queuepersistent = true;
1057				if (QueueIntvl == 0)
1058					QueueIntvl = 1;
1059				if (optarg[1] == '\0')
1060					break;
1061				++optarg;
1062				/* FALLTHROUGH */
1063
1064			  default:
1065				i = Errors;
1066				QueueIntvl = convtime(optarg, 'm');
1067
1068				/* check for bad conversion */
1069				if (i < Errors)
1070					ExitStat = EX_USAGE;
1071				break;
1072			}
1073			break;
1074
1075		  case 'R':	/* DSN RET: what to return */
1076			CHECK_AGAINST_OPMODE(j);
1077			if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1078			{
1079				usrerr("Duplicate -R flag");
1080				ExitStat = EX_USAGE;
1081				break;
1082			}
1083			BlankEnvelope.e_flags |= EF_RET_PARAM;
1084			if (sm_strcasecmp(optarg, "hdrs") == 0)
1085				BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1086			else if (sm_strcasecmp(optarg, "full") != 0)
1087			{
1088				usrerr("Invalid -R value");
1089				ExitStat = EX_USAGE;
1090			}
1091			macdefine(&BlankEnvelope.e_macro, A_TEMP,
1092				  macid("{dsn_ret}"), optarg);
1093			break;
1094
1095		  case 't':	/* read recipients from message */
1096			CHECK_AGAINST_OPMODE(j);
1097			GrabTo = true;
1098			break;
1099
1100		  case 'V':	/* DSN ENVID: set "original" envelope id */
1101			CHECK_AGAINST_OPMODE(j);
1102			if (!xtextok(optarg))
1103			{
1104				usrerr("Invalid syntax in -V flag");
1105				ExitStat = EX_USAGE;
1106			}
1107			else
1108			{
1109				BlankEnvelope.e_envid = newstr(optarg);
1110				macdefine(&BlankEnvelope.e_macro, A_TEMP,
1111					  macid("{dsn_envid}"), optarg);
1112			}
1113			break;
1114
1115		  case 'X':	/* traffic log file */
1116			dp = drop_privileges(true);
1117			setstat(dp);
1118			if (stat(optarg, &traf_st) == 0 &&
1119			    S_ISFIFO(traf_st.st_mode))
1120				TrafficLogFile = sm_io_open(SmFtStdio,
1121							    SM_TIME_DEFAULT,
1122							    optarg,
1123							    SM_IO_WRONLY, NULL);
1124			else
1125				TrafficLogFile = sm_io_open(SmFtStdio,
1126							    SM_TIME_DEFAULT,
1127							    optarg,
1128							    SM_IO_APPEND, NULL);
1129			if (TrafficLogFile == NULL)
1130			{
1131				syserr("cannot open %s", optarg);
1132				ExitStat = EX_CANTCREAT;
1133				break;
1134			}
1135			(void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1136					     NULL, SM_IO_LBF, 0);
1137			break;
1138
1139			/* compatibility flags */
1140		  case 'c':	/* connect to non-local mailers */
1141		  case 'i':	/* don't let dot stop me */
1142		  case 'm':	/* send to me too */
1143		  case 'T':	/* set timeout interval */
1144		  case 'v':	/* give blow-by-blow description */
1145			setoption(j, "T", false, true, &BlankEnvelope);
1146			break;
1147
1148		  case 'e':	/* error message disposition */
1149		  case 'M':	/* define macro */
1150			setoption(j, optarg, false, true, &BlankEnvelope);
1151			break;
1152
1153		  case 's':	/* save From lines in headers */
1154			setoption('f', "T", false, true, &BlankEnvelope);
1155			break;
1156
1157#ifdef DBM
1158		  case 'I':	/* initialize alias DBM file */
1159			set_op_mode(MD_INITALIAS);
1160			break;
1161#endif /* DBM */
1162
1163#if defined(__osf__) || defined(_AIX3)
1164		  case 'x':	/* random flag that OSF/1 & AIX mailx passes */
1165			break;
1166#endif /* defined(__osf__) || defined(_AIX3) */
1167#if defined(sony_news)
1168		  case 'E':
1169		  case 'J':	/* ignore flags for Japanese code conversion
1170				   implemented on Sony NEWS */
1171			break;
1172#endif /* defined(sony_news) */
1173
1174		  default:
1175			finis(true, true, EX_USAGE);
1176			/* NOTREACHED */
1177			break;
1178		}
1179	}
1180
1181	/* if we've had errors so far, exit now */
1182	if ((ExitStat != EX_OK && OpMode != MD_TEST) ||
1183	    ExitStat == EX_OSERR)
1184	{
1185		finis(false, true, ExitStat);
1186		/* NOTREACHED */
1187	}
1188
1189	if (bitset(SUBMIT_MTA, SubmitMode))
1190	{
1191		macdefine(&BlankEnvelope.e_macro, A_PERM,
1192			  macid("{daemon_flags}"), "CC f");
1193	}
1194	else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1195	{
1196		SubmitMode = SUBMIT_MSA;
1197		macdefine(&BlankEnvelope.e_macro, A_PERM,
1198			  macid("{daemon_flags}"), "c u");
1199	}
1200
1201	/*
1202	**  Do basic initialization.
1203	**	Read system control file.
1204	**	Extract special fields for local use.
1205	*/
1206
1207#if XDEBUG
1208	checkfd012("before readcf");
1209#endif /* XDEBUG */
1210	vendor_pre_defaults(&BlankEnvelope);
1211
1212	readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1213			 safecf, &BlankEnvelope);
1214#if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1215	ConfigFileRead = true;
1216#endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1217	vendor_post_defaults(&BlankEnvelope);
1218
1219	/* now we can complain about missing fds */
1220	if (MissingFds != 0 && LogLevel > 8)
1221	{
1222		char mbuf[MAXLINE];
1223
1224		mbuf[0] = '\0';
1225		if (bitset(1 << STDIN_FILENO, MissingFds))
1226			(void) sm_strlcat(mbuf, ", stdin", sizeof mbuf);
1227		if (bitset(1 << STDOUT_FILENO, MissingFds))
1228			(void) sm_strlcat(mbuf, ", stdout", sizeof mbuf);
1229		if (bitset(1 << STDERR_FILENO, MissingFds))
1230			(void) sm_strlcat(mbuf, ", stderr", sizeof mbuf);
1231
1232		/* Notice: fill_errno is from high above: fill_fd() */
1233		sm_syslog(LOG_WARNING, NOQID,
1234			  "File descriptors missing on startup: %s; %s",
1235			  &mbuf[2], sm_errstring(fill_errno));
1236	}
1237
1238	/* Remove the ability for a normal user to send signals */
1239	if (RealUid != 0 && RealUid != geteuid())
1240	{
1241		uid_t new_uid = geteuid();
1242
1243#if HASSETREUID
1244		/*
1245		**  Since we can differentiate between uid and euid,
1246		**  make the uid a different user so the real user
1247		**  can't send signals.  However, it doesn't need to be
1248		**  root (euid has root).
1249		*/
1250
1251		if (new_uid == 0)
1252			new_uid = DefUid;
1253		if (tTd(47, 5))
1254			sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1255		if (setreuid(new_uid, geteuid()) < 0)
1256		{
1257			syserr("main: setreuid(%d, %d) failed",
1258			       (int) new_uid, (int) geteuid());
1259			finis(false, true, EX_OSERR);
1260			/* NOTREACHED */
1261		}
1262		if (tTd(47, 10))
1263			sm_dprintf("Now running as e/ruid %d:%d\n",
1264				   (int) geteuid(), (int) getuid());
1265#else /* HASSETREUID */
1266		/*
1267		**  Have to change both effective and real so need to
1268		**  change them both to effective to keep privs.
1269		*/
1270
1271		if (tTd(47, 5))
1272			sm_dprintf("Changing uid to %d\n", (int) new_uid);
1273		if (setuid(new_uid) < 0)
1274		{
1275			syserr("main: setuid(%d) failed", (int) new_uid);
1276			finis(false, true, EX_OSERR);
1277			/* NOTREACHED */
1278		}
1279		if (tTd(47, 10))
1280			sm_dprintf("Now running as e/ruid %d:%d\n",
1281				   (int) geteuid(), (int) getuid());
1282#endif /* HASSETREUID */
1283	}
1284
1285#if NAMED_BIND
1286	if (FallBackMX != NULL)
1287		(void) getfallbackmxrr(FallBackMX);
1288#endif /* NAMED_BIND */
1289
1290	if (SuperSafe == SAFE_INTERACTIVE && CurEnv->e_sendmode != SM_DELIVER)
1291	{
1292		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1293				     "WARNING: SuperSafe=interactive should only be used with\n         DeliveryMode=interactive\n");
1294	}
1295
1296	if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1297	{
1298		usrerr("Mail submission program cannot be used as daemon");
1299		finis(false, true, EX_USAGE);
1300	}
1301
1302	if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1303	    OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1304	    OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1305		makeworkgroups();
1306
1307	/* set up the basic signal handlers */
1308	if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1309		(void) sm_signal(SIGINT, intsig);
1310	(void) sm_signal(SIGTERM, intsig);
1311
1312	/* Enforce use of local time (null string overrides this) */
1313	if (TimeZoneSpec == NULL)
1314		unsetenv("TZ");
1315	else if (TimeZoneSpec[0] != '\0')
1316		setuserenv("TZ", TimeZoneSpec);
1317	else
1318		setuserenv("TZ", NULL);
1319	tzset();
1320
1321	/* initialize mailbox database */
1322	i = sm_mbdb_initialize(Mbdb);
1323	if (i != EX_OK)
1324	{
1325		usrerr("Can't initialize mailbox database \"%s\": %s",
1326		       Mbdb, sm_strexit(i));
1327		ExitStat = i;
1328	}
1329
1330	/* avoid denial-of-service attacks */
1331	resetlimits();
1332
1333	if (OpMode == MD_TEST)
1334	{
1335		/* can't be done after readcf if RunAs* is used */
1336		dp = drop_privileges(true);
1337		if (dp != EX_OK)
1338		{
1339			finis(false, true, dp);
1340			/* NOTREACHED */
1341		}
1342	}
1343	else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1344	{
1345		/* drop privileges -- daemon mode done after socket/bind */
1346		dp = drop_privileges(false);
1347		setstat(dp);
1348		if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1349		{
1350			usrerr("Mail submission program must have RunAsUser set to non root user");
1351			finis(false, true, EX_CONFIG);
1352			/* NOTREACHED */
1353		}
1354	}
1355
1356#if NAMED_BIND
1357	_res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1358	_res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1359#endif /* NAMED_BIND */
1360
1361	/*
1362	**  Find our real host name for future logging.
1363	*/
1364
1365	authinfo = getauthinfo(STDIN_FILENO, &forged);
1366	macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1367
1368	/* suppress error printing if errors mailed back or whatever */
1369	if (BlankEnvelope.e_errormode != EM_PRINT)
1370		HoldErrs = true;
1371
1372	/* set up the $=m class now, after .cf has a chance to redefine $m */
1373	expand("\201m", jbuf, sizeof jbuf, &BlankEnvelope);
1374	if (jbuf[0] != '\0')
1375		setclass('m', jbuf);
1376
1377	/* probe interfaces and locate any additional names */
1378	if (DontProbeInterfaces != DPI_PROBENONE)
1379		load_if_names();
1380
1381	if (tTd(0, 10))
1382	{
1383		/* Now we know which .cf file we use */
1384		sm_dprintf("     Conf file:\t%s (selected)\n",
1385			   getcfname(OpMode, SubmitMode, cftype, conffile));
1386		sm_dprintf("      Pid file:\t%s (selected)\n", PidFile);
1387	}
1388
1389	if (tTd(0, 1))
1390	{
1391		sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1392		sm_dprintf("\n      (short domain name) $w = ");
1393		xputs(macvalue('w', &BlankEnvelope));
1394		sm_dprintf("\n  (canonical domain name) $j = ");
1395		xputs(macvalue('j', &BlankEnvelope));
1396		sm_dprintf("\n         (subdomain name) $m = ");
1397		xputs(macvalue('m', &BlankEnvelope));
1398		sm_dprintf("\n              (node name) $k = ");
1399		xputs(macvalue('k', &BlankEnvelope));
1400		sm_dprintf("\n========================================================\n\n");
1401	}
1402
1403	/*
1404	**  Do more command line checking -- these are things that
1405	**  have to modify the results of reading the config file.
1406	*/
1407
1408	/* process authorization warnings from command line */
1409	if (warn_C_flag)
1410		auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1411			     RealUserName, conffile);
1412	if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1413		auth_warning(&BlankEnvelope, "Processed from queue %s",
1414			     QueueDir);
1415	if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1416	    RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1417		sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1418			  (int) RealUid);
1419
1420	/* check body type for legality */
1421	i = check_bodytype(BlankEnvelope.e_bodytype);
1422	if (i == BODYTYPE_ILLEGAL)
1423	{
1424		usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1425		BlankEnvelope.e_bodytype = NULL;
1426	}
1427	else if (i != BODYTYPE_NONE)
1428		SevenBitInput = (i == BODYTYPE_7BIT);
1429
1430	/* tweak default DSN notifications */
1431	if (DefaultNotify == 0)
1432		DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1433
1434	/* be sure we don't pick up bogus HOSTALIASES environment variable */
1435	if (OpMode == MD_QUEUERUN && RealUid != 0)
1436		(void) unsetenv("HOSTALIASES");
1437
1438	/* check for sane configuration level */
1439	if (ConfigLevel > MAXCONFIGLEVEL)
1440	{
1441		syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1442		       ConfigLevel, Version, MAXCONFIGLEVEL);
1443	}
1444
1445	/* need MCI cache to have persistence */
1446	if (HostStatDir != NULL && MaxMciCache == 0)
1447	{
1448		HostStatDir = NULL;
1449		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1450				     "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1451	}
1452
1453	/* need HostStatusDir in order to have SingleThreadDelivery */
1454	if (SingleThreadDelivery && HostStatDir == NULL)
1455	{
1456		SingleThreadDelivery = false;
1457		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1458				     "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1459	}
1460
1461	/* check for permissions */
1462	if (RealUid != 0 &&
1463	    RealUid != TrustedUid)
1464	{
1465		char *action = NULL;
1466
1467		switch (OpMode)
1468		{
1469		  case MD_QUEUERUN:
1470#if _FFR_QUARANTINE
1471			if (quarantining != NULL)
1472				action = "quarantine jobs";
1473			else
1474#endif /* _FFR_QUARANTINE */
1475			/* Normal users can do a single queue run */
1476			if (QueueIntvl == 0)
1477				break;
1478
1479			/* but not persistent queue runners */
1480			if (action == NULL)
1481				action = "start a queue runner daemon";
1482			/* FALLTHROUGH */
1483
1484		  case MD_PURGESTAT:
1485			if (action == NULL)
1486				action = "purge host status";
1487			/* FALLTHROUGH */
1488
1489		  case MD_DAEMON:
1490		  case MD_FGDAEMON:
1491			if (action == NULL)
1492				action = "run daemon";
1493
1494			if (tTd(65, 1))
1495				sm_dprintf("Deny user %d attempt to %s\n",
1496					   (int) RealUid, action);
1497
1498			if (LogLevel > 1)
1499				sm_syslog(LOG_ALERT, NOQID,
1500					  "user %d attempted to %s",
1501					  (int) RealUid, action);
1502			HoldErrs = false;
1503			usrerr("Permission denied (real uid not trusted)");
1504			finis(false, true, EX_USAGE);
1505			/* NOTREACHED */
1506			break;
1507
1508		  case MD_VERIFY:
1509			if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1510			{
1511				/*
1512				**  If -bv and RestrictExpand,
1513				**  drop privs to prevent normal
1514				**  users from reading private
1515				**  aliases/forwards/:include:s
1516				*/
1517
1518				if (tTd(65, 1))
1519					sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1520						   (int) RealUid);
1521
1522				dp = drop_privileges(true);
1523
1524				/* Fake address safety */
1525				if (tTd(65, 1))
1526					sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1527				setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1528
1529				if (dp != EX_OK)
1530				{
1531					if (tTd(65, 1))
1532						sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1533							   (int) RealUid);
1534					CurEnv->e_id = NULL;
1535					finis(true, true, dp);
1536					/* NOTREACHED */
1537				}
1538			}
1539			break;
1540
1541		  case MD_TEST:
1542		  case MD_PRINT:
1543		  case MD_PRINTNQE:
1544		  case MD_FREEZE:
1545		  case MD_HOSTSTAT:
1546			/* Nothing special to check */
1547			break;
1548
1549		  case MD_INITALIAS:
1550			if (!wordinclass(RealUserName, 't'))
1551			{
1552				if (tTd(65, 1))
1553					sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1554						   (int) RealUid);
1555				if (LogLevel > 1)
1556					sm_syslog(LOG_ALERT, NOQID,
1557						  "user %d attempted to rebuild the alias map",
1558						  (int) RealUid);
1559				HoldErrs = false;
1560				usrerr("Permission denied (real uid not trusted)");
1561				finis(false, true, EX_USAGE);
1562				/* NOTREACHED */
1563			}
1564			if (UseMSP)
1565			{
1566				HoldErrs = false;
1567				usrerr("User %d cannot rebuild aliases in mail submission program",
1568				       (int) RealUid);
1569				finis(false, true, EX_USAGE);
1570				/* NOTREACHED */
1571			}
1572			/* FALLTHROUGH */
1573
1574		  default:
1575			if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1576			    Verbose != 0)
1577			{
1578				/*
1579				**  If -v and RestrictExpand, reset
1580				**  Verbose to prevent normal users
1581				**  from seeing the expansion of
1582				**  aliases/forwards/:include:s
1583				*/
1584
1585				if (tTd(65, 1))
1586					sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1587						   (int) RealUid);
1588				Verbose = 0;
1589			}
1590			break;
1591		}
1592	}
1593
1594	if (MeToo)
1595		BlankEnvelope.e_flags |= EF_METOO;
1596
1597	switch (OpMode)
1598	{
1599	  case MD_TEST:
1600		/* don't have persistent host status in test mode */
1601		HostStatDir = NULL;
1602		if (Verbose == 0)
1603			Verbose = 2;
1604		BlankEnvelope.e_errormode = EM_PRINT;
1605		HoldErrs = false;
1606		break;
1607
1608	  case MD_VERIFY:
1609		BlankEnvelope.e_errormode = EM_PRINT;
1610		HoldErrs = false;
1611		/* arrange to exit cleanly on hangup signal */
1612		if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1613			(void) sm_signal(SIGHUP, intsig);
1614		if (geteuid() != 0)
1615			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1616					     "Notice: -bv may give misleading output for non-privileged user\n");
1617		break;
1618
1619	  case MD_FGDAEMON:
1620		run_in_foreground = true;
1621		set_op_mode(MD_DAEMON);
1622		/* FALLTHROUGH */
1623
1624	  case MD_DAEMON:
1625		vendor_daemon_setup(&BlankEnvelope);
1626
1627		/* remove things that don't make sense in daemon mode */
1628		FullName = NULL;
1629		GrabTo = false;
1630
1631		/* arrange to restart on hangup signal */
1632		if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1633			sm_syslog(LOG_WARNING, NOQID,
1634				  "daemon invoked without full pathname; kill -1 won't work");
1635		break;
1636
1637	  case MD_INITALIAS:
1638		Verbose = 2;
1639		BlankEnvelope.e_errormode = EM_PRINT;
1640		HoldErrs = false;
1641		/* FALLTHROUGH */
1642
1643	  default:
1644		/* arrange to exit cleanly on hangup signal */
1645		if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1646			(void) sm_signal(SIGHUP, intsig);
1647		break;
1648	}
1649
1650	/* special considerations for FullName */
1651	if (FullName != NULL)
1652	{
1653		char *full = NULL;
1654
1655		/* full names can't have newlines */
1656		if (strchr(FullName, '\n') != NULL)
1657		{
1658			full = newstr(denlstring(FullName, true, true));
1659			FullName = full;
1660		}
1661
1662		/* check for characters that may have to be quoted */
1663		if (!rfc822_string(FullName))
1664		{
1665			/*
1666			**  Quote a full name with special characters
1667			**  as a comment so crackaddr() doesn't destroy
1668			**  the name portion of the address.
1669			*/
1670
1671			FullName = addquotes(FullName, NULL);
1672			if (full != NULL)
1673				sm_free(full);  /* XXX */
1674		}
1675	}
1676
1677	/* do heuristic mode adjustment */
1678	if (Verbose)
1679	{
1680		/* turn off noconnect option */
1681		setoption('c', "F", true, false, &BlankEnvelope);
1682
1683		/* turn on interactive delivery */
1684		setoption('d', "", true, false, &BlankEnvelope);
1685	}
1686
1687#ifdef VENDOR_CODE
1688	/* check for vendor mismatch */
1689	if (VendorCode != VENDOR_CODE)
1690	{
1691		message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1692			getvendor(VENDOR_CODE), getvendor(VendorCode));
1693	}
1694#endif /* VENDOR_CODE */
1695
1696	/* check for out of date configuration level */
1697	if (ConfigLevel < MAXCONFIGLEVEL)
1698	{
1699		message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1700			Version, MAXCONFIGLEVEL, ConfigLevel);
1701	}
1702
1703	if (ConfigLevel < 3)
1704		UseErrorsTo = true;
1705
1706	/* set options that were previous macros */
1707	if (SmtpGreeting == NULL)
1708	{
1709		if (ConfigLevel < 7 &&
1710		    (p = macvalue('e', &BlankEnvelope)) != NULL)
1711			SmtpGreeting = newstr(p);
1712		else
1713			SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1714	}
1715	if (UnixFromLine == NULL)
1716	{
1717		if (ConfigLevel < 7 &&
1718		    (p = macvalue('l', &BlankEnvelope)) != NULL)
1719			UnixFromLine = newstr(p);
1720		else
1721			UnixFromLine = "From \201g  \201d";
1722	}
1723	SmtpError[0] = '\0';
1724
1725	/* our name for SMTP codes */
1726	expand("\201j", jbuf, sizeof jbuf, &BlankEnvelope);
1727	if (jbuf[0] == '\0')
1728		PSTRSET(MyHostName, "localhost");
1729	else
1730		PSTRSET(MyHostName, jbuf);
1731	if (strchr(MyHostName, '.') == NULL)
1732		message("WARNING: local host name (%s) is not qualified; fix $j in config file",
1733			MyHostName);
1734
1735	/* make certain that this name is part of the $=w class */
1736	setclass('w', MyHostName);
1737
1738	/* fill in the structure of the *default* queue */
1739	st = stab("mqueue", ST_QUEUE, ST_FIND);
1740	if (st == NULL)
1741		syserr("No default queue (mqueue) defined");
1742	else
1743		set_def_queueval(st->s_quegrp, true);
1744
1745	/* the indices of built-in mailers */
1746	st = stab("local", ST_MAILER, ST_FIND);
1747	if (st != NULL)
1748		LocalMailer = st->s_mailer;
1749	else if (OpMode != MD_TEST || !warn_C_flag)
1750		syserr("No local mailer defined");
1751
1752	st = stab("prog", ST_MAILER, ST_FIND);
1753	if (st == NULL)
1754		syserr("No prog mailer defined");
1755	else
1756	{
1757		ProgMailer = st->s_mailer;
1758		clrbitn(M_MUSER, ProgMailer->m_flags);
1759	}
1760
1761	st = stab("*file*", ST_MAILER, ST_FIND);
1762	if (st == NULL)
1763		syserr("No *file* mailer defined");
1764	else
1765	{
1766		FileMailer = st->s_mailer;
1767		clrbitn(M_MUSER, FileMailer->m_flags);
1768	}
1769
1770	st = stab("*include*", ST_MAILER, ST_FIND);
1771	if (st == NULL)
1772		syserr("No *include* mailer defined");
1773	else
1774		InclMailer = st->s_mailer;
1775
1776	if (ConfigLevel < 6)
1777	{
1778		/* heuristic tweaking of local mailer for back compat */
1779		if (LocalMailer != NULL)
1780		{
1781			setbitn(M_ALIASABLE, LocalMailer->m_flags);
1782			setbitn(M_HASPWENT, LocalMailer->m_flags);
1783			setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1784			setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1785			setbitn(M_CHECKPROG, LocalMailer->m_flags);
1786			setbitn(M_CHECKFILE, LocalMailer->m_flags);
1787			setbitn(M_CHECKUDB, LocalMailer->m_flags);
1788		}
1789		if (ProgMailer != NULL)
1790			setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1791		if (FileMailer != NULL)
1792			setbitn(M_RUNASRCPT, FileMailer->m_flags);
1793	}
1794	if (ConfigLevel < 7)
1795	{
1796		if (LocalMailer != NULL)
1797			setbitn(M_VRFY250, LocalMailer->m_flags);
1798		if (ProgMailer != NULL)
1799			setbitn(M_VRFY250, ProgMailer->m_flags);
1800		if (FileMailer != NULL)
1801			setbitn(M_VRFY250, FileMailer->m_flags);
1802	}
1803
1804	/* MIME Content-Types that cannot be transfer encoded */
1805	setclass('n', "multipart/signed");
1806
1807	/* MIME message/xxx subtypes that can be treated as messages */
1808	setclass('s', "rfc822");
1809
1810	/* MIME Content-Transfer-Encodings that can be encoded */
1811	setclass('e', "7bit");
1812	setclass('e', "8bit");
1813	setclass('e', "binary");
1814
1815#ifdef USE_B_CLASS
1816	/* MIME Content-Types that should be treated as binary */
1817	setclass('b', "image");
1818	setclass('b', "audio");
1819	setclass('b', "video");
1820	setclass('b', "application/octet-stream");
1821#endif /* USE_B_CLASS */
1822
1823	/* MIME headers which have fields to check for overflow */
1824	setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1825	setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1826
1827	/* MIME headers to check for length overflow */
1828	setclass(macid("{checkMIMETextHeaders}"), "content-description");
1829
1830	/* MIME headers to check for overflow and rebalance */
1831	setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1832	setclass(macid("{checkMIMEHeaders}"), "content-id");
1833	setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1834	setclass(macid("{checkMIMEHeaders}"), "content-type");
1835	setclass(macid("{checkMIMEHeaders}"), "mime-version");
1836
1837	/* Macros to save in the queue file -- don't remove any */
1838	setclass(macid("{persistentMacros}"), "r");
1839	setclass(macid("{persistentMacros}"), "s");
1840	setclass(macid("{persistentMacros}"), "_");
1841	setclass(macid("{persistentMacros}"), "{if_addr}");
1842	setclass(macid("{persistentMacros}"), "{daemon_flags}");
1843
1844	/* operate in queue directory */
1845	if (QueueDir == NULL || *QueueDir == '\0')
1846	{
1847		if (OpMode != MD_TEST)
1848		{
1849			syserr("QueueDirectory (Q) option must be set");
1850			ExitStat = EX_CONFIG;
1851		}
1852	}
1853	else
1854	{
1855		if (OpMode != MD_TEST)
1856			setup_queues(OpMode == MD_DAEMON);
1857	}
1858
1859	/* check host status directory for validity */
1860	if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1861	{
1862		/* cannot use this value */
1863		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1864				     "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1865				     HostStatDir, sm_errstring(errno));
1866		HostStatDir = NULL;
1867	}
1868
1869	if (OpMode == MD_QUEUERUN &&
1870	    RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1871	{
1872		struct stat stbuf;
1873
1874		/* check to see if we own the queue directory */
1875		if (stat(".", &stbuf) < 0)
1876			syserr("main: cannot stat %s", QueueDir);
1877		if (stbuf.st_uid != RealUid)
1878		{
1879			/* nope, really a botch */
1880			HoldErrs = false;
1881			usrerr("You do not have permission to process the queue");
1882			finis(false, true, EX_NOPERM);
1883			/* NOTREACHED */
1884		}
1885	}
1886
1887#if MILTER
1888	/* sanity checks on milter filters */
1889	if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1890	{
1891		milter_config(InputFilterList, InputFilters, MAXFILTERS);
1892# if _FFR_MILTER_PERDAEMON
1893		setup_daemon_milters();
1894# endif /* _FFR_MILTER_PERDAEMON */
1895	}
1896#endif /* MILTER */
1897
1898	/* Convert queuegroup string to qgrp number */
1899	if (queuegroup != NULL)
1900	{
1901		qgrp = name2qid(queuegroup);
1902		if (qgrp == NOQGRP)
1903		{
1904			HoldErrs = false;
1905			usrerr("Queue group %s unknown", queuegroup);
1906			finis(false, true, ExitStat);
1907			/* NOTREACHED */
1908		}
1909	}
1910
1911	/* if we've had errors so far, exit now */
1912	if (ExitStat != EX_OK && OpMode != MD_TEST)
1913	{
1914		finis(false, true, ExitStat);
1915		/* NOTREACHED */
1916	}
1917
1918#if SASL
1919	/* sendmail specific SASL initialization */
1920	sm_sasl_init();
1921#endif /* SASL */
1922
1923#if XDEBUG
1924	checkfd012("before main() initmaps");
1925#endif /* XDEBUG */
1926
1927	/*
1928	**  Do operation-mode-dependent initialization.
1929	*/
1930
1931	switch (OpMode)
1932	{
1933	  case MD_PRINT:
1934		/* print the queue */
1935		HoldErrs = false;
1936		dropenvelope(&BlankEnvelope, true, false);
1937		(void) sm_signal(SIGPIPE, sigpipe);
1938		if (qgrp != NOQGRP)
1939		{
1940			int j;
1941
1942			/* Selecting a particular queue group to run */
1943			for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1944			{
1945				if (StopRequest)
1946					stop_sendmail();
1947				(void) print_single_queue(qgrp, j);
1948			}
1949			finis(false, true, EX_OK);
1950			/* NOTREACHED */
1951		}
1952		printqueue();
1953		finis(false, true, EX_OK);
1954		/* NOTREACHED */
1955		break;
1956
1957	  case MD_PRINTNQE:
1958		/* print number of entries in queue */
1959		dropenvelope(&BlankEnvelope, true, false);
1960		(void) sm_signal(SIGPIPE, sigpipe);
1961		printnqe(smioout, NULL);
1962		finis(false, true, EX_OK);
1963		/* NOTREACHED */
1964		break;
1965
1966#if _FFR_QUARANTINE
1967	  case MD_QUEUERUN:
1968		/* only handle quarantining here */
1969		if (quarantining == NULL)
1970			break;
1971
1972		if (QueueMode != QM_QUARANTINE &&
1973		    QueueMode != QM_NORMAL)
1974		{
1975			HoldErrs = false;
1976			usrerr("Can not use -Q with -q%c", QueueMode);
1977			ExitStat = EX_USAGE;
1978			finis(false, true, ExitStat);
1979			/* NOTREACHED */
1980		}
1981		quarantine_queue(quarantining, qgrp);
1982		finis(false, true, EX_OK);
1983		break;
1984#endif /* _FFR_QUARANTINE */
1985
1986	  case MD_HOSTSTAT:
1987		(void) sm_signal(SIGPIPE, sigpipe);
1988		(void) mci_traverse_persistent(mci_print_persistent, NULL);
1989		finis(false, true, EX_OK);
1990		/* NOTREACHED */
1991		break;
1992
1993	  case MD_PURGESTAT:
1994		(void) mci_traverse_persistent(mci_purge_persistent, NULL);
1995		finis(false, true, EX_OK);
1996		/* NOTREACHED */
1997		break;
1998
1999	  case MD_INITALIAS:
2000		/* initialize maps */
2001		initmaps();
2002		finis(false, true, ExitStat);
2003		/* NOTREACHED */
2004		break;
2005
2006	  case MD_SMTP:
2007	  case MD_DAEMON:
2008		/* reset DSN parameters */
2009		DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2010		macdefine(&BlankEnvelope.e_macro, A_PERM,
2011			  macid("{dsn_notify}"), NULL);
2012		BlankEnvelope.e_envid = NULL;
2013		macdefine(&BlankEnvelope.e_macro, A_PERM,
2014			  macid("{dsn_envid}"), NULL);
2015		BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2016		macdefine(&BlankEnvelope.e_macro, A_PERM,
2017			  macid("{dsn_ret}"), NULL);
2018
2019		/* don't open maps for daemon -- done below in child */
2020		break;
2021	}
2022
2023	if (tTd(0, 15))
2024	{
2025		/* print configuration table (or at least part of it) */
2026		if (tTd(0, 90))
2027			printrules();
2028		for (i = 0; i < MAXMAILERS; i++)
2029		{
2030			if (Mailer[i] != NULL)
2031				printmailer(Mailer[i]);
2032		}
2033	}
2034
2035	/*
2036	**  Switch to the main envelope.
2037	*/
2038
2039	CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2040			     sm_rpool_new_x(NULL));
2041	MainEnvelope.e_flags = BlankEnvelope.e_flags;
2042
2043	/*
2044	**  If test mode, read addresses from stdin and process.
2045	*/
2046
2047	if (OpMode == MD_TEST)
2048	{
2049		if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2050			Verbose = 2;
2051
2052		if (Verbose)
2053		{
2054			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2055				     "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2056			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2057				     "Enter <ruleset> <address>\n");
2058		}
2059		macdefine(&(MainEnvelope.e_macro), A_PERM,
2060			  macid("{addr_type}"), "e r");
2061		for (;;)
2062		{
2063			SM_TRY
2064			{
2065				(void) sm_signal(SIGINT, intindebug);
2066				(void) sm_releasesignal(SIGINT);
2067				if (Verbose == 2)
2068					(void) sm_io_fprintf(smioout,
2069							     SM_TIME_DEFAULT,
2070							     "> ");
2071				(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2072				if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2073						sizeof buf) == NULL)
2074					testmodeline("/quit", &MainEnvelope);
2075				p = strchr(buf, '\n');
2076				if (p != NULL)
2077					*p = '\0';
2078				if (Verbose < 2)
2079					(void) sm_io_fprintf(smioout,
2080							     SM_TIME_DEFAULT,
2081							     "> %s\n", buf);
2082				testmodeline(buf, &MainEnvelope);
2083			}
2084			SM_EXCEPT(exc, "[!F]*")
2085			{
2086				/*
2087				**  8.10 just prints \n on interrupt.
2088				**  I'm printing the exception here in case
2089				**  sendmail is extended to raise additional
2090				**  exceptions in this context.
2091				*/
2092
2093				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2094						     "\n");
2095				sm_exc_print(exc, smioout);
2096			}
2097			SM_END_TRY
2098		}
2099	}
2100
2101#if STARTTLS
2102	tls_ok = true;
2103	if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER)
2104	{
2105		/* check whether STARTTLS is turned off for the client */
2106		if (chkclientmodifiers(D_NOTLS))
2107			tls_ok = false;
2108	}
2109	else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2110		 OpMode == MD_SMTP)
2111	{
2112		/* check whether STARTTLS is turned off for the server */
2113		if (chkdaemonmodifiers(D_NOTLS))
2114			tls_ok = false;
2115	}
2116	else	/* other modes don't need STARTTLS */
2117		tls_ok = false;
2118
2119	if (tls_ok)
2120	{
2121		/* basic TLS initialization */
2122		tls_ok = init_tls_library();
2123	}
2124
2125	if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2126	{
2127		/* disable TLS for client */
2128		setclttls(false);
2129	}
2130#endif /* STARTTLS */
2131
2132	/*
2133	**  If collecting stuff from the queue, go start doing that.
2134	*/
2135
2136	if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2137	{
2138		pid_t pid = -1;
2139
2140#if STARTTLS
2141		/* init TLS for client, ignore result for now */
2142		(void) initclttls(tls_ok);
2143#endif /* STARTTLS */
2144
2145		/*
2146		**  The parent process of the caller of runqueue() needs
2147		**  to stay around for a possible SIGTERM. The SIGTERM will
2148		**  tell this process that all of the queue runners children
2149		**  need to be sent SIGTERM as well. At the same time, we
2150		**  want to return control to the command line. So we do an
2151		**  extra fork().
2152		*/
2153
2154		if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2155		{
2156			/*
2157			**  If the fork() failed we should still try to do
2158			**  the queue run. If it succeeded then the child
2159			**  is going to start the run and wait for all
2160			**  of the children to finish.
2161			*/
2162
2163			if (pid == 0)
2164			{
2165				/* Reset global flags */
2166				RestartRequest = NULL;
2167				ShutdownRequest = NULL;
2168				PendingSignal = 0;
2169
2170				/* disconnect from terminal */
2171				disconnect(2, CurEnv);
2172			}
2173
2174			CurrentPid = getpid();
2175			if (qgrp != NOQGRP)
2176			{
2177				/*
2178				**  To run a specific queue group mark it to
2179				**  be run, select the work group it's in and
2180				**  increment the work counter.
2181				*/
2182
2183				for (i = 0; i < NumQueue && Queue[i] != NULL;
2184				     i++)
2185					Queue[i]->qg_nextrun = (time_t) -1;
2186				Queue[qgrp]->qg_nextrun = 0;
2187				(void) run_work_group(Queue[qgrp]->qg_wgrp,
2188						      false, Verbose,
2189						      queuepersistent, false);
2190			}
2191			else
2192				(void) runqueue(false, Verbose,
2193						queuepersistent, true);
2194
2195			/* set the title to make it easier to find */
2196			sm_setproctitle(true, CurEnv, "Queue control");
2197			(void) sm_signal(SIGCHLD, SIG_DFL);
2198			while (CurChildren > 0)
2199			{
2200				int status;
2201				pid_t ret;
2202
2203				while ((ret = sm_wait(&status)) <= 0)
2204					continue;
2205
2206				/* Only drop when a child gives status */
2207				if (WIFSTOPPED(status))
2208					continue;
2209
2210				proc_list_drop(ret, status, NULL);
2211			}
2212		}
2213		finis(true, true, ExitStat);
2214		/* NOTREACHED */
2215	}
2216
2217# if SASL
2218	if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2219	{
2220		/* check whether AUTH is turned off for the server */
2221		if (!chkdaemonmodifiers(D_NOAUTH) &&
2222		    (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2223			syserr("!sasl_server_init failed! [%s]",
2224				sasl_errstring(i, NULL, NULL));
2225	}
2226# endif /* SASL */
2227
2228	if (OpMode == MD_SMTP)
2229	{
2230		proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2231			      PROC_DAEMON, 0, -1);
2232
2233		/* clean up background delivery children */
2234		(void) sm_signal(SIGCHLD, reapchild);
2235	}
2236
2237	/*
2238	**  If a daemon, wait for a request.
2239	**	getrequests will always return in a child.
2240	**	If we should also be processing the queue, start
2241	**		doing it in background.
2242	**	We check for any errors that might have happened
2243	**		during startup.
2244	*/
2245
2246	if (OpMode == MD_DAEMON || QueueIntvl != 0)
2247	{
2248		char dtype[200];
2249
2250		if (!run_in_foreground && !tTd(99, 100))
2251		{
2252			/* put us in background */
2253			i = fork();
2254			if (i < 0)
2255				syserr("daemon: cannot fork");
2256			if (i != 0)
2257			{
2258				finis(false, true, EX_OK);
2259				/* NOTREACHED */
2260			}
2261
2262			/*
2263			**  Initialize exception stack and default exception
2264			**  handler for child process.
2265			*/
2266
2267			/* Reset global flags */
2268			RestartRequest = NULL;
2269			RestartWorkGroup = false;
2270			ShutdownRequest = NULL;
2271			PendingSignal = 0;
2272			CurrentPid = getpid();
2273
2274			sm_exc_newthread(fatal_error);
2275
2276			/* disconnect from our controlling tty */
2277			disconnect(2, &MainEnvelope);
2278		}
2279
2280		dtype[0] = '\0';
2281		if (OpMode == MD_DAEMON)
2282		{
2283			(void) sm_strlcat(dtype, "+SMTP", sizeof dtype);
2284			DaemonPid = CurrentPid;
2285		}
2286		if (QueueIntvl != 0)
2287		{
2288			(void) sm_strlcat2(dtype,
2289					   queuepersistent
2290					   ? "+persistent-queueing@"
2291					   : "+queueing@",
2292					   pintvl(QueueIntvl, true),
2293					   sizeof dtype);
2294		}
2295		if (tTd(0, 1))
2296			(void) sm_strlcat(dtype, "+debugging", sizeof dtype);
2297
2298		sm_syslog(LOG_INFO, NOQID,
2299			  "starting daemon (%s): %s", Version, dtype + 1);
2300#if XLA
2301		xla_create_file();
2302#endif /* XLA */
2303
2304		/* save daemon type in a macro for possible PidFile use */
2305		macdefine(&BlankEnvelope.e_macro, A_TEMP,
2306			macid("{daemon_info}"), dtype + 1);
2307
2308		/* save queue interval in a macro for possible PidFile use */
2309		macdefine(&MainEnvelope.e_macro, A_TEMP,
2310			macid("{queue_interval}"), pintvl(QueueIntvl, true));
2311
2312		/* workaround: can't seem to release the signal in the parent */
2313		(void) sm_signal(SIGHUP, sighup);
2314		(void) sm_releasesignal(SIGHUP);
2315		(void) sm_signal(SIGTERM, sigterm);
2316
2317		if (QueueIntvl != 0)
2318		{
2319			(void) runqueue(true, false, queuepersistent, true);
2320
2321			/*
2322			**  If queuepersistent but not in daemon mode then
2323			**  we're going to do the queue runner monitoring here.
2324			**  If in daemon mode then the monitoring will happen
2325			**  elsewhere.
2326			*/
2327
2328			if (OpMode != MD_DAEMON && queuepersistent)
2329			{
2330				/* set the title to make it easier to find */
2331				sm_setproctitle(true, CurEnv, "Queue control");
2332				(void) sm_signal(SIGCHLD, SIG_DFL);
2333				while (CurChildren > 0)
2334				{
2335					int status;
2336					pid_t ret;
2337					int group;
2338
2339					if (ShutdownRequest != NULL)
2340						shutdown_daemon();
2341					else if (RestartRequest != NULL)
2342						restart_daemon();
2343					else if (RestartWorkGroup)
2344						restart_marked_work_groups();
2345
2346					while ((ret = sm_wait(&status)) <= 0)
2347						continue;
2348
2349					if (WIFSTOPPED(status))
2350						continue;
2351
2352					/* Probe only on a child status */
2353					proc_list_drop(ret, status, &group);
2354
2355					if (WIFSIGNALED(status))
2356					{
2357						if (WCOREDUMP(status))
2358						{
2359							sm_syslog(LOG_ERR, NOQID,
2360								  "persistent queue runner=%d core dumped, signal=%d",
2361								  group, WTERMSIG(status));
2362
2363							/* don't restart this one */
2364							mark_work_group_restart(group, -1);
2365							continue;
2366						}
2367
2368						sm_syslog(LOG_ERR, NOQID,
2369							  "persistent queue runner=%d died, signal=%d",
2370							  group, WTERMSIG(status));
2371					}
2372
2373					/*
2374					**  When debugging active, don't
2375					**  restart the persistent queues.
2376					**  But do log this as info.
2377					*/
2378
2379					if (sm_debug_active(&DebugNoPRestart,
2380							    1))
2381					{
2382						sm_syslog(LOG_DEBUG, NOQID,
2383							  "persistent queue runner=%d, exited",
2384							  group);
2385						mark_work_group_restart(group, -1);
2386					}
2387				}
2388				finis(true, true, ExitStat);
2389				/* NOTREACHED */
2390			}
2391
2392			if (OpMode != MD_DAEMON)
2393			{
2394				char qtype[200];
2395
2396				/*
2397				**  Write the pid to file
2398				**  XXX Overwrites sendmail.pid
2399				*/
2400
2401				log_sendmail_pid(&MainEnvelope);
2402
2403				/* set the title to make it easier to find */
2404				qtype[0] = '\0';
2405				(void) sm_strlcpyn(qtype, sizeof qtype, 4,
2406						   "Queue runner@",
2407						   pintvl(QueueIntvl, true),
2408						   " for ",
2409						   QueueDir);
2410				sm_setproctitle(true, CurEnv, qtype);
2411				for (;;)
2412				{
2413					(void) pause();
2414					if (ShutdownRequest != NULL)
2415						shutdown_daemon();
2416					else if (RestartRequest != NULL)
2417						restart_daemon();
2418					else if (RestartWorkGroup)
2419						restart_marked_work_groups();
2420
2421					if (doqueuerun())
2422						(void) runqueue(true, false,
2423								false, false);
2424				}
2425			}
2426		}
2427		dropenvelope(&MainEnvelope, true, false);
2428
2429#if STARTTLS
2430		/* init TLS for server, ignore result for now */
2431		(void) initsrvtls(tls_ok);
2432#endif /* STARTTLS */
2433#if PROFILING
2434	nextreq:
2435#endif /* PROFILING */
2436		p_flags = getrequests(&MainEnvelope);
2437
2438		/* drop privileges */
2439		(void) drop_privileges(false);
2440
2441		/*
2442		**  Get authentication data
2443		**  Set _ macro in BlankEnvelope before calling newenvelope().
2444		*/
2445
2446		authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2447						     NULL), &forged);
2448		macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2449
2450		/* at this point we are in a child: reset state */
2451		sm_rpool_free(MainEnvelope.e_rpool);
2452		(void) newenvelope(&MainEnvelope, &MainEnvelope,
2453				   sm_rpool_new_x(NULL));
2454	}
2455
2456	if (LogLevel > 9)
2457	{
2458		/* log connection information */
2459		sm_syslog(LOG_INFO, NULL, "connect from %.100s", authinfo);
2460	}
2461
2462	/*
2463	**  If running SMTP protocol, start collecting and executing
2464	**  commands.  This will never return.
2465	*/
2466
2467	if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2468	{
2469		char pbuf[20];
2470
2471		/*
2472		**  Save some macros for check_* rulesets.
2473		*/
2474
2475		if (forged)
2476		{
2477			char ipbuf[103];
2478
2479			(void) sm_snprintf(ipbuf, sizeof ipbuf, "[%.100s]",
2480					   anynet_ntoa(&RealHostAddr));
2481			macdefine(&BlankEnvelope.e_macro, A_TEMP,
2482				  macid("{client_name}"), ipbuf);
2483		}
2484		else
2485			macdefine(&BlankEnvelope.e_macro, A_PERM,
2486				  macid("{client_name}"), RealHostName);
2487		macdefine(&BlankEnvelope.e_macro, A_TEMP,
2488			  macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2489		sm_getla();
2490
2491		switch (RealHostAddr.sa.sa_family)
2492		{
2493#if NETINET
2494		  case AF_INET:
2495			(void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2496					   RealHostAddr.sin.sin_port);
2497			break;
2498#endif /* NETINET */
2499#if NETINET6
2500		  case AF_INET6:
2501			(void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2502					   RealHostAddr.sin6.sin6_port);
2503			break;
2504#endif /* NETINET6 */
2505		  default:
2506			(void) sm_snprintf(pbuf, sizeof pbuf, "0");
2507			break;
2508		}
2509		macdefine(&BlankEnvelope.e_macro, A_TEMP,
2510			macid("{client_port}"), pbuf);
2511
2512		if (OpMode == MD_DAEMON)
2513		{
2514			/* validate the connection */
2515			HoldErrs = true;
2516			nullserver = validate_connection(&RealHostAddr,
2517							 RealHostName,
2518							 &MainEnvelope);
2519			HoldErrs = false;
2520		}
2521		else if (p_flags == NULL)
2522		{
2523			p_flags = (BITMAP256 *) xalloc(sizeof *p_flags);
2524			clrbitmap(p_flags);
2525		}
2526#if STARTTLS
2527		if (OpMode == MD_SMTP)
2528			(void) initsrvtls(tls_ok);
2529#endif /* STARTTLS */
2530
2531		/* turn off profiling */
2532		SM_PROF(1);
2533		smtp(nullserver, *p_flags, &MainEnvelope);
2534#if PROFILING
2535		/* turn off profiling */
2536		SM_PROF(0);
2537		if (OpMode == MD_DAEMON)
2538			goto nextreq;
2539#endif /* PROFILING */
2540	}
2541
2542	sm_rpool_free(MainEnvelope.e_rpool);
2543	clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2544	if (OpMode == MD_VERIFY)
2545	{
2546		set_delivery_mode(SM_VERIFY, &MainEnvelope);
2547		PostMasterCopy = NULL;
2548	}
2549	else
2550	{
2551		/* interactive -- all errors are global */
2552		MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2553	}
2554
2555	/*
2556	**  Do basic system initialization and set the sender
2557	*/
2558
2559	initsys(&MainEnvelope);
2560	macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2561	macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2562	setsender(from, &MainEnvelope, NULL, '\0', false);
2563	if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2564	    (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2565	     strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2566	{
2567		auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2568			     RealUserName, from, warn_f_flag);
2569#if SASL
2570		auth = false;
2571#endif /* SASL */
2572	}
2573	if (auth)
2574	{
2575		char *fv;
2576
2577		/* set the initial sender for AUTH= to $f@$j */
2578		fv = macvalue('f', &MainEnvelope);
2579		if (fv == NULL || *fv == '\0')
2580			MainEnvelope.e_auth_param = NULL;
2581		else
2582		{
2583			if (strchr(fv, '@') == NULL)
2584			{
2585				i = strlen(fv) + strlen(macvalue('j',
2586							&MainEnvelope)) + 2;
2587				p = sm_malloc_x(i);
2588				(void) sm_strlcpyn(p, i, 3, fv, "@",
2589						   macvalue('j',
2590							    &MainEnvelope));
2591			}
2592			else
2593				p = sm_strdup_x(fv);
2594			MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2595								      xtextify(p, "="));
2596			sm_free(p);  /* XXX */
2597		}
2598	}
2599	if (macvalue('s', &MainEnvelope) == NULL)
2600		macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2601
2602	av = argv + optind;
2603	if (*av == NULL && !GrabTo)
2604	{
2605		MainEnvelope.e_to = NULL;
2606		MainEnvelope.e_flags |= EF_GLOBALERRS;
2607		HoldErrs = false;
2608		SuperSafe = SAFE_NO;
2609		usrerr("Recipient names must be specified");
2610
2611		/* collect body for UUCP return */
2612		if (OpMode != MD_VERIFY)
2613			collect(InChannel, false, NULL, &MainEnvelope);
2614		finis(true, true, EX_USAGE);
2615		/* NOTREACHED */
2616	}
2617
2618	/*
2619	**  Scan argv and deliver the message to everyone.
2620	*/
2621
2622	save_val = LogUsrErrs;
2623	LogUsrErrs = true;
2624	sendtoargv(av, &MainEnvelope);
2625	LogUsrErrs = save_val;
2626
2627	/* if we have had errors sofar, arrange a meaningful exit stat */
2628	if (Errors > 0 && ExitStat == EX_OK)
2629		ExitStat = EX_USAGE;
2630
2631#if _FFR_FIX_DASHT
2632	/*
2633	**  If using -t, force not sending to argv recipients, even
2634	**  if they are mentioned in the headers.
2635	*/
2636
2637	if (GrabTo)
2638	{
2639		ADDRESS *q;
2640
2641		for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2642			q->q_state = QS_REMOVED;
2643	}
2644#endif /* _FFR_FIX_DASHT */
2645
2646	/*
2647	**  Read the input mail.
2648	*/
2649
2650	MainEnvelope.e_to = NULL;
2651	if (OpMode != MD_VERIFY || GrabTo)
2652	{
2653		int savederrors;
2654		unsigned long savedflags;
2655
2656		/*
2657		**  workaround for compiler warning on Irix:
2658		**  do not initialize variable in the definition, but
2659		**  later on:
2660		**  warning(1548): transfer of control bypasses
2661		**  initialization of:
2662		**  variable "savederrors" (declared at line 2570)
2663		**  variable "savedflags" (declared at line 2571)
2664		**  goto giveup;
2665		*/
2666
2667		savederrors = Errors;
2668		savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2669		MainEnvelope.e_flags |= EF_GLOBALERRS;
2670		MainEnvelope.e_flags &= ~EF_FATALERRS;
2671		Errors = 0;
2672		buffer_errors();
2673		collect(InChannel, false, NULL, &MainEnvelope);
2674
2675		/* header checks failed */
2676		if (Errors > 0)
2677		{
2678  giveup:
2679			if (!GrabTo)
2680			{
2681				/* Log who the mail would have gone to */
2682				logundelrcpts(&MainEnvelope,
2683					      MainEnvelope.e_message,
2684					      8, false);
2685			}
2686			flush_errors(true);
2687			finis(true, true, ExitStat);
2688			/* NOTREACHED */
2689			return -1;
2690		}
2691
2692		/* bail out if message too large */
2693		if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2694		{
2695			finis(true, true, ExitStat != EX_OK ? ExitStat
2696							    : EX_DATAERR);
2697			/* NOTREACHED */
2698			return -1;
2699		}
2700		Errors = savederrors;
2701		MainEnvelope.e_flags |= savedflags;
2702	}
2703	errno = 0;
2704
2705	if (tTd(1, 1))
2706		sm_dprintf("From person = \"%s\"\n",
2707			   MainEnvelope.e_from.q_paddr);
2708
2709#if _FFR_QUARANTINE
2710	/* Check if quarantining stats should be updated */
2711	if (MainEnvelope.e_quarmsg != NULL)
2712		markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2713#endif /* _FFR_QUARANTINE */
2714
2715	/*
2716	**  Actually send everything.
2717	**	If verifying, just ack.
2718	*/
2719
2720	if (Errors == 0)
2721	{
2722		if (!split_by_recipient(&MainEnvelope) &&
2723		    bitset(EF_FATALERRS, MainEnvelope.e_flags))
2724			goto giveup;
2725	}
2726
2727	/* make sure we deliver at least the first envelope */
2728	i = FastSplit > 0 ? 0 : -1;
2729	for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2730	{
2731		ENVELOPE *next;
2732
2733		e->e_from.q_state = QS_SENDER;
2734		if (tTd(1, 5))
2735		{
2736			sm_dprintf("main[%d]: QS_SENDER ", i);
2737			printaddr(&e->e_from, false);
2738		}
2739		e->e_to = NULL;
2740		sm_getla();
2741		GrabTo = false;
2742#if NAMED_BIND
2743		_res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2744		_res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2745#endif /* NAMED_BIND */
2746		next = e->e_sibling;
2747		e->e_sibling = NULL;
2748
2749		/* after FastSplit envelopes: queue up */
2750		sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2751		e->e_sibling = next;
2752	}
2753
2754	/*
2755	**  All done.
2756	**	Don't send return error message if in VERIFY mode.
2757	*/
2758
2759	finis(true, true, ExitStat);
2760	/* NOTREACHED */
2761	return ExitStat;
2762}
2763/*
2764**  STOP_SENDMAIL -- Stop the running program
2765**
2766**	Parameters:
2767**		none.
2768**
2769**	Returns:
2770**		none.
2771**
2772**	Side Effects:
2773**		exits.
2774*/
2775
2776void
2777stop_sendmail()
2778{
2779	/* reset uid for process accounting */
2780	endpwent();
2781	(void) setuid(RealUid);
2782	exit(EX_OK);
2783}
2784/*
2785**  FINIS -- Clean up and exit.
2786**
2787**	Parameters:
2788**		drop -- whether or not to drop CurEnv envelope
2789**		cleanup -- call exit() or _exit()?
2790**		exitstat -- exit status to use for exit() call
2791**
2792**	Returns:
2793**		never
2794**
2795**	Side Effects:
2796**		exits sendmail
2797*/
2798
2799void
2800finis(drop, cleanup, exitstat)
2801	bool drop;
2802	bool cleanup;
2803	volatile int exitstat;
2804{
2805	/* Still want to process new timeouts added below */
2806	sm_clear_events();
2807	(void) sm_releasesignal(SIGALRM);
2808
2809	if (tTd(2, 1))
2810	{
2811		sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2812			   exitstat,
2813			   CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2814		printenvflags(CurEnv);
2815	}
2816	if (tTd(2, 9))
2817		printopenfds(false);
2818
2819	SM_TRY
2820		/*
2821		**  Clean up.  This might raise E:mta.quickabort
2822		*/
2823
2824		/* clean up temp files */
2825		CurEnv->e_to = NULL;
2826		if (drop)
2827		{
2828			if (CurEnv->e_id != NULL)
2829			{
2830				dropenvelope(CurEnv, true, false);
2831				sm_rpool_free(CurEnv->e_rpool);
2832				CurEnv->e_rpool = NULL;
2833			}
2834			else
2835				poststats(StatFile);
2836		}
2837
2838		/* flush any cached connections */
2839		mci_flush(true, NULL);
2840
2841		/* close maps belonging to this pid */
2842		closemaps(false);
2843
2844#if USERDB
2845		/* close UserDatabase */
2846		_udbx_close();
2847#endif /* USERDB */
2848
2849#if SASL
2850		stop_sasl_client();
2851#endif /* SASL */
2852
2853#if XLA
2854		/* clean up extended load average stuff */
2855		xla_all_end();
2856#endif /* XLA */
2857
2858	SM_FINALLY
2859		/*
2860		**  And exit.
2861		*/
2862
2863		if (LogLevel > 78)
2864			sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
2865				  (int) CurrentPid);
2866		if (exitstat == EX_TEMPFAIL ||
2867		    CurEnv->e_errormode == EM_BERKNET)
2868			exitstat = EX_OK;
2869
2870		/* XXX clean up queues and related data structures */
2871		cleanup_queues();
2872#if SM_CONF_SHM
2873		cleanup_shm(DaemonPid == getpid());
2874#endif /* SM_CONF_SHM */
2875
2876		/* reset uid for process accounting */
2877		endpwent();
2878		sm_mbdb_terminate();
2879		(void) setuid(RealUid);
2880#if SM_HEAP_CHECK
2881		/* dump the heap, if we are checking for memory leaks */
2882		if (sm_debug_active(&SmHeapCheck, 2))
2883			sm_heap_report(smioout,
2884				       sm_debug_level(&SmHeapCheck) - 1);
2885#endif /* SM_HEAP_CHECK */
2886		if (sm_debug_active(&SmXtrapReport, 1))
2887			sm_dprintf("xtrap count = %d\n", SmXtrapCount);
2888		if (cleanup)
2889			exit(exitstat);
2890		else
2891			_exit(exitstat);
2892	SM_END_TRY
2893}
2894/*
2895**  INTINDEBUG -- signal handler for SIGINT in -bt mode
2896**
2897**	Parameters:
2898**		sig -- incoming signal.
2899**
2900**	Returns:
2901**		none.
2902**
2903**	Side Effects:
2904**		longjmps back to test mode loop.
2905**
2906**	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
2907**		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2908**		DOING.
2909*/
2910
2911/* Type of an exception generated on SIGINT during address test mode.  */
2912static const SM_EXC_TYPE_T EtypeInterrupt =
2913{
2914	SmExcTypeMagic,
2915	"S:mta.interrupt",
2916	"",
2917	sm_etype_printf,
2918	"interrupt",
2919};
2920
2921/* ARGSUSED */
2922static SIGFUNC_DECL
2923intindebug(sig)
2924	int sig;
2925{
2926	int save_errno = errno;
2927
2928	FIX_SYSV_SIGNAL(sig, intindebug);
2929	errno = save_errno;
2930	CHECK_CRITICAL(sig);
2931	errno = save_errno;
2932	sm_exc_raisenew_x(&EtypeInterrupt);
2933	errno = save_errno;
2934	return SIGFUNC_RETURN;
2935}
2936/*
2937**  SIGTERM -- SIGTERM handler for the daemon
2938**
2939**	Parameters:
2940**		sig -- signal number.
2941**
2942**	Returns:
2943**		none.
2944**
2945**	Side Effects:
2946**		Sets ShutdownRequest which will hopefully trigger
2947**		the daemon to exit.
2948**
2949**	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
2950**		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2951**		DOING.
2952*/
2953
2954/* ARGSUSED */
2955static SIGFUNC_DECL
2956sigterm(sig)
2957	int sig;
2958{
2959	int save_errno = errno;
2960
2961	FIX_SYSV_SIGNAL(sig, sigterm);
2962	ShutdownRequest = "signal";
2963	errno = save_errno;
2964	return SIGFUNC_RETURN;
2965}
2966/*
2967**  SIGHUP -- handle a SIGHUP signal
2968**
2969**	Parameters:
2970**		sig -- incoming signal.
2971**
2972**	Returns:
2973**		none.
2974**
2975**	Side Effects:
2976**		Sets RestartRequest which should cause the daemon
2977**		to restart.
2978**
2979**	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
2980**		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2981**		DOING.
2982*/
2983
2984/* ARGSUSED */
2985static SIGFUNC_DECL
2986sighup(sig)
2987	int sig;
2988{
2989	int save_errno = errno;
2990
2991	FIX_SYSV_SIGNAL(sig, sighup);
2992	RestartRequest = "signal";
2993	errno = save_errno;
2994	return SIGFUNC_RETURN;
2995}
2996/*
2997**  SIGPIPE -- signal handler for SIGPIPE
2998**
2999**	Parameters:
3000**		sig -- incoming signal.
3001**
3002**	Returns:
3003**		none.
3004**
3005**	Side Effects:
3006**		Sets StopRequest which should cause the mailq/hoststatus
3007**		display to stop.
3008**
3009**	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3010**		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3011**		DOING.
3012*/
3013
3014/* ARGSUSED */
3015static SIGFUNC_DECL
3016sigpipe(sig)
3017	int sig;
3018{
3019	int save_errno = errno;
3020
3021	FIX_SYSV_SIGNAL(sig, sigpipe);
3022	StopRequest = true;
3023	errno = save_errno;
3024	return SIGFUNC_RETURN;
3025}
3026/*
3027**  INTSIG -- clean up on interrupt
3028**
3029**	This just arranges to exit.  It pessimizes in that it
3030**	may resend a message.
3031**
3032**	Parameters:
3033**		none.
3034**
3035**	Returns:
3036**		none.
3037**
3038**	Side Effects:
3039**		Unlocks the current job.
3040**
3041**	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3042**		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3043**		DOING.
3044**
3045**		XXX: More work is needed for this signal handler.
3046*/
3047
3048/* ARGSUSED */
3049SIGFUNC_DECL
3050intsig(sig)
3051	int sig;
3052{
3053	bool drop = false;
3054	int save_errno = errno;
3055
3056	FIX_SYSV_SIGNAL(sig, intsig);
3057	errno = save_errno;
3058	CHECK_CRITICAL(sig);
3059	sm_allsignals(true);
3060
3061	if (sig != 0 && LogLevel > 79)
3062		sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3063	FileName = NULL;
3064
3065	/* Clean-up on aborted stdin message submission */
3066	if (CurEnv->e_id != NULL &&
3067	    (OpMode == MD_SMTP ||
3068	     OpMode == MD_DELIVER ||
3069	     OpMode == MD_ARPAFTP))
3070	{
3071		register ADDRESS *q;
3072
3073		/* don't return an error indication */
3074		CurEnv->e_to = NULL;
3075		CurEnv->e_flags &= ~EF_FATALERRS;
3076		CurEnv->e_flags |= EF_CLRQUEUE;
3077
3078		/*
3079		**  Spin through the addresses and
3080		**  mark them dead to prevent bounces
3081		*/
3082
3083		for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
3084			q->q_state = QS_DONTSEND;
3085
3086		drop = true;
3087	}
3088	else if (OpMode != MD_TEST)
3089	{
3090		unlockqueue(CurEnv);
3091	}
3092
3093	finis(drop, false, EX_OK);
3094	/* NOTREACHED */
3095}
3096/*
3097**  DISCONNECT -- remove our connection with any foreground process
3098**
3099**	Parameters:
3100**		droplev -- how "deeply" we should drop the line.
3101**			0 -- ignore signals, mail back errors, make sure
3102**			     output goes to stdout.
3103**			1 -- also, make stdout go to /dev/null.
3104**			2 -- also, disconnect from controlling terminal
3105**			     (only for daemon mode).
3106**		e -- the current envelope.
3107**
3108**	Returns:
3109**		none
3110**
3111**	Side Effects:
3112**		Trys to insure that we are immune to vagaries of
3113**		the controlling tty.
3114*/
3115
3116void
3117disconnect(droplev, e)
3118	int droplev;
3119	register ENVELOPE *e;
3120{
3121	int fd;
3122
3123	if (tTd(52, 1))
3124		sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3125			   sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3126			   sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3127	if (tTd(52, 100))
3128	{
3129		sm_dprintf("don't\n");
3130		return;
3131	}
3132	if (LogLevel > 93)
3133		sm_syslog(LOG_DEBUG, e->e_id,
3134			  "disconnect level %d",
3135			  droplev);
3136
3137	/* be sure we don't get nasty signals */
3138	(void) sm_signal(SIGINT, SIG_IGN);
3139	(void) sm_signal(SIGQUIT, SIG_IGN);
3140
3141	/* we can't communicate with our caller, so.... */
3142	HoldErrs = true;
3143	CurEnv->e_errormode = EM_MAIL;
3144	Verbose = 0;
3145	DisConnected = true;
3146
3147	/* all input from /dev/null */
3148	if (InChannel != smioin)
3149	{
3150		(void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3151		InChannel = smioin;
3152	}
3153	if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3154			 SM_IO_RDONLY, NULL, smioin) == NULL)
3155		sm_syslog(LOG_ERR, e->e_id,
3156			  "disconnect: sm_io_reopen(\"%s\") failed: %s",
3157			  SM_PATH_DEVNULL, sm_errstring(errno));
3158
3159	/*
3160	**  output to the transcript
3161	**	We also compare the fd numbers here since OutChannel
3162	**	might be a layer on top of smioout due to encryption
3163	**	(see sfsasl.c).
3164	*/
3165
3166	if (OutChannel != smioout &&
3167	    sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3168	    sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3169	{
3170		(void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3171		OutChannel = smioout;
3172
3173#if 0
3174		/*
3175		**  Has smioout been closed? Reopen it.
3176		**	This shouldn't happen anymore, the code is here
3177		**	just as a reminder.
3178		*/
3179
3180		if (smioout->sm_magic == NULL &&
3181		    sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3182				 SM_IO_WRONLY, NULL, smioout) == NULL)
3183			sm_syslog(LOG_ERR, e->e_id,
3184				  "disconnect: sm_io_reopen(\"%s\") failed: %s",
3185				  SM_PATH_DEVNULL, sm_errstring(errno));
3186#endif /* 0 */
3187	}
3188	if (droplev > 0)
3189	{
3190		fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3191		if (fd == -1)
3192			sm_syslog(LOG_ERR, e->e_id,
3193				  "disconnect: open(\"%s\") failed: %s",
3194				  SM_PATH_DEVNULL, sm_errstring(errno));
3195		(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3196		(void) dup2(fd, STDOUT_FILENO);
3197		(void) dup2(fd, STDERR_FILENO);
3198		(void) close(fd);
3199	}
3200
3201	/* drop our controlling TTY completely if possible */
3202	if (droplev > 1)
3203	{
3204		(void) setsid();
3205		errno = 0;
3206	}
3207
3208#if XDEBUG
3209	checkfd012("disconnect");
3210#endif /* XDEBUG */
3211
3212	if (LogLevel > 71)
3213		sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3214			  (int) CurrentPid);
3215
3216	errno = 0;
3217}
3218
3219static void
3220obsolete(argv)
3221	char *argv[];
3222{
3223	register char *ap;
3224	register char *op;
3225
3226	while ((ap = *++argv) != NULL)
3227	{
3228		/* Return if "--" or not an option of any form. */
3229		if (ap[0] != '-' || ap[1] == '-')
3230			return;
3231
3232#if _FFR_QUARANTINE
3233		/* Don't allow users to use "-Q." or "-Q ." */
3234		if ((ap[1] == 'Q' && ap[2] == '.') ||
3235		    (ap[1] == 'Q' && argv[1] != NULL &&
3236		     argv[1][0] == '.' && argv[1][1] == '\0'))
3237		{
3238			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3239					     "Can not use -Q.\n");
3240			exit(EX_USAGE);
3241		}
3242#endif /* _FFR_QUARANTINE */
3243
3244		/* skip over options that do have a value */
3245		op = strchr(OPTIONS, ap[1]);
3246		if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3247		    ap[1] != 'd' &&
3248#if defined(sony_news)
3249		    ap[1] != 'E' && ap[1] != 'J' &&
3250#endif /* defined(sony_news) */
3251		    argv[1] != NULL && argv[1][0] != '-')
3252		{
3253			argv++;
3254			continue;
3255		}
3256
3257		/* If -C doesn't have an argument, use sendmail.cf. */
3258#define __DEFPATH	"sendmail.cf"
3259		if (ap[1] == 'C' && ap[2] == '\0')
3260		{
3261			*argv = xalloc(sizeof(__DEFPATH) + 2);
3262			(void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3263					   "-C", __DEFPATH);
3264		}
3265
3266		/* If -q doesn't have an argument, run it once. */
3267		if (ap[1] == 'q' && ap[2] == '\0')
3268			*argv = "-q0";
3269
3270#if _FFR_QUARANTINE
3271		/* If -Q doesn't have an argument, disable quarantining */
3272		if (ap[1] == 'Q' && ap[2] == '\0')
3273			*argv = "-Q.";
3274#endif /* _FFR_QUARANTINE */
3275
3276		/* if -d doesn't have an argument, use 0-99.1 */
3277		if (ap[1] == 'd' && ap[2] == '\0')
3278			*argv = "-d0-99.1";
3279
3280#if defined(sony_news)
3281		/* if -E doesn't have an argument, use -EC */
3282		if (ap[1] == 'E' && ap[2] == '\0')
3283			*argv = "-EC";
3284
3285		/* if -J doesn't have an argument, use -JJ */
3286		if (ap[1] == 'J' && ap[2] == '\0')
3287			*argv = "-JJ";
3288#endif /* defined(sony_news) */
3289	}
3290}
3291/*
3292**  AUTH_WARNING -- specify authorization warning
3293**
3294**	Parameters:
3295**		e -- the current envelope.
3296**		msg -- the text of the message.
3297**		args -- arguments to the message.
3298**
3299**	Returns:
3300**		none.
3301*/
3302
3303void
3304#ifdef __STDC__
3305auth_warning(register ENVELOPE *e, const char *msg, ...)
3306#else /* __STDC__ */
3307auth_warning(e, msg, va_alist)
3308	register ENVELOPE *e;
3309	const char *msg;
3310	va_dcl
3311#endif /* __STDC__ */
3312{
3313	char buf[MAXLINE];
3314	SM_VA_LOCAL_DECL
3315
3316	if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3317	{
3318		register char *p;
3319		static char hostbuf[48];
3320
3321		if (hostbuf[0] == '\0')
3322		{
3323			struct hostent *hp;
3324
3325			hp = myhostname(hostbuf, sizeof hostbuf);
3326#if NETINET6
3327			if (hp != NULL)
3328			{
3329				freehostent(hp);
3330				hp = NULL;
3331			}
3332#endif /* NETINET6 */
3333		}
3334
3335		(void) sm_strlcpyn(buf, sizeof buf, 2, hostbuf, ": ");
3336		p = &buf[strlen(buf)];
3337		SM_VA_START(ap, msg);
3338		(void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3339		SM_VA_END(ap);
3340		addheader("X-Authentication-Warning", buf, 0, e);
3341		if (LogLevel > 3)
3342			sm_syslog(LOG_INFO, e->e_id,
3343				  "Authentication-Warning: %.400s",
3344				  buf);
3345	}
3346}
3347/*
3348**  GETEXTENV -- get from external environment
3349**
3350**	Parameters:
3351**		envar -- the name of the variable to retrieve
3352**
3353**	Returns:
3354**		The value, if any.
3355*/
3356
3357static char *
3358getextenv(envar)
3359	const char *envar;
3360{
3361	char **envp;
3362	int l;
3363
3364	l = strlen(envar);
3365	for (envp = ExternalEnviron; *envp != NULL; envp++)
3366	{
3367		if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3368			return &(*envp)[l + 1];
3369	}
3370	return NULL;
3371}
3372/*
3373**  SETUSERENV -- set an environment in the propagated environment
3374**
3375**	Parameters:
3376**		envar -- the name of the environment variable.
3377**		value -- the value to which it should be set.  If
3378**			null, this is extracted from the incoming
3379**			environment.  If that is not set, the call
3380**			to setuserenv is ignored.
3381**
3382**	Returns:
3383**		none.
3384*/
3385
3386void
3387setuserenv(envar, value)
3388	const char *envar;
3389	const char *value;
3390{
3391	int i, l;
3392	char **evp = UserEnviron;
3393	char *p;
3394
3395	if (value == NULL)
3396	{
3397		value = getextenv(envar);
3398		if (value == NULL)
3399			return;
3400	}
3401
3402	/* XXX enforce reasonable size? */
3403	i = strlen(envar) + 1;
3404	l = strlen(value) + i + 1;
3405	p = (char *) xalloc(l);
3406	(void) sm_strlcpyn(p, l, 3, envar, "=", value);
3407
3408	while (*evp != NULL && strncmp(*evp, p, i) != 0)
3409		evp++;
3410	if (*evp != NULL)
3411	{
3412		*evp++ = p;
3413	}
3414	else if (evp < &UserEnviron[MAXUSERENVIRON])
3415	{
3416		*evp++ = p;
3417		*evp = NULL;
3418	}
3419
3420	/* make sure it is in our environment as well */
3421	if (putenv(p) < 0)
3422		syserr("setuserenv: putenv(%s) failed", p);
3423}
3424/*
3425**  DUMPSTATE -- dump state
3426**
3427**	For debugging.
3428*/
3429
3430void
3431dumpstate(when)
3432	char *when;
3433{
3434	register char *j = macvalue('j', CurEnv);
3435	int rs;
3436	extern int NextMacroId;
3437
3438	sm_syslog(LOG_DEBUG, CurEnv->e_id,
3439		  "--- dumping state on %s: $j = %s ---",
3440		  when,
3441		  j == NULL ? "<NULL>" : j);
3442	if (j != NULL)
3443	{
3444		if (!wordinclass(j, 'w'))
3445			sm_syslog(LOG_DEBUG, CurEnv->e_id,
3446				  "*** $j not in $=w ***");
3447	}
3448	sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3449	sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3450		  NextMacroId, MAXMACROID);
3451	sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3452	printopenfds(true);
3453	sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3454	mci_dump_all(true);
3455	rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3456	if (rs > 0)
3457	{
3458		int status;
3459		register char **pvp;
3460		char *pv[MAXATOM + 1];
3461
3462		pv[0] = NULL;
3463		status = REWRITE(pv, rs, CurEnv);
3464		sm_syslog(LOG_DEBUG, CurEnv->e_id,
3465			  "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3466			  status);
3467		for (pvp = pv; *pvp != NULL; pvp++)
3468			sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3469	}
3470	sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3471}
3472
3473#ifdef SIGUSR1
3474/*
3475**  SIGUSR1 -- Signal a request to dump state.
3476**
3477**	Parameters:
3478**		sig -- calling signal.
3479**
3480**	Returns:
3481**		none.
3482**
3483**	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3484**		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3485**		DOING.
3486**
3487**		XXX: More work is needed for this signal handler.
3488*/
3489
3490/* ARGSUSED */
3491static SIGFUNC_DECL
3492sigusr1(sig)
3493	int sig;
3494{
3495	int save_errno = errno;
3496# if SM_HEAP_CHECK
3497	extern void dumpstab __P((void));
3498# endif /* SM_HEAP_CHECK */
3499
3500	FIX_SYSV_SIGNAL(sig, sigusr1);
3501	errno = save_errno;
3502	CHECK_CRITICAL(sig);
3503	dumpstate("user signal");
3504# if SM_HEAP_CHECK
3505	dumpstab();
3506# endif /* SM_HEAP_CHECK */
3507	errno = save_errno;
3508	return SIGFUNC_RETURN;
3509}
3510#endif /* SIGUSR1 */
3511
3512/*
3513**  DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3514**
3515**	Parameters:
3516**		to_real_uid -- if set, drop to the real uid instead
3517**			of the RunAsUser.
3518**
3519**	Returns:
3520**		EX_OSERR if the setuid failed.
3521**		EX_OK otherwise.
3522*/
3523
3524int
3525drop_privileges(to_real_uid)
3526	bool to_real_uid;
3527{
3528	int rval = EX_OK;
3529	GIDSET_T emptygidset[1];
3530
3531	if (tTd(47, 1))
3532		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",
3533			   (int) to_real_uid,
3534			   (int) RealUid, (int) RealGid,
3535			   (int) getuid(), (int) getgid(),
3536			   (int) geteuid(), (int) getegid(),
3537			   (int) RunAsUid, (int) RunAsGid);
3538
3539	if (to_real_uid)
3540	{
3541		RunAsUserName = RealUserName;
3542		RunAsUid = RealUid;
3543		RunAsGid = RealGid;
3544		EffGid = RunAsGid;
3545	}
3546
3547	/* make sure no one can grab open descriptors for secret files */
3548	endpwent();
3549	sm_mbdb_terminate();
3550
3551	/* reset group permissions; these can be set later */
3552	emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3553
3554	/*
3555	**  Notice:  on some OS (Linux...) the setgroups() call causes
3556	**	a logfile entry if sendmail is not run by root.
3557	**	However, it is unclear (no POSIX standard) whether
3558	**	setgroups() can only succeed if executed by root.
3559	**	So for now we keep it as it is; if you want to change it, use
3560	**  if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3561	*/
3562
3563	if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3564	{
3565		syserr("drop_privileges: setgroups(1, %d) failed",
3566		       (int) emptygidset[0]);
3567		rval = EX_OSERR;
3568	}
3569
3570	/* reset primary group id */
3571	if (to_real_uid)
3572	{
3573		/*
3574		**  Drop gid to real gid.
3575		**  On some OS we must reset the effective[/real[/saved]] gid,
3576		**  and then use setgid() to finally drop all group privileges.
3577		**  Later on we check whether we can get back the
3578		**  effective gid.
3579		*/
3580
3581#if HASSETEGID
3582		if (setegid(RunAsGid) < 0)
3583		{
3584			syserr("drop_privileges: setegid(%d) failed",
3585			       (int) RunAsGid);
3586			rval = EX_OSERR;
3587		}
3588#else /* HASSETEGID */
3589# if HASSETREGID
3590		if (setregid(RunAsGid, RunAsGid) < 0)
3591		{
3592			syserr("drop_privileges: setregid(%d, %d) failed",
3593			       (int) RunAsGid, (int) RunAsGid);
3594			rval = EX_OSERR;
3595		}
3596# else /* HASSETREGID */
3597#  if HASSETRESGID
3598		if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3599		{
3600			syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3601			       (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3602			rval = EX_OSERR;
3603		}
3604#  endif /* HASSETRESGID */
3605# endif /* HASSETREGID */
3606#endif /* HASSETEGID */
3607	}
3608	if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3609	{
3610		if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3611		{
3612			syserr("drop_privileges: setgid(%d) failed",
3613			       (int) RunAsGid);
3614			rval = EX_OSERR;
3615		}
3616		errno = 0;
3617		if (rval == EX_OK && getegid() != RunAsGid)
3618		{
3619			syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3620			       (int) getegid(), (int) RunAsGid);
3621			rval = EX_OSERR;
3622		}
3623	}
3624
3625	/* fiddle with uid */
3626	if (to_real_uid || RunAsUid != 0)
3627	{
3628		uid_t euid;
3629
3630		/*
3631		**  Try to setuid(RunAsUid).
3632		**  euid must be RunAsUid,
3633		**  ruid must be RunAsUid unless (e|r)uid wasn't 0
3634		**	and we didn't have to drop privileges to the real uid.
3635		*/
3636
3637		if (setuid(RunAsUid) < 0 ||
3638		    geteuid() != RunAsUid ||
3639		    (getuid() != RunAsUid &&
3640		     (to_real_uid || geteuid() == 0 || getuid() == 0)))
3641		{
3642#if HASSETREUID
3643			/*
3644			**  if ruid != RunAsUid, euid == RunAsUid, then
3645			**  try resetting just the real uid, then using
3646			**  setuid() to drop the saved-uid as well.
3647			*/
3648
3649			if (geteuid() == RunAsUid)
3650			{
3651				if (setreuid(RunAsUid, -1) < 0)
3652				{
3653					syserr("drop_privileges: setreuid(%d, -1) failed",
3654					       (int) RunAsUid);
3655					rval = EX_OSERR;
3656				}
3657				if (setuid(RunAsUid) < 0)
3658				{
3659					syserr("drop_privileges: second setuid(%d) attempt failed",
3660					       (int) RunAsUid);
3661					rval = EX_OSERR;
3662				}
3663			}
3664			else
3665#endif /* HASSETREUID */
3666			{
3667				syserr("drop_privileges: setuid(%d) failed",
3668				       (int) RunAsUid);
3669				rval = EX_OSERR;
3670			}
3671		}
3672		euid = geteuid();
3673		if (RunAsUid != 0 && setuid(0) == 0)
3674		{
3675			/*
3676			**  Believe it or not, the Linux capability model
3677			**  allows a non-root process to override setuid()
3678			**  on a process running as root and prevent that
3679			**  process from dropping privileges.
3680			*/
3681
3682			syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3683			rval = EX_OSERR;
3684		}
3685		else if (RunAsUid != euid && setuid(euid) == 0)
3686		{
3687			/*
3688			**  Some operating systems will keep the saved-uid
3689			**  if a non-root effective-uid calls setuid(real-uid)
3690			**  making it possible to set it back again later.
3691			*/
3692
3693			syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3694			rval = EX_OSERR;
3695		}
3696	}
3697
3698	if ((to_real_uid || RunAsGid != 0) &&
3699	    rval == EX_OK && RunAsGid != EffGid &&
3700	    getuid() != 0 && geteuid() != 0)
3701	{
3702		errno = 0;
3703		if (setgid(EffGid) == 0)
3704		{
3705			syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3706			       (int) EffGid);
3707			rval = EX_OSERR;
3708		}
3709	}
3710
3711	if (tTd(47, 5))
3712	{
3713		sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3714			   (int) geteuid(), (int) getuid(),
3715			   (int) getegid(), (int) getgid());
3716		sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3717			   (int) RunAsUid, (int) RunAsGid);
3718		if (tTd(47, 10))
3719			sm_dprintf("drop_privileges: rval = %d\n", rval);
3720	}
3721	return rval;
3722}
3723/*
3724**  FILL_FD -- make sure a file descriptor has been properly allocated
3725**
3726**	Used to make sure that stdin/out/err are allocated on startup
3727**
3728**	Parameters:
3729**		fd -- the file descriptor to be filled.
3730**		where -- a string used for logging.  If NULL, this is
3731**			being called on startup, and logging should
3732**			not be done.
3733**
3734**	Returns:
3735**		none
3736**
3737**	Side Effects:
3738**		possibly changes MissingFds
3739*/
3740
3741void
3742fill_fd(fd, where)
3743	int fd;
3744	char *where;
3745{
3746	int i;
3747	struct stat stbuf;
3748
3749	if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3750		return;
3751
3752	if (where != NULL)
3753		syserr("fill_fd: %s: fd %d not open", where, fd);
3754	else
3755		MissingFds |= 1 << fd;
3756	i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3757	if (i < 0)
3758	{
3759		syserr("!fill_fd: %s: cannot open %s",
3760		       where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3761	}
3762	if (fd != i)
3763	{
3764		(void) dup2(i, fd);
3765		(void) close(i);
3766	}
3767}
3768/*
3769**  SM_PRINTOPTIONS -- print options
3770**
3771**	Parameters:
3772**		options -- array of options.
3773**
3774**	Returns:
3775**		none.
3776*/
3777
3778static void
3779sm_printoptions(options)
3780	char **options;
3781{
3782	int ll;
3783	char **av;
3784
3785	av = options;
3786	ll = 7;
3787	while (*av != NULL)
3788	{
3789		if (ll + strlen(*av) > 63)
3790		{
3791			sm_dprintf("\n");
3792			ll = 0;
3793		}
3794		if (ll == 0)
3795			sm_dprintf("\t\t");
3796		else
3797			sm_dprintf(" ");
3798		sm_dprintf("%s", *av);
3799		ll += strlen(*av++) + 1;
3800	}
3801	sm_dprintf("\n");
3802}
3803/*
3804**  TESTMODELINE -- process a test mode input line
3805**
3806**	Parameters:
3807**		line -- the input line.
3808**		e -- the current environment.
3809**	Syntax:
3810**		#  a comment
3811**		.X process X as a configuration line
3812**		=X dump a configuration item (such as mailers)
3813**		$X dump a macro or class
3814**		/X try an activity
3815**		X  normal process through rule set X
3816*/
3817
3818static void
3819testmodeline(line, e)
3820	char *line;
3821	ENVELOPE *e;
3822{
3823	register char *p;
3824	char *q;
3825	auto char *delimptr;
3826	int mid;
3827	int i, rs;
3828	STAB *map;
3829	char **s;
3830	struct rewrite *rw;
3831	ADDRESS a;
3832	static int tryflags = RF_COPYNONE;
3833	char exbuf[MAXLINE];
3834	extern unsigned char TokTypeNoC[];
3835
3836	/* skip leading spaces */
3837	while (*line == ' ')
3838		line++;
3839
3840	switch (line[0])
3841	{
3842	  case '#':
3843	  case '\0':
3844		return;
3845
3846	  case '?':
3847		help("-bt", e);
3848		return;
3849
3850	  case '.':		/* config-style settings */
3851		switch (line[1])
3852		{
3853		  case 'D':
3854			mid = macid_parse(&line[2], &delimptr);
3855			if (mid == 0)
3856				return;
3857			translate_dollars(delimptr);
3858			macdefine(&e->e_macro, A_TEMP, mid, delimptr);
3859			break;
3860
3861		  case 'C':
3862			if (line[2] == '\0')	/* not to call syserr() */
3863				return;
3864
3865			mid = macid_parse(&line[2], &delimptr);
3866			if (mid == 0)
3867				return;
3868			translate_dollars(delimptr);
3869			expand(delimptr, exbuf, sizeof exbuf, e);
3870			p = exbuf;
3871			while (*p != '\0')
3872			{
3873				register char *wd;
3874				char delim;
3875
3876				while (*p != '\0' && isascii(*p) && isspace(*p))
3877					p++;
3878				wd = p;
3879				while (*p != '\0' && !(isascii(*p) && isspace(*p)))
3880					p++;
3881				delim = *p;
3882				*p = '\0';
3883				if (wd[0] != '\0')
3884					setclass(mid, wd);
3885				*p = delim;
3886			}
3887			break;
3888
3889		  case '\0':
3890			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3891					     "Usage: .[DC]macro value(s)\n");
3892			break;
3893
3894		  default:
3895			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3896					     "Unknown \".\" command %s\n", line);
3897			break;
3898		}
3899		return;
3900
3901	  case '=':		/* config-style settings */
3902		switch (line[1])
3903		{
3904		  case 'S':		/* dump rule set */
3905			rs = strtorwset(&line[2], NULL, ST_FIND);
3906			if (rs < 0)
3907			{
3908				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3909						     "Undefined ruleset %s\n", &line[2]);
3910				return;
3911			}
3912			rw = RewriteRules[rs];
3913			if (rw == NULL)
3914				return;
3915			do
3916			{
3917				(void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3918						  'R');
3919				s = rw->r_lhs;
3920				while (*s != NULL)
3921				{
3922					xputs(*s++);
3923					(void) sm_io_putc(smioout,
3924							  SM_TIME_DEFAULT, ' ');
3925				}
3926				(void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3927						  '\t');
3928				(void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3929						  '\t');
3930				s = rw->r_rhs;
3931				while (*s != NULL)
3932				{
3933					xputs(*s++);
3934					(void) sm_io_putc(smioout,
3935							  SM_TIME_DEFAULT, ' ');
3936				}
3937				(void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3938						  '\n');
3939			} while ((rw = rw->r_next) != NULL);
3940			break;
3941
3942		  case 'M':
3943			for (i = 0; i < MAXMAILERS; i++)
3944			{
3945				if (Mailer[i] != NULL)
3946					printmailer(Mailer[i]);
3947			}
3948			break;
3949
3950		  case '\0':
3951			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3952					     "Usage: =Sruleset or =M\n");
3953			break;
3954
3955		  default:
3956			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3957					     "Unknown \"=\" command %s\n", line);
3958			break;
3959		}
3960		return;
3961
3962	  case '-':		/* set command-line-like opts */
3963		switch (line[1])
3964		{
3965		  case 'd':
3966			tTflag(&line[2]);
3967			break;
3968
3969		  case '\0':
3970			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3971					     "Usage: -d{debug arguments}\n");
3972			break;
3973
3974		  default:
3975			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3976					     "Unknown \"-\" command %s\n", line);
3977			break;
3978		}
3979		return;
3980
3981	  case '$':
3982		if (line[1] == '=')
3983		{
3984			mid = macid(&line[2]);
3985			if (mid != 0)
3986				stabapply(dump_class, mid);
3987			return;
3988		}
3989		mid = macid(&line[1]);
3990		if (mid == 0)
3991			return;
3992		p = macvalue(mid, e);
3993		if (p == NULL)
3994			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3995					     "Undefined\n");
3996		else
3997		{
3998			xputs(p);
3999			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4000					     "\n");
4001		}
4002		return;
4003
4004	  case '/':		/* miscellaneous commands */
4005		p = &line[strlen(line)];
4006		while (--p >= line && isascii(*p) && isspace(*p))
4007			*p = '\0';
4008		p = strpbrk(line, " \t");
4009		if (p != NULL)
4010		{
4011			while (isascii(*p) && isspace(*p))
4012				*p++ = '\0';
4013		}
4014		else
4015			p = "";
4016		if (line[1] == '\0')
4017		{
4018			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4019					     "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4020			return;
4021		}
4022		if (sm_strcasecmp(&line[1], "quit") == 0)
4023		{
4024			CurEnv->e_id = NULL;
4025			finis(true, true, ExitStat);
4026			/* NOTREACHED */
4027		}
4028		if (sm_strcasecmp(&line[1], "mx") == 0)
4029		{
4030#if NAMED_BIND
4031			/* look up MX records */
4032			int nmx;
4033			auto int rcode;
4034			char *mxhosts[MAXMXHOSTS + 1];
4035
4036			if (*p == '\0')
4037			{
4038				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4039						     "Usage: /mx address\n");
4040				return;
4041			}
4042			nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4043				      NULL);
4044			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4045					     "getmxrr(%s) returns %d value(s):\n",
4046				p, nmx);
4047			for (i = 0; i < nmx; i++)
4048				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4049						     "\t%s\n", mxhosts[i]);
4050#else /* NAMED_BIND */
4051			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4052					     "No MX code compiled in\n");
4053#endif /* NAMED_BIND */
4054		}
4055		else if (sm_strcasecmp(&line[1], "canon") == 0)
4056		{
4057			char host[MAXHOSTNAMELEN];
4058
4059			if (*p == '\0')
4060			{
4061				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4062						     "Usage: /canon address\n");
4063				return;
4064			}
4065			else if (sm_strlcpy(host, p, sizeof host) >= sizeof host)
4066			{
4067				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4068						     "Name too long\n");
4069				return;
4070			}
4071			(void) getcanonname(host, sizeof host, HasWildcardMX,
4072					    NULL);
4073			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4074					     "getcanonname(%s) returns %s\n",
4075					     p, host);
4076		}
4077		else if (sm_strcasecmp(&line[1], "map") == 0)
4078		{
4079			auto int rcode = EX_OK;
4080			char *av[2];
4081
4082			if (*p == '\0')
4083			{
4084				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4085						     "Usage: /map mapname key\n");
4086				return;
4087			}
4088			for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q));			     q++)
4089				continue;
4090			if (*q == '\0')
4091			{
4092				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4093						     "No key specified\n");
4094				return;
4095			}
4096			*q++ = '\0';
4097			map = stab(p, ST_MAP, ST_FIND);
4098			if (map == NULL)
4099			{
4100				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4101						     "Map named \"%s\" not found\n", p);
4102				return;
4103			}
4104			if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4105			    !openmap(&(map->s_map)))
4106			{
4107				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4108						     "Map named \"%s\" not open\n", p);
4109				return;
4110			}
4111			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4112					     "map_lookup: %s (%s) ", p, q);
4113			av[0] = q;
4114			av[1] = NULL;
4115			p = (*map->s_map.map_class->map_lookup)
4116					(&map->s_map, q, av, &rcode);
4117			if (p == NULL)
4118				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4119						     "no match (%d)\n",
4120						     rcode);
4121			else
4122				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4123						     "returns %s (%d)\n", p,
4124						     rcode);
4125		}
4126		else if (sm_strcasecmp(&line[1], "try") == 0)
4127		{
4128			MAILER *m;
4129			STAB *st;
4130			auto int rcode = EX_OK;
4131
4132			q = strpbrk(p, " \t");
4133			if (q != NULL)
4134			{
4135				while (isascii(*q) && isspace(*q))
4136					*q++ = '\0';
4137			}
4138			if (q == NULL || *q == '\0')
4139			{
4140				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4141						     "Usage: /try mailer address\n");
4142				return;
4143			}
4144			st = stab(p, ST_MAILER, ST_FIND);
4145			if (st == NULL)
4146			{
4147				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4148						     "Unknown mailer %s\n", p);
4149				return;
4150			}
4151			m = st->s_mailer;
4152			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4153					     "Trying %s %s address %s for mailer %s\n",
4154				     bitset(RF_HEADERADDR, tryflags) ? "header"
4155							: "envelope",
4156				     bitset(RF_SENDERADDR, tryflags) ? "sender"
4157							: "recipient", q, p);
4158			p = remotename(q, m, tryflags, &rcode, CurEnv);
4159			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4160					     "Rcode = %d, addr = %s\n",
4161					     rcode, p == NULL ? "<NULL>" : p);
4162			e->e_to = NULL;
4163		}
4164		else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4165		{
4166			if (*p == '\0')
4167			{
4168				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4169						     "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4170				return;
4171			}
4172			for (; *p != '\0'; p++)
4173			{
4174				switch (*p)
4175				{
4176				  case 'H':
4177				  case 'h':
4178					tryflags |= RF_HEADERADDR;
4179					break;
4180
4181				  case 'E':
4182				  case 'e':
4183					tryflags &= ~RF_HEADERADDR;
4184					break;
4185
4186				  case 'S':
4187				  case 's':
4188					tryflags |= RF_SENDERADDR;
4189					break;
4190
4191				  case 'R':
4192				  case 'r':
4193					tryflags &= ~RF_SENDERADDR;
4194					break;
4195				}
4196			}
4197			exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4198			exbuf[1] = ' ';
4199			exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4200			exbuf[3] = '\0';
4201			macdefine(&e->e_macro, A_TEMP,
4202				macid("{addr_type}"), exbuf);
4203		}
4204		else if (sm_strcasecmp(&line[1], "parse") == 0)
4205		{
4206			if (*p == '\0')
4207			{
4208				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4209						     "Usage: /parse address\n");
4210				return;
4211			}
4212			q = crackaddr(p);
4213			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4214					     "Cracked address = ");
4215			xputs(q);
4216			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4217					     "\nParsing %s %s address\n",
4218					     bitset(RF_HEADERADDR, tryflags) ?
4219							"header" : "envelope",
4220					     bitset(RF_SENDERADDR, tryflags) ?
4221							"sender" : "recipient");
4222			if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4223			    == NULL)
4224				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4225						     "Cannot parse\n");
4226			else if (a.q_host != NULL && a.q_host[0] != '\0')
4227				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4228						     "mailer %s, host %s, user %s\n",
4229						     a.q_mailer->m_name,
4230						     a.q_host,
4231						     a.q_user);
4232			else
4233				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4234						     "mailer %s, user %s\n",
4235						     a.q_mailer->m_name,
4236						     a.q_user);
4237			e->e_to = NULL;
4238		}
4239		else
4240		{
4241			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4242					     "Unknown \"/\" command %s\n",
4243					     line);
4244		}
4245		return;
4246	}
4247
4248	for (p = line; isascii(*p) && isspace(*p); p++)
4249		continue;
4250	q = p;
4251	while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4252		p++;
4253	if (*p == '\0')
4254	{
4255		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4256				     "No address!\n");
4257		return;
4258	}
4259	*p = '\0';
4260	if (invalidaddr(p + 1, NULL, true))
4261		return;
4262	do
4263	{
4264		register char **pvp;
4265		char pvpbuf[PSBUFSIZE];
4266
4267		pvp = prescan(++p, ',', pvpbuf, sizeof pvpbuf,
4268			      &delimptr, ConfigLevel >= 9 ? TokTypeNoC : NULL);
4269		if (pvp == NULL)
4270			continue;
4271		p = q;
4272		while (*p != '\0')
4273		{
4274			int status;
4275
4276			rs = strtorwset(p, NULL, ST_FIND);
4277			if (rs < 0)
4278			{
4279				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4280						     "Undefined ruleset %s\n",
4281						     p);
4282				break;
4283			}
4284			status = REWRITE(pvp, rs, e);
4285			if (status != EX_OK)
4286				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4287						     "== Ruleset %s (%d) status %d\n",
4288						     p, rs, status);
4289			while (*p != '\0' && *p++ != ',')
4290				continue;
4291		}
4292	} while (*(p = delimptr) != '\0');
4293}
4294
4295static void
4296dump_class(s, id)
4297	register STAB *s;
4298	int id;
4299{
4300	if (s->s_symtype != ST_CLASS)
4301		return;
4302	if (bitnset(bitidx(id), s->s_class))
4303		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4304				     "%s\n", s->s_name);
4305}
4306
4307/*
4308**  An exception type used to create QuickAbort exceptions.
4309**  This is my first cut at converting QuickAbort from longjmp to exceptions.
4310**  These exceptions have a single integer argument, which is the argument
4311**  to longjmp in the original code (either 1 or 2).  I don't know the
4312**  significance of 1 vs 2: the calls to setjmp don't care.
4313*/
4314
4315const SM_EXC_TYPE_T EtypeQuickAbort =
4316{
4317	SmExcTypeMagic,
4318	"E:mta.quickabort",
4319	"i",
4320	sm_etype_printf,
4321	"quick abort %0",
4322};
4323