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