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