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