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