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