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