xref: /illumos-gate/usr/src/cmd/sendmail/src/main.c (revision b6c3f786)
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.963 2007/06/29 20:07: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 #if _FFR_RUNPQG
2375 			if (qgrp != NOQGRP)
2376 			{
2377 				int rwgflags = RWG_NONE;
2378 
2379 				/*
2380 				**  To run a specific queue group mark it to
2381 				**  be run, select the work group it's in and
2382 				**  increment the work counter.
2383 				*/
2384 
2385 				for (i = 0; i < NumQueue && Queue[i] != NULL;
2386 				     i++)
2387 					Queue[i]->qg_nextrun = (time_t) -1;
2388 				Queue[qgrp]->qg_nextrun = 0;
2389 				if (Verbose)
2390 					rwgflags |= RWG_VERBOSE;
2391 				if (queuepersistent)
2392 					rwgflags |= RWG_PERSISTENT;
2393 				rwgflags |= RWG_FORCE;
2394 				(void) run_work_group(Queue[qgrp]->qg_wgrp,
2395 						      rwgflags);
2396 			}
2397 			else
2398 #endif /* _FFR_RUNPQG */
2399 				(void) runqueue(true, false, queuepersistent,
2400 						true);
2401 
2402 			/*
2403 			**  If queuepersistent but not in daemon mode then
2404 			**  we're going to do the queue runner monitoring here.
2405 			**  If in daemon mode then the monitoring will happen
2406 			**  elsewhere.
2407 			*/
2408 
2409 			if (OpMode != MD_DAEMON && queuepersistent)
2410 			{
2411 				/*
2412 				**  Write the pid to file
2413 				**  XXX Overwrites sendmail.pid
2414 				*/
2415 
2416 				log_sendmail_pid(&MainEnvelope);
2417 
2418 				/* set the title to make it easier to find */
2419 				sm_setproctitle(true, CurEnv, "Queue control");
2420 				(void) sm_signal(SIGCHLD, SIG_DFL);
2421 				while (CurChildren > 0)
2422 				{
2423 					int status;
2424 					pid_t ret;
2425 					int group;
2426 
2427 					CHECK_RESTART;
2428 					errno = 0;
2429 					while ((ret = sm_wait(&status)) <= 0)
2430 					{
2431 						/*
2432 						**  Waiting for non-existent
2433 						**  children shouldn't happen.
2434 						**  Let's get out of here if
2435 						**  it occurs.
2436 						*/
2437 
2438 						if (errno == ECHILD)
2439 						{
2440 							CurChildren = 0;
2441 							break;
2442 						}
2443 						continue;
2444 					}
2445 
2446 					/* something is really really wrong */
2447 					if (errno == ECHILD)
2448 					{
2449 						sm_syslog(LOG_ERR, NOQID,
2450 							  "persistent queue runner control process: lost all children: wait returned ECHILD");
2451 						break;
2452 					}
2453 
2454 					if (WIFSTOPPED(status))
2455 						continue;
2456 
2457 					/* Probe only on a child status */
2458 					proc_list_drop(ret, status, &group);
2459 
2460 					if (WIFSIGNALED(status))
2461 					{
2462 						if (WCOREDUMP(status))
2463 						{
2464 							sm_syslog(LOG_ERR, NOQID,
2465 								  "persistent queue runner=%d core dumped, signal=%d",
2466 								  group, WTERMSIG(status));
2467 
2468 							/* don't restart this */
2469 							mark_work_group_restart(
2470 								group, -1);
2471 							continue;
2472 						}
2473 
2474 						sm_syslog(LOG_ERR, NOQID,
2475 							  "persistent queue runner=%d died, pid=%ld, signal=%d",
2476 							  group, (long) ret,
2477 							  WTERMSIG(status));
2478 					}
2479 
2480 					/*
2481 					**  When debugging active, don't
2482 					**  restart the persistent queues.
2483 					**  But do log this as info.
2484 					*/
2485 
2486 					if (sm_debug_active(&DebugNoPRestart,
2487 							    1))
2488 					{
2489 						sm_syslog(LOG_DEBUG, NOQID,
2490 							  "persistent queue runner=%d, exited",
2491 							  group);
2492 						mark_work_group_restart(group,
2493 									-1);
2494 					}
2495 					CHECK_RESTART;
2496 				}
2497 				finis(true, true, ExitStat);
2498 				/* NOTREACHED */
2499 			}
2500 
2501 			if (OpMode != MD_DAEMON)
2502 			{
2503 				char qtype[200];
2504 
2505 				/*
2506 				**  Write the pid to file
2507 				**  XXX Overwrites sendmail.pid
2508 				*/
2509 
2510 				log_sendmail_pid(&MainEnvelope);
2511 
2512 				/* set the title to make it easier to find */
2513 				qtype[0] = '\0';
2514 				(void) sm_strlcpyn(qtype, sizeof(qtype), 4,
2515 						   "Queue runner@",
2516 						   pintvl(QueueIntvl, true),
2517 						   " for ",
2518 						   QueueDir);
2519 				sm_setproctitle(true, CurEnv, qtype);
2520 				for (;;)
2521 				{
2522 					(void) pause();
2523 
2524 					CHECK_RESTART;
2525 
2526 					if (doqueuerun())
2527 						(void) runqueue(true, false,
2528 								false, false);
2529 				}
2530 			}
2531 		}
2532 		dropenvelope(&MainEnvelope, true, false);
2533 
2534 #if STARTTLS
2535 		/* init TLS for server, ignore result for now */
2536 		(void) initsrvtls(tls_ok);
2537 #endif /* STARTTLS */
2538 
2539 	nextreq:
2540 		p_flags = getrequests(&MainEnvelope);
2541 
2542 		/* drop privileges */
2543 		(void) drop_privileges(false);
2544 
2545 		/*
2546 		**  Get authentication data
2547 		**  Set _ macro in BlankEnvelope before calling newenvelope().
2548 		*/
2549 
2550 		authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2551 						     NULL), &forged);
2552 		macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2553 
2554 		/* at this point we are in a child: reset state */
2555 		sm_rpool_free(MainEnvelope.e_rpool);
2556 		(void) newenvelope(&MainEnvelope, &MainEnvelope,
2557 				   sm_rpool_new_x(NULL));
2558 	}
2559 
2560 	if (LogLevel > 9)
2561 	{
2562 		/* log connection information */
2563 		sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2564 	}
2565 
2566 	/*
2567 	**  If running SMTP protocol, start collecting and executing
2568 	**  commands.  This will never return.
2569 	*/
2570 
2571 	if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2572 	{
2573 		char pbuf[20];
2574 
2575 		/*
2576 		**  Save some macros for check_* rulesets.
2577 		*/
2578 
2579 		if (forged)
2580 		{
2581 			char ipbuf[103];
2582 
2583 			(void) sm_snprintf(ipbuf, sizeof(ipbuf), "[%.100s]",
2584 					   anynet_ntoa(&RealHostAddr));
2585 			macdefine(&BlankEnvelope.e_macro, A_TEMP,
2586 				  macid("{client_name}"), ipbuf);
2587 		}
2588 		else
2589 			macdefine(&BlankEnvelope.e_macro, A_PERM,
2590 				  macid("{client_name}"), RealHostName);
2591 		macdefine(&BlankEnvelope.e_macro, A_PERM,
2592 			  macid("{client_ptr}"), RealHostName);
2593 		macdefine(&BlankEnvelope.e_macro, A_TEMP,
2594 			  macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2595 		sm_getla();
2596 
2597 		switch (RealHostAddr.sa.sa_family)
2598 		{
2599 #if NETINET
2600 		  case AF_INET:
2601 			(void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2602 					   RealHostAddr.sin.sin_port);
2603 			break;
2604 #endif /* NETINET */
2605 #if NETINET6
2606 		  case AF_INET6:
2607 			(void) sm_snprintf(pbuf, sizeof(pbuf), "%d",
2608 					   RealHostAddr.sin6.sin6_port);
2609 			break;
2610 #endif /* NETINET6 */
2611 		  default:
2612 			(void) sm_snprintf(pbuf, sizeof(pbuf), "0");
2613 			break;
2614 		}
2615 		macdefine(&BlankEnvelope.e_macro, A_TEMP,
2616 			macid("{client_port}"), pbuf);
2617 
2618 		if (OpMode == MD_DAEMON)
2619 		{
2620 			ENVELOPE *saved_env;
2621 
2622 			/* validate the connection */
2623 			HoldErrs = true;
2624 			saved_env = CurEnv;
2625 			CurEnv = &BlankEnvelope;
2626 			nullserver = validate_connection(&RealHostAddr,
2627 						macvalue(macid("{client_name}"),
2628 							&BlankEnvelope),
2629 						&BlankEnvelope);
2630 			if (bitset(EF_DISCARD, BlankEnvelope.e_flags))
2631 				MainEnvelope.e_flags |= EF_DISCARD;
2632 			CurEnv = saved_env;
2633 			HoldErrs = false;
2634 		}
2635 		else if (p_flags == NULL)
2636 		{
2637 			p_flags = (BITMAP256 *) xalloc(sizeof(*p_flags));
2638 			clrbitmap(p_flags);
2639 		}
2640 #if STARTTLS
2641 		if (OpMode == MD_SMTP)
2642 			(void) initsrvtls(tls_ok);
2643 #endif /* STARTTLS */
2644 
2645 		/* turn off profiling */
2646 		SM_PROF(1);
2647 		smtp(nullserver, *p_flags, &MainEnvelope);
2648 
2649 		if (tTd(93, 100))
2650 		{
2651 			/* turn off profiling */
2652 			SM_PROF(0);
2653 			if (OpMode == MD_DAEMON)
2654 				goto nextreq;
2655 		}
2656 	}
2657 
2658 	sm_rpool_free(MainEnvelope.e_rpool);
2659 	clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2660 	if (OpMode == MD_VERIFY)
2661 	{
2662 		set_delivery_mode(SM_VERIFY, &MainEnvelope);
2663 		PostMasterCopy = NULL;
2664 	}
2665 	else
2666 	{
2667 		/* interactive -- all errors are global */
2668 		MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2669 	}
2670 
2671 	/*
2672 	**  Do basic system initialization and set the sender
2673 	*/
2674 
2675 	initsys(&MainEnvelope);
2676 	macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2677 	macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2678 	setsender(from, &MainEnvelope, NULL, '\0', false);
2679 	if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2680 	    (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2681 	     strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2682 	{
2683 		auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2684 			     RealUserName, from, warn_f_flag);
2685 #if SASL
2686 		auth = false;
2687 #endif /* SASL */
2688 	}
2689 	if (auth)
2690 	{
2691 		char *fv;
2692 
2693 		/* set the initial sender for AUTH= to $f@$j */
2694 		fv = macvalue('f', &MainEnvelope);
2695 		if (fv == NULL || *fv == '\0')
2696 			MainEnvelope.e_auth_param = NULL;
2697 		else
2698 		{
2699 			if (strchr(fv, '@') == NULL)
2700 			{
2701 				i = strlen(fv) + strlen(macvalue('j',
2702 							&MainEnvelope)) + 2;
2703 				p = sm_malloc_x(i);
2704 				(void) sm_strlcpyn(p, i, 3, fv, "@",
2705 						   macvalue('j',
2706 							    &MainEnvelope));
2707 			}
2708 			else
2709 				p = sm_strdup_x(fv);
2710 			MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2711 								      xtextify(p, "="));
2712 			sm_free(p);  /* XXX */
2713 		}
2714 	}
2715 	if (macvalue('s', &MainEnvelope) == NULL)
2716 		macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2717 
2718 	av = argv + optind;
2719 	if (*av == NULL && !GrabTo)
2720 	{
2721 		MainEnvelope.e_to = NULL;
2722 		MainEnvelope.e_flags |= EF_GLOBALERRS;
2723 		HoldErrs = false;
2724 		SuperSafe = SAFE_NO;
2725 		usrerr("Recipient names must be specified");
2726 
2727 		/* collect body for UUCP return */
2728 		if (OpMode != MD_VERIFY)
2729 			collect(InChannel, false, NULL, &MainEnvelope, true);
2730 		finis(true, true, EX_USAGE);
2731 		/* NOTREACHED */
2732 	}
2733 
2734 	/*
2735 	**  Scan argv and deliver the message to everyone.
2736 	*/
2737 
2738 	save_val = LogUsrErrs;
2739 	LogUsrErrs = true;
2740 	sendtoargv(av, &MainEnvelope);
2741 	LogUsrErrs = save_val;
2742 
2743 	/* if we have had errors sofar, arrange a meaningful exit stat */
2744 	if (Errors > 0 && ExitStat == EX_OK)
2745 		ExitStat = EX_USAGE;
2746 
2747 #if _FFR_FIX_DASHT
2748 	/*
2749 	**  If using -t, force not sending to argv recipients, even
2750 	**  if they are mentioned in the headers.
2751 	*/
2752 
2753 	if (GrabTo)
2754 	{
2755 		ADDRESS *q;
2756 
2757 		for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2758 			q->q_state = QS_REMOVED;
2759 	}
2760 #endif /* _FFR_FIX_DASHT */
2761 
2762 	/*
2763 	**  Read the input mail.
2764 	*/
2765 
2766 	MainEnvelope.e_to = NULL;
2767 	if (OpMode != MD_VERIFY || GrabTo)
2768 	{
2769 		int savederrors;
2770 		unsigned long savedflags;
2771 
2772 		/*
2773 		**  workaround for compiler warning on Irix:
2774 		**  do not initialize variable in the definition, but
2775 		**  later on:
2776 		**  warning(1548): transfer of control bypasses
2777 		**  initialization of:
2778 		**  variable "savederrors" (declared at line 2570)
2779 		**  variable "savedflags" (declared at line 2571)
2780 		**  goto giveup;
2781 		*/
2782 
2783 		savederrors = Errors;
2784 		savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2785 		MainEnvelope.e_flags |= EF_GLOBALERRS;
2786 		MainEnvelope.e_flags &= ~EF_FATALERRS;
2787 		Errors = 0;
2788 		buffer_errors();
2789 		collect(InChannel, false, NULL, &MainEnvelope, true);
2790 
2791 		/* header checks failed */
2792 		if (Errors > 0)
2793 		{
2794   giveup:
2795 			if (!GrabTo)
2796 			{
2797 				/* Log who the mail would have gone to */
2798 				logundelrcpts(&MainEnvelope,
2799 					      MainEnvelope.e_message,
2800 					      8, false);
2801 			}
2802 			flush_errors(true);
2803 			finis(true, true, ExitStat);
2804 			/* NOTREACHED */
2805 			return -1;
2806 		}
2807 
2808 		/* bail out if message too large */
2809 		if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2810 		{
2811 			finis(true, true, ExitStat != EX_OK ? ExitStat
2812 							    : EX_DATAERR);
2813 			/* NOTREACHED */
2814 			return -1;
2815 		}
2816 
2817 		/* set message size */
2818 		(void) sm_snprintf(buf, sizeof(buf), "%ld",
2819 				   MainEnvelope.e_msgsize);
2820 		macdefine(&MainEnvelope.e_macro, A_TEMP,
2821 			  macid("{msg_size}"), buf);
2822 
2823 		Errors = savederrors;
2824 		MainEnvelope.e_flags |= savedflags;
2825 	}
2826 	errno = 0;
2827 
2828 	if (tTd(1, 1))
2829 		sm_dprintf("From person = \"%s\"\n",
2830 			   MainEnvelope.e_from.q_paddr);
2831 
2832 	/* Check if quarantining stats should be updated */
2833 	if (MainEnvelope.e_quarmsg != NULL)
2834 		markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2835 
2836 	/*
2837 	**  Actually send everything.
2838 	**	If verifying, just ack.
2839 	*/
2840 
2841 	if (Errors == 0)
2842 	{
2843 		if (!split_by_recipient(&MainEnvelope) &&
2844 		    bitset(EF_FATALERRS, MainEnvelope.e_flags))
2845 			goto giveup;
2846 	}
2847 
2848 	/* make sure we deliver at least the first envelope */
2849 	i = FastSplit > 0 ? 0 : -1;
2850 	for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2851 	{
2852 		ENVELOPE *next;
2853 
2854 		e->e_from.q_state = QS_SENDER;
2855 		if (tTd(1, 5))
2856 		{
2857 			sm_dprintf("main[%d]: QS_SENDER ", i);
2858 			printaddr(sm_debug_file(), &e->e_from, false);
2859 		}
2860 		e->e_to = NULL;
2861 		sm_getla();
2862 		GrabTo = false;
2863 #if NAMED_BIND
2864 		_res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2865 		_res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2866 #endif /* NAMED_BIND */
2867 		next = e->e_sibling;
2868 		e->e_sibling = NULL;
2869 
2870 		/* after FastSplit envelopes: queue up */
2871 		sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2872 		e->e_sibling = next;
2873 	}
2874 
2875 	/*
2876 	**  All done.
2877 	**	Don't send return error message if in VERIFY mode.
2878 	*/
2879 
2880 	finis(true, true, ExitStat);
2881 	/* NOTREACHED */
2882 	return ExitStat;
2883 }
2884 /*
2885 **  STOP_SENDMAIL -- Stop the running program
2886 **
2887 **	Parameters:
2888 **		none.
2889 **
2890 **	Returns:
2891 **		none.
2892 **
2893 **	Side Effects:
2894 **		exits.
2895 */
2896 
2897 void
2898 stop_sendmail()
2899 {
2900 	/* reset uid for process accounting */
2901 	endpwent();
2902 	(void) setuid(RealUid);
2903 	exit(EX_OK);
2904 }
2905 /*
2906 **  FINIS -- Clean up and exit.
2907 **
2908 **	Parameters:
2909 **		drop -- whether or not to drop CurEnv envelope
2910 **		cleanup -- call exit() or _exit()?
2911 **		exitstat -- exit status to use for exit() call
2912 **
2913 **	Returns:
2914 **		never
2915 **
2916 **	Side Effects:
2917 **		exits sendmail
2918 */
2919 
2920 void
2921 finis(drop, cleanup, exitstat)
2922 	bool drop;
2923 	bool cleanup;
2924 	volatile int exitstat;
2925 {
2926 	char pidpath[MAXPATHLEN];
2927 	pid_t pid;
2928 
2929 	/* Still want to process new timeouts added below */
2930 	sm_clear_events();
2931 	(void) sm_releasesignal(SIGALRM);
2932 
2933 	if (tTd(2, 1))
2934 	{
2935 		sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2936 			   exitstat,
2937 			   CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2938 		printenvflags(CurEnv);
2939 	}
2940 	if (tTd(2, 9))
2941 		printopenfds(false);
2942 
2943 	SM_TRY
2944 		/*
2945 		**  Clean up.  This might raise E:mta.quickabort
2946 		*/
2947 
2948 		/* clean up temp files */
2949 		CurEnv->e_to = NULL;
2950 		if (drop)
2951 		{
2952 			if (CurEnv->e_id != NULL)
2953 			{
2954 				dropenvelope(CurEnv, true, false);
2955 				sm_rpool_free(CurEnv->e_rpool);
2956 				CurEnv->e_rpool = NULL;
2957 
2958 				/* these may have pointed to the rpool */
2959 				CurEnv->e_to = NULL;
2960 				CurEnv->e_message = NULL;
2961 				CurEnv->e_statmsg = NULL;
2962 				CurEnv->e_quarmsg = NULL;
2963 				CurEnv->e_bodytype = NULL;
2964 				CurEnv->e_id = NULL;
2965 				CurEnv->e_envid = NULL;
2966 				CurEnv->e_auth_param = NULL;
2967 			}
2968 			else
2969 				poststats(StatFile);
2970 		}
2971 
2972 		/* flush any cached connections */
2973 		mci_flush(true, NULL);
2974 
2975 		/* close maps belonging to this pid */
2976 		closemaps(false);
2977 
2978 #if USERDB
2979 		/* close UserDatabase */
2980 		_udbx_close();
2981 #endif /* USERDB */
2982 
2983 #if SASL
2984 		stop_sasl_client();
2985 #endif /* SASL */
2986 
2987 #if XLA
2988 		/* clean up extended load average stuff */
2989 		xla_all_end();
2990 #endif /* XLA */
2991 
2992 	SM_FINALLY
2993 		/*
2994 		**  And exit.
2995 		*/
2996 
2997 		if (LogLevel > 78)
2998 			sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
2999 				  (int) CurrentPid);
3000 		if (exitstat == EX_TEMPFAIL ||
3001 		    CurEnv->e_errormode == EM_BERKNET)
3002 			exitstat = EX_OK;
3003 
3004 		/* XXX clean up queues and related data structures */
3005 		cleanup_queues();
3006 		pid = getpid();
3007 #if SM_CONF_SHM
3008 		cleanup_shm(DaemonPid == pid);
3009 #endif /* SM_CONF_SHM */
3010 
3011 		/* close locked pid file */
3012 		close_sendmail_pid();
3013 
3014 		if (DaemonPid == pid || PidFilePid == pid)
3015 		{
3016 			/* blow away the pid file */
3017 			expand(PidFile, pidpath, sizeof(pidpath), CurEnv);
3018 			(void) unlink(pidpath);
3019 		}
3020 
3021 		/* reset uid for process accounting */
3022 		endpwent();
3023 		sm_mbdb_terminate();
3024 #if _FFR_MEMSTAT
3025 		(void) sm_memstat_close();
3026 #endif /* _FFR_MEMSTAT */
3027 		(void) setuid(RealUid);
3028 #if SM_HEAP_CHECK
3029 		/* dump the heap, if we are checking for memory leaks */
3030 		if (sm_debug_active(&SmHeapCheck, 2))
3031 			sm_heap_report(smioout,
3032 				       sm_debug_level(&SmHeapCheck) - 1);
3033 #endif /* SM_HEAP_CHECK */
3034 		if (sm_debug_active(&SmXtrapReport, 1))
3035 			sm_dprintf("xtrap count = %d\n", SmXtrapCount);
3036 		if (cleanup)
3037 			exit(exitstat);
3038 		else
3039 			_exit(exitstat);
3040 	SM_END_TRY
3041 }
3042 /*
3043 **  INTINDEBUG -- signal handler for SIGINT in -bt mode
3044 **
3045 **	Parameters:
3046 **		sig -- incoming signal.
3047 **
3048 **	Returns:
3049 **		none.
3050 **
3051 **	Side Effects:
3052 **		longjmps back to test mode loop.
3053 **
3054 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3055 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3056 **		DOING.
3057 */
3058 
3059 /* Type of an exception generated on SIGINT during address test mode.  */
3060 static const SM_EXC_TYPE_T EtypeInterrupt =
3061 {
3062 	SmExcTypeMagic,
3063 	"S:mta.interrupt",
3064 	"",
3065 	sm_etype_printf,
3066 	"interrupt",
3067 };
3068 
3069 /* ARGSUSED */
3070 static SIGFUNC_DECL
3071 intindebug(sig)
3072 	int sig;
3073 {
3074 	int save_errno = errno;
3075 
3076 	FIX_SYSV_SIGNAL(sig, intindebug);
3077 	errno = save_errno;
3078 	CHECK_CRITICAL(sig);
3079 	errno = save_errno;
3080 	sm_exc_raisenew_x(&EtypeInterrupt);
3081 	errno = save_errno;
3082 	return SIGFUNC_RETURN;
3083 }
3084 /*
3085 **  SIGTERM -- SIGTERM handler for the daemon
3086 **
3087 **	Parameters:
3088 **		sig -- signal number.
3089 **
3090 **	Returns:
3091 **		none.
3092 **
3093 **	Side Effects:
3094 **		Sets ShutdownRequest which will hopefully trigger
3095 **		the daemon to exit.
3096 **
3097 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3098 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3099 **		DOING.
3100 */
3101 
3102 /* ARGSUSED */
3103 static SIGFUNC_DECL
3104 sigterm(sig)
3105 	int sig;
3106 {
3107 	int save_errno = errno;
3108 
3109 	FIX_SYSV_SIGNAL(sig, sigterm);
3110 	ShutdownRequest = "signal";
3111 	errno = save_errno;
3112 	return SIGFUNC_RETURN;
3113 }
3114 /*
3115 **  SIGHUP -- handle a SIGHUP signal
3116 **
3117 **	Parameters:
3118 **		sig -- incoming signal.
3119 **
3120 **	Returns:
3121 **		none.
3122 **
3123 **	Side Effects:
3124 **		Sets RestartRequest which should cause the daemon
3125 **		to restart.
3126 **
3127 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3128 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3129 **		DOING.
3130 */
3131 
3132 /* ARGSUSED */
3133 static SIGFUNC_DECL
3134 sighup(sig)
3135 	int sig;
3136 {
3137 	int save_errno = errno;
3138 
3139 	FIX_SYSV_SIGNAL(sig, sighup);
3140 	RestartRequest = "signal";
3141 	errno = save_errno;
3142 	return SIGFUNC_RETURN;
3143 }
3144 /*
3145 **  SIGPIPE -- signal handler for SIGPIPE
3146 **
3147 **	Parameters:
3148 **		sig -- incoming signal.
3149 **
3150 **	Returns:
3151 **		none.
3152 **
3153 **	Side Effects:
3154 **		Sets StopRequest which should cause the mailq/hoststatus
3155 **		display to stop.
3156 **
3157 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3158 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3159 **		DOING.
3160 */
3161 
3162 /* ARGSUSED */
3163 static SIGFUNC_DECL
3164 sigpipe(sig)
3165 	int sig;
3166 {
3167 	int save_errno = errno;
3168 
3169 	FIX_SYSV_SIGNAL(sig, sigpipe);
3170 	StopRequest = true;
3171 	errno = save_errno;
3172 	return SIGFUNC_RETURN;
3173 }
3174 /*
3175 **  INTSIG -- clean up on interrupt
3176 **
3177 **	This just arranges to exit.  It pessimizes in that it
3178 **	may resend a message.
3179 **
3180 **	Parameters:
3181 **		none.
3182 **
3183 **	Returns:
3184 **		none.
3185 **
3186 **	Side Effects:
3187 **		Unlocks the current job.
3188 **
3189 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3190 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3191 **		DOING.
3192 **
3193 **		XXX: More work is needed for this signal handler.
3194 */
3195 
3196 /* ARGSUSED */
3197 SIGFUNC_DECL
3198 intsig(sig)
3199 	int sig;
3200 {
3201 	bool drop = false;
3202 	int save_errno = errno;
3203 
3204 	FIX_SYSV_SIGNAL(sig, intsig);
3205 	errno = save_errno;
3206 	CHECK_CRITICAL(sig);
3207 	sm_allsignals(true);
3208 
3209 	if (sig != 0 && LogLevel > 79)
3210 		sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3211 	FileName = NULL;
3212 
3213 	/* Clean-up on aborted stdin message submission */
3214 	if (CurEnv->e_id != NULL &&
3215 	    (OpMode == MD_SMTP ||
3216 	     OpMode == MD_DELIVER ||
3217 	     OpMode == MD_ARPAFTP))
3218 	{
3219 		register ADDRESS *q;
3220 
3221 		/* don't return an error indication */
3222 		CurEnv->e_to = NULL;
3223 		CurEnv->e_flags &= ~EF_FATALERRS;
3224 		CurEnv->e_flags |= EF_CLRQUEUE;
3225 
3226 		/*
3227 		**  Spin through the addresses and
3228 		**  mark them dead to prevent bounces
3229 		*/
3230 
3231 		for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
3232 			q->q_state = QS_DONTSEND;
3233 
3234 		drop = true;
3235 	}
3236 	else if (OpMode != MD_TEST)
3237 	{
3238 		unlockqueue(CurEnv);
3239 	}
3240 
3241 	finis(drop, false, EX_OK);
3242 	/* NOTREACHED */
3243 }
3244 /*
3245 **  DISCONNECT -- remove our connection with any foreground process
3246 **
3247 **	Parameters:
3248 **		droplev -- how "deeply" we should drop the line.
3249 **			0 -- ignore signals, mail back errors, make sure
3250 **			     output goes to stdout.
3251 **			1 -- also, make stdout go to /dev/null.
3252 **			2 -- also, disconnect from controlling terminal
3253 **			     (only for daemon mode).
3254 **		e -- the current envelope.
3255 **
3256 **	Returns:
3257 **		none
3258 **
3259 **	Side Effects:
3260 **		Trys to insure that we are immune to vagaries of
3261 **		the controlling tty.
3262 */
3263 
3264 void
3265 disconnect(droplev, e)
3266 	int droplev;
3267 	register ENVELOPE *e;
3268 {
3269 	int fd;
3270 
3271 	if (tTd(52, 1))
3272 		sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3273 			   sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3274 			   sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3275 	if (tTd(52, 100))
3276 	{
3277 		sm_dprintf("don't\n");
3278 		return;
3279 	}
3280 	if (LogLevel > 93)
3281 		sm_syslog(LOG_DEBUG, e->e_id,
3282 			  "disconnect level %d",
3283 			  droplev);
3284 
3285 	/* be sure we don't get nasty signals */
3286 	(void) sm_signal(SIGINT, SIG_IGN);
3287 	(void) sm_signal(SIGQUIT, SIG_IGN);
3288 
3289 	/* we can't communicate with our caller, so.... */
3290 	HoldErrs = true;
3291 	CurEnv->e_errormode = EM_MAIL;
3292 	Verbose = 0;
3293 	DisConnected = true;
3294 
3295 	/* all input from /dev/null */
3296 	if (InChannel != smioin)
3297 	{
3298 		(void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3299 		InChannel = smioin;
3300 	}
3301 	if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3302 			 SM_IO_RDONLY, NULL, smioin) == NULL)
3303 		sm_syslog(LOG_ERR, e->e_id,
3304 			  "disconnect: sm_io_reopen(\"%s\") failed: %s",
3305 			  SM_PATH_DEVNULL, sm_errstring(errno));
3306 
3307 	/*
3308 	**  output to the transcript
3309 	**	We also compare the fd numbers here since OutChannel
3310 	**	might be a layer on top of smioout due to encryption
3311 	**	(see sfsasl.c).
3312 	*/
3313 
3314 	if (OutChannel != smioout &&
3315 	    sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3316 	    sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3317 	{
3318 		(void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3319 		OutChannel = smioout;
3320 
3321 #if 0
3322 		/*
3323 		**  Has smioout been closed? Reopen it.
3324 		**	This shouldn't happen anymore, the code is here
3325 		**	just as a reminder.
3326 		*/
3327 
3328 		if (smioout->sm_magic == NULL &&
3329 		    sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3330 				 SM_IO_WRONLY, NULL, smioout) == NULL)
3331 			sm_syslog(LOG_ERR, e->e_id,
3332 				  "disconnect: sm_io_reopen(\"%s\") failed: %s",
3333 				  SM_PATH_DEVNULL, sm_errstring(errno));
3334 #endif /* 0 */
3335 	}
3336 	if (droplev > 0)
3337 	{
3338 		fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3339 		if (fd == -1)
3340 		{
3341 			sm_syslog(LOG_ERR, e->e_id,
3342 				  "disconnect: open(\"%s\") failed: %s",
3343 				  SM_PATH_DEVNULL, sm_errstring(errno));
3344 		}
3345 		(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3346 		if (fd >= 0)
3347 		{
3348 			(void) dup2(fd, STDOUT_FILENO);
3349 			(void) dup2(fd, STDERR_FILENO);
3350 			(void) close(fd);
3351 		}
3352 	}
3353 
3354 	/* drop our controlling TTY completely if possible */
3355 	if (droplev > 1)
3356 	{
3357 		(void) setsid();
3358 		errno = 0;
3359 	}
3360 
3361 #if XDEBUG
3362 	checkfd012("disconnect");
3363 #endif /* XDEBUG */
3364 
3365 	if (LogLevel > 71)
3366 		sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3367 			  (int) CurrentPid);
3368 
3369 	errno = 0;
3370 }
3371 
3372 static void
3373 obsolete(argv)
3374 	char *argv[];
3375 {
3376 	register char *ap;
3377 	register char *op;
3378 
3379 	while ((ap = *++argv) != NULL)
3380 	{
3381 		/* Return if "--" or not an option of any form. */
3382 		if (ap[0] != '-' || ap[1] == '-')
3383 			return;
3384 
3385 		/* Don't allow users to use "-Q." or "-Q ." */
3386 		if ((ap[1] == 'Q' && ap[2] == '.') ||
3387 		    (ap[1] == 'Q' && argv[1] != NULL &&
3388 		     argv[1][0] == '.' && argv[1][1] == '\0'))
3389 		{
3390 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3391 					     "Can not use -Q.\n");
3392 			exit(EX_USAGE);
3393 		}
3394 
3395 		/* skip over options that do have a value */
3396 		op = strchr(OPTIONS, ap[1]);
3397 		if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3398 		    ap[1] != 'd' &&
3399 #if defined(sony_news)
3400 		    ap[1] != 'E' && ap[1] != 'J' &&
3401 #endif /* defined(sony_news) */
3402 		    argv[1] != NULL && argv[1][0] != '-')
3403 		{
3404 			argv++;
3405 			continue;
3406 		}
3407 
3408 		/* If -C doesn't have an argument, use sendmail.cf. */
3409 #define __DEFPATH	"sendmail.cf"
3410 		if (ap[1] == 'C' && ap[2] == '\0')
3411 		{
3412 			*argv = xalloc(sizeof(__DEFPATH) + 2);
3413 			(void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3414 					   "-C", __DEFPATH);
3415 		}
3416 
3417 		/* If -q doesn't have an argument, run it once. */
3418 		if (ap[1] == 'q' && ap[2] == '\0')
3419 			*argv = "-q0";
3420 
3421 		/* If -Q doesn't have an argument, disable quarantining */
3422 		if (ap[1] == 'Q' && ap[2] == '\0')
3423 			*argv = "-Q.";
3424 
3425 		/* if -d doesn't have an argument, use 0-99.1 */
3426 		if (ap[1] == 'd' && ap[2] == '\0')
3427 			*argv = "-d0-99.1";
3428 
3429 #if defined(sony_news)
3430 		/* if -E doesn't have an argument, use -EC */
3431 		if (ap[1] == 'E' && ap[2] == '\0')
3432 			*argv = "-EC";
3433 
3434 		/* if -J doesn't have an argument, use -JJ */
3435 		if (ap[1] == 'J' && ap[2] == '\0')
3436 			*argv = "-JJ";
3437 #endif /* defined(sony_news) */
3438 	}
3439 }
3440 /*
3441 **  AUTH_WARNING -- specify authorization warning
3442 **
3443 **	Parameters:
3444 **		e -- the current envelope.
3445 **		msg -- the text of the message.
3446 **		args -- arguments to the message.
3447 **
3448 **	Returns:
3449 **		none.
3450 */
3451 
3452 void
3453 #ifdef __STDC__
3454 auth_warning(register ENVELOPE *e, const char *msg, ...)
3455 #else /* __STDC__ */
3456 auth_warning(e, msg, va_alist)
3457 	register ENVELOPE *e;
3458 	const char *msg;
3459 	va_dcl
3460 #endif /* __STDC__ */
3461 {
3462 	char buf[MAXLINE];
3463 	SM_VA_LOCAL_DECL
3464 
3465 	if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3466 	{
3467 		register char *p;
3468 		static char hostbuf[48];
3469 
3470 		if (hostbuf[0] == '\0')
3471 		{
3472 			struct hostent *hp;
3473 
3474 			hp = myhostname(hostbuf, sizeof(hostbuf));
3475 #if NETINET6
3476 			if (hp != NULL)
3477 			{
3478 				freehostent(hp);
3479 				hp = NULL;
3480 			}
3481 #endif /* NETINET6 */
3482 		}
3483 
3484 		(void) sm_strlcpyn(buf, sizeof(buf), 2, hostbuf, ": ");
3485 		p = &buf[strlen(buf)];
3486 		SM_VA_START(ap, msg);
3487 		(void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3488 		SM_VA_END(ap);
3489 		addheader("X-Authentication-Warning", buf, 0, e, true);
3490 		if (LogLevel > 3)
3491 			sm_syslog(LOG_INFO, e->e_id,
3492 				  "Authentication-Warning: %.400s",
3493 				  buf);
3494 	}
3495 }
3496 /*
3497 **  GETEXTENV -- get from external environment
3498 **
3499 **	Parameters:
3500 **		envar -- the name of the variable to retrieve
3501 **
3502 **	Returns:
3503 **		The value, if any.
3504 */
3505 
3506 static char *
3507 getextenv(envar)
3508 	const char *envar;
3509 {
3510 	char **envp;
3511 	int l;
3512 
3513 	l = strlen(envar);
3514 	for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3515 	{
3516 		if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3517 			return &(*envp)[l + 1];
3518 	}
3519 	return NULL;
3520 }
3521 /*
3522 **  SM_SETUSERENV -- set an environment variable in the propagated environment
3523 **
3524 **	Parameters:
3525 **		envar -- the name of the environment variable.
3526 **		value -- the value to which it should be set.  If
3527 **			null, this is extracted from the incoming
3528 **			environment.  If that is not set, the call
3529 **			to sm_setuserenv is ignored.
3530 **
3531 **	Returns:
3532 **		none.
3533 */
3534 
3535 void
3536 sm_setuserenv(envar, value)
3537 	const char *envar;
3538 	const char *value;
3539 {
3540 	int i, l;
3541 	char **evp = UserEnviron;
3542 	char *p;
3543 
3544 	if (value == NULL)
3545 	{
3546 		value = getextenv(envar);
3547 		if (value == NULL)
3548 			return;
3549 	}
3550 
3551 	/* XXX enforce reasonable size? */
3552 	i = strlen(envar) + 1;
3553 	l = strlen(value) + i + 1;
3554 	p = (char *) xalloc(l);
3555 	(void) sm_strlcpyn(p, l, 3, envar, "=", value);
3556 
3557 	while (*evp != NULL && strncmp(*evp, p, i) != 0)
3558 		evp++;
3559 	if (*evp != NULL)
3560 	{
3561 		*evp++ = p;
3562 	}
3563 	else if (evp < &UserEnviron[MAXUSERENVIRON])
3564 	{
3565 		*evp++ = p;
3566 		*evp = NULL;
3567 	}
3568 
3569 	/* make sure it is in our environment as well */
3570 	if (putenv(p) < 0)
3571 		syserr("sm_setuserenv: putenv(%s) failed", p);
3572 }
3573 /*
3574 **  DUMPSTATE -- dump state
3575 **
3576 **	For debugging.
3577 */
3578 
3579 void
3580 dumpstate(when)
3581 	char *when;
3582 {
3583 	register char *j = macvalue('j', CurEnv);
3584 	int rs;
3585 	extern int NextMacroId;
3586 
3587 	sm_syslog(LOG_DEBUG, CurEnv->e_id,
3588 		  "--- dumping state on %s: $j = %s ---",
3589 		  when,
3590 		  j == NULL ? "<NULL>" : j);
3591 	if (j != NULL)
3592 	{
3593 		if (!wordinclass(j, 'w'))
3594 			sm_syslog(LOG_DEBUG, CurEnv->e_id,
3595 				  "*** $j not in $=w ***");
3596 	}
3597 	sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3598 	sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3599 		  NextMacroId, MAXMACROID);
3600 	sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3601 	printopenfds(true);
3602 	sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3603 	mci_dump_all(smioout, true);
3604 	rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3605 	if (rs > 0)
3606 	{
3607 		int status;
3608 		register char **pvp;
3609 		char *pv[MAXATOM + 1];
3610 
3611 		pv[0] = NULL;
3612 		status = REWRITE(pv, rs, CurEnv);
3613 		sm_syslog(LOG_DEBUG, CurEnv->e_id,
3614 			  "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3615 			  status);
3616 		for (pvp = pv; *pvp != NULL; pvp++)
3617 			sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3618 	}
3619 	sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3620 }
3621 
3622 #ifdef SIGUSR1
3623 /*
3624 **  SIGUSR1 -- Signal a request to dump state.
3625 **
3626 **	Parameters:
3627 **		sig -- calling signal.
3628 **
3629 **	Returns:
3630 **		none.
3631 **
3632 **	NOTE:	THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3633 **		ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3634 **		DOING.
3635 **
3636 **		XXX: More work is needed for this signal handler.
3637 */
3638 
3639 /* ARGSUSED */
3640 static SIGFUNC_DECL
3641 sigusr1(sig)
3642 	int sig;
3643 {
3644 	int save_errno = errno;
3645 
3646 	FIX_SYSV_SIGNAL(sig, sigusr1);
3647 	errno = save_errno;
3648 	CHECK_CRITICAL(sig);
3649 	dumpstate("user signal");
3650 # if SM_HEAP_CHECK
3651 	dumpstab();
3652 # endif /* SM_HEAP_CHECK */
3653 	errno = save_errno;
3654 	return SIGFUNC_RETURN;
3655 }
3656 #endif /* SIGUSR1 */
3657 
3658 /*
3659 **  DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3660 **
3661 **	Parameters:
3662 **		to_real_uid -- if set, drop to the real uid instead
3663 **			of the RunAsUser.
3664 **
3665 **	Returns:
3666 **		EX_OSERR if the setuid failed.
3667 **		EX_OK otherwise.
3668 */
3669 
3670 int
3671 drop_privileges(to_real_uid)
3672 	bool to_real_uid;
3673 {
3674 	int rval = EX_OK;
3675 	GIDSET_T emptygidset[1];
3676 
3677 	if (tTd(47, 1))
3678 		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",
3679 			   (int) to_real_uid,
3680 			   (int) RealUid, (int) RealGid,
3681 			   (int) getuid(), (int) getgid(),
3682 			   (int) geteuid(), (int) getegid(),
3683 			   (int) RunAsUid, (int) RunAsGid);
3684 
3685 	if (to_real_uid)
3686 	{
3687 		RunAsUserName = RealUserName;
3688 		RunAsUid = RealUid;
3689 		RunAsGid = RealGid;
3690 		EffGid = RunAsGid;
3691 	}
3692 
3693 	/* make sure no one can grab open descriptors for secret files */
3694 	endpwent();
3695 	sm_mbdb_terminate();
3696 
3697 	/* reset group permissions; these can be set later */
3698 	emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3699 
3700 	/*
3701 	**  Notice:  on some OS (Linux...) the setgroups() call causes
3702 	**	a logfile entry if sendmail is not run by root.
3703 	**	However, it is unclear (no POSIX standard) whether
3704 	**	setgroups() can only succeed if executed by root.
3705 	**	So for now we keep it as it is; if you want to change it, use
3706 	**  if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3707 	*/
3708 
3709 	if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3710 	{
3711 		syserr("drop_privileges: setgroups(1, %d) failed",
3712 		       (int) emptygidset[0]);
3713 		rval = EX_OSERR;
3714 	}
3715 
3716 	/* reset primary group id */
3717 	if (to_real_uid)
3718 	{
3719 		/*
3720 		**  Drop gid to real gid.
3721 		**  On some OS we must reset the effective[/real[/saved]] gid,
3722 		**  and then use setgid() to finally drop all group privileges.
3723 		**  Later on we check whether we can get back the
3724 		**  effective gid.
3725 		*/
3726 
3727 #if HASSETEGID
3728 		if (setegid(RunAsGid) < 0)
3729 		{
3730 			syserr("drop_privileges: setegid(%d) failed",
3731 			       (int) RunAsGid);
3732 			rval = EX_OSERR;
3733 		}
3734 #else /* HASSETEGID */
3735 # if HASSETREGID
3736 		if (setregid(RunAsGid, RunAsGid) < 0)
3737 		{
3738 			syserr("drop_privileges: setregid(%d, %d) failed",
3739 			       (int) RunAsGid, (int) RunAsGid);
3740 			rval = EX_OSERR;
3741 		}
3742 # else /* HASSETREGID */
3743 #  if HASSETRESGID
3744 		if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3745 		{
3746 			syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3747 			       (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3748 			rval = EX_OSERR;
3749 		}
3750 #  endif /* HASSETRESGID */
3751 # endif /* HASSETREGID */
3752 #endif /* HASSETEGID */
3753 	}
3754 	if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3755 	{
3756 		if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3757 		{
3758 			syserr("drop_privileges: setgid(%d) failed",
3759 			       (int) RunAsGid);
3760 			rval = EX_OSERR;
3761 		}
3762 		errno = 0;
3763 		if (rval == EX_OK && getegid() != RunAsGid)
3764 		{
3765 			syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3766 			       (int) getegid(), (int) RunAsGid);
3767 			rval = EX_OSERR;
3768 		}
3769 	}
3770 
3771 	/* fiddle with uid */
3772 	if (to_real_uid || RunAsUid != 0)
3773 	{
3774 		uid_t euid;
3775 
3776 		/*
3777 		**  Try to setuid(RunAsUid).
3778 		**  euid must be RunAsUid,
3779 		**  ruid must be RunAsUid unless (e|r)uid wasn't 0
3780 		**	and we didn't have to drop privileges to the real uid.
3781 		*/
3782 
3783 		if (setuid(RunAsUid) < 0 ||
3784 		    geteuid() != RunAsUid ||
3785 		    (getuid() != RunAsUid &&
3786 		     (to_real_uid || geteuid() == 0 || getuid() == 0)))
3787 		{
3788 #if HASSETREUID
3789 			/*
3790 			**  if ruid != RunAsUid, euid == RunAsUid, then
3791 			**  try resetting just the real uid, then using
3792 			**  setuid() to drop the saved-uid as well.
3793 			*/
3794 
3795 			if (geteuid() == RunAsUid)
3796 			{
3797 				if (setreuid(RunAsUid, -1) < 0)
3798 				{
3799 					syserr("drop_privileges: setreuid(%d, -1) failed",
3800 					       (int) RunAsUid);
3801 					rval = EX_OSERR;
3802 				}
3803 				if (setuid(RunAsUid) < 0)
3804 				{
3805 					syserr("drop_privileges: second setuid(%d) attempt failed",
3806 					       (int) RunAsUid);
3807 					rval = EX_OSERR;
3808 				}
3809 			}
3810 			else
3811 #endif /* HASSETREUID */
3812 			{
3813 				syserr("drop_privileges: setuid(%d) failed",
3814 				       (int) RunAsUid);
3815 				rval = EX_OSERR;
3816 			}
3817 		}
3818 		euid = geteuid();
3819 		if (RunAsUid != 0 && setuid(0) == 0)
3820 		{
3821 			/*
3822 			**  Believe it or not, the Linux capability model
3823 			**  allows a non-root process to override setuid()
3824 			**  on a process running as root and prevent that
3825 			**  process from dropping privileges.
3826 			*/
3827 
3828 			syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3829 			rval = EX_OSERR;
3830 		}
3831 		else if (RunAsUid != euid && setuid(euid) == 0)
3832 		{
3833 			/*
3834 			**  Some operating systems will keep the saved-uid
3835 			**  if a non-root effective-uid calls setuid(real-uid)
3836 			**  making it possible to set it back again later.
3837 			*/
3838 
3839 			syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3840 			rval = EX_OSERR;
3841 		}
3842 	}
3843 
3844 	if ((to_real_uid || RunAsGid != 0) &&
3845 	    rval == EX_OK && RunAsGid != EffGid &&
3846 	    getuid() != 0 && geteuid() != 0)
3847 	{
3848 		errno = 0;
3849 		if (setgid(EffGid) == 0)
3850 		{
3851 			syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3852 			       (int) EffGid);
3853 			rval = EX_OSERR;
3854 		}
3855 	}
3856 
3857 	if (tTd(47, 5))
3858 	{
3859 		sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3860 			   (int) geteuid(), (int) getuid(),
3861 			   (int) getegid(), (int) getgid());
3862 		sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3863 			   (int) RunAsUid, (int) RunAsGid);
3864 		if (tTd(47, 10))
3865 			sm_dprintf("drop_privileges: rval = %d\n", rval);
3866 	}
3867 	return rval;
3868 }
3869 /*
3870 **  FILL_FD -- make sure a file descriptor has been properly allocated
3871 **
3872 **	Used to make sure that stdin/out/err are allocated on startup
3873 **
3874 **	Parameters:
3875 **		fd -- the file descriptor to be filled.
3876 **		where -- a string used for logging.  If NULL, this is
3877 **			being called on startup, and logging should
3878 **			not be done.
3879 **
3880 **	Returns:
3881 **		none
3882 **
3883 **	Side Effects:
3884 **		possibly changes MissingFds
3885 */
3886 
3887 void
3888 fill_fd(fd, where)
3889 	int fd;
3890 	char *where;
3891 {
3892 	int i;
3893 	struct stat stbuf;
3894 
3895 	if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3896 		return;
3897 
3898 	if (where != NULL)
3899 		syserr("fill_fd: %s: fd %d not open", where, fd);
3900 	else
3901 		MissingFds |= 1 << fd;
3902 	i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3903 	if (i < 0)
3904 	{
3905 		syserr("!fill_fd: %s: cannot open %s",
3906 		       where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3907 	}
3908 	if (fd != i)
3909 	{
3910 		(void) dup2(i, fd);
3911 		(void) close(i);
3912 	}
3913 }
3914 /*
3915 **  SM_PRINTOPTIONS -- print options
3916 **
3917 **	Parameters:
3918 **		options -- array of options.
3919 **
3920 **	Returns:
3921 **		none.
3922 */
3923 
3924 static void
3925 sm_printoptions(options)
3926 	char **options;
3927 {
3928 	int ll;
3929 	char **av;
3930 
3931 	av = options;
3932 	ll = 7;
3933 	while (*av != NULL)
3934 	{
3935 		if (ll + strlen(*av) > 63)
3936 		{
3937 			sm_dprintf("\n");
3938 			ll = 0;
3939 		}
3940 		if (ll == 0)
3941 			sm_dprintf("\t\t");
3942 		else
3943 			sm_dprintf(" ");
3944 		sm_dprintf("%s", *av);
3945 		ll += strlen(*av++) + 1;
3946 	}
3947 	sm_dprintf("\n");
3948 }
3949 
3950 /*
3951 **  TO8BIT -- convert \octal sequences in a test mode input line
3952 **
3953 **	Parameters:
3954 **		str -- the input line.
3955 **
3956 **	Returns:
3957 **		none.
3958 **
3959 **	Side Effects:
3960 **		replaces \0octal in str with octal value.
3961 */
3962 
3963 static bool to8bit __P((char *));
3964 
3965 static bool
3966 to8bit(str)
3967 	char *str;
3968 {
3969 	int c, len;
3970 	char *out, *in;
3971 	bool changed;
3972 
3973 	if (str == NULL)
3974 		return false;
3975 	in = out = str;
3976 	changed = false;
3977 	len = 0;
3978 	while ((c = (*str++ & 0377)) != '\0')
3979 	{
3980 		int oct, nxtc;
3981 
3982 		++len;
3983 		if (c == '\\' &&
3984 		    (nxtc = (*str & 0377)) == '0')
3985 		{
3986 			oct = 0;
3987 			while ((nxtc = (*str & 0377)) != '\0' &&
3988 				isascii(nxtc) && isdigit(nxtc))
3989 			{
3990 				oct <<= 3;
3991 				oct += nxtc - '0';
3992 				++str;
3993 				++len;
3994 			}
3995 			changed = true;
3996 			c = oct;
3997 		}
3998 		*out++ = c;
3999 	}
4000 	*out++ = c;
4001 	if (changed)
4002 	{
4003 		char *q;
4004 
4005 		q = quote_internal_chars(in, in, &len);
4006 		if (q != in)
4007 			sm_strlcpy(in, q, len);
4008 	}
4009 	return changed;
4010 }
4011 
4012 /*
4013 **  TESTMODELINE -- process a test mode input line
4014 **
4015 **	Parameters:
4016 **		line -- the input line.
4017 **		e -- the current environment.
4018 **	Syntax:
4019 **		#  a comment
4020 **		.X process X as a configuration line
4021 **		=X dump a configuration item (such as mailers)
4022 **		$X dump a macro or class
4023 **		/X try an activity
4024 **		X  normal process through rule set X
4025 */
4026 
4027 static void
4028 testmodeline(line, e)
4029 	char *line;
4030 	ENVELOPE *e;
4031 {
4032 	register char *p;
4033 	char *q;
4034 	auto char *delimptr;
4035 	int mid;
4036 	int i, rs;
4037 	STAB *map;
4038 	char **s;
4039 	struct rewrite *rw;
4040 	ADDRESS a;
4041 	char *lbp;
4042 	auto int lbs;
4043 	static int tryflags = RF_COPYNONE;
4044 	char exbuf[MAXLINE];
4045 	char lbuf[MAXLINE];
4046 	extern unsigned char TokTypeNoC[];
4047 	bool eightbit;
4048 
4049 	/* skip leading spaces */
4050 	while (*line == ' ')
4051 		line++;
4052 
4053 	lbp = NULL;
4054 	eightbit = false;
4055 	switch (line[0])
4056 	{
4057 	  case '#':
4058 	  case '\0':
4059 		return;
4060 
4061 	  case '?':
4062 		help("-bt", e);
4063 		return;
4064 
4065 	  case '.':		/* config-style settings */
4066 		switch (line[1])
4067 		{
4068 		  case 'D':
4069 			mid = macid_parse(&line[2], &delimptr);
4070 			if (mid == 0)
4071 				return;
4072 			lbs = sizeof(lbuf);
4073 			lbp = translate_dollars(delimptr, lbuf, &lbs);
4074 			macdefine(&e->e_macro, A_TEMP, mid, lbp);
4075 			if (lbp != lbuf)
4076 				SM_FREE(lbp);
4077 			break;
4078 
4079 		  case 'C':
4080 			if (line[2] == '\0')	/* not to call syserr() */
4081 				return;
4082 
4083 			mid = macid_parse(&line[2], &delimptr);
4084 			if (mid == 0)
4085 				return;
4086 			lbs = sizeof(lbuf);
4087 			lbp = translate_dollars(delimptr, lbuf, &lbs);
4088 			expand(lbp, exbuf, sizeof(exbuf), e);
4089 			if (lbp != lbuf)
4090 				SM_FREE(lbp);
4091 			p = exbuf;
4092 			while (*p != '\0')
4093 			{
4094 				register char *wd;
4095 				char delim;
4096 
4097 				while (*p != '\0' && isascii(*p) && isspace(*p))
4098 					p++;
4099 				wd = p;
4100 				while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4101 					p++;
4102 				delim = *p;
4103 				*p = '\0';
4104 				if (wd[0] != '\0')
4105 					setclass(mid, wd);
4106 				*p = delim;
4107 			}
4108 			break;
4109 
4110 		  case '\0':
4111 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4112 					     "Usage: .[DC]macro value(s)\n");
4113 			break;
4114 
4115 		  default:
4116 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4117 					     "Unknown \".\" command %s\n", line);
4118 			break;
4119 		}
4120 		return;
4121 
4122 	  case '=':		/* config-style settings */
4123 		switch (line[1])
4124 		{
4125 		  case 'S':		/* dump rule set */
4126 			rs = strtorwset(&line[2], NULL, ST_FIND);
4127 			if (rs < 0)
4128 			{
4129 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4130 						     "Undefined ruleset %s\n", &line[2]);
4131 				return;
4132 			}
4133 			rw = RewriteRules[rs];
4134 			if (rw == NULL)
4135 				return;
4136 			do
4137 			{
4138 				(void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4139 						  'R');
4140 				s = rw->r_lhs;
4141 				while (*s != NULL)
4142 				{
4143 					xputs(smioout, *s++);
4144 					(void) sm_io_putc(smioout,
4145 							  SM_TIME_DEFAULT, ' ');
4146 				}
4147 				(void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4148 						  '\t');
4149 				(void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4150 						  '\t');
4151 				s = rw->r_rhs;
4152 				while (*s != NULL)
4153 				{
4154 					xputs(smioout, *s++);
4155 					(void) sm_io_putc(smioout,
4156 							  SM_TIME_DEFAULT, ' ');
4157 				}
4158 				(void) sm_io_putc(smioout, SM_TIME_DEFAULT,
4159 						  '\n');
4160 			} while ((rw = rw->r_next) != NULL);
4161 			break;
4162 
4163 		  case 'M':
4164 			for (i = 0; i < MAXMAILERS; i++)
4165 			{
4166 				if (Mailer[i] != NULL)
4167 					printmailer(smioout, Mailer[i]);
4168 			}
4169 			break;
4170 
4171 		  case '\0':
4172 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4173 					     "Usage: =Sruleset or =M\n");
4174 			break;
4175 
4176 		  default:
4177 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4178 					     "Unknown \"=\" command %s\n", line);
4179 			break;
4180 		}
4181 		return;
4182 
4183 	  case '-':		/* set command-line-like opts */
4184 		switch (line[1])
4185 		{
4186 		  case 'd':
4187 			tTflag(&line[2]);
4188 			break;
4189 
4190 		  case '\0':
4191 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4192 					     "Usage: -d{debug arguments}\n");
4193 			break;
4194 
4195 		  default:
4196 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4197 					     "Unknown \"-\" command %s\n", line);
4198 			break;
4199 		}
4200 		return;
4201 
4202 	  case '$':
4203 		if (line[1] == '=')
4204 		{
4205 			mid = macid(&line[2]);
4206 			if (mid != 0)
4207 				stabapply(dump_class, mid);
4208 			return;
4209 		}
4210 		mid = macid(&line[1]);
4211 		if (mid == 0)
4212 			return;
4213 		p = macvalue(mid, e);
4214 		if (p == NULL)
4215 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4216 					     "Undefined\n");
4217 		else
4218 		{
4219 			xputs(smioout, p);
4220 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4221 					     "\n");
4222 		}
4223 		return;
4224 
4225 	  case '/':		/* miscellaneous commands */
4226 		p = &line[strlen(line)];
4227 		while (--p >= line && isascii(*p) && isspace(*p))
4228 			*p = '\0';
4229 		p = strpbrk(line, " \t");
4230 		if (p != NULL)
4231 		{
4232 			while (isascii(*p) && isspace(*p))
4233 				*p++ = '\0';
4234 		}
4235 		else
4236 			p = "";
4237 		if (line[1] == '\0')
4238 		{
4239 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4240 					     "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4241 			return;
4242 		}
4243 		if (sm_strcasecmp(&line[1], "quit") == 0)
4244 		{
4245 			CurEnv->e_id = NULL;
4246 			finis(true, true, ExitStat);
4247 			/* NOTREACHED */
4248 		}
4249 		if (sm_strcasecmp(&line[1], "mx") == 0)
4250 		{
4251 #if NAMED_BIND
4252 			/* look up MX records */
4253 			int nmx;
4254 			auto int rcode;
4255 			char *mxhosts[MAXMXHOSTS + 1];
4256 
4257 			if (*p == '\0')
4258 			{
4259 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4260 						     "Usage: /mx address\n");
4261 				return;
4262 			}
4263 			nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4264 				      NULL);
4265 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4266 					     "getmxrr(%s) returns %d value(s):\n",
4267 				p, nmx);
4268 			for (i = 0; i < nmx; i++)
4269 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4270 						     "\t%s\n", mxhosts[i]);
4271 #else /* NAMED_BIND */
4272 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4273 					     "No MX code compiled in\n");
4274 #endif /* NAMED_BIND */
4275 		}
4276 		else if (sm_strcasecmp(&line[1], "canon") == 0)
4277 		{
4278 			char host[MAXHOSTNAMELEN];
4279 
4280 			if (*p == '\0')
4281 			{
4282 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4283 						     "Usage: /canon address\n");
4284 				return;
4285 			}
4286 			else if (sm_strlcpy(host, p, sizeof(host)) >= sizeof(host))
4287 			{
4288 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4289 						     "Name too long\n");
4290 				return;
4291 			}
4292 			(void) getcanonname(host, sizeof(host), !HasWildcardMX,
4293 					    NULL);
4294 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4295 					     "getcanonname(%s) returns %s\n",
4296 					     p, host);
4297 		}
4298 		else if (sm_strcasecmp(&line[1], "map") == 0)
4299 		{
4300 			auto int rcode = EX_OK;
4301 			char *av[2];
4302 
4303 			if (*p == '\0')
4304 			{
4305 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4306 						     "Usage: /map mapname key\n");
4307 				return;
4308 			}
4309 			for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q));			     q++)
4310 				continue;
4311 			if (*q == '\0')
4312 			{
4313 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4314 						     "No key specified\n");
4315 				return;
4316 			}
4317 			*q++ = '\0';
4318 			map = stab(p, ST_MAP, ST_FIND);
4319 			if (map == NULL)
4320 			{
4321 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4322 						     "Map named \"%s\" not found\n", p);
4323 				return;
4324 			}
4325 			if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4326 			    !openmap(&(map->s_map)))
4327 			{
4328 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4329 						     "Map named \"%s\" not open\n", p);
4330 				return;
4331 			}
4332 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4333 					     "map_lookup: %s (%s) ", p, q);
4334 			av[0] = q;
4335 			av[1] = NULL;
4336 			p = (*map->s_map.map_class->map_lookup)
4337 					(&map->s_map, q, av, &rcode);
4338 			if (p == NULL)
4339 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4340 						     "no match (%d)\n",
4341 						     rcode);
4342 			else
4343 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4344 						     "returns %s (%d)\n", p,
4345 						     rcode);
4346 		}
4347 		else if (sm_strcasecmp(&line[1], "try") == 0)
4348 		{
4349 			MAILER *m;
4350 			STAB *st;
4351 			auto int rcode = EX_OK;
4352 
4353 			q = strpbrk(p, " \t");
4354 			if (q != NULL)
4355 			{
4356 				while (isascii(*q) && isspace(*q))
4357 					*q++ = '\0';
4358 			}
4359 			if (q == NULL || *q == '\0')
4360 			{
4361 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4362 						     "Usage: /try mailer address\n");
4363 				return;
4364 			}
4365 			st = stab(p, ST_MAILER, ST_FIND);
4366 			if (st == NULL)
4367 			{
4368 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4369 						     "Unknown mailer %s\n", p);
4370 				return;
4371 			}
4372 			m = st->s_mailer;
4373 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4374 					     "Trying %s %s address %s for mailer %s\n",
4375 				     bitset(RF_HEADERADDR, tryflags) ? "header"
4376 							: "envelope",
4377 				     bitset(RF_SENDERADDR, tryflags) ? "sender"
4378 							: "recipient", q, p);
4379 			p = remotename(q, m, tryflags, &rcode, CurEnv);
4380 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4381 					     "Rcode = %d, addr = %s\n",
4382 					     rcode, p == NULL ? "<NULL>" : p);
4383 			e->e_to = NULL;
4384 		}
4385 		else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4386 		{
4387 			if (*p == '\0')
4388 			{
4389 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4390 						     "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4391 				return;
4392 			}
4393 			for (; *p != '\0'; p++)
4394 			{
4395 				switch (*p)
4396 				{
4397 				  case 'H':
4398 				  case 'h':
4399 					tryflags |= RF_HEADERADDR;
4400 					break;
4401 
4402 				  case 'E':
4403 				  case 'e':
4404 					tryflags &= ~RF_HEADERADDR;
4405 					break;
4406 
4407 				  case 'S':
4408 				  case 's':
4409 					tryflags |= RF_SENDERADDR;
4410 					break;
4411 
4412 				  case 'R':
4413 				  case 'r':
4414 					tryflags &= ~RF_SENDERADDR;
4415 					break;
4416 				}
4417 			}
4418 			exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4419 			exbuf[1] = ' ';
4420 			exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4421 			exbuf[3] = '\0';
4422 			macdefine(&e->e_macro, A_TEMP,
4423 				macid("{addr_type}"), exbuf);
4424 		}
4425 		else if (sm_strcasecmp(&line[1], "parse") == 0)
4426 		{
4427 			if (*p == '\0')
4428 			{
4429 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4430 						     "Usage: /parse address\n");
4431 				return;
4432 			}
4433 			q = crackaddr(p, e);
4434 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4435 					     "Cracked address = ");
4436 			xputs(smioout, q);
4437 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4438 					     "\nParsing %s %s address\n",
4439 					     bitset(RF_HEADERADDR, tryflags) ?
4440 							"header" : "envelope",
4441 					     bitset(RF_SENDERADDR, tryflags) ?
4442 							"sender" : "recipient");
4443 			if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4444 			    == NULL)
4445 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4446 						     "Cannot parse\n");
4447 			else if (a.q_host != NULL && a.q_host[0] != '\0')
4448 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4449 						     "mailer %s, host %s, user %s\n",
4450 						     a.q_mailer->m_name,
4451 						     a.q_host,
4452 						     a.q_user);
4453 			else
4454 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4455 						     "mailer %s, user %s\n",
4456 						     a.q_mailer->m_name,
4457 						     a.q_user);
4458 			e->e_to = NULL;
4459 		}
4460 		else if (sm_strcasecmp(&line[1], "header") == 0)
4461 		{
4462 			unsigned long ul;
4463 
4464 			ul = chompheader(p, CHHDR_CHECK|CHHDR_USER, NULL, e);
4465 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4466 					     "ul = %lu\n", ul);
4467 		}
4468 		else
4469 		{
4470 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4471 					     "Unknown \"/\" command %s\n",
4472 					     line);
4473 		}
4474 		(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4475 		return;
4476 	}
4477 
4478 	for (p = line; isascii(*p) && isspace(*p); p++)
4479 		continue;
4480 	q = p;
4481 	while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4482 		p++;
4483 	if (*p == '\0')
4484 	{
4485 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4486 				     "No address!\n");
4487 		return;
4488 	}
4489 	*p = '\0';
4490 	if (tTd(23, 101))
4491 		eightbit = to8bit(p + 1);
4492 	if (invalidaddr(p + 1, NULL, true))
4493 		return;
4494 	do
4495 	{
4496 		register char **pvp;
4497 		char pvpbuf[PSBUFSIZE];
4498 
4499 		pvp = prescan(++p, ',', pvpbuf, sizeof(pvpbuf), &delimptr,
4500 			      ConfigLevel >= 9 ? TokTypeNoC : ExtTokenTab, false);
4501 		if (pvp == NULL)
4502 			continue;
4503 		p = q;
4504 		while (*p != '\0')
4505 		{
4506 			int status;
4507 
4508 			rs = strtorwset(p, NULL, ST_FIND);
4509 			if (rs < 0)
4510 			{
4511 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4512 						     "Undefined ruleset %s\n",
4513 						     p);
4514 				break;
4515 			}
4516 			status = REWRITE(pvp, rs, e);
4517 			if (status != EX_OK)
4518 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4519 						     "== Ruleset %s (%d) status %d\n",
4520 						     p, rs, status);
4521 			else if (eightbit)
4522 			{
4523 				cataddr(pvp, NULL, exbuf, sizeof(exbuf), '\0',
4524 					true);
4525 				(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4526 						     "cataddr: %s\n",
4527 						     str2prt(exbuf));
4528 			}
4529 			while (*p != '\0' && *p++ != ',')
4530 				continue;
4531 		}
4532 	} while (*(p = delimptr) != '\0');
4533 	(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
4534 }
4535 
4536 static void
4537 dump_class(s, id)
4538 	register STAB *s;
4539 	int id;
4540 {
4541 	if (s->s_symtype != ST_CLASS)
4542 		return;
4543 	if (bitnset(bitidx(id), s->s_class))
4544 		(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4545 				     "%s\n", s->s_name);
4546 }
4547 
4548 /*
4549 **  An exception type used to create QuickAbort exceptions.
4550 **  This is my first cut at converting QuickAbort from longjmp to exceptions.
4551 **  These exceptions have a single integer argument, which is the argument
4552 **  to longjmp in the original code (either 1 or 2).  I don't know the
4553 **  significance of 1 vs 2: the calls to setjmp don't care.
4554 */
4555 
4556 const SM_EXC_TYPE_T EtypeQuickAbort =
4557 {
4558 	SmExcTypeMagic,
4559 	"E:mta.quickabort",
4560 	"i",
4561 	sm_etype_printf,
4562 	"quick abort %0",
4563 };
4564