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