xref: /illumos-gate/usr/src/cmd/sendmail/src/srvrsmtp.c (revision 004388ebfdfe2ed7dfd2d153a876dfcc22d2c006)
1 /*
2  * Copyright (c) 1998-2006 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
4  * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5  * Copyright (c) 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * By using this file, you agree to the terms and conditions set
9  * forth in the LICENSE file which can be found at the top level of
10  * the sendmail distribution.
11  *
12  */
13 
14 #pragma ident	"%Z%%M%	%I%	%E% SMI"
15 
16 #include <sendmail.h>
17 #if MILTER
18 # include <libmilter/mfapi.h>
19 # include <libmilter/mfdef.h>
20 #endif /* MILTER */
21 
22 SM_RCSID("@(#)$Id: srvrsmtp.c,v 8.922 2006/02/28 00:42:13 ca Exp $")
23 
24 #include <sm/time.h>
25 #include <sm/fdset.h>
26 
27 #if SASL || STARTTLS
28 # include "sfsasl.h"
29 #endif /* SASL || STARTTLS */
30 #if SASL
31 # define ENC64LEN(l)	(((l) + 2) * 4 / 3 + 1)
32 static int saslmechs __P((sasl_conn_t *, char **));
33 #endif /* SASL */
34 #if STARTTLS
35 # include <sysexits.h>
36 
37 static SSL_CTX	*srv_ctx = NULL;	/* TLS server context */
38 static SSL	*srv_ssl = NULL;	/* per connection context */
39 
40 static bool	tls_ok_srv = false;
41 #if _FFR_DM_ONE
42 static bool	NotFirstDelivery = false;
43 #endif /* _FFR_DM_ONE */
44 
45 extern void	tls_set_verify __P((SSL_CTX *, SSL *, bool));
46 # define TLS_VERIFY_CLIENT() tls_set_verify(srv_ctx, srv_ssl, \
47 				bitset(SRV_VRFY_CLT, features))
48 #endif /* STARTTLS */
49 
50 /* server features */
51 #define SRV_NONE	0x0000	/* none... */
52 #define SRV_OFFER_TLS	0x0001	/* offer STARTTLS */
53 #define SRV_VRFY_CLT	0x0002	/* request a cert */
54 #define SRV_OFFER_AUTH	0x0004	/* offer AUTH */
55 #define SRV_OFFER_ETRN	0x0008	/* offer ETRN */
56 #define SRV_OFFER_VRFY	0x0010	/* offer VRFY (not yet used) */
57 #define SRV_OFFER_EXPN	0x0020	/* offer EXPN */
58 #define SRV_OFFER_VERB	0x0040	/* offer VERB */
59 #define SRV_OFFER_DSN	0x0080	/* offer DSN */
60 #if PIPELINING
61 # define SRV_OFFER_PIPE	0x0100	/* offer PIPELINING */
62 # if _FFR_NO_PIPE
63 #  define SRV_NO_PIPE	0x0200	/* disable PIPELINING, sleep if used */
64 # endif /* _FFR_NO_PIPE */
65 #endif /* PIPELINING */
66 #define SRV_REQ_AUTH	0x0400	/* require AUTH */
67 #define SRV_REQ_SEC	0x0800	/* require security - equiv to AuthOptions=p */
68 #define SRV_TMP_FAIL	0x1000	/* ruleset caused a temporary failure */
69 
70 static unsigned int	srvfeatures __P((ENVELOPE *, char *, unsigned int));
71 
72 #define	STOP_ATTACK	((time_t) -1)
73 static time_t	checksmtpattack __P((volatile unsigned int *, unsigned int,
74 				     bool, char *, ENVELOPE *));
75 static void	mail_esmtp_args __P((char *, char *, ENVELOPE *));
76 static void	printvrfyaddr __P((ADDRESS *, bool, bool));
77 static void	rcpt_esmtp_args __P((ADDRESS *, char *, char *, ENVELOPE *));
78 static char	*skipword __P((char *volatile, char *));
79 static void	setup_smtpd_io __P((void));
80 
81 #if SASL
82 # if SASL >= 20000
83 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
84 				char *_remoteip, char *_localip,
85 				char *_auth_id, sasl_ssf_t *_ext_ssf));
86 
87 # define RESET_SASLCONN	\
88 	do							\
89 	{							\
90 		result = reset_saslconn(&conn, AuthRealm, remoteip, \
91 					localip, auth_id, &ext_ssf); \
92 		if (result != SASL_OK)				\
93 			sasl_ok = false;			\
94 	} while (0)
95 
96 # else /* SASL >= 20000 */
97 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
98 				struct sockaddr_in *_saddr_r,
99 				struct sockaddr_in *_saddr_l,
100 				sasl_external_properties_t *_ext_ssf));
101 # define RESET_SASLCONN	\
102 	do							\
103 	{							\
104 		result = reset_saslconn(&conn, AuthRealm, &saddr_r, \
105 					&saddr_l, &ext_ssf);	\
106 		if (result != SASL_OK)				\
107 			sasl_ok = false;			\
108 	} while (0)
109 
110 # endif /* SASL >= 20000 */
111 #endif /* SASL */
112 
113 extern ENVELOPE	BlankEnvelope;
114 
115 #define NBADRCPTS						\
116 	do							\
117 	{							\
118 		char buf[16];					\
119 		(void) sm_snprintf(buf, sizeof buf, "%d",	\
120 			BadRcptThrottle > 0 && n_badrcpts > BadRcptThrottle \
121 				? n_badrcpts - 1 : n_badrcpts);	\
122 		macdefine(&e->e_macro, A_TEMP, macid("{nbadrcpts}"), buf); \
123 	} while (0)
124 
125 #define SKIP_SPACE(s)	while (isascii(*s) && isspace(*s))	\
126 				(s)++
127 
128 /*
129 **  SMTP -- run the SMTP protocol.
130 **
131 **	Parameters:
132 **		nullserver -- if non-NULL, rejection message for
133 **			(almost) all SMTP commands.
134 **		d_flags -- daemon flags
135 **		e -- the envelope.
136 **
137 **	Returns:
138 **		never.
139 **
140 **	Side Effects:
141 **		Reads commands from the input channel and processes them.
142 */
143 
144 /*
145 **  Notice: The smtp server doesn't have a session context like the client
146 **	side has (mci). Therefore some data (session oriented) is allocated
147 **	or assigned to the "wrong" structure (esp. STARTTLS, AUTH).
148 **	This should be fixed in a successor version.
149 */
150 
151 struct cmd
152 {
153 	char	*cmd_name;	/* command name */
154 	int	cmd_code;	/* internal code, see below */
155 };
156 
157 /* values for cmd_code */
158 #define CMDERROR	0	/* bad command */
159 #define CMDMAIL	1	/* mail -- designate sender */
160 #define CMDRCPT	2	/* rcpt -- designate recipient */
161 #define CMDDATA	3	/* data -- send message text */
162 #define CMDRSET	4	/* rset -- reset state */
163 #define CMDVRFY	5	/* vrfy -- verify address */
164 #define CMDEXPN	6	/* expn -- expand address */
165 #define CMDNOOP	7	/* noop -- do nothing */
166 #define CMDQUIT	8	/* quit -- close connection and die */
167 #define CMDHELO	9	/* helo -- be polite */
168 #define CMDHELP	10	/* help -- give usage info */
169 #define CMDEHLO	11	/* ehlo -- extended helo (RFC 1425) */
170 #define CMDETRN	12	/* etrn -- flush queue */
171 #if SASL
172 # define CMDAUTH	13	/* auth -- SASL authenticate */
173 #endif /* SASL */
174 #if STARTTLS
175 # define CMDSTLS	14	/* STARTTLS -- start TLS session */
176 #endif /* STARTTLS */
177 /* non-standard commands */
178 #define CMDVERB	17	/* verb -- go into verbose mode */
179 /* unimplemented commands from RFC 821 */
180 #define CMDUNIMPL	19	/* unimplemented rfc821 commands */
181 /* use this to catch and log "door handle" attempts on your system */
182 #define CMDLOGBOGUS	23	/* bogus command that should be logged */
183 /* debugging-only commands, only enabled if SMTPDEBUG is defined */
184 #define CMDDBGQSHOW	24	/* showq -- show send queue */
185 #define CMDDBGDEBUG	25	/* debug -- set debug mode */
186 
187 /*
188 **  Note: If you change this list, remember to update 'helpfile'
189 */
190 
191 static struct cmd	CmdTab[] =
192 {
193 	{ "mail",	CMDMAIL		},
194 	{ "rcpt",	CMDRCPT		},
195 	{ "data",	CMDDATA		},
196 	{ "rset",	CMDRSET		},
197 	{ "vrfy",	CMDVRFY		},
198 	{ "expn",	CMDEXPN		},
199 	{ "help",	CMDHELP		},
200 	{ "noop",	CMDNOOP		},
201 	{ "quit",	CMDQUIT		},
202 	{ "helo",	CMDHELO		},
203 	{ "ehlo",	CMDEHLO		},
204 	{ "etrn",	CMDETRN		},
205 	{ "verb",	CMDVERB		},
206 	{ "send",	CMDUNIMPL	},
207 	{ "saml",	CMDUNIMPL	},
208 	{ "soml",	CMDUNIMPL	},
209 	{ "turn",	CMDUNIMPL	},
210 #if SASL
211 	{ "auth",	CMDAUTH,	},
212 #endif /* SASL */
213 #if STARTTLS
214 	{ "starttls",	CMDSTLS,	},
215 #endif /* STARTTLS */
216     /* remaining commands are here only to trap and log attempts to use them */
217 	{ "showq",	CMDDBGQSHOW	},
218 	{ "debug",	CMDDBGDEBUG	},
219 	{ "wiz",	CMDLOGBOGUS	},
220 
221 	{ NULL,		CMDERROR	}
222 };
223 
224 static char	*CurSmtpClient;		/* who's at the other end of channel */
225 
226 #ifndef MAXBADCOMMANDS
227 # define MAXBADCOMMANDS 25	/* maximum number of bad commands */
228 #endif /* ! MAXBADCOMMANDS */
229 #ifndef MAXHELOCOMMANDS
230 # define MAXHELOCOMMANDS 3	/* max HELO/EHLO commands before slowdown */
231 #endif /* ! MAXHELOCOMMANDS */
232 #ifndef MAXVRFYCOMMANDS
233 # define MAXVRFYCOMMANDS 6	/* max VRFY/EXPN commands before slowdown */
234 #endif /* ! MAXVRFYCOMMANDS */
235 #ifndef MAXETRNCOMMANDS
236 # define MAXETRNCOMMANDS 8	/* max ETRN commands before slowdown */
237 #endif /* ! MAXETRNCOMMANDS */
238 #ifndef MAXTIMEOUT
239 # define MAXTIMEOUT (4 * 60)	/* max timeout for bad commands */
240 #endif /* ! MAXTIMEOUT */
241 
242 /*
243 **  Maximum shift value to compute timeout for bad commands.
244 **  This introduces an upper limit of 2^MAXSHIFT for the timeout.
245 */
246 
247 #ifndef MAXSHIFT
248 # define MAXSHIFT 8
249 #endif /* ! MAXSHIFT */
250 #if MAXSHIFT > 31
251  ERROR _MAXSHIFT > 31 is invalid
252 #endif /* MAXSHIFT */
253 
254 
255 #if MAXBADCOMMANDS > 0
256 # define STOP_IF_ATTACK(r)	do		\
257 	{					\
258 		if ((r) == STOP_ATTACK)		\
259 			goto stopattack;	\
260 	} while (0)
261 
262 #else /* MAXBADCOMMANDS > 0 */
263 # define STOP_IF_ATTACK(r)	r
264 #endif /* MAXBADCOMMANDS > 0 */
265 
266 
267 #if SM_HEAP_CHECK
268 static SM_DEBUG_T DebugLeakSmtp = SM_DEBUG_INITIALIZER("leak_smtp",
269 	"@(#)$Debug: leak_smtp - trace memory leaks during SMTP processing $");
270 #endif /* SM_HEAP_CHECK */
271 
272 typedef struct
273 {
274 	bool	sm_gotmail;	/* mail command received */
275 	unsigned int sm_nrcpts;	/* number of successful RCPT commands */
276 	bool	sm_discard;
277 #if MILTER
278 	bool	sm_milterize;
279 	bool	sm_milterlist;	/* any filters in the list? */
280 #endif /* MILTER */
281 	char	*sm_quarmsg;	/* carry quarantining across messages */
282 } SMTP_T;
283 
284 static bool	smtp_data __P((SMTP_T *, ENVELOPE *));
285 
286 #define MSG_TEMPFAIL "451 4.3.2 Please try again later"
287 
288 #if MILTER
289 # define MILTER_ABORT(e)	milter_abort((e))
290 
291 # define MILTER_REPLY(str)						\
292 	{								\
293 		int savelogusrerrs = LogUsrErrs;			\
294 									\
295 		switch (state)						\
296 		{							\
297 		  case SMFIR_SHUTDOWN:					\
298 			if (MilterLogLevel > 3)				\
299 			{						\
300 				sm_syslog(LOG_INFO, e->e_id,		\
301 					  "Milter: %s=%s, reject=421, errormode=4",	\
302 					  str, addr);			\
303 				LogUsrErrs = false;			\
304 			}						\
305 			{						\
306 				bool tsave = QuickAbort;		\
307 									\
308 				QuickAbort = false;			\
309 				usrerr("421 4.3.0 closing connection");	\
310 				QuickAbort = tsave;			\
311 				e->e_sendqueue = NULL;			\
312 				goto doquit;				\
313 			}						\
314 			break;						\
315 		  case SMFIR_REPLYCODE:					\
316 			if (MilterLogLevel > 3)				\
317 			{						\
318 				sm_syslog(LOG_INFO, e->e_id,		\
319 					  "Milter: %s=%s, reject=%s",	\
320 					  str, addr, response);		\
321 				LogUsrErrs = false;			\
322 			}						\
323 			if (strncmp(response, "421 ", 4) == 0		\
324 			    || strncmp(response, "421-", 4) == 0)	\
325 			{						\
326 				bool tsave = QuickAbort;		\
327 									\
328 				QuickAbort = false;			\
329 				usrerr(response);			\
330 				QuickAbort = tsave;			\
331 				e->e_sendqueue = NULL;			\
332 				goto doquit;				\
333 			}						\
334 			else						\
335 				usrerr(response);			\
336 			break;						\
337 									\
338 		  case SMFIR_REJECT:					\
339 			if (MilterLogLevel > 3)				\
340 			{						\
341 				sm_syslog(LOG_INFO, e->e_id,		\
342 					  "Milter: %s=%s, reject=550 5.7.1 Command rejected", \
343 					  str, addr);			\
344 				LogUsrErrs = false;			\
345 			}						\
346 			usrerr("550 5.7.1 Command rejected");		\
347 			break;						\
348 									\
349 		  case SMFIR_DISCARD:					\
350 			if (MilterLogLevel > 3)				\
351 				sm_syslog(LOG_INFO, e->e_id,		\
352 					  "Milter: %s=%s, discard",	\
353 					  str, addr);			\
354 			e->e_flags |= EF_DISCARD;			\
355 			break;						\
356 									\
357 		  case SMFIR_TEMPFAIL:					\
358 			if (MilterLogLevel > 3)				\
359 			{						\
360 				sm_syslog(LOG_INFO, e->e_id,		\
361 					  "Milter: %s=%s, reject=%s",	\
362 					  str, addr, MSG_TEMPFAIL);	\
363 				LogUsrErrs = false;			\
364 			}						\
365 			usrerr(MSG_TEMPFAIL);				\
366 			break;						\
367 		}							\
368 		LogUsrErrs = savelogusrerrs;				\
369 		if (response != NULL)					\
370 			sm_free(response); /* XXX */			\
371 	}
372 
373 #else /* MILTER */
374 # define MILTER_ABORT(e)
375 #endif /* MILTER */
376 
377 /* clear all SMTP state (for HELO/EHLO/RSET) */
378 #define CLEAR_STATE(cmd)					\
379 do								\
380 {								\
381 	/* abort milter filters */				\
382 	MILTER_ABORT(e);					\
383 								\
384 	if (smtp.sm_nrcpts > 0)					\
385 	{							\
386 		logundelrcpts(e, cmd, 10, false);		\
387 		smtp.sm_nrcpts = 0;				\
388 		macdefine(&e->e_macro, A_PERM,			\
389 			  macid("{nrcpts}"), "0");		\
390 	}							\
391 								\
392 	e->e_sendqueue = NULL;					\
393 	e->e_flags |= EF_CLRQUEUE;				\
394 								\
395 	if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))	\
396 		logsender(e, NULL);				\
397 	e->e_flags &= ~EF_LOGSENDER;				\
398 								\
399 	/* clean up a bit */					\
400 	smtp.sm_gotmail = false;				\
401 	SuprErrs = true;					\
402 	dropenvelope(e, true, false);				\
403 	sm_rpool_free(e->e_rpool);				\
404 	e = newenvelope(e, CurEnv, sm_rpool_new_x(NULL));	\
405 	CurEnv = e;						\
406 								\
407 	/* put back discard bit */				\
408 	if (smtp.sm_discard)					\
409 		e->e_flags |= EF_DISCARD;			\
410 								\
411 	/* restore connection quarantining */			\
412 	if (smtp.sm_quarmsg == NULL)				\
413 	{							\
414 		e->e_quarmsg = NULL;				\
415 		macdefine(&e->e_macro, A_PERM,			\
416 			macid("{quarantine}"), "");		\
417 	}							\
418 	else							\
419 	{							\
420 		e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool,	\
421 						smtp.sm_quarmsg);	\
422 		macdefine(&e->e_macro, A_PERM, macid("{quarantine}"),	\
423 			  e->e_quarmsg);			\
424 	}							\
425 } while (0)
426 
427 /* sleep to flatten out connection load */
428 #define MIN_DELAY_LOG	15	/* wait before logging this again */
429 
430 /* is it worth setting the process title for 1s? */
431 #define DELAY_CONN(cmd)						\
432 	if (DelayLA > 0 && (CurrentLA = getla()) >= DelayLA)	\
433 	{							\
434 		time_t dnow;					\
435 								\
436 		sm_setproctitle(true, e,			\
437 				"%s: %s: delaying %s: load average: %d", \
438 				qid_printname(e), CurSmtpClient,	\
439 				cmd, DelayLA);	\
440 		if (LogLevel > 8 && (dnow = curtime()) > log_delay)	\
441 		{						\
442 			sm_syslog(LOG_INFO, e->e_id,		\
443 				  "delaying=%s, load average=%d >= %d",	\
444 				  cmd, CurrentLA, DelayLA);		\
445 			log_delay = dnow + MIN_DELAY_LOG;	\
446 		}						\
447 		(void) sleep(1);				\
448 		sm_setproctitle(true, e, "%s %s: %.80s",	\
449 				qid_printname(e), CurSmtpClient, inp);	\
450 	}
451 
452 
453 void
454 smtp(nullserver, d_flags, e)
455 	char *volatile nullserver;
456 	BITMAP256 d_flags;
457 	register ENVELOPE *volatile e;
458 {
459 	register char *volatile p;
460 	register struct cmd *volatile c = NULL;
461 	char *cmd;
462 	auto ADDRESS *vrfyqueue;
463 	ADDRESS *a;
464 	volatile bool gothello;		/* helo command received */
465 	bool vrfy;			/* set if this is a vrfy command */
466 	char *volatile protocol;	/* sending protocol */
467 	char *volatile sendinghost;	/* sending hostname */
468 	char *volatile peerhostname;	/* name of SMTP peer or "localhost" */
469 	auto char *delimptr;
470 	char *id;
471 	volatile unsigned int n_badcmds = 0;	/* count of bad commands */
472 	volatile unsigned int n_badrcpts = 0;	/* number of rejected RCPT */
473 	volatile unsigned int n_verifies = 0;	/* count of VRFY/EXPN */
474 	volatile unsigned int n_etrn = 0;	/* count of ETRN */
475 	volatile unsigned int n_noop = 0;	/* count of NOOP/VERB/etc */
476 	volatile unsigned int n_helo = 0;	/* count of HELO/EHLO */
477 	volatile int save_sevenbitinput;
478 	bool ok;
479 #if _FFR_BLOCK_PROXIES
480 	volatile bool first;
481 #endif /* _FFR_BLOCK_PROXIES */
482 	volatile bool tempfail = false;
483 	volatile time_t wt;		/* timeout after too many commands */
484 	volatile time_t previous;	/* time after checksmtpattack() */
485 	volatile bool lognullconnection = true;
486 	register char *q;
487 	SMTP_T smtp;
488 	char *addr;
489 	char *greetcode = "220";
490 	char *hostname;			/* my hostname ($j) */
491 	QUEUE_CHAR *new;
492 	int argno;
493 	char *args[MAXSMTPARGS];
494 	char inp[MAXLINE];
495 	char cmdbuf[MAXLINE];
496 #if SASL
497 	sasl_conn_t *conn;
498 	volatile bool sasl_ok;
499 	volatile unsigned int n_auth = 0;	/* count of AUTH commands */
500 	bool ismore;
501 	int result;
502 	volatile int authenticating;
503 	char *user;
504 	char *in, *out2;
505 # if SASL >= 20000
506 	char *auth_id;
507 	const char *out;
508 	sasl_ssf_t ext_ssf;
509 	char localip[60], remoteip[60];
510 # else /* SASL >= 20000 */
511 	char *out;
512 	const char *errstr;
513 	sasl_external_properties_t ext_ssf;
514 	struct sockaddr_in saddr_l;
515 	struct sockaddr_in saddr_r;
516 # endif /* SASL >= 20000 */
517 	sasl_security_properties_t ssp;
518 	sasl_ssf_t *ssf;
519 	unsigned int inlen, out2len;
520 	unsigned int outlen;
521 	char *volatile auth_type;
522 	char *mechlist;
523 	volatile unsigned int n_mechs;
524 	unsigned int len;
525 #endif /* SASL */
526 	int r;
527 #if STARTTLS
528 	int rfd, wfd;
529 	volatile bool tls_active = false;
530 	volatile bool smtps = bitnset(D_SMTPS, d_flags);
531 	bool saveQuickAbort;
532 	bool saveSuprErrs;
533 	time_t tlsstart;
534 #endif /* STARTTLS */
535 	volatile unsigned int features;
536 #if PIPELINING
537 # if _FFR_NO_PIPE
538 	int np_log = 0;
539 # endif /* _FFR_NO_PIPE */
540 #endif /* PIPELINING */
541 	volatile time_t log_delay = (time_t) 0;
542 
543 	save_sevenbitinput = SevenBitInput;
544 	smtp.sm_nrcpts = 0;
545 #if MILTER
546 	smtp.sm_milterize = (nullserver == NULL);
547 	smtp.sm_milterlist = false;
548 #endif /* MILTER */
549 
550 	/* setup I/O fd correctly for the SMTP server */
551 	setup_smtpd_io();
552 
553 #if SM_HEAP_CHECK
554 	if (sm_debug_active(&DebugLeakSmtp, 1))
555 	{
556 		sm_heap_newgroup();
557 		sm_dprintf("smtp() heap group #%d\n", sm_heap_group());
558 	}
559 #endif /* SM_HEAP_CHECK */
560 
561 	/* XXX the rpool should be set when e is initialized in main() */
562 	e->e_rpool = sm_rpool_new_x(NULL);
563 	e->e_macro.mac_rpool = e->e_rpool;
564 
565 	settime(e);
566 	sm_getla();
567 	peerhostname = RealHostName;
568 	if (peerhostname == NULL)
569 		peerhostname = "localhost";
570 	CurHostName = peerhostname;
571 	CurSmtpClient = macvalue('_', e);
572 	if (CurSmtpClient == NULL)
573 		CurSmtpClient = CurHostName;
574 
575 	/* check_relay may have set discard bit, save for later */
576 	smtp.sm_discard = bitset(EF_DISCARD, e->e_flags);
577 
578 #if PIPELINING
579 	/* auto-flush output when reading input */
580 	(void) sm_io_autoflush(InChannel, OutChannel);
581 #endif /* PIPELINING */
582 
583 	sm_setproctitle(true, e, "server %s startup", CurSmtpClient);
584 
585 	/* Set default features for server. */
586 	features = ((bitset(PRIV_NOETRN, PrivacyFlags) ||
587 		     bitnset(D_NOETRN, d_flags)) ? SRV_NONE : SRV_OFFER_ETRN)
588 		| (bitnset(D_AUTHREQ, d_flags) ? SRV_REQ_AUTH : SRV_NONE)
589 		| (bitset(PRIV_NOEXPN, PrivacyFlags) ? SRV_NONE
590 			: (SRV_OFFER_EXPN
591 			  | (bitset(PRIV_NOVERB, PrivacyFlags)
592 			     ? SRV_NONE : SRV_OFFER_VERB)))
593 		| (bitset(PRIV_NORECEIPTS, PrivacyFlags) ? SRV_NONE
594 							 : SRV_OFFER_DSN)
595 #if SASL
596 		| (bitnset(D_NOAUTH, d_flags) ? SRV_NONE : SRV_OFFER_AUTH)
597 		| (bitset(SASL_SEC_NOPLAINTEXT, SASLOpts) ? SRV_REQ_SEC
598 							  : SRV_NONE)
599 #endif /* SASL */
600 #if PIPELINING
601 		| SRV_OFFER_PIPE
602 #endif /* PIPELINING */
603 #if STARTTLS
604 		| (bitnset(D_NOTLS, d_flags) ? SRV_NONE : SRV_OFFER_TLS)
605 		| (bitset(TLS_I_NO_VRFY, TLS_Srv_Opts) ? SRV_NONE
606 						       : SRV_VRFY_CLT)
607 #endif /* STARTTLS */
608 		;
609 	if (nullserver == NULL)
610 	{
611 		features = srvfeatures(e, CurSmtpClient, features);
612 		if (bitset(SRV_TMP_FAIL, features))
613 		{
614 			if (LogLevel > 4)
615 				sm_syslog(LOG_ERR, NOQID,
616 					  "ERROR: srv_features=tempfail, relay=%.100s, access temporarily disabled",
617 					  CurSmtpClient);
618 			nullserver = "450 4.3.0 Please try again later.";
619 		}
620 		else
621 		{
622 #if PIPELINING
623 # if _FFR_NO_PIPE
624 			if (bitset(SRV_NO_PIPE, features))
625 			{
626 				/* for consistency */
627 				features &= ~SRV_OFFER_PIPE;
628 			}
629 # endif /* _FFR_NO_PIPE */
630 #endif /* PIPELINING */
631 #if SASL
632 			if (bitset(SRV_REQ_SEC, features))
633 				SASLOpts |= SASL_SEC_NOPLAINTEXT;
634 			else
635 				SASLOpts &= ~SASL_SEC_NOPLAINTEXT;
636 #endif /* SASL */
637 		}
638 	}
639 	else if (strncmp(nullserver, "421 ", 4) == 0)
640 	{
641 		message(nullserver);
642 		goto doquit;
643 	}
644 
645 	hostname = macvalue('j', e);
646 #if SASL
647 	if (AuthRealm == NULL)
648 		AuthRealm = hostname;
649 	sasl_ok = bitset(SRV_OFFER_AUTH, features);
650 	n_mechs = 0;
651 	authenticating = SASL_NOT_AUTH;
652 
653 	/* SASL server new connection */
654 	if (sasl_ok)
655 	{
656 # if SASL >= 20000
657 		result = sasl_server_new("smtp", AuthRealm, NULL, NULL, NULL,
658 					 NULL, 0, &conn);
659 # elif SASL > 10505
660 		/* use empty realm: only works in SASL > 1.5.5 */
661 		result = sasl_server_new("smtp", AuthRealm, "", NULL, 0, &conn);
662 # else /* SASL >= 20000 */
663 		/* use no realm -> realm is set to hostname by SASL lib */
664 		result = sasl_server_new("smtp", AuthRealm, NULL, NULL, 0,
665 					 &conn);
666 # endif /* SASL >= 20000 */
667 		sasl_ok = result == SASL_OK;
668 		if (!sasl_ok)
669 		{
670 			if (LogLevel > 9)
671 				sm_syslog(LOG_WARNING, NOQID,
672 					  "AUTH error: sasl_server_new failed=%d",
673 					  result);
674 		}
675 	}
676 	if (sasl_ok)
677 	{
678 		/*
679 		**  SASL set properties for sasl
680 		**  set local/remote IP
681 		**  XXX Cyrus SASL v1 only supports IPv4
682 		**
683 		**  XXX where exactly are these used/required?
684 		**  Kerberos_v4
685 		*/
686 
687 # if SASL >= 20000
688 		localip[0] = remoteip[0] = '\0';
689 #  if NETINET || NETINET6
690 		in = macvalue(macid("{daemon_family}"), e);
691 		if (in != NULL && (
692 #   if NETINET6
693 		    strcmp(in, "inet6") == 0 ||
694 #   endif /* NETINET6 */
695 		    strcmp(in, "inet") == 0))
696 		{
697 			SOCKADDR_LEN_T addrsize;
698 			SOCKADDR saddr_l;
699 			SOCKADDR saddr_r;
700 
701 			addrsize = sizeof(saddr_r);
702 			if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
703 						      NULL),
704 					(struct sockaddr *) &saddr_r,
705 					&addrsize) == 0)
706 			{
707 				if (iptostring(&saddr_r, addrsize,
708 					       remoteip, sizeof remoteip))
709 				{
710 					sasl_setprop(conn, SASL_IPREMOTEPORT,
711 						     remoteip);
712 				}
713 				addrsize = sizeof(saddr_l);
714 				if (getsockname(sm_io_getinfo(InChannel,
715 							      SM_IO_WHAT_FD,
716 							      NULL),
717 						(struct sockaddr *) &saddr_l,
718 						&addrsize) == 0)
719 				{
720 					if (iptostring(&saddr_l, addrsize,
721 						       localip,
722 						       sizeof localip))
723 					{
724 						sasl_setprop(conn,
725 							     SASL_IPLOCALPORT,
726 							     localip);
727 					}
728 				}
729 			}
730 		}
731 #  endif /* NETINET || NETINET6 */
732 # else /* SASL >= 20000 */
733 #  if NETINET
734 		in = macvalue(macid("{daemon_family}"), e);
735 		if (in != NULL && strcmp(in, "inet") == 0)
736 		{
737 			SOCKADDR_LEN_T addrsize;
738 
739 			addrsize = sizeof(struct sockaddr_in);
740 			if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
741 						      NULL),
742 					(struct sockaddr *)&saddr_r,
743 					&addrsize) == 0)
744 			{
745 				sasl_setprop(conn, SASL_IP_REMOTE, &saddr_r);
746 				addrsize = sizeof(struct sockaddr_in);
747 				if (getsockname(sm_io_getinfo(InChannel,
748 							      SM_IO_WHAT_FD,
749 							      NULL),
750 						(struct sockaddr *)&saddr_l,
751 						&addrsize) == 0)
752 					sasl_setprop(conn, SASL_IP_LOCAL,
753 						     &saddr_l);
754 			}
755 		}
756 #  endif /* NETINET */
757 # endif /* SASL >= 20000 */
758 
759 		auth_type = NULL;
760 		mechlist = NULL;
761 		user = NULL;
762 # if 0
763 		macdefine(&BlankEnvelope.e_macro, A_PERM,
764 			macid("{auth_author}"), NULL);
765 # endif /* 0 */
766 
767 		/* set properties */
768 		(void) memset(&ssp, '\0', sizeof ssp);
769 
770 		/* XXX should these be options settable via .cf ? */
771 		/* ssp.min_ssf = 0; is default due to memset() */
772 		{
773 			ssp.max_ssf = MaxSLBits;
774 			ssp.maxbufsize = MAXOUTLEN;
775 		}
776 		ssp.security_flags = SASLOpts & SASL_SEC_MASK;
777 		sasl_ok = sasl_setprop(conn, SASL_SEC_PROPS, &ssp) == SASL_OK;
778 
779 		if (sasl_ok)
780 		{
781 			/*
782 			**  external security strength factor;
783 			**	currently we have none so zero
784 			*/
785 
786 # if SASL >= 20000
787 			ext_ssf = 0;
788 			auth_id = NULL;
789 			sasl_ok = ((sasl_setprop(conn, SASL_SSF_EXTERNAL,
790 						 &ext_ssf) == SASL_OK) &&
791 				   (sasl_setprop(conn, SASL_AUTH_EXTERNAL,
792 						 auth_id) == SASL_OK));
793 # else /* SASL >= 20000 */
794 			ext_ssf.ssf = 0;
795 			ext_ssf.auth_id = NULL;
796 			sasl_ok = sasl_setprop(conn, SASL_SSF_EXTERNAL,
797 					       &ext_ssf) == SASL_OK;
798 # endif /* SASL >= 20000 */
799 		}
800 		if (sasl_ok)
801 			n_mechs = saslmechs(conn, &mechlist);
802 	}
803 #endif /* SASL */
804 
805 #if STARTTLS
806 #endif /* STARTTLS */
807 
808 #if MILTER
809 	if (smtp.sm_milterize)
810 	{
811 		char state;
812 
813 		/* initialize mail filter connection */
814 		smtp.sm_milterlist = milter_init(e, &state);
815 		switch (state)
816 		{
817 		  case SMFIR_REJECT:
818 			if (MilterLogLevel > 3)
819 				sm_syslog(LOG_INFO, e->e_id,
820 					  "Milter: initialization failed, rejecting commands");
821 			greetcode = "554";
822 			nullserver = "Command rejected";
823 			smtp.sm_milterize = false;
824 			break;
825 
826 		  case SMFIR_TEMPFAIL:
827 			if (MilterLogLevel > 3)
828 				sm_syslog(LOG_INFO, e->e_id,
829 					  "Milter: initialization failed, temp failing commands");
830 			tempfail = true;
831 			smtp.sm_milterize = false;
832 			break;
833 
834 		  case SMFIR_SHUTDOWN:
835 			if (MilterLogLevel > 3)
836 				sm_syslog(LOG_INFO, e->e_id,
837 					  "Milter: initialization failed, closing connection");
838 			tempfail = true;
839 			smtp.sm_milterize = false;
840 			message("421 4.7.0 %s closing connection",
841 					MyHostName);
842 
843 			/* arrange to ignore send list */
844 			e->e_sendqueue = NULL;
845 			goto doquit;
846 		}
847 	}
848 
849 	if (smtp.sm_milterlist && smtp.sm_milterize &&
850 	    !bitset(EF_DISCARD, e->e_flags))
851 	{
852 		char state;
853 		char *response;
854 
855 		response = milter_connect(peerhostname, RealHostAddr,
856 					  e, &state);
857 		switch (state)
858 		{
859 		  case SMFIR_REPLYCODE:	/* REPLYCODE shouldn't happen */
860 		  case SMFIR_REJECT:
861 			if (MilterLogLevel > 3)
862 				sm_syslog(LOG_INFO, e->e_id,
863 					  "Milter: connect: host=%s, addr=%s, rejecting commands",
864 					  peerhostname,
865 					  anynet_ntoa(&RealHostAddr));
866 			greetcode = "554";
867 			nullserver = "Command rejected";
868 			smtp.sm_milterize = false;
869 			break;
870 
871 		  case SMFIR_TEMPFAIL:
872 			if (MilterLogLevel > 3)
873 				sm_syslog(LOG_INFO, e->e_id,
874 					  "Milter: connect: host=%s, addr=%s, temp failing commands",
875 					  peerhostname,
876 					  anynet_ntoa(&RealHostAddr));
877 			tempfail = true;
878 			smtp.sm_milterize = false;
879 			break;
880 
881 		  case SMFIR_SHUTDOWN:
882 			if (MilterLogLevel > 3)
883 				sm_syslog(LOG_INFO, e->e_id,
884 					  "Milter: connect: host=%s, addr=%s, shutdown",
885 					  peerhostname,
886 					  anynet_ntoa(&RealHostAddr));
887 			tempfail = true;
888 			smtp.sm_milterize = false;
889 			message("421 4.7.0 %s closing connection",
890 					MyHostName);
891 
892 			/* arrange to ignore send list */
893 			e->e_sendqueue = NULL;
894 			goto doquit;
895 		}
896 		if (response != NULL)
897 			sm_free(response); /* XXX */
898 	}
899 #endif /* MILTER */
900 
901 	/*
902 	**  Broken proxies and SMTP slammers
903 	**  push data without waiting, catch them
904 	*/
905 
906 	if (
907 #if STARTTLS
908 	    !smtps &&
909 #endif /* STARTTLS */
910 	    *greetcode == '2')
911 	{
912 		time_t msecs = 0;
913 		char **pvp;
914 		char pvpbuf[PSBUFSIZE];
915 
916 		/* Ask the rulesets how long to pause */
917 		pvp = NULL;
918 		r = rscap("greet_pause", peerhostname,
919 			  anynet_ntoa(&RealHostAddr), e,
920 			  &pvp, pvpbuf, sizeof(pvpbuf));
921 		if (r == EX_OK && pvp != NULL && pvp[0] != NULL &&
922 		    (pvp[0][0] & 0377) == CANONNET && pvp[1] != NULL)
923 		{
924 			msecs = strtol(pvp[1], NULL, 10);
925 		}
926 
927 		if (msecs > 0)
928 		{
929 			int fd;
930 			fd_set readfds;
931 			struct timeval timeout;
932 #if _FFR_LOG_GREET_PAUSE
933 			struct timeval bp, ep, tp; /* {begin,end,total}pause */
934 #endif /* _FFR_LOG_GREET_PAUSE */
935 
936 			/* pause for a moment */
937 			timeout.tv_sec = msecs / 1000;
938 			timeout.tv_usec = (msecs % 1000) * 1000;
939 
940 			/* Obey RFC 2821: 4.3.5.2: 220 timeout of 5 minutes */
941 			if (timeout.tv_sec >= 300)
942 			{
943 				timeout.tv_sec = 300;
944 				timeout.tv_usec = 0;
945 			}
946 
947 			/* check if data is on the socket during the pause */
948 			fd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
949 			FD_ZERO(&readfds);
950 			SM_FD_SET(fd, &readfds);
951 #if _FFR_LOG_GREET_PAUSE
952 			gettimeofday(&bp, NULL);
953 #endif /* _FFR_LOG_GREET_PAUSE */
954 			if (select(fd + 1, FDSET_CAST &readfds,
955 			    NULL, NULL, &timeout) > 0 &&
956 			    FD_ISSET(fd, &readfds))
957 			{
958 #if _FFR_LOG_GREET_PAUSE
959 				gettimeofday(&ep, NULL);
960 				timersub(&ep, &bp, &tp);
961 #endif /* _FFR_LOG_GREET_PAUSE */
962 				greetcode = "554";
963 				nullserver = "Command rejected";
964 				sm_syslog(LOG_INFO, e->e_id,
965 #if _FFR_LOG_GREET_PAUSE
966 					  "rejecting commands from %s [%s] after %d seconds due to pre-greeting traffic",
967 #else /* _FFR_LOG_GREET_PAUSE */
968 					  "rejecting commands from %s [%s] due to pre-greeting traffic",
969 #endif /* _FFR_LOG_GREET_PAUSE */
970 					  peerhostname,
971 					  anynet_ntoa(&RealHostAddr)
972 #if _FFR_LOG_GREET_PAUSE
973 					  , (int) tp.tv_sec +
974 						(tp.tv_usec >= 500000 ? 1 : 0)
975 #endif /* _FFR_LOG_GREET_PAUSE */
976 					 );
977 			}
978 		}
979 	}
980 
981 #if STARTTLS
982 	/* If this an smtps connection, start TLS now */
983 	if (smtps)
984 	{
985 		Errors = 0;
986 		goto starttls;
987 	}
988 
989   greeting:
990 
991 #endif /* STARTTLS */
992 
993 	/* output the first line, inserting "ESMTP" as second word */
994 	if (*greetcode == '5')
995 		(void) sm_snprintf(inp, sizeof inp, "%s not accepting messages",
996 				   hostname);
997 	else
998 		expand(SmtpGreeting, inp, sizeof inp, e);
999 
1000 	p = strchr(inp, '\n');
1001 	if (p != NULL)
1002 		*p++ = '\0';
1003 	id = strchr(inp, ' ');
1004 	if (id == NULL)
1005 		id = &inp[strlen(inp)];
1006 	if (p == NULL)
1007 		(void) sm_snprintf(cmdbuf, sizeof cmdbuf,
1008 			 "%s %%.*s ESMTP%%s", greetcode);
1009 	else
1010 		(void) sm_snprintf(cmdbuf, sizeof cmdbuf,
1011 			 "%s-%%.*s ESMTP%%s", greetcode);
1012 	message(cmdbuf, (int) (id - inp), inp, id);
1013 
1014 	/* output remaining lines */
1015 	while ((id = p) != NULL && (p = strchr(id, '\n')) != NULL)
1016 	{
1017 		*p++ = '\0';
1018 		if (isascii(*id) && isspace(*id))
1019 			id++;
1020 		(void) sm_strlcpyn(cmdbuf, sizeof cmdbuf, 2, greetcode, "-%s");
1021 		message(cmdbuf, id);
1022 	}
1023 	if (id != NULL)
1024 	{
1025 		if (isascii(*id) && isspace(*id))
1026 			id++;
1027 		(void) sm_strlcpyn(cmdbuf, sizeof cmdbuf, 2, greetcode, " %s");
1028 		message(cmdbuf, id);
1029 	}
1030 
1031 	protocol = NULL;
1032 	sendinghost = macvalue('s', e);
1033 
1034 	/* If quarantining by a connect/ehlo action, save between messages */
1035 	if (e->e_quarmsg == NULL)
1036 		smtp.sm_quarmsg = NULL;
1037 	else
1038 		smtp.sm_quarmsg = newstr(e->e_quarmsg);
1039 
1040 	/* sendinghost's storage must outlive the current envelope */
1041 	if (sendinghost != NULL)
1042 		sendinghost = sm_strdup_x(sendinghost);
1043 #if _FFR_BLOCK_PROXIES
1044 	first = true;
1045 #endif /* _FFR_BLOCK_PROXIES */
1046 	gothello = false;
1047 	smtp.sm_gotmail = false;
1048 	for (;;)
1049 	{
1050 	    SM_TRY
1051 	    {
1052 		QuickAbort = false;
1053 		HoldErrs = false;
1054 		SuprErrs = false;
1055 		LogUsrErrs = false;
1056 		OnlyOneError = true;
1057 		e->e_flags &= ~(EF_VRFYONLY|EF_GLOBALERRS);
1058 
1059 		/* setup for the read */
1060 		e->e_to = NULL;
1061 		Errors = 0;
1062 		FileName = NULL;
1063 		(void) sm_io_flush(smioout, SM_TIME_DEFAULT);
1064 
1065 		/* read the input line */
1066 		SmtpPhase = "server cmd read";
1067 		sm_setproctitle(true, e, "server %s cmd read", CurSmtpClient);
1068 #if SASL
1069 		/*
1070 		**  XXX SMTP AUTH requires accepting any length,
1071 		**	at least for challenge/response
1072 		*/
1073 #endif /* SASL */
1074 
1075 		/* handle errors */
1076 		if (sm_io_error(OutChannel) ||
1077 		    (p = sfgets(inp, sizeof inp, InChannel,
1078 				TimeOuts.to_nextcommand, SmtpPhase)) == NULL)
1079 		{
1080 			char *d;
1081 
1082 			d = macvalue(macid("{daemon_name}"), e);
1083 			if (d == NULL)
1084 				d = "stdin";
1085 			/* end of file, just die */
1086 			disconnect(1, e);
1087 
1088 #if MILTER
1089 			/* close out milter filters */
1090 			milter_quit(e);
1091 #endif /* MILTER */
1092 
1093 			message("421 4.4.1 %s Lost input channel from %s",
1094 				MyHostName, CurSmtpClient);
1095 			if (LogLevel > (smtp.sm_gotmail ? 1 : 19))
1096 				sm_syslog(LOG_NOTICE, e->e_id,
1097 					  "lost input channel from %s to %s after %s",
1098 					  CurSmtpClient, d,
1099 					  (c == NULL || c->cmd_name == NULL) ? "startup" : c->cmd_name);
1100 			/*
1101 			**  If have not accepted mail (DATA), do not bounce
1102 			**  bad addresses back to sender.
1103 			*/
1104 
1105 			if (bitset(EF_CLRQUEUE, e->e_flags))
1106 				e->e_sendqueue = NULL;
1107 			goto doquit;
1108 		}
1109 
1110 #if _FFR_BLOCK_PROXIES
1111 		if (first)
1112 		{
1113 			size_t inplen, cmdlen;
1114 			int idx;
1115 			char *http_cmd;
1116 			static char *http_cmds[] = { "GET", "POST",
1117 						     "CONNECT", "USER", NULL };
1118 
1119 			inplen = strlen(inp);
1120 			for (idx = 0; (http_cmd = http_cmds[idx]) != NULL;
1121 			     idx++)
1122 			{
1123 				cmdlen = strlen(http_cmd);
1124 				if (cmdlen < inplen &&
1125 				    sm_strncasecmp(inp, http_cmd, cmdlen) == 0 &&
1126 				    isascii(inp[cmdlen]) && isspace(inp[cmdlen]))
1127 				{
1128 					/* Open proxy, drop it */
1129 					message("421 4.7.0 %s Rejecting open proxy %s",
1130 						MyHostName, CurSmtpClient);
1131 					sm_syslog(LOG_INFO, e->e_id,
1132 						  "%s: probable open proxy: command=%.40s",
1133 						  CurSmtpClient, inp);
1134 					goto doquit;
1135 				}
1136 			}
1137 			first = false;
1138 		}
1139 #endif /* _FFR_BLOCK_PROXIES */
1140 
1141 		/* clean up end of line */
1142 		fixcrlf(inp, true);
1143 
1144 #if PIPELINING
1145 # if _FFR_NO_PIPE
1146 		/*
1147 		**  if there is more input and pipelining is disabled:
1148 		**	delay ... (and maybe discard the input?)
1149 		**  XXX this doesn't really work, at least in tests using
1150 		**  telnet SM_IO_IS_READABLE only returns 1 if there were
1151 		**  more than 2 input lines available.
1152 		*/
1153 
1154 		if (bitset(SRV_NO_PIPE, features) &&
1155 		    sm_io_getinfo(InChannel, SM_IO_IS_READABLE, NULL) > 0)
1156 		{
1157 			if (++np_log < 3)
1158 				sm_syslog(LOG_INFO, NOQID,
1159 					  "unauthorized PIPELINING, sleeping");
1160 			sleep(1);
1161 		}
1162 
1163 # endif /* _FFR_NO_PIPE */
1164 #endif /* PIPELINING */
1165 
1166 #if SASL
1167 		if (authenticating == SASL_PROC_AUTH)
1168 		{
1169 # if 0
1170 			if (*inp == '\0')
1171 			{
1172 				authenticating = SASL_NOT_AUTH;
1173 				message("501 5.5.2 missing input");
1174 				RESET_SASLCONN;
1175 				continue;
1176 			}
1177 # endif /* 0 */
1178 			if (*inp == '*' && *(inp + 1) == '\0')
1179 			{
1180 				authenticating = SASL_NOT_AUTH;
1181 
1182 				/* rfc 2254 4. */
1183 				message("501 5.0.0 AUTH aborted");
1184 				RESET_SASLCONN;
1185 				continue;
1186 			}
1187 
1188 			/* could this be shorter? XXX */
1189 # if SASL >= 20000
1190 			in = xalloc(strlen(inp) + 1);
1191 			result = sasl_decode64(inp, strlen(inp), in,
1192 					       strlen(inp), &inlen);
1193 # else /* SASL >= 20000 */
1194 			out = xalloc(strlen(inp));
1195 			result = sasl_decode64(inp, strlen(inp), out, &outlen);
1196 # endif /* SASL >= 20000 */
1197 			if (result != SASL_OK)
1198 			{
1199 				authenticating = SASL_NOT_AUTH;
1200 
1201 				/* rfc 2254 4. */
1202 				message("501 5.5.4 cannot decode AUTH parameter %s",
1203 					inp);
1204 # if SASL >= 20000
1205 				sm_free(in);
1206 # endif /* SASL >= 20000 */
1207 				RESET_SASLCONN;
1208 				continue;
1209 			}
1210 
1211 # if SASL >= 20000
1212 			result = sasl_server_step(conn,	in, inlen,
1213 						  &out, &outlen);
1214 			sm_free(in);
1215 # else /* SASL >= 20000 */
1216 			result = sasl_server_step(conn,	out, outlen,
1217 						  &out, &outlen, &errstr);
1218 # endif /* SASL >= 20000 */
1219 
1220 			/* get an OK if we're done */
1221 			if (result == SASL_OK)
1222 			{
1223   authenticated:
1224 				message("235 2.0.0 OK Authenticated");
1225 				authenticating = SASL_IS_AUTH;
1226 				macdefine(&BlankEnvelope.e_macro, A_TEMP,
1227 					macid("{auth_type}"), auth_type);
1228 
1229 # if SASL >= 20000
1230 				user = macvalue(macid("{auth_authen}"), e);
1231 
1232 				/* get security strength (features) */
1233 				result = sasl_getprop(conn, SASL_SSF,
1234 						      (const void **) &ssf);
1235 # else /* SASL >= 20000 */
1236 				result = sasl_getprop(conn, SASL_USERNAME,
1237 						      (void **)&user);
1238 				if (result != SASL_OK)
1239 				{
1240 					user = "";
1241 					macdefine(&BlankEnvelope.e_macro,
1242 						  A_PERM,
1243 						  macid("{auth_authen}"), NULL);
1244 				}
1245 				else
1246 				{
1247 					macdefine(&BlankEnvelope.e_macro,
1248 						  A_TEMP,
1249 						  macid("{auth_authen}"),
1250 						  xtextify(user, "<>\")"));
1251 				}
1252 
1253 # if 0
1254 				/* get realm? */
1255 				sasl_getprop(conn, SASL_REALM, (void **) &data);
1256 # endif /* 0 */
1257 
1258 				/* get security strength (features) */
1259 				result = sasl_getprop(conn, SASL_SSF,
1260 						      (void **) &ssf);
1261 # endif /* SASL >= 20000 */
1262 				if (result != SASL_OK)
1263 				{
1264 					macdefine(&BlankEnvelope.e_macro,
1265 						  A_PERM,
1266 						  macid("{auth_ssf}"), "0");
1267 					ssf = NULL;
1268 				}
1269 				else
1270 				{
1271 					char pbuf[8];
1272 
1273 					(void) sm_snprintf(pbuf, sizeof pbuf,
1274 							   "%u", *ssf);
1275 					macdefine(&BlankEnvelope.e_macro,
1276 						  A_TEMP,
1277 						  macid("{auth_ssf}"), pbuf);
1278 					if (tTd(95, 8))
1279 						sm_dprintf("AUTH auth_ssf: %u\n",
1280 							   *ssf);
1281 				}
1282 
1283 				/*
1284 				**  Only switch to encrypted connection
1285 				**  if a security layer has been negotiated
1286 				*/
1287 
1288 				if (ssf != NULL && *ssf > 0)
1289 				{
1290 					/*
1291 					**  Convert I/O layer to use SASL.
1292 					**  If the call fails, the connection
1293 					**  is aborted.
1294 					*/
1295 
1296 					if (sfdcsasl(&InChannel, &OutChannel,
1297 						     conn) == 0)
1298 					{
1299 						/* restart dialogue */
1300 						n_helo = 0;
1301 # if PIPELINING
1302 						(void) sm_io_autoflush(InChannel,
1303 								       OutChannel);
1304 # endif /* PIPELINING */
1305 					}
1306 					else
1307 						syserr("503 5.3.3 SASL TLS failed");
1308 				}
1309 
1310 				/* NULL pointer ok since it's our function */
1311 				if (LogLevel > 8)
1312 					sm_syslog(LOG_INFO, NOQID,
1313 						  "AUTH=server, relay=%s, authid=%.128s, mech=%.16s, bits=%d",
1314 						  CurSmtpClient,
1315 						  shortenstring(user, 128),
1316 						  auth_type, *ssf);
1317 			}
1318 			else if (result == SASL_CONTINUE)
1319 			{
1320 				len = ENC64LEN(outlen);
1321 				out2 = xalloc(len);
1322 				result = sasl_encode64(out, outlen, out2, len,
1323 						       &out2len);
1324 				if (result != SASL_OK)
1325 				{
1326 					/* correct code? XXX */
1327 					/* 454 Temp. authentication failure */
1328 					message("454 4.5.4 Internal error: unable to encode64");
1329 					if (LogLevel > 5)
1330 						sm_syslog(LOG_WARNING, e->e_id,
1331 							  "AUTH encode64 error [%d for \"%s\"]",
1332 							  result, out);
1333 					/* start over? */
1334 					authenticating = SASL_NOT_AUTH;
1335 				}
1336 				else
1337 				{
1338 					message("334 %s", out2);
1339 					if (tTd(95, 2))
1340 						sm_dprintf("AUTH continue: msg='%s' len=%u\n",
1341 							   out2, out2len);
1342 				}
1343 # if SASL >= 20000
1344 				sm_free(out2);
1345 # endif /* SASL >= 20000 */
1346 			}
1347 			else
1348 			{
1349 				/* not SASL_OK or SASL_CONT */
1350 				message("535 5.7.0 authentication failed");
1351 				if (LogLevel > 9)
1352 					sm_syslog(LOG_WARNING, e->e_id,
1353 						  "AUTH failure (%s): %s (%d) %s",
1354 						  auth_type,
1355 						  sasl_errstring(result, NULL,
1356 								 NULL),
1357 						  result,
1358 # if SASL >= 20000
1359 						  sasl_errdetail(conn));
1360 # else /* SASL >= 20000 */
1361 						  errstr == NULL ? "" : errstr);
1362 # endif /* SASL >= 20000 */
1363 				RESET_SASLCONN;
1364 				authenticating = SASL_NOT_AUTH;
1365 			}
1366 		}
1367 		else
1368 		{
1369 			/* don't want to do any of this if authenticating */
1370 #endif /* SASL */
1371 
1372 		/* echo command to transcript */
1373 		if (e->e_xfp != NULL)
1374 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1375 					     "<<< %s\n", inp);
1376 
1377 		if (LogLevel > 14)
1378 			sm_syslog(LOG_INFO, e->e_id, "<-- %s", inp);
1379 
1380 		/* break off command */
1381 		for (p = inp; isascii(*p) && isspace(*p); p++)
1382 			continue;
1383 		cmd = cmdbuf;
1384 		while (*p != '\0' &&
1385 		       !(isascii(*p) && isspace(*p)) &&
1386 		       cmd < &cmdbuf[sizeof cmdbuf - 2])
1387 			*cmd++ = *p++;
1388 		*cmd = '\0';
1389 
1390 		/* throw away leading whitespace */
1391 		SKIP_SPACE(p);
1392 
1393 		/* decode command */
1394 		for (c = CmdTab; c->cmd_name != NULL; c++)
1395 		{
1396 			if (sm_strcasecmp(c->cmd_name, cmdbuf) == 0)
1397 				break;
1398 		}
1399 
1400 		/* reset errors */
1401 		errno = 0;
1402 
1403 		/* check whether a "non-null" command has been used */
1404 		switch (c->cmd_code)
1405 		{
1406 #if SASL
1407 		  case CMDAUTH:
1408 			/* avoid information leak; take first two words? */
1409 			q = "AUTH";
1410 			break;
1411 #endif /* SASL */
1412 
1413 		  case CMDMAIL:
1414 		  case CMDEXPN:
1415 		  case CMDVRFY:
1416 		  case CMDETRN:
1417 			lognullconnection = false;
1418 			/* FALLTHROUGH */
1419 		  default:
1420 			q = inp;
1421 			break;
1422 		}
1423 
1424 		if (e->e_id == NULL)
1425 			sm_setproctitle(true, e, "%s: %.80s",
1426 					CurSmtpClient, q);
1427 		else
1428 			sm_setproctitle(true, e, "%s %s: %.80s",
1429 					qid_printname(e),
1430 					CurSmtpClient, q);
1431 
1432 		/*
1433 		**  Process command.
1434 		**
1435 		**	If we are running as a null server, return 550
1436 		**	to almost everything.
1437 		*/
1438 
1439 		if (nullserver != NULL || bitnset(D_ETRNONLY, d_flags))
1440 		{
1441 			switch (c->cmd_code)
1442 			{
1443 			  case CMDQUIT:
1444 			  case CMDHELO:
1445 			  case CMDEHLO:
1446 			  case CMDNOOP:
1447 			  case CMDRSET:
1448 			  case CMDERROR:
1449 				/* process normally */
1450 				break;
1451 
1452 			  case CMDETRN:
1453 				if (bitnset(D_ETRNONLY, d_flags) &&
1454 				    nullserver == NULL)
1455 					break;
1456 				DELAY_CONN("ETRN");
1457 				/* FALLTHROUGH */
1458 
1459 			  default:
1460 #if MAXBADCOMMANDS > 0
1461 				/* theoretically this could overflow */
1462 				if (nullserver != NULL &&
1463 				    ++n_badcmds > MAXBADCOMMANDS)
1464 				{
1465 					message("421 4.7.0 %s Too many bad commands; closing connection",
1466 						MyHostName);
1467 
1468 					/* arrange to ignore send list */
1469 					e->e_sendqueue = NULL;
1470 					goto doquit;
1471 				}
1472 #endif /* MAXBADCOMMANDS > 0 */
1473 				if (nullserver != NULL)
1474 				{
1475 					if (ISSMTPREPLY(nullserver))
1476 						usrerr(nullserver);
1477 					else
1478 						usrerr("550 5.0.0 %s",
1479 						       nullserver);
1480 				}
1481 				else
1482 					usrerr("452 4.4.5 Insufficient disk space; try again later");
1483 				continue;
1484 			}
1485 		}
1486 
1487 		switch (c->cmd_code)
1488 		{
1489 #if SASL
1490 		  case CMDAUTH: /* sasl */
1491 			DELAY_CONN("AUTH");
1492 			if (!sasl_ok || n_mechs <= 0)
1493 			{
1494 				message("503 5.3.3 AUTH not available");
1495 				break;
1496 			}
1497 			if (authenticating == SASL_IS_AUTH)
1498 			{
1499 				message("503 5.5.0 Already Authenticated");
1500 				break;
1501 			}
1502 			if (smtp.sm_gotmail)
1503 			{
1504 				message("503 5.5.0 AUTH not permitted during a mail transaction");
1505 				break;
1506 			}
1507 			if (tempfail)
1508 			{
1509 				if (LogLevel > 9)
1510 					sm_syslog(LOG_INFO, e->e_id,
1511 						  "SMTP AUTH command (%.100s) from %s tempfailed (due to previous checks)",
1512 						  p, CurSmtpClient);
1513 				usrerr("454 4.3.0 Please try again later");
1514 				break;
1515 			}
1516 
1517 			ismore = false;
1518 
1519 			/* crude way to avoid crack attempts */
1520 			STOP_IF_ATTACK(checksmtpattack(&n_auth, n_mechs + 1,
1521 							true, "AUTH", e));
1522 
1523 			/* make sure mechanism (p) is a valid string */
1524 			for (q = p; *q != '\0' && isascii(*q); q++)
1525 			{
1526 				if (isspace(*q))
1527 				{
1528 					*q = '\0';
1529 					while (*++q != '\0' &&
1530 					       isascii(*q) && isspace(*q))
1531 						continue;
1532 					*(q - 1) = '\0';
1533 					ismore = (*q != '\0');
1534 					break;
1535 				}
1536 			}
1537 
1538 			if (*p == '\0')
1539 			{
1540 				message("501 5.5.2 AUTH mechanism must be specified");
1541 				break;
1542 			}
1543 
1544 			/* check whether mechanism is available */
1545 			if (iteminlist(p, mechlist, " ") == NULL)
1546 			{
1547 				message("504 5.3.3 AUTH mechanism %.32s not available",
1548 					p);
1549 				break;
1550 			}
1551 
1552 			if (ismore)
1553 			{
1554 				/* could this be shorter? XXX */
1555 # if SASL >= 20000
1556 				in = xalloc(strlen(q) + 1);
1557 				result = sasl_decode64(q, strlen(q), in,
1558 						       strlen(q), &inlen);
1559 # else /* SASL >= 20000 */
1560 				in = sm_rpool_malloc(e->e_rpool, strlen(q));
1561 				result = sasl_decode64(q, strlen(q), in,
1562 						       &inlen);
1563 # endif /* SASL >= 20000 */
1564 				if (result != SASL_OK)
1565 				{
1566 					message("501 5.5.4 cannot BASE64 decode '%s'",
1567 						q);
1568 					if (LogLevel > 5)
1569 						sm_syslog(LOG_WARNING, e->e_id,
1570 							  "AUTH decode64 error [%d for \"%s\"]",
1571 							  result, q);
1572 					/* start over? */
1573 					authenticating = SASL_NOT_AUTH;
1574 # if SASL >= 20000
1575 					sm_free(in);
1576 # endif /* SASL >= 20000 */
1577 					in = NULL;
1578 					inlen = 0;
1579 					break;
1580 				}
1581 			}
1582 			else
1583 			{
1584 				in = NULL;
1585 				inlen = 0;
1586 			}
1587 
1588 			/* see if that auth type exists */
1589 # if SASL >= 20000
1590 			result = sasl_server_start(conn, p, in, inlen,
1591 						   &out, &outlen);
1592 			if (in != NULL)
1593 				sm_free(in);
1594 # else /* SASL >= 20000 */
1595 			result = sasl_server_start(conn, p, in, inlen,
1596 						   &out, &outlen, &errstr);
1597 # endif /* SASL >= 20000 */
1598 
1599 			if (result != SASL_OK && result != SASL_CONTINUE)
1600 			{
1601 				message("535 5.7.0 authentication failed");
1602 				if (LogLevel > 9)
1603 					sm_syslog(LOG_ERR, e->e_id,
1604 						  "AUTH failure (%s): %s (%d) %s",
1605 						  p,
1606 						  sasl_errstring(result, NULL,
1607 								 NULL),
1608 						  result,
1609 # if SASL >= 20000
1610 						  sasl_errdetail(conn));
1611 # else /* SASL >= 20000 */
1612 						  errstr);
1613 # endif /* SASL >= 20000 */
1614 				RESET_SASLCONN;
1615 				break;
1616 			}
1617 			auth_type = newstr(p);
1618 
1619 			if (result == SASL_OK)
1620 			{
1621 				/* ugly, but same code */
1622 				goto authenticated;
1623 				/* authenticated by the initial response */
1624 			}
1625 
1626 			/* len is at least 2 */
1627 			len = ENC64LEN(outlen);
1628 			out2 = xalloc(len);
1629 			result = sasl_encode64(out, outlen, out2, len,
1630 					       &out2len);
1631 
1632 			if (result != SASL_OK)
1633 			{
1634 				message("454 4.5.4 Temporary authentication failure");
1635 				if (LogLevel > 5)
1636 					sm_syslog(LOG_WARNING, e->e_id,
1637 						  "AUTH encode64 error [%d for \"%s\"]",
1638 						  result, out);
1639 
1640 				/* start over? */
1641 				authenticating = SASL_NOT_AUTH;
1642 				RESET_SASLCONN;
1643 			}
1644 			else
1645 			{
1646 				message("334 %s", out2);
1647 				authenticating = SASL_PROC_AUTH;
1648 			}
1649 # if SASL >= 20000
1650 			sm_free(out2);
1651 # endif /* SASL >= 20000 */
1652 			break;
1653 #endif /* SASL */
1654 
1655 #if STARTTLS
1656 		  case CMDSTLS: /* starttls */
1657 			DELAY_CONN("STARTTLS");
1658 			if (*p != '\0')
1659 			{
1660 				message("501 5.5.2 Syntax error (no parameters allowed)");
1661 				break;
1662 			}
1663 			if (!bitset(SRV_OFFER_TLS, features))
1664 			{
1665 				message("503 5.5.0 TLS not available");
1666 				break;
1667 			}
1668 			if (!tls_ok_srv)
1669 			{
1670 				message("454 4.3.3 TLS not available after start");
1671 				break;
1672 			}
1673 			if (smtp.sm_gotmail)
1674 			{
1675 				message("503 5.5.0 TLS not permitted during a mail transaction");
1676 				break;
1677 			}
1678 			if (tempfail)
1679 			{
1680 				if (LogLevel > 9)
1681 					sm_syslog(LOG_INFO, e->e_id,
1682 						  "SMTP STARTTLS command (%.100s) from %s tempfailed (due to previous checks)",
1683 						  p, CurSmtpClient);
1684 				usrerr("454 4.7.0 Please try again later");
1685 				break;
1686 			}
1687   starttls:
1688 # if TLS_NO_RSA
1689 			/*
1690 			**  XXX do we need a temp key ?
1691 			*/
1692 # else /* TLS_NO_RSA */
1693 # endif /* TLS_NO_RSA */
1694 
1695 # if TLS_VRFY_PER_CTX
1696 			/*
1697 			**  Note: this sets the verification globally
1698 			**  (per SSL_CTX)
1699 			**  it's ok since it applies only to one transaction
1700 			*/
1701 
1702 			TLS_VERIFY_CLIENT();
1703 # endif /* TLS_VRFY_PER_CTX */
1704 
1705 			if (srv_ssl != NULL)
1706 				SSL_clear(srv_ssl);
1707 			else if ((srv_ssl = SSL_new(srv_ctx)) == NULL)
1708 			{
1709 				message("454 4.3.3 TLS not available: error generating SSL handle");
1710 				if (LogLevel > 8)
1711 					tlslogerr("server");
1712 				goto tls_done;
1713 			}
1714 
1715 # if !TLS_VRFY_PER_CTX
1716 			/*
1717 			**  this could be used if it were possible to set
1718 			**  verification per SSL (connection)
1719 			**  not just per SSL_CTX (global)
1720 			*/
1721 
1722 			TLS_VERIFY_CLIENT();
1723 # endif /* !TLS_VRFY_PER_CTX */
1724 
1725 			rfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
1726 			wfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
1727 
1728 			if (rfd < 0 || wfd < 0 ||
1729 			    SSL_set_rfd(srv_ssl, rfd) <= 0 ||
1730 			    SSL_set_wfd(srv_ssl, wfd) <= 0)
1731 			{
1732 				message("454 4.3.3 TLS not available: error set fd");
1733 				SSL_free(srv_ssl);
1734 				srv_ssl = NULL;
1735 				goto tls_done;
1736 			}
1737 			if (!smtps)
1738 				message("220 2.0.0 Ready to start TLS");
1739 # if PIPELINING
1740 			(void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
1741 # endif /* PIPELINING */
1742 
1743 			SSL_set_accept_state(srv_ssl);
1744 
1745 #  define SSL_ACC(s)	SSL_accept(s)
1746 
1747 			tlsstart = curtime();
1748   ssl_retry:
1749 			if ((r = SSL_ACC(srv_ssl)) <= 0)
1750 			{
1751 				int i, ssl_err;
1752 
1753 				ssl_err = SSL_get_error(srv_ssl, r);
1754 				i = tls_retry(srv_ssl, rfd, wfd, tlsstart,
1755 						TimeOuts.to_starttls, ssl_err,
1756 						"server");
1757 				if (i > 0)
1758 					goto ssl_retry;
1759 
1760 				if (LogLevel > 5)
1761 				{
1762 					sm_syslog(LOG_WARNING, NOQID,
1763 						  "STARTTLS=server, error: accept failed=%d, SSL_error=%d, errno=%d, retry=%d",
1764 						  r, ssl_err, errno, i);
1765 					if (LogLevel > 8)
1766 						tlslogerr("server");
1767 				}
1768 				tls_ok_srv = false;
1769 				SSL_free(srv_ssl);
1770 				srv_ssl = NULL;
1771 
1772 				/*
1773 				**  according to the next draft of
1774 				**  RFC 2487 the connection should be dropped
1775 				*/
1776 
1777 				/* arrange to ignore any current send list */
1778 				e->e_sendqueue = NULL;
1779 				goto doquit;
1780 			}
1781 
1782 			/* ignore return code for now, it's in {verify} */
1783 			(void) tls_get_info(srv_ssl, true,
1784 					    CurSmtpClient,
1785 					    &BlankEnvelope.e_macro,
1786 					    bitset(SRV_VRFY_CLT, features));
1787 
1788 			/*
1789 			**  call Stls_client to find out whether
1790 			**  to accept the connection from the client
1791 			*/
1792 
1793 			saveQuickAbort = QuickAbort;
1794 			saveSuprErrs = SuprErrs;
1795 			SuprErrs = true;
1796 			QuickAbort = false;
1797 			if (rscheck("tls_client",
1798 				     macvalue(macid("{verify}"), e),
1799 				     "STARTTLS", e,
1800 				     RSF_RMCOMM|RSF_COUNT,
1801 				     5, NULL, NOQID) != EX_OK ||
1802 			    Errors > 0)
1803 			{
1804 				extern char MsgBuf[];
1805 
1806 				if (MsgBuf[0] != '\0' && ISSMTPREPLY(MsgBuf))
1807 					nullserver = newstr(MsgBuf);
1808 				else
1809 					nullserver = "503 5.7.0 Authentication required.";
1810 			}
1811 			QuickAbort = saveQuickAbort;
1812 			SuprErrs = saveSuprErrs;
1813 
1814 			tls_ok_srv = false;	/* don't offer STARTTLS again */
1815 			n_helo = 0;
1816 # if SASL
1817 			if (sasl_ok)
1818 			{
1819 				int cipher_bits;
1820 				bool verified;
1821 				char *s, *v, *c;
1822 
1823 				s = macvalue(macid("{cipher_bits}"), e);
1824 				v = macvalue(macid("{verify}"), e);
1825 				c = macvalue(macid("{cert_subject}"), e);
1826 				verified = (v != NULL && strcmp(v, "OK") == 0);
1827 				if (s != NULL && (cipher_bits = atoi(s)) > 0)
1828 				{
1829 #  if SASL >= 20000
1830 					ext_ssf = cipher_bits;
1831 					auth_id = verified ? c : NULL;
1832 					sasl_ok = ((sasl_setprop(conn,
1833 							SASL_SSF_EXTERNAL,
1834 							&ext_ssf) == SASL_OK) &&
1835 						   (sasl_setprop(conn,
1836 							SASL_AUTH_EXTERNAL,
1837 							auth_id) == SASL_OK));
1838 #  else /* SASL >= 20000 */
1839 					ext_ssf.ssf = cipher_bits;
1840 					ext_ssf.auth_id = verified ? c : NULL;
1841 					sasl_ok = sasl_setprop(conn,
1842 							SASL_SSF_EXTERNAL,
1843 							&ext_ssf) == SASL_OK;
1844 #  endif /* SASL >= 20000 */
1845 					mechlist = NULL;
1846 					if (sasl_ok)
1847 						n_mechs = saslmechs(conn,
1848 								    &mechlist);
1849 				}
1850 			}
1851 # endif /* SASL */
1852 
1853 			/* switch to secure connection */
1854 			if (sfdctls(&InChannel, &OutChannel, srv_ssl) == 0)
1855 			{
1856 				tls_active = true;
1857 # if PIPELINING
1858 				(void) sm_io_autoflush(InChannel, OutChannel);
1859 # endif /* PIPELINING */
1860 			}
1861 			else
1862 			{
1863 				/*
1864 				**  XXX this is an internal error
1865 				**  how to deal with it?
1866 				**  we can't generate an error message
1867 				**  since the other side switched to an
1868 				**  encrypted layer, but we could not...
1869 				**  just "hang up"?
1870 				*/
1871 
1872 				nullserver = "454 4.3.3 TLS not available: can't switch to encrypted layer";
1873 				syserr("STARTTLS: can't switch to encrypted layer");
1874 			}
1875 		  tls_done:
1876 			if (smtps)
1877 			{
1878 				if (tls_active)
1879 					goto greeting;
1880 				else
1881 					goto doquit;
1882 			}
1883 			break;
1884 #endif /* STARTTLS */
1885 
1886 		  case CMDHELO:		/* hello -- introduce yourself */
1887 		  case CMDEHLO:		/* extended hello */
1888 			DELAY_CONN("EHLO");
1889 			if (c->cmd_code == CMDEHLO)
1890 			{
1891 				protocol = "ESMTP";
1892 				SmtpPhase = "server EHLO";
1893 			}
1894 			else
1895 			{
1896 				protocol = "SMTP";
1897 				SmtpPhase = "server HELO";
1898 			}
1899 
1900 			/* avoid denial-of-service */
1901 			STOP_IF_ATTACK(checksmtpattack(&n_helo, MAXHELOCOMMANDS,
1902 							true, "HELO/EHLO", e));
1903 
1904 #if 0
1905 			/* RFC2821 4.1.4 allows duplicate HELO/EHLO */
1906 			/* check for duplicate HELO/EHLO per RFC 1651 4.2 */
1907 			if (gothello)
1908 			{
1909 				usrerr("503 %s Duplicate HELO/EHLO",
1910 				       MyHostName);
1911 				break;
1912 			}
1913 #endif /* 0 */
1914 
1915 			/* check for valid domain name (re 1123 5.2.5) */
1916 			if (*p == '\0' && !AllowBogusHELO)
1917 			{
1918 				usrerr("501 %s requires domain address",
1919 					cmdbuf);
1920 				break;
1921 			}
1922 
1923 			/* check for long domain name (hides Received: info) */
1924 			if (strlen(p) > MAXNAME)
1925 			{
1926 				usrerr("501 Invalid domain name");
1927 				if (LogLevel > 9)
1928 					sm_syslog(LOG_INFO, CurEnv->e_id,
1929 						  "invalid domain name (too long) from %s",
1930 						  CurSmtpClient);
1931 				break;
1932 			}
1933 
1934 			ok = true;
1935 			for (q = p; *q != '\0'; q++)
1936 			{
1937 				if (!isascii(*q))
1938 					break;
1939 				if (isalnum(*q))
1940 					continue;
1941 				if (isspace(*q))
1942 				{
1943 					*q = '\0';
1944 
1945 					/* only complain if strict check */
1946 					ok = AllowBogusHELO;
1947 
1948 					/* allow trailing whitespace */
1949 					while (!ok && *++q != '\0' &&
1950 					       isspace(*q))
1951 						;
1952 					if (*q == '\0')
1953 						ok = true;
1954 					break;
1955 				}
1956 				if (strchr("[].-_#:", *q) == NULL)
1957 					break;
1958 			}
1959 
1960 			if (*q == '\0' && ok)
1961 			{
1962 				q = "pleased to meet you";
1963 				sendinghost = sm_strdup_x(p);
1964 			}
1965 			else if (!AllowBogusHELO)
1966 			{
1967 				usrerr("501 Invalid domain name");
1968 				if (LogLevel > 9)
1969 					sm_syslog(LOG_INFO, CurEnv->e_id,
1970 						  "invalid domain name (%s) from %.100s",
1971 						  p, CurSmtpClient);
1972 				break;
1973 			}
1974 			else
1975 			{
1976 				q = "accepting invalid domain name";
1977 			}
1978 
1979 			if (gothello || smtp.sm_gotmail)
1980 				CLEAR_STATE(cmdbuf);
1981 
1982 #if MILTER
1983 			if (smtp.sm_milterlist && smtp.sm_milterize &&
1984 			    !bitset(EF_DISCARD, e->e_flags))
1985 			{
1986 				char state;
1987 				char *response;
1988 
1989 				response = milter_helo(p, e, &state);
1990 				switch (state)
1991 				{
1992 				  case SMFIR_REPLYCODE:
1993 					if (MilterLogLevel > 3)
1994 						sm_syslog(LOG_INFO, e->e_id,
1995 							  "Milter: helo=%s, reject=%s",
1996 							  p, response);
1997 					nullserver = newstr(response);
1998 					smtp.sm_milterize = false;
1999 					break;
2000 
2001 				  case SMFIR_REJECT:
2002 					if (MilterLogLevel > 3)
2003 						sm_syslog(LOG_INFO, e->e_id,
2004 							  "Milter: helo=%s, reject=Command rejected",
2005 							  p);
2006 					nullserver = "Command rejected";
2007 					smtp.sm_milterize = false;
2008 					break;
2009 
2010 				  case SMFIR_TEMPFAIL:
2011 					if (MilterLogLevel > 3)
2012 						sm_syslog(LOG_INFO, e->e_id,
2013 							  "Milter: helo=%s, reject=%s",
2014 							  p, MSG_TEMPFAIL);
2015 					tempfail = true;
2016 					smtp.sm_milterize = false;
2017 					break;
2018 
2019 				  case SMFIR_SHUTDOWN:
2020 					if (MilterLogLevel > 3)
2021 						sm_syslog(LOG_INFO, e->e_id,
2022 							  "Milter: Milter: helo=%s, reject=421 4.7.0 %s closing connection",
2023 							  p, MyHostName);
2024 					tempfail = true;
2025 					smtp.sm_milterize = false;
2026 					message("421 4.7.0 %s closing connection",
2027 						MyHostName);
2028 					/* arrange to ignore send list */
2029 					e->e_sendqueue = NULL;
2030 					goto doquit;
2031 				}
2032 				if (response != NULL)
2033 					sm_free(response);
2034 
2035 				/*
2036 				**  If quarantining by a connect/ehlo action,
2037 				**  save between messages
2038 				*/
2039 
2040 				if (smtp.sm_quarmsg == NULL &&
2041 				    e->e_quarmsg != NULL)
2042 					smtp.sm_quarmsg = newstr(e->e_quarmsg);
2043 			}
2044 #endif /* MILTER */
2045 			gothello = true;
2046 
2047 			/* print HELO response message */
2048 			if (c->cmd_code != CMDEHLO)
2049 			{
2050 				message("250 %s Hello %s, %s",
2051 					MyHostName, CurSmtpClient, q);
2052 				break;
2053 			}
2054 
2055 			message("250-%s Hello %s, %s",
2056 				MyHostName, CurSmtpClient, q);
2057 
2058 			/* offer ENHSC even for nullserver */
2059 			if (nullserver != NULL)
2060 			{
2061 				message("250 ENHANCEDSTATUSCODES");
2062 				break;
2063 			}
2064 
2065 			/*
2066 			**  print EHLO features list
2067 			**
2068 			**  Note: If you change this list,
2069 			**	  remember to update 'helpfile'
2070 			*/
2071 
2072 			message("250-ENHANCEDSTATUSCODES");
2073 #if PIPELINING
2074 			if (bitset(SRV_OFFER_PIPE, features))
2075 				message("250-PIPELINING");
2076 #endif /* PIPELINING */
2077 			if (bitset(SRV_OFFER_EXPN, features))
2078 			{
2079 				message("250-EXPN");
2080 				if (bitset(SRV_OFFER_VERB, features))
2081 					message("250-VERB");
2082 			}
2083 #if MIME8TO7
2084 			message("250-8BITMIME");
2085 #endif /* MIME8TO7 */
2086 			if (MaxMessageSize > 0)
2087 				message("250-SIZE %ld", MaxMessageSize);
2088 			else
2089 				message("250-SIZE");
2090 #if DSN
2091 			if (SendMIMEErrors && bitset(SRV_OFFER_DSN, features))
2092 				message("250-DSN");
2093 #endif /* DSN */
2094 			if (bitset(SRV_OFFER_ETRN, features))
2095 				message("250-ETRN");
2096 #if SASL
2097 			if (sasl_ok && mechlist != NULL && *mechlist != '\0')
2098 				message("250-AUTH %s", mechlist);
2099 #endif /* SASL */
2100 #if STARTTLS
2101 			if (tls_ok_srv &&
2102 			    bitset(SRV_OFFER_TLS, features))
2103 				message("250-STARTTLS");
2104 #endif /* STARTTLS */
2105 			if (DeliverByMin > 0)
2106 				message("250-DELIVERBY %ld",
2107 					(long) DeliverByMin);
2108 			else if (DeliverByMin == 0)
2109 				message("250-DELIVERBY");
2110 
2111 			/* < 0: no deliver-by */
2112 
2113 			message("250 HELP");
2114 			break;
2115 
2116 		  case CMDMAIL:		/* mail -- designate sender */
2117 			SmtpPhase = "server MAIL";
2118 			DELAY_CONN("MAIL");
2119 
2120 			/* check for validity of this command */
2121 			if (!gothello && bitset(PRIV_NEEDMAILHELO, PrivacyFlags))
2122 			{
2123 				usrerr("503 5.0.0 Polite people say HELO first");
2124 				break;
2125 			}
2126 			if (smtp.sm_gotmail)
2127 			{
2128 				usrerr("503 5.5.0 Sender already specified");
2129 				break;
2130 			}
2131 #if SASL
2132 			if (bitset(SRV_REQ_AUTH, features) &&
2133 			    authenticating != SASL_IS_AUTH)
2134 			{
2135 				usrerr("530 5.7.0 Authentication required");
2136 				break;
2137 			}
2138 #endif /* SASL */
2139 
2140 			p = skipword(p, "from");
2141 			if (p == NULL)
2142 				break;
2143 			if (tempfail)
2144 			{
2145 				if (LogLevel > 9)
2146 					sm_syslog(LOG_INFO, e->e_id,
2147 						  "SMTP MAIL command (%.100s) from %s tempfailed (due to previous checks)",
2148 						  p, CurSmtpClient);
2149 				usrerr(MSG_TEMPFAIL);
2150 				break;
2151 			}
2152 
2153 			/* make sure we know who the sending host is */
2154 			if (sendinghost == NULL)
2155 				sendinghost = peerhostname;
2156 
2157 
2158 #if SM_HEAP_CHECK
2159 			if (sm_debug_active(&DebugLeakSmtp, 1))
2160 			{
2161 				sm_heap_newgroup();
2162 				sm_dprintf("smtp() heap group #%d\n",
2163 					sm_heap_group());
2164 			}
2165 #endif /* SM_HEAP_CHECK */
2166 
2167 			if (Errors > 0)
2168 				goto undo_no_pm;
2169 			if (!gothello)
2170 			{
2171 				auth_warning(e, "%s didn't use HELO protocol",
2172 					     CurSmtpClient);
2173 			}
2174 #ifdef PICKY_HELO_CHECK
2175 			if (sm_strcasecmp(sendinghost, peerhostname) != 0 &&
2176 			    (sm_strcasecmp(peerhostname, "localhost") != 0 ||
2177 			     sm_strcasecmp(sendinghost, MyHostName) != 0))
2178 			{
2179 				auth_warning(e, "Host %s claimed to be %s",
2180 					     CurSmtpClient, sendinghost);
2181 			}
2182 #endif /* PICKY_HELO_CHECK */
2183 
2184 			if (protocol == NULL)
2185 				protocol = "SMTP";
2186 			macdefine(&e->e_macro, A_PERM, 'r', protocol);
2187 			macdefine(&e->e_macro, A_PERM, 's', sendinghost);
2188 
2189 			if (Errors > 0)
2190 				goto undo_no_pm;
2191 			smtp.sm_nrcpts = 0;
2192 			n_badrcpts = 0;
2193 			macdefine(&e->e_macro, A_PERM, macid("{ntries}"), "0");
2194 			macdefine(&e->e_macro, A_PERM, macid("{nrcpts}"), "0");
2195 			macdefine(&e->e_macro, A_PERM, macid("{nbadrcpts}"),
2196 				"0");
2197 			e->e_flags |= EF_CLRQUEUE;
2198 			sm_setproctitle(true, e, "%s %s: %.80s",
2199 					qid_printname(e),
2200 					CurSmtpClient, inp);
2201 
2202 			/* do the processing */
2203 		    SM_TRY
2204 		    {
2205 			extern char *FullName;
2206 
2207 			QuickAbort = true;
2208 			SM_FREE_CLR(FullName);
2209 
2210 			/* must parse sender first */
2211 			delimptr = NULL;
2212 			setsender(p, e, &delimptr, ' ', false);
2213 			if (delimptr != NULL && *delimptr != '\0')
2214 				*delimptr++ = '\0';
2215 			if (Errors > 0)
2216 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2217 
2218 			/* Successfully set e_from, allow logging */
2219 			e->e_flags |= EF_LOGSENDER;
2220 
2221 			/* put resulting triple from parseaddr() into macros */
2222 			if (e->e_from.q_mailer != NULL)
2223 				 macdefine(&e->e_macro, A_PERM,
2224 					macid("{mail_mailer}"),
2225 					e->e_from.q_mailer->m_name);
2226 			else
2227 				 macdefine(&e->e_macro, A_PERM,
2228 					macid("{mail_mailer}"), NULL);
2229 			if (e->e_from.q_host != NULL)
2230 				macdefine(&e->e_macro, A_PERM,
2231 					macid("{mail_host}"),
2232 					e->e_from.q_host);
2233 			else
2234 				macdefine(&e->e_macro, A_PERM,
2235 					macid("{mail_host}"), "localhost");
2236 			if (e->e_from.q_user != NULL)
2237 				macdefine(&e->e_macro, A_PERM,
2238 					macid("{mail_addr}"),
2239 					e->e_from.q_user);
2240 			else
2241 				macdefine(&e->e_macro, A_PERM,
2242 					macid("{mail_addr}"), NULL);
2243 			if (Errors > 0)
2244 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2245 
2246 			/* check for possible spoofing */
2247 			if (RealUid != 0 && OpMode == MD_SMTP &&
2248 			    !wordinclass(RealUserName, 't') &&
2249 			    (!bitnset(M_LOCALMAILER,
2250 				      e->e_from.q_mailer->m_flags) ||
2251 			     strcmp(e->e_from.q_user, RealUserName) != 0))
2252 			{
2253 				auth_warning(e, "%s owned process doing -bs",
2254 					RealUserName);
2255 			}
2256 
2257 			/* reset to default value */
2258 			SevenBitInput = save_sevenbitinput;
2259 
2260 			/* now parse ESMTP arguments */
2261 			e->e_msgsize = 0;
2262 			addr = p;
2263 			argno = 0;
2264 			args[argno++] = p;
2265 			p = delimptr;
2266 			while (p != NULL && *p != '\0')
2267 			{
2268 				char *kp;
2269 				char *vp = NULL;
2270 				char *equal = NULL;
2271 
2272 				/* locate the beginning of the keyword */
2273 				SKIP_SPACE(p);
2274 				if (*p == '\0')
2275 					break;
2276 				kp = p;
2277 
2278 				/* skip to the value portion */
2279 				while ((isascii(*p) && isalnum(*p)) || *p == '-')
2280 					p++;
2281 				if (*p == '=')
2282 				{
2283 					equal = p;
2284 					*p++ = '\0';
2285 					vp = p;
2286 
2287 					/* skip to the end of the value */
2288 					while (*p != '\0' && *p != ' ' &&
2289 					       !(isascii(*p) && iscntrl(*p)) &&
2290 					       *p != '=')
2291 						p++;
2292 				}
2293 
2294 				if (*p != '\0')
2295 					*p++ = '\0';
2296 
2297 				if (tTd(19, 1))
2298 					sm_dprintf("MAIL: got arg %s=\"%s\"\n", kp,
2299 						vp == NULL ? "<null>" : vp);
2300 
2301 				mail_esmtp_args(kp, vp, e);
2302 				if (equal != NULL)
2303 					*equal = '=';
2304 				args[argno++] = kp;
2305 				if (argno >= MAXSMTPARGS - 1)
2306 					usrerr("501 5.5.4 Too many parameters");
2307 				if (Errors > 0)
2308 					sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2309 			}
2310 			args[argno] = NULL;
2311 			if (Errors > 0)
2312 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2313 
2314 #if SASL
2315 # if _FFR_AUTH_PASSING
2316 			/* set the default AUTH= if the sender didn't */
2317 			if (e->e_auth_param == NULL)
2318 			{
2319 				/* XXX only do this for an MSA? */
2320 				e->e_auth_param = macvalue(macid("{auth_authen}"),
2321 							   e);
2322 				if (e->e_auth_param == NULL)
2323 					e->e_auth_param = "<>";
2324 
2325 				/*
2326 				**  XXX should we invoke Strust_auth now?
2327 				**  authorizing as the client that just
2328 				**  authenticated, so we'll trust implicitly
2329 				*/
2330 			}
2331 # endif /* _FFR_AUTH_PASSING */
2332 #endif /* SASL */
2333 
2334 			/* do config file checking of the sender */
2335 			macdefine(&e->e_macro, A_PERM,
2336 				macid("{addr_type}"), "e s");
2337 #if _FFR_MAIL_MACRO
2338 			/* make the "real" sender address available */
2339 			macdefine(&e->e_macro, A_TEMP, macid("{mail_from}"),
2340 				  e->e_from.q_paddr);
2341 #endif /* _FFR_MAIL_MACRO */
2342 			if (rscheck("check_mail", addr,
2343 				    NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2344 				    NULL, e->e_id) != EX_OK ||
2345 			    Errors > 0)
2346 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2347 			macdefine(&e->e_macro, A_PERM,
2348 				  macid("{addr_type}"), NULL);
2349 
2350 			if (MaxMessageSize > 0 &&
2351 			    (e->e_msgsize > MaxMessageSize ||
2352 			     e->e_msgsize < 0))
2353 			{
2354 				usrerr("552 5.2.3 Message size exceeds fixed maximum message size (%ld)",
2355 					MaxMessageSize);
2356 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2357 			}
2358 
2359 			/*
2360 			**  XXX always check whether there is at least one fs
2361 			**  with enough space?
2362 			**  However, this may not help much: the queue group
2363 			**  selection may later on select a FS that hasn't
2364 			**  enough space.
2365 			*/
2366 
2367 			if ((NumFileSys == 1 || NumQueue == 1) &&
2368 			    !enoughdiskspace(e->e_msgsize, e)
2369 #if _FFR_ANY_FREE_FS
2370 			    && !filesys_free(e->e_msgsize)
2371 #endif /* _FFR_ANY_FREE_FS */
2372 			   )
2373 			{
2374 				/*
2375 				**  We perform this test again when the
2376 				**  queue directory is selected, in collect.
2377 				*/
2378 
2379 				usrerr("452 4.4.5 Insufficient disk space; try again later");
2380 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2381 			}
2382 			if (Errors > 0)
2383 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2384 
2385 			LogUsrErrs = true;
2386 #if MILTER
2387 			if (smtp.sm_milterlist && smtp.sm_milterize &&
2388 			    !bitset(EF_DISCARD, e->e_flags))
2389 			{
2390 				char state;
2391 				char *response;
2392 
2393 				response = milter_envfrom(args, e, &state);
2394 				MILTER_REPLY("from");
2395 			}
2396 #endif /* MILTER */
2397 			if (Errors > 0)
2398 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2399 
2400 			message("250 2.1.0 Sender ok");
2401 			smtp.sm_gotmail = true;
2402 		    }
2403 		    SM_EXCEPT(exc, "[!F]*")
2404 		    {
2405 			/*
2406 			**  An error occurred while processing a MAIL command.
2407 			**  Jump to the common error handling code.
2408 			*/
2409 
2410 			sm_exc_free(exc);
2411 			goto undo_no_pm;
2412 		    }
2413 		    SM_END_TRY
2414 			break;
2415 
2416 		  undo_no_pm:
2417 			e->e_flags &= ~EF_PM_NOTIFY;
2418 		  undo:
2419 			break;
2420 
2421 		  case CMDRCPT:		/* rcpt -- designate recipient */
2422 			DELAY_CONN("RCPT");
2423 			if (BadRcptThrottle > 0 &&
2424 			    n_badrcpts >= BadRcptThrottle)
2425 			{
2426 				if (LogLevel > 5 &&
2427 				    n_badrcpts == BadRcptThrottle)
2428 				{
2429 					sm_syslog(LOG_INFO, e->e_id,
2430 						  "%s: Possible SMTP RCPT flood, throttling.",
2431 						  CurSmtpClient);
2432 
2433 					/* To avoid duplicated message */
2434 					n_badrcpts++;
2435 				}
2436 				NBADRCPTS;
2437 
2438 				/*
2439 				**  Don't use exponential backoff for now.
2440 				**  Some servers will open more connections
2441 				**  and actually overload the receiver even
2442 				**  more.
2443 				*/
2444 
2445 				(void) sleep(1);
2446 			}
2447 			if (!smtp.sm_gotmail)
2448 			{
2449 				usrerr("503 5.0.0 Need MAIL before RCPT");
2450 				break;
2451 			}
2452 			SmtpPhase = "server RCPT";
2453 		    SM_TRY
2454 		    {
2455 			QuickAbort = true;
2456 			LogUsrErrs = true;
2457 
2458 			/* limit flooding of our machine */
2459 			if (MaxRcptPerMsg > 0 &&
2460 			    smtp.sm_nrcpts >= MaxRcptPerMsg)
2461 			{
2462 				/* sleep(1); / * slow down? */
2463 				usrerr("452 4.5.3 Too many recipients");
2464 				goto rcpt_done;
2465 			}
2466 
2467 			if (e->e_sendmode != SM_DELIVER
2468 #if _FFR_DM_ONE
2469 			    && (NotFirstDelivery || SM_DM_ONE != e->e_sendmode)
2470 #endif /* _FFR_DM_ONE */
2471 			   )
2472 				e->e_flags |= EF_VRFYONLY;
2473 
2474 #if MILTER
2475 			/*
2476 			**  If the filter will be deleting recipients,
2477 			**  don't expand them at RCPT time (in the call
2478 			**  to recipient()).  If they are expanded, it
2479 			**  is impossible for removefromlist() to figure
2480 			**  out the expanded members of the original
2481 			**  recipient and mark them as QS_DONTSEND.
2482 			*/
2483 
2484 			if (milter_can_delrcpts())
2485 				e->e_flags |= EF_VRFYONLY;
2486 #endif /* MILTER */
2487 
2488 			p = skipword(p, "to");
2489 			if (p == NULL)
2490 				goto rcpt_done;
2491 			macdefine(&e->e_macro, A_PERM,
2492 				macid("{addr_type}"), "e r");
2493 			a = parseaddr(p, NULLADDR, RF_COPYALL, ' ', &delimptr,
2494 				      e, true);
2495 			macdefine(&e->e_macro, A_PERM,
2496 				macid("{addr_type}"), NULL);
2497 			if (Errors > 0)
2498 				goto rcpt_done;
2499 			if (a == NULL)
2500 			{
2501 				usrerr("501 5.0.0 Missing recipient");
2502 				goto rcpt_done;
2503 			}
2504 
2505 			if (delimptr != NULL && *delimptr != '\0')
2506 				*delimptr++ = '\0';
2507 
2508 			/* put resulting triple from parseaddr() into macros */
2509 			if (a->q_mailer != NULL)
2510 				macdefine(&e->e_macro, A_PERM,
2511 					macid("{rcpt_mailer}"),
2512 					a->q_mailer->m_name);
2513 			else
2514 				macdefine(&e->e_macro, A_PERM,
2515 					macid("{rcpt_mailer}"), NULL);
2516 			if (a->q_host != NULL)
2517 				macdefine(&e->e_macro, A_PERM,
2518 					macid("{rcpt_host}"), a->q_host);
2519 			else
2520 				macdefine(&e->e_macro, A_PERM,
2521 					macid("{rcpt_host}"), "localhost");
2522 			if (a->q_user != NULL)
2523 				macdefine(&e->e_macro, A_PERM,
2524 					macid("{rcpt_addr}"), a->q_user);
2525 			else
2526 				macdefine(&e->e_macro, A_PERM,
2527 					macid("{rcpt_addr}"), NULL);
2528 			if (Errors > 0)
2529 				goto rcpt_done;
2530 
2531 			/* now parse ESMTP arguments */
2532 			addr = p;
2533 			argno = 0;
2534 			args[argno++] = p;
2535 			p = delimptr;
2536 			while (p != NULL && *p != '\0')
2537 			{
2538 				char *kp;
2539 				char *vp = NULL;
2540 				char *equal = NULL;
2541 
2542 				/* locate the beginning of the keyword */
2543 				SKIP_SPACE(p);
2544 				if (*p == '\0')
2545 					break;
2546 				kp = p;
2547 
2548 				/* skip to the value portion */
2549 				while ((isascii(*p) && isalnum(*p)) || *p == '-')
2550 					p++;
2551 				if (*p == '=')
2552 				{
2553 					equal = p;
2554 					*p++ = '\0';
2555 					vp = p;
2556 
2557 					/* skip to the end of the value */
2558 					while (*p != '\0' && *p != ' ' &&
2559 					       !(isascii(*p) && iscntrl(*p)) &&
2560 					       *p != '=')
2561 						p++;
2562 				}
2563 
2564 				if (*p != '\0')
2565 					*p++ = '\0';
2566 
2567 				if (tTd(19, 1))
2568 					sm_dprintf("RCPT: got arg %s=\"%s\"\n", kp,
2569 						vp == NULL ? "<null>" : vp);
2570 
2571 				rcpt_esmtp_args(a, kp, vp, e);
2572 				if (equal != NULL)
2573 					*equal = '=';
2574 				args[argno++] = kp;
2575 				if (argno >= MAXSMTPARGS - 1)
2576 					usrerr("501 5.5.4 Too many parameters");
2577 				if (Errors > 0)
2578 					break;
2579 			}
2580 			args[argno] = NULL;
2581 			if (Errors > 0)
2582 				goto rcpt_done;
2583 
2584 			/* do config file checking of the recipient */
2585 			macdefine(&e->e_macro, A_PERM,
2586 				macid("{addr_type}"), "e r");
2587 			if (rscheck("check_rcpt", addr,
2588 				    NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2589 				    NULL, e->e_id) != EX_OK ||
2590 			    Errors > 0)
2591 				goto rcpt_done;
2592 			macdefine(&e->e_macro, A_PERM,
2593 				macid("{addr_type}"), NULL);
2594 
2595 			/* If discarding, don't bother to verify user */
2596 			if (bitset(EF_DISCARD, e->e_flags))
2597 				a->q_state = QS_VERIFIED;
2598 
2599 #if MILTER
2600 			if (smtp.sm_milterlist && smtp.sm_milterize &&
2601 			    !bitset(EF_DISCARD, e->e_flags))
2602 			{
2603 				char state;
2604 				char *response;
2605 
2606 				response = milter_envrcpt(args, e, &state);
2607 				MILTER_REPLY("to");
2608 			}
2609 #endif /* MILTER */
2610 
2611 			macdefine(&e->e_macro, A_PERM,
2612 				macid("{rcpt_mailer}"), NULL);
2613 			macdefine(&e->e_macro, A_PERM,
2614 				macid("{rcpt_host}"), NULL);
2615 			macdefine(&e->e_macro, A_PERM,
2616 				macid("{rcpt_addr}"), NULL);
2617 			macdefine(&e->e_macro, A_PERM,
2618 				macid("{dsn_notify}"), NULL);
2619 			if (Errors > 0)
2620 				goto rcpt_done;
2621 
2622 			/* save in recipient list after ESMTP mods */
2623 			a = recipient(a, &e->e_sendqueue, 0, e);
2624 			if (Errors > 0)
2625 				goto rcpt_done;
2626 
2627 			/* no errors during parsing, but might be a duplicate */
2628 			e->e_to = a->q_paddr;
2629 			if (!QS_IS_BADADDR(a->q_state))
2630 			{
2631 				if (smtp.sm_nrcpts == 0)
2632 					initsys(e);
2633 				message("250 2.1.5 Recipient ok%s",
2634 					QS_IS_QUEUEUP(a->q_state) ?
2635 						" (will queue)" : "");
2636 				smtp.sm_nrcpts++;
2637 			}
2638 			else
2639 			{
2640 				/* punt -- should keep message in ADDRESS.... */
2641 				usrerr("550 5.1.1 Addressee unknown");
2642 			}
2643 		    rcpt_done:
2644 			if (Errors > 0)
2645 			{
2646 				++n_badrcpts;
2647 				NBADRCPTS;
2648 			}
2649 		    }
2650 		    SM_EXCEPT(exc, "[!F]*")
2651 		    {
2652 			/* An exception occurred while processing RCPT */
2653 			e->e_flags &= ~(EF_FATALERRS|EF_PM_NOTIFY);
2654 			++n_badrcpts;
2655 			NBADRCPTS;
2656 		    }
2657 		    SM_END_TRY
2658 			break;
2659 
2660 		  case CMDDATA:		/* data -- text of mail */
2661 			DELAY_CONN("DATA");
2662 			if (!smtp_data(&smtp, e))
2663 				goto doquit;
2664 			break;
2665 
2666 		  case CMDRSET:		/* rset -- reset state */
2667 			if (tTd(94, 100))
2668 				message("451 4.0.0 Test failure");
2669 			else
2670 				message("250 2.0.0 Reset state");
2671 			CLEAR_STATE(cmdbuf);
2672 			break;
2673 
2674 		  case CMDVRFY:		/* vrfy -- verify address */
2675 		  case CMDEXPN:		/* expn -- expand address */
2676 			vrfy = c->cmd_code == CMDVRFY;
2677 			DELAY_CONN(vrfy ? "VRFY" : "EXPN");
2678 			if (tempfail)
2679 			{
2680 				if (LogLevel > 9)
2681 					sm_syslog(LOG_INFO, e->e_id,
2682 						  "SMTP %s command (%.100s) from %s tempfailed (due to previous checks)",
2683 						  vrfy ? "VRFY" : "EXPN",
2684 						  p, CurSmtpClient);
2685 
2686 				/* RFC 821 doesn't allow 4xy reply code */
2687 				usrerr("550 5.7.1 Please try again later");
2688 				break;
2689 			}
2690 			wt = checksmtpattack(&n_verifies, MAXVRFYCOMMANDS,
2691 					     false, vrfy ? "VRFY" : "EXPN", e);
2692 			STOP_IF_ATTACK(wt);
2693 			previous = curtime();
2694 			if ((vrfy && bitset(PRIV_NOVRFY, PrivacyFlags)) ||
2695 			    (!vrfy && !bitset(SRV_OFFER_EXPN, features)))
2696 			{
2697 				if (vrfy)
2698 					message("252 2.5.2 Cannot VRFY user; try RCPT to attempt delivery (or try finger)");
2699 				else
2700 					message("502 5.7.0 Sorry, we do not allow this operation");
2701 				if (LogLevel > 5)
2702 					sm_syslog(LOG_INFO, e->e_id,
2703 						  "%s: %s [rejected]",
2704 						  CurSmtpClient,
2705 						  shortenstring(inp, MAXSHORTSTR));
2706 				break;
2707 			}
2708 			else if (!gothello &&
2709 				 bitset(vrfy ? PRIV_NEEDVRFYHELO : PRIV_NEEDEXPNHELO,
2710 						PrivacyFlags))
2711 			{
2712 				usrerr("503 5.0.0 I demand that you introduce yourself first");
2713 				break;
2714 			}
2715 			if (Errors > 0)
2716 				break;
2717 			if (LogLevel > 5)
2718 				sm_syslog(LOG_INFO, e->e_id, "%s: %s",
2719 					  CurSmtpClient,
2720 					  shortenstring(inp, MAXSHORTSTR));
2721 		    SM_TRY
2722 		    {
2723 			QuickAbort = true;
2724 			vrfyqueue = NULL;
2725 			if (vrfy)
2726 				e->e_flags |= EF_VRFYONLY;
2727 			while (*p != '\0' && isascii(*p) && isspace(*p))
2728 				p++;
2729 			if (*p == '\0')
2730 			{
2731 				usrerr("501 5.5.2 Argument required");
2732 			}
2733 			else
2734 			{
2735 				/* do config file checking of the address */
2736 				if (rscheck(vrfy ? "check_vrfy" : "check_expn",
2737 					    p, NULL, e, RSF_RMCOMM,
2738 					    3, NULL, NOQID) != EX_OK ||
2739 				    Errors > 0)
2740 					sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2741 				(void) sendtolist(p, NULLADDR, &vrfyqueue, 0, e);
2742 			}
2743 			if (wt > 0)
2744 			{
2745 				time_t t;
2746 
2747 				t = wt - (curtime() - previous);
2748 				if (t > 0)
2749 					(void) sleep(t);
2750 			}
2751 			if (Errors > 0)
2752 				sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2753 			if (vrfyqueue == NULL)
2754 			{
2755 				usrerr("554 5.5.2 Nothing to %s", vrfy ? "VRFY" : "EXPN");
2756 			}
2757 			while (vrfyqueue != NULL)
2758 			{
2759 				if (!QS_IS_UNDELIVERED(vrfyqueue->q_state))
2760 				{
2761 					vrfyqueue = vrfyqueue->q_next;
2762 					continue;
2763 				}
2764 
2765 				/* see if there is more in the vrfy list */
2766 				a = vrfyqueue;
2767 				while ((a = a->q_next) != NULL &&
2768 				       (!QS_IS_UNDELIVERED(a->q_state)))
2769 					continue;
2770 				printvrfyaddr(vrfyqueue, a == NULL, vrfy);
2771 				vrfyqueue = a;
2772 			}
2773 		    }
2774 		    SM_EXCEPT(exc, "[!F]*")
2775 		    {
2776 			/*
2777 			**  An exception occurred while processing VRFY/EXPN
2778 			*/
2779 
2780 			sm_exc_free(exc);
2781 			goto undo;
2782 		    }
2783 		    SM_END_TRY
2784 			break;
2785 
2786 		  case CMDETRN:		/* etrn -- force queue flush */
2787 			DELAY_CONN("ETRN");
2788 
2789 			/* Don't leak queue information via debug flags */
2790 			if (!bitset(SRV_OFFER_ETRN, features) || UseMSP ||
2791 			    (RealUid != 0 && RealUid != TrustedUid &&
2792 			     OpMode == MD_SMTP))
2793 			{
2794 				/* different message for MSA ? */
2795 				message("502 5.7.0 Sorry, we do not allow this operation");
2796 				if (LogLevel > 5)
2797 					sm_syslog(LOG_INFO, e->e_id,
2798 						  "%s: %s [rejected]",
2799 						  CurSmtpClient,
2800 						  shortenstring(inp, MAXSHORTSTR));
2801 				break;
2802 			}
2803 			if (tempfail)
2804 			{
2805 				if (LogLevel > 9)
2806 					sm_syslog(LOG_INFO, e->e_id,
2807 						  "SMTP ETRN command (%.100s) from %s tempfailed (due to previous checks)",
2808 						  p, CurSmtpClient);
2809 				usrerr(MSG_TEMPFAIL);
2810 				break;
2811 			}
2812 
2813 			if (strlen(p) <= 0)
2814 			{
2815 				usrerr("500 5.5.2 Parameter required");
2816 				break;
2817 			}
2818 
2819 			/* crude way to avoid denial-of-service attacks */
2820 			STOP_IF_ATTACK(checksmtpattack(&n_etrn, MAXETRNCOMMANDS,
2821 							true, "ETRN", e));
2822 
2823 			/*
2824 			**  Do config file checking of the parameter.
2825 			**  Even though we have srv_features now, we still
2826 			**  need this ruleset because the former is called
2827 			**  when the connection has been established, while
2828 			**  this ruleset is called when the command is
2829 			**  actually issued and therefore has all information
2830 			**  available to make a decision.
2831 			*/
2832 
2833 			if (rscheck("check_etrn", p, NULL, e,
2834 				    RSF_RMCOMM, 3, NULL, NOQID) != EX_OK ||
2835 			    Errors > 0)
2836 				break;
2837 
2838 			if (LogLevel > 5)
2839 				sm_syslog(LOG_INFO, e->e_id,
2840 					  "%s: ETRN %s", CurSmtpClient,
2841 					  shortenstring(p, MAXSHORTSTR));
2842 
2843 			id = p;
2844 			if (*id == '#')
2845 			{
2846 				int i, qgrp;
2847 
2848 				id++;
2849 				qgrp = name2qid(id);
2850 				if (!ISVALIDQGRP(qgrp))
2851 				{
2852 					usrerr("459 4.5.4 Queue %s unknown",
2853 					       id);
2854 					break;
2855 				}
2856 				for (i = 0; i < NumQueue && Queue[i] != NULL;
2857 				     i++)
2858 					Queue[i]->qg_nextrun = (time_t) -1;
2859 				Queue[qgrp]->qg_nextrun = 0;
2860 				ok = run_work_group(Queue[qgrp]->qg_wgrp,
2861 						    RWG_FORK|RWG_FORCE);
2862 				if (ok && Errors == 0)
2863 					message("250 2.0.0 Queuing for queue group %s started", id);
2864 				break;
2865 			}
2866 
2867 			if (*id == '@')
2868 				id++;
2869 			else
2870 				*--id = '@';
2871 
2872 			new = (QUEUE_CHAR *) sm_malloc(sizeof(QUEUE_CHAR));
2873 			if (new == NULL)
2874 			{
2875 				syserr("500 5.5.0 ETRN out of memory");
2876 				break;
2877 			}
2878 			new->queue_match = id;
2879 			new->queue_negate = false;
2880 			new->queue_next = NULL;
2881 			QueueLimitRecipient = new;
2882 			ok = runqueue(true, false, false, true);
2883 			sm_free(QueueLimitRecipient); /* XXX */
2884 			QueueLimitRecipient = NULL;
2885 			if (ok && Errors == 0)
2886 				message("250 2.0.0 Queuing for node %s started", p);
2887 			break;
2888 
2889 		  case CMDHELP:		/* help -- give user info */
2890 			DELAY_CONN("HELP");
2891 			help(p, e);
2892 			break;
2893 
2894 		  case CMDNOOP:		/* noop -- do nothing */
2895 			DELAY_CONN("NOOP");
2896 			STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
2897 							true, "NOOP", e));
2898 			message("250 2.0.0 OK");
2899 			break;
2900 
2901 		  case CMDQUIT:		/* quit -- leave mail */
2902 			message("221 2.0.0 %s closing connection", MyHostName);
2903 #if PIPELINING
2904 			(void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
2905 #endif /* PIPELINING */
2906 
2907 			if (smtp.sm_nrcpts > 0)
2908 				logundelrcpts(e, "aborted by sender", 9, false);
2909 
2910 			/* arrange to ignore any current send list */
2911 			e->e_sendqueue = NULL;
2912 
2913 #if STARTTLS
2914 			/* shutdown TLS connection */
2915 			if (tls_active)
2916 			{
2917 				(void) endtls(srv_ssl, "server");
2918 				tls_active = false;
2919 			}
2920 #endif /* STARTTLS */
2921 #if SASL
2922 			if (authenticating == SASL_IS_AUTH)
2923 			{
2924 				sasl_dispose(&conn);
2925 				authenticating = SASL_NOT_AUTH;
2926 				/* XXX sasl_done(); this is a child */
2927 			}
2928 #endif /* SASL */
2929 
2930 doquit:
2931 			/* avoid future 050 messages */
2932 			disconnect(1, e);
2933 
2934 #if MILTER
2935 			/* close out milter filters */
2936 			milter_quit(e);
2937 #endif /* MILTER */
2938 
2939 			if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
2940 				logsender(e, NULL);
2941 			e->e_flags &= ~EF_LOGSENDER;
2942 
2943 			if (lognullconnection && LogLevel > 5 &&
2944 			    nullserver == NULL)
2945 			{
2946 				char *d;
2947 
2948 				d = macvalue(macid("{daemon_name}"), e);
2949 				if (d == NULL)
2950 					d = "stdin";
2951 
2952 				/*
2953 				**  even though this id is "bogus", it makes
2954 				**  it simpler to "grep" related events, e.g.,
2955 				**  timeouts for the same connection.
2956 				*/
2957 
2958 				sm_syslog(LOG_INFO, e->e_id,
2959 					  "%s did not issue MAIL/EXPN/VRFY/ETRN during connection to %s",
2960 					  CurSmtpClient, d);
2961 			}
2962 			if (tTd(93, 100))
2963 			{
2964 				/* return to handle next connection */
2965 				return;
2966 			}
2967 			finis(true, true, ExitStat);
2968 			/* NOTREACHED */
2969 
2970 			/* just to avoid bogus warning from some compilers */
2971 			exit(EX_OSERR);
2972 
2973 		  case CMDVERB:		/* set verbose mode */
2974 			DELAY_CONN("VERB");
2975 			if (!bitset(SRV_OFFER_EXPN, features) ||
2976 			    !bitset(SRV_OFFER_VERB, features))
2977 			{
2978 				/* this would give out the same info */
2979 				message("502 5.7.0 Verbose unavailable");
2980 				break;
2981 			}
2982 			STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
2983 							true, "VERB", e));
2984 			Verbose = 1;
2985 			set_delivery_mode(SM_DELIVER, e);
2986 			message("250 2.0.0 Verbose mode");
2987 			break;
2988 
2989 #if SMTPDEBUG
2990 		  case CMDDBGQSHOW:	/* show queues */
2991 			(void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2992 					     "Send Queue=");
2993 			printaddr(smioout, e->e_sendqueue, true);
2994 			break;
2995 
2996 		  case CMDDBGDEBUG:	/* set debug mode */
2997 			tTsetup(tTdvect, sizeof tTdvect, "0-99.1");
2998 			tTflag(p);
2999 			message("200 2.0.0 Debug set");
3000 			break;
3001 
3002 #else /* SMTPDEBUG */
3003 		  case CMDDBGQSHOW:	/* show queues */
3004 		  case CMDDBGDEBUG:	/* set debug mode */
3005 #endif /* SMTPDEBUG */
3006 		  case CMDLOGBOGUS:	/* bogus command */
3007 			DELAY_CONN("Bogus");
3008 			if (LogLevel > 0)
3009 				sm_syslog(LOG_CRIT, e->e_id,
3010 					  "\"%s\" command from %s (%.100s)",
3011 					  c->cmd_name, CurSmtpClient,
3012 					  anynet_ntoa(&RealHostAddr));
3013 			/* FALLTHROUGH */
3014 
3015 		  case CMDERROR:	/* unknown command */
3016 #if MAXBADCOMMANDS > 0
3017 			if (++n_badcmds > MAXBADCOMMANDS)
3018 			{
3019   stopattack:
3020 				message("421 4.7.0 %s Too many bad commands; closing connection",
3021 					MyHostName);
3022 
3023 				/* arrange to ignore any current send list */
3024 				e->e_sendqueue = NULL;
3025 				goto doquit;
3026 			}
3027 #endif /* MAXBADCOMMANDS > 0 */
3028 
3029 #if MILTER && SMFI_VERSION > 2
3030 			if (smtp.sm_milterlist && smtp.sm_milterize &&
3031 			    !bitset(EF_DISCARD, e->e_flags))
3032 			{
3033 				char state;
3034 				char *response;
3035 
3036 				if (MilterLogLevel > 9)
3037 					sm_syslog(LOG_INFO, e->e_id,
3038 						"Sending \"%s\" to Milter", inp);
3039 				response = milter_unknown(inp, e, &state);
3040 				MILTER_REPLY("unknown");
3041 				if (state == SMFIR_REPLYCODE ||
3042 				    state == SMFIR_REJECT ||
3043 				    state == SMFIR_TEMPFAIL ||
3044 				    state == SMFIR_SHUTDOWN)
3045 				{
3046 					/* MILTER_REPLY already gave an error */
3047 					break;
3048 				}
3049 			}
3050 #endif /* MILTER && SMFI_VERSION > 2 */
3051 
3052 			usrerr("500 5.5.1 Command unrecognized: \"%s\"",
3053 			       shortenstring(inp, MAXSHORTSTR));
3054 			break;
3055 
3056 		  case CMDUNIMPL:
3057 			DELAY_CONN("Unimpl");
3058 			usrerr("502 5.5.1 Command not implemented: \"%s\"",
3059 			       shortenstring(inp, MAXSHORTSTR));
3060 			break;
3061 
3062 		  default:
3063 			DELAY_CONN("default");
3064 			errno = 0;
3065 			syserr("500 5.5.0 smtp: unknown code %d", c->cmd_code);
3066 			break;
3067 		}
3068 #if SASL
3069 		}
3070 #endif /* SASL */
3071 	    }
3072 	    SM_EXCEPT(exc, "[!F]*")
3073 	    {
3074 		/*
3075 		**  The only possible exception is "E:mta.quickabort".
3076 		**  There is nothing to do except fall through and loop.
3077 		*/
3078 	    }
3079 	    SM_END_TRY
3080 	}
3081 }
3082 /*
3083 **  SMTP_DATA -- implement the SMTP DATA command.
3084 **
3085 **	Parameters:
3086 **		smtp -- status of SMTP connection.
3087 **		e -- envelope.
3088 **
3089 **	Returns:
3090 **		true iff SMTP session can continue.
3091 **
3092 **	Side Effects:
3093 **		possibly sends message.
3094 */
3095 
3096 static bool
3097 smtp_data(smtp, e)
3098 	SMTP_T *smtp;
3099 	ENVELOPE *e;
3100 {
3101 #if MILTER
3102 	bool milteraccept;
3103 #endif /* MILTER */
3104 	bool aborting;
3105 	bool doublequeue;
3106 	ADDRESS *a;
3107 	ENVELOPE *ee;
3108 	char *id;
3109 	char *oldid;
3110 	char buf[32];
3111 	bool rv = true;
3112 
3113 	SmtpPhase = "server DATA";
3114 	if (!smtp->sm_gotmail)
3115 	{
3116 		usrerr("503 5.0.0 Need MAIL command");
3117 		return true;
3118 	}
3119 	else if (smtp->sm_nrcpts <= 0)
3120 	{
3121 		usrerr("503 5.0.0 Need RCPT (recipient)");
3122 		return true;
3123 	}
3124 	(void) sm_snprintf(buf, sizeof buf, "%u", smtp->sm_nrcpts);
3125 	if (rscheck("check_data", buf, NULL, e,
3126 		    RSF_RMCOMM|RSF_UNSTRUCTURED|RSF_COUNT, 3, NULL,
3127 		    e->e_id) != EX_OK)
3128 		return true;
3129 
3130 #if MILTER && SMFI_VERSION > 3
3131 	if (smtp->sm_milterlist && smtp->sm_milterize &&
3132 	    !bitset(EF_DISCARD, e->e_flags))
3133 	{
3134 		char state;
3135 		char *response;
3136 		int savelogusrerrs = LogUsrErrs;
3137 
3138 		response = milter_data_cmd(e, &state);
3139 		switch (state)
3140 		{
3141 		  case SMFIR_REPLYCODE:
3142 			if (MilterLogLevel > 3)
3143 			{
3144 				sm_syslog(LOG_INFO, e->e_id,
3145 					  "Milter: cmd=data, reject=%s",
3146 					  response);
3147 				LogUsrErrs = false;
3148 			}
3149 			usrerr(response);
3150 			if (strncmp(response, "421 ", 4) == 0
3151 			    || strncmp(response, "421-", 4) == 0)
3152 			{
3153 				e->e_sendqueue = NULL;
3154 				return false;
3155 			}
3156 			return true;
3157 
3158 		  case SMFIR_REJECT:
3159 			if (MilterLogLevel > 3)
3160 			{
3161 				sm_syslog(LOG_INFO, e->e_id,
3162 					  "Milter: cmd=data, reject=550 5.7.1 Command rejected");
3163 				LogUsrErrs = false;
3164 			}
3165 			usrerr("550 5.7.1 Command rejected");
3166 			return true;
3167 
3168 		  case SMFIR_DISCARD:
3169 			if (MilterLogLevel > 3)
3170 				sm_syslog(LOG_INFO, e->e_id,
3171 					  "Milter: cmd=data, discard");
3172 			e->e_flags |= EF_DISCARD;
3173 			break;
3174 
3175 		  case SMFIR_TEMPFAIL:
3176 			if (MilterLogLevel > 3)
3177 			{
3178 				sm_syslog(LOG_INFO, e->e_id,
3179 					  "Milter: cmd=data, reject=%s",
3180 					  MSG_TEMPFAIL);
3181 				LogUsrErrs = false;
3182 			}
3183 			usrerr(MSG_TEMPFAIL);
3184 			return true;
3185 
3186 		  case SMFIR_SHUTDOWN:
3187 			if (MilterLogLevel > 3)
3188 			{
3189 				sm_syslog(LOG_INFO, e->e_id,
3190 					  "Milter: cmd=data, reject=421 4.7.0 %s closing connection",
3191 					  MyHostName);
3192 				LogUsrErrs = false;
3193 			}
3194 			usrerr("421 4.7.0 %s closing connection", MyHostName);
3195 			e->e_sendqueue = NULL;
3196 			return false;
3197 		}
3198 		LogUsrErrs = savelogusrerrs;
3199 		if (response != NULL)
3200 			sm_free(response); /* XXX */
3201 	}
3202 #endif /* MILTER && SMFI_VERSION > 3 */
3203 
3204 	/* put back discard bit */
3205 	if (smtp->sm_discard)
3206 		e->e_flags |= EF_DISCARD;
3207 
3208 	/* check to see if we need to re-expand aliases */
3209 	/* also reset QS_BADADDR on already-diagnosted addrs */
3210 	doublequeue = false;
3211 	for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3212 	{
3213 		if (QS_IS_VERIFIED(a->q_state) &&
3214 		    !bitset(EF_DISCARD, e->e_flags))
3215 		{
3216 			/* need to re-expand aliases */
3217 			doublequeue = true;
3218 		}
3219 		if (QS_IS_BADADDR(a->q_state))
3220 		{
3221 			/* make this "go away" */
3222 			a->q_state = QS_DONTSEND;
3223 		}
3224 	}
3225 
3226 	/* collect the text of the message */
3227 	SmtpPhase = "collect";
3228 	buffer_errors();
3229 
3230 	collect(InChannel, true, NULL, e, true);
3231 
3232 	/* redefine message size */
3233 	(void) sm_snprintf(buf, sizeof buf, "%ld", e->e_msgsize);
3234 	macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3235 
3236 #if _FFR_CHECK_EOM
3237 	/* rscheck() will set Errors or EF_DISCARD if it trips */
3238 	(void) rscheck("check_eom", buf, NULL, e, RSF_UNSTRUCTURED|RSF_COUNT,
3239 		       3, NULL, e->e_id);
3240 #endif /* _FFR_CHECK_EOM */
3241 
3242 #if MILTER
3243 	milteraccept = true;
3244 	if (smtp->sm_milterlist && smtp->sm_milterize &&
3245 	    Errors <= 0 &&
3246 	    !bitset(EF_DISCARD, e->e_flags))
3247 	{
3248 		char state;
3249 		char *response;
3250 
3251 		response = milter_data(e, &state);
3252 		switch (state)
3253 		{
3254 		  case SMFIR_REPLYCODE:
3255 			if (MilterLogLevel > 3)
3256 				sm_syslog(LOG_INFO, e->e_id,
3257 					  "Milter: data, reject=%s",
3258 					  response);
3259 			milteraccept = false;
3260 			usrerr(response);
3261 			break;
3262 
3263 		  case SMFIR_REJECT:
3264 			milteraccept = false;
3265 			if (MilterLogLevel > 3)
3266 				sm_syslog(LOG_INFO, e->e_id,
3267 					  "Milter: data, reject=554 5.7.1 Command rejected");
3268 			usrerr("554 5.7.1 Command rejected");
3269 			break;
3270 
3271 		  case SMFIR_DISCARD:
3272 			if (MilterLogLevel > 3)
3273 				sm_syslog(LOG_INFO, e->e_id,
3274 					  "Milter: data, discard");
3275 			milteraccept = false;
3276 			e->e_flags |= EF_DISCARD;
3277 			break;
3278 
3279 		  case SMFIR_TEMPFAIL:
3280 			if (MilterLogLevel > 3)
3281 				sm_syslog(LOG_INFO, e->e_id,
3282 					  "Milter: data, reject=%s",
3283 					  MSG_TEMPFAIL);
3284 			milteraccept = false;
3285 			usrerr(MSG_TEMPFAIL);
3286 			break;
3287 
3288 		  case SMFIR_SHUTDOWN:
3289 			if (MilterLogLevel > 3)
3290 				sm_syslog(LOG_INFO, e->e_id,
3291 					  "Milter: data, reject=421 4.7.0 %s closing connection",
3292 					  MyHostName);
3293 			milteraccept = false;
3294 			usrerr("421 4.7.0 %s closing connection", MyHostName);
3295 			rv = false;
3296 			break;
3297 		}
3298 		if (response != NULL)
3299 			sm_free(response);
3300 	}
3301 
3302 	/* Milter may have changed message size */
3303 	(void) sm_snprintf(buf, sizeof buf, "%ld", e->e_msgsize);
3304 	macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3305 
3306 	/* abort message filters that didn't get the body & log msg is OK */
3307 	if (smtp->sm_milterlist && smtp->sm_milterize)
3308 	{
3309 		milter_abort(e);
3310 		if (milteraccept && MilterLogLevel > 9)
3311 			sm_syslog(LOG_INFO, e->e_id, "Milter accept: message");
3312 	}
3313 
3314 	/*
3315 	**  If SuperSafe is SAFE_REALLY_POSTMILTER, and we don't have milter or
3316 	**  milter accepted message, sync it now
3317 	**
3318 	**  XXX This is almost a copy of the code in collect(): put it into
3319 	**	a function that is called from both places?
3320 	*/
3321 
3322 	if (milteraccept && SuperSafe == SAFE_REALLY_POSTMILTER)
3323 	{
3324 		int afd;
3325 		SM_FILE_T *volatile df;
3326 		char *dfname;
3327 
3328 		df = e->e_dfp;
3329 		dfname = queuename(e, DATAFL_LETTER);
3330 		if (sm_io_setinfo(df, SM_BF_COMMIT, NULL) < 0
3331 		    && errno != EINVAL)
3332 		{
3333 			int save_errno;
3334 
3335 			save_errno = errno;
3336 			if (save_errno == EEXIST)
3337 			{
3338 				struct stat st;
3339 				int dfd;
3340 
3341 				if (stat(dfname, &st) < 0)
3342 					st.st_size = -1;
3343 				errno = EEXIST;
3344 				syserr("@collect: bfcommit(%s): already on disk, size=%ld",
3345 				       dfname, (long) st.st_size);
3346 				dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL);
3347 				if (dfd >= 0)
3348 					dumpfd(dfd, true, true);
3349 			}
3350 			errno = save_errno;
3351 			dferror(df, "bfcommit", e);
3352 			flush_errors(true);
3353 			finis(save_errno != EEXIST, true, ExitStat);
3354 		}
3355 		else if ((afd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL)) < 0)
3356 		{
3357 			dferror(df, "sm_io_getinfo", e);
3358 			flush_errors(true);
3359 			finis(true, true, ExitStat);
3360 			/* NOTREACHED */
3361 		}
3362 		else if (fsync(afd) < 0)
3363 		{
3364 			dferror(df, "fsync", e);
3365 			flush_errors(true);
3366 			finis(true, true, ExitStat);
3367 			/* NOTREACHED */
3368 		}
3369 		else if (sm_io_close(df, SM_TIME_DEFAULT) < 0)
3370 		{
3371 			dferror(df, "sm_io_close", e);
3372 			flush_errors(true);
3373 			finis(true, true, ExitStat);
3374 			/* NOTREACHED */
3375 		}
3376 
3377 		/* Now reopen the df file */
3378 		e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname,
3379 					SM_IO_RDONLY, NULL);
3380 		if (e->e_dfp == NULL)
3381 		{
3382 			/* we haven't acked receipt yet, so just chuck this */
3383 			syserr("@Cannot reopen %s", dfname);
3384 			finis(true, true, ExitStat);
3385 			/* NOTREACHED */
3386 		}
3387 	}
3388 #endif /* MILTER */
3389 
3390 	/* Check if quarantining stats should be updated */
3391 	if (e->e_quarmsg != NULL)
3392 		markstats(e, NULL, STATS_QUARANTINE);
3393 
3394 	/*
3395 	**  If a header/body check (header checks or milter)
3396 	**  set EF_DISCARD, don't queueup the message --
3397 	**  that would lose the EF_DISCARD bit and deliver
3398 	**  the message.
3399 	*/
3400 
3401 	if (bitset(EF_DISCARD, e->e_flags))
3402 		doublequeue = false;
3403 
3404 	aborting = Errors > 0;
3405 	if (!(aborting || bitset(EF_DISCARD, e->e_flags)) &&
3406 	    (QueueMode == QM_QUARANTINE || e->e_quarmsg == NULL) &&
3407 	    !split_by_recipient(e))
3408 		aborting = bitset(EF_FATALERRS, e->e_flags);
3409 
3410 	if (aborting)
3411 	{
3412 		/* Log who the mail would have gone to */
3413 		logundelrcpts(e, e->e_message, 8, false);
3414 		flush_errors(true);
3415 		buffer_errors();
3416 		goto abortmessage;
3417 	}
3418 
3419 	/* from now on, we have to operate silently */
3420 	buffer_errors();
3421 
3422 #if 0
3423 	/*
3424 	**  Clear message, it may contain an error from the SMTP dialogue.
3425 	**  This error must not show up in the queue.
3426 	**	Some error message should show up, e.g., alias database
3427 	**	not available, but others shouldn't, e.g., from check_rcpt.
3428 	*/
3429 
3430 	e->e_message = NULL;
3431 #endif /* 0 */
3432 
3433 	/*
3434 	**  Arrange to send to everyone.
3435 	**	If sending to multiple people, mail back
3436 	**		errors rather than reporting directly.
3437 	**	In any case, don't mail back errors for
3438 	**		anything that has happened up to
3439 	**		now (the other end will do this).
3440 	**	Truncate our transcript -- the mail has gotten
3441 	**		to us successfully, and if we have
3442 	**		to mail this back, it will be easier
3443 	**		on the reader.
3444 	**	Then send to everyone.
3445 	**	Finally give a reply code.  If an error has
3446 	**		already been given, don't mail a
3447 	**		message back.
3448 	**	We goose error returns by clearing error bit.
3449 	*/
3450 
3451 	SmtpPhase = "delivery";
3452 	(void) sm_io_setinfo(e->e_xfp, SM_BF_TRUNCATE, NULL);
3453 	id = e->e_id;
3454 
3455 #if NAMED_BIND
3456 	_res.retry = TimeOuts.res_retry[RES_TO_FIRST];
3457 	_res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
3458 #endif /* NAMED_BIND */
3459 
3460 	for (ee = e; ee != NULL; ee = ee->e_sibling)
3461 	{
3462 		/* make sure we actually do delivery */
3463 		ee->e_flags &= ~EF_CLRQUEUE;
3464 
3465 		/* from now on, operate silently */
3466 		ee->e_errormode = EM_MAIL;
3467 
3468 		if (doublequeue)
3469 		{
3470 			/* make sure it is in the queue */
3471 			queueup(ee, false, true);
3472 		}
3473 		else
3474 		{
3475 			int mode;
3476 
3477 			/* send to all recipients */
3478 			mode = SM_DEFAULT;
3479 #if _FFR_DM_ONE
3480 			if (SM_DM_ONE == e->e_sendmode)
3481 			{
3482 				if (NotFirstDelivery)
3483 				{
3484 					mode = SM_QUEUE;
3485 					e->e_sendmode = SM_QUEUE;
3486 				}
3487 				else
3488 				{
3489 					mode = SM_FORK;
3490 					NotFirstDelivery = true;
3491 				}
3492 			}
3493 #endif /* _FFR_DM_ONE */
3494 			sendall(ee, mode);
3495 		}
3496 		ee->e_to = NULL;
3497 	}
3498 
3499 	/* put back id for SMTP logging in putoutmsg() */
3500 	oldid = CurEnv->e_id;
3501 	CurEnv->e_id = id;
3502 
3503 	/* issue success message */
3504 #if _FFR_MSG_ACCEPT
3505 	if (MessageAccept != NULL && *MessageAccept != '\0')
3506 	{
3507 		char msg[MAXLINE];
3508 
3509 		expand(MessageAccept, msg, sizeof msg, e);
3510 		message("250 2.0.0 %s", msg);
3511 	}
3512 	else
3513 #endif /* _FFR_MSG_ACCEPT */
3514 	message("250 2.0.0 %s Message accepted for delivery", id);
3515 	CurEnv->e_id = oldid;
3516 
3517 	/* if we just queued, poke it */
3518 	if (doublequeue)
3519 	{
3520 		bool anything_to_send = false;
3521 
3522 		sm_getla();
3523 		for (ee = e; ee != NULL; ee = ee->e_sibling)
3524 		{
3525 			if (WILL_BE_QUEUED(ee->e_sendmode))
3526 				continue;
3527 			if (shouldqueue(ee->e_msgpriority, ee->e_ctime))
3528 			{
3529 				ee->e_sendmode = SM_QUEUE;
3530 				continue;
3531 			}
3532 			else if (QueueMode != QM_QUARANTINE &&
3533 				 ee->e_quarmsg != NULL)
3534 			{
3535 				ee->e_sendmode = SM_QUEUE;
3536 				continue;
3537 			}
3538 			anything_to_send = true;
3539 
3540 			/* close all the queue files */
3541 			closexscript(ee);
3542 			if (ee->e_dfp != NULL)
3543 			{
3544 				(void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
3545 				ee->e_dfp = NULL;
3546 			}
3547 			unlockqueue(ee);
3548 		}
3549 		if (anything_to_send)
3550 		{
3551 #if PIPELINING
3552 			/*
3553 			**  XXX if we don't do this, we get 250 twice
3554 			**	because it is also flushed in the child.
3555 			*/
3556 
3557 			(void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
3558 #endif /* PIPELINING */
3559 			(void) doworklist(e, true, true);
3560 		}
3561 	}
3562 
3563   abortmessage:
3564 	if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
3565 		logsender(e, NULL);
3566 	e->e_flags &= ~EF_LOGSENDER;
3567 
3568 	/* clean up a bit */
3569 	smtp->sm_gotmail = false;
3570 
3571 	/*
3572 	**  Call dropenvelope if and only if the envelope is *not*
3573 	**  being processed by the child process forked by doworklist().
3574 	*/
3575 
3576 	if (aborting || bitset(EF_DISCARD, e->e_flags))
3577 		dropenvelope(e, true, false);
3578 	else
3579 	{
3580 		for (ee = e; ee != NULL; ee = ee->e_sibling)
3581 		{
3582 			if (!doublequeue &&
3583 			    QueueMode != QM_QUARANTINE &&
3584 			    ee->e_quarmsg != NULL)
3585 			{
3586 				dropenvelope(ee, true, false);
3587 				continue;
3588 			}
3589 			if (WILL_BE_QUEUED(ee->e_sendmode))
3590 				dropenvelope(ee, true, false);
3591 		}
3592 	}
3593 	sm_rpool_free(e->e_rpool);
3594 
3595 	/*
3596 	**  At this point, e == &MainEnvelope, but if we did splitting,
3597 	**  then CurEnv may point to an envelope structure that was just
3598 	**  freed with the rpool.  So reset CurEnv *before* calling
3599 	**  newenvelope.
3600 	*/
3601 
3602 	CurEnv = e;
3603 	newenvelope(e, e, sm_rpool_new_x(NULL));
3604 	e->e_flags = BlankEnvelope.e_flags;
3605 
3606 	/* restore connection quarantining */
3607 	if (smtp->sm_quarmsg == NULL)
3608 	{
3609 		e->e_quarmsg = NULL;
3610 		macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), "");
3611 	}
3612 	else
3613 	{
3614 		e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, smtp->sm_quarmsg);
3615 		macdefine(&e->e_macro, A_PERM,
3616 			  macid("{quarantine}"), e->e_quarmsg);
3617 	}
3618 	return rv;
3619 }
3620 /*
3621 **  LOGUNDELRCPTS -- log undelivered (or all) recipients.
3622 **
3623 **	Parameters:
3624 **		e -- envelope.
3625 **		msg -- message for Stat=
3626 **		level -- log level.
3627 **		all -- log all recipients.
3628 **
3629 **	Returns:
3630 **		none.
3631 **
3632 **	Side Effects:
3633 **		logs undelivered (or all) recipients
3634 */
3635 
3636 void
3637 logundelrcpts(e, msg, level, all)
3638 	ENVELOPE *e;
3639 	char *msg;
3640 	int level;
3641 	bool all;
3642 {
3643 	ADDRESS *a;
3644 
3645 	if (LogLevel <= level || msg == NULL || *msg == '\0')
3646 		return;
3647 
3648 	/* Clear $h so relay= doesn't get mislogged by logdelivery() */
3649 	macdefine(&e->e_macro, A_PERM, 'h', NULL);
3650 
3651 	/* Log who the mail would have gone to */
3652 	for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3653 	{
3654 		if (!QS_IS_UNDELIVERED(a->q_state) && !all)
3655 			continue;
3656 		e->e_to = a->q_paddr;
3657 		logdelivery(NULL, NULL, a->q_status, msg, NULL,
3658 			    (time_t) 0, e);
3659 	}
3660 	e->e_to = NULL;
3661 }
3662 /*
3663 **  CHECKSMTPATTACK -- check for denial-of-service attack by repetition
3664 **
3665 **	Parameters:
3666 **		pcounter -- pointer to a counter for this command.
3667 **		maxcount -- maximum value for this counter before we
3668 **			slow down.
3669 **		waitnow -- sleep now (in this routine)?
3670 **		cname -- command name for logging.
3671 **		e -- the current envelope.
3672 **
3673 **	Returns:
3674 **		time to wait,
3675 **		STOP_ATTACK if twice as many commands as allowed and
3676 **			MaxChildren > 0.
3677 **
3678 **	Side Effects:
3679 **		Slows down if we seem to be under attack.
3680 */
3681 
3682 static time_t
3683 checksmtpattack(pcounter, maxcount, waitnow, cname, e)
3684 	volatile unsigned int *pcounter;
3685 	unsigned int maxcount;
3686 	bool waitnow;
3687 	char *cname;
3688 	ENVELOPE *e;
3689 {
3690 	if (maxcount <= 0)	/* no limit */
3691 		return (time_t) 0;
3692 
3693 	if (++(*pcounter) >= maxcount)
3694 	{
3695 		unsigned int shift;
3696 		time_t s;
3697 
3698 		if (*pcounter == maxcount && LogLevel > 5)
3699 		{
3700 			sm_syslog(LOG_INFO, e->e_id,
3701 				  "%s: possible SMTP attack: command=%.40s, count=%u",
3702 				  CurSmtpClient, cname, *pcounter);
3703 		}
3704 		shift = *pcounter - maxcount;
3705 		s = 1 << shift;
3706 		if (shift > MAXSHIFT || s >= MAXTIMEOUT || s <= 0)
3707 			s = MAXTIMEOUT;
3708 
3709 #define IS_ATTACK(s)	((MaxChildren > 0 && *pcounter >= maxcount * 2)	\
3710 				? STOP_ATTACK : (time_t) s)
3711 
3712 		/* sleep at least 1 second before returning */
3713 		(void) sleep(*pcounter / maxcount);
3714 		s -= *pcounter / maxcount;
3715 		if (s >= MAXTIMEOUT || s < 0)
3716 			s = MAXTIMEOUT;
3717 		if (waitnow && s > 0)
3718 		{
3719 			(void) sleep(s);
3720 			return IS_ATTACK(0);
3721 		}
3722 		return IS_ATTACK(s);
3723 	}
3724 	return (time_t) 0;
3725 }
3726 /*
3727 **  SETUP_SMTPD_IO -- setup I/O fd correctly for the SMTP server
3728 **
3729 **	Parameters:
3730 **		none.
3731 **
3732 **	Returns:
3733 **		nothing.
3734 **
3735 **	Side Effects:
3736 **		may change I/O fd.
3737 */
3738 
3739 static void
3740 setup_smtpd_io()
3741 {
3742 	int inchfd, outchfd, outfd;
3743 
3744 	inchfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
3745 	outchfd  = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
3746 	outfd = sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL);
3747 	if (outchfd != outfd)
3748 	{
3749 		/* arrange for debugging output to go to remote host */
3750 		(void) dup2(outchfd, outfd);
3751 	}
3752 
3753 	/*
3754 	**  if InChannel and OutChannel are stdin/stdout
3755 	**  and connected to ttys
3756 	**  and fcntl(STDIN, F_SETFL, O_NONBLOCKING) also changes STDOUT,
3757 	**  then "chain" them together.
3758 	*/
3759 
3760 	if (inchfd == STDIN_FILENO && outchfd == STDOUT_FILENO &&
3761 	    isatty(inchfd) && isatty(outchfd))
3762 	{
3763 		int inmode, outmode;
3764 
3765 		inmode = fcntl(inchfd, F_GETFL, 0);
3766 		if (inmode == -1)
3767 		{
3768 			if (LogLevel > 11)
3769 				sm_syslog(LOG_INFO, NOQID,
3770 					"fcntl(inchfd, F_GETFL) failed: %s",
3771 					sm_errstring(errno));
3772 			return;
3773 		}
3774 		outmode = fcntl(outchfd, F_GETFL, 0);
3775 		if (outmode == -1)
3776 		{
3777 			if (LogLevel > 11)
3778 				sm_syslog(LOG_INFO, NOQID,
3779 					"fcntl(outchfd, F_GETFL) failed: %s",
3780 					sm_errstring(errno));
3781 			return;
3782 		}
3783 		if (bitset(O_NONBLOCK, inmode) ||
3784 		    bitset(O_NONBLOCK, outmode) ||
3785 		    fcntl(inchfd, F_SETFL, inmode | O_NONBLOCK) == -1)
3786 			return;
3787 		outmode = fcntl(outchfd, F_GETFL, 0);
3788 		if (outmode != -1 && bitset(O_NONBLOCK, outmode))
3789 		{
3790 			/* changing InChannel also changes OutChannel */
3791 			sm_io_automode(OutChannel, InChannel);
3792 			if (tTd(97, 4) && LogLevel > 9)
3793 				sm_syslog(LOG_INFO, NOQID,
3794 					  "set automode for I (%d)/O (%d) in SMTP server",
3795 					  inchfd, outchfd);
3796 		}
3797 
3798 		/* undo change of inchfd */
3799 		(void) fcntl(inchfd, F_SETFL, inmode);
3800 	}
3801 }
3802 /*
3803 **  SKIPWORD -- skip a fixed word.
3804 **
3805 **	Parameters:
3806 **		p -- place to start looking.
3807 **		w -- word to skip.
3808 **
3809 **	Returns:
3810 **		p following w.
3811 **		NULL on error.
3812 **
3813 **	Side Effects:
3814 **		clobbers the p data area.
3815 */
3816 
3817 static char *
3818 skipword(p, w)
3819 	register char *volatile p;
3820 	char *w;
3821 {
3822 	register char *q;
3823 	char *firstp = p;
3824 
3825 	/* find beginning of word */
3826 	SKIP_SPACE(p);
3827 	q = p;
3828 
3829 	/* find end of word */
3830 	while (*p != '\0' && *p != ':' && !(isascii(*p) && isspace(*p)))
3831 		p++;
3832 	while (isascii(*p) && isspace(*p))
3833 		*p++ = '\0';
3834 	if (*p != ':')
3835 	{
3836 	  syntax:
3837 		usrerr("501 5.5.2 Syntax error in parameters scanning \"%s\"",
3838 			shortenstring(firstp, MAXSHORTSTR));
3839 		return NULL;
3840 	}
3841 	*p++ = '\0';
3842 	SKIP_SPACE(p);
3843 
3844 	if (*p == '\0')
3845 		goto syntax;
3846 
3847 	/* see if the input word matches desired word */
3848 	if (sm_strcasecmp(q, w))
3849 		goto syntax;
3850 
3851 	return p;
3852 }
3853 /*
3854 **  MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line
3855 **
3856 **	Parameters:
3857 **		kp -- the parameter key.
3858 **		vp -- the value of that parameter.
3859 **		e -- the envelope.
3860 **
3861 **	Returns:
3862 **		none.
3863 */
3864 
3865 static void
3866 mail_esmtp_args(kp, vp, e)
3867 	char *kp;
3868 	char *vp;
3869 	ENVELOPE *e;
3870 {
3871 	if (sm_strcasecmp(kp, "size") == 0)
3872 	{
3873 		if (vp == NULL)
3874 		{
3875 			usrerr("501 5.5.2 SIZE requires a value");
3876 			/* NOTREACHED */
3877 		}
3878 		macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), vp);
3879 		errno = 0;
3880 		e->e_msgsize = strtol(vp, (char **) NULL, 10);
3881 		if (e->e_msgsize == LONG_MAX && errno == ERANGE)
3882 		{
3883 			usrerr("552 5.2.3 Message size exceeds maximum value");
3884 			/* NOTREACHED */
3885 		}
3886 		if (e->e_msgsize < 0)
3887 		{
3888 			usrerr("552 5.2.3 Message size invalid");
3889 			/* NOTREACHED */
3890 		}
3891 	}
3892 	else if (sm_strcasecmp(kp, "body") == 0)
3893 	{
3894 		if (vp == NULL)
3895 		{
3896 			usrerr("501 5.5.2 BODY requires a value");
3897 			/* NOTREACHED */
3898 		}
3899 		else if (sm_strcasecmp(vp, "8bitmime") == 0)
3900 		{
3901 			SevenBitInput = false;
3902 		}
3903 		else if (sm_strcasecmp(vp, "7bit") == 0)
3904 		{
3905 			SevenBitInput = true;
3906 		}
3907 		else
3908 		{
3909 			usrerr("501 5.5.4 Unknown BODY type %s", vp);
3910 			/* NOTREACHED */
3911 		}
3912 		e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, vp);
3913 	}
3914 	else if (sm_strcasecmp(kp, "envid") == 0)
3915 	{
3916 		if (bitset(PRIV_NORECEIPTS, PrivacyFlags))
3917 		{
3918 			usrerr("504 5.7.0 Sorry, ENVID not supported, we do not allow DSN");
3919 			/* NOTREACHED */
3920 		}
3921 		if (vp == NULL)
3922 		{
3923 			usrerr("501 5.5.2 ENVID requires a value");
3924 			/* NOTREACHED */
3925 		}
3926 		if (!xtextok(vp))
3927 		{
3928 			usrerr("501 5.5.4 Syntax error in ENVID parameter value");
3929 			/* NOTREACHED */
3930 		}
3931 		if (e->e_envid != NULL)
3932 		{
3933 			usrerr("501 5.5.0 Duplicate ENVID parameter");
3934 			/* NOTREACHED */
3935 		}
3936 		e->e_envid = sm_rpool_strdup_x(e->e_rpool, vp);
3937 		macdefine(&e->e_macro, A_PERM,
3938 			macid("{dsn_envid}"), e->e_envid);
3939 	}
3940 	else if (sm_strcasecmp(kp, "ret") == 0)
3941 	{
3942 		if (bitset(PRIV_NORECEIPTS, PrivacyFlags))
3943 		{
3944 			usrerr("504 5.7.0 Sorry, RET not supported, we do not allow DSN");
3945 			/* NOTREACHED */
3946 		}
3947 		if (vp == NULL)
3948 		{
3949 			usrerr("501 5.5.2 RET requires a value");
3950 			/* NOTREACHED */
3951 		}
3952 		if (bitset(EF_RET_PARAM, e->e_flags))
3953 		{
3954 			usrerr("501 5.5.0 Duplicate RET parameter");
3955 			/* NOTREACHED */
3956 		}
3957 		e->e_flags |= EF_RET_PARAM;
3958 		if (sm_strcasecmp(vp, "hdrs") == 0)
3959 			e->e_flags |= EF_NO_BODY_RETN;
3960 		else if (sm_strcasecmp(vp, "full") != 0)
3961 		{
3962 			usrerr("501 5.5.2 Bad argument \"%s\" to RET", vp);
3963 			/* NOTREACHED */
3964 		}
3965 		macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), vp);
3966 	}
3967 #if SASL
3968 	else if (sm_strcasecmp(kp, "auth") == 0)
3969 	{
3970 		int len;
3971 		char *q;
3972 		char *auth_param;	/* the value of the AUTH=x */
3973 		bool saveQuickAbort = QuickAbort;
3974 		bool saveSuprErrs = SuprErrs;
3975 		bool saveExitStat = ExitStat;
3976 
3977 		if (vp == NULL)
3978 		{
3979 			usrerr("501 5.5.2 AUTH= requires a value");
3980 			/* NOTREACHED */
3981 		}
3982 		if (e->e_auth_param != NULL)
3983 		{
3984 			usrerr("501 5.5.0 Duplicate AUTH parameter");
3985 			/* NOTREACHED */
3986 		}
3987 		if ((q = strchr(vp, ' ')) != NULL)
3988 			len = q - vp + 1;
3989 		else
3990 			len = strlen(vp) + 1;
3991 		auth_param = xalloc(len);
3992 		(void) sm_strlcpy(auth_param, vp, len);
3993 		if (!xtextok(auth_param))
3994 		{
3995 			usrerr("501 5.5.4 Syntax error in AUTH parameter value");
3996 			/* just a warning? */
3997 			/* NOTREACHED */
3998 		}
3999 
4000 		/* XXX define this always or only if trusted? */
4001 		macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"),
4002 			  auth_param);
4003 
4004 		/*
4005 		**  call Strust_auth to find out whether
4006 		**  auth_param is acceptable (trusted)
4007 		**  we shouldn't trust it if not authenticated
4008 		**  (required by RFC, leave it to ruleset?)
4009 		*/
4010 
4011 		SuprErrs = true;
4012 		QuickAbort = false;
4013 		if (strcmp(auth_param, "<>") != 0 &&
4014 		     (rscheck("trust_auth", auth_param, NULL, e, RSF_RMCOMM,
4015 			      9, NULL, NOQID) != EX_OK || Errors > 0))
4016 		{
4017 			if (tTd(95, 8))
4018 			{
4019 				q = e->e_auth_param;
4020 				sm_dprintf("auth=\"%.100s\" not trusted user=\"%.100s\"\n",
4021 					auth_param, (q == NULL) ? "" : q);
4022 			}
4023 
4024 			/* not trusted */
4025 			e->e_auth_param = "<>";
4026 # if _FFR_AUTH_PASSING
4027 			macdefine(&BlankEnvelope.e_macro, A_PERM,
4028 				  macid("{auth_author}"), NULL);
4029 # endif /* _FFR_AUTH_PASSING */
4030 		}
4031 		else
4032 		{
4033 			if (tTd(95, 8))
4034 				sm_dprintf("auth=\"%.100s\" trusted\n", auth_param);
4035 			e->e_auth_param = sm_rpool_strdup_x(e->e_rpool,
4036 							    auth_param);
4037 		}
4038 		sm_free(auth_param); /* XXX */
4039 
4040 		/* reset values */
4041 		Errors = 0;
4042 		QuickAbort = saveQuickAbort;
4043 		SuprErrs = saveSuprErrs;
4044 		ExitStat = saveExitStat;
4045 	}
4046 #endif /* SASL */
4047 #define PRTCHAR(c)	((isascii(c) && isprint(c)) ? (c) : '?')
4048 
4049 	/*
4050 	**  "by" is only accepted if DeliverByMin >= 0.
4051 	**  We maybe could add this to the list of server_features.
4052 	*/
4053 
4054 	else if (sm_strcasecmp(kp, "by") == 0 && DeliverByMin >= 0)
4055 	{
4056 		char *s;
4057 
4058 		if (vp == NULL)
4059 		{
4060 			usrerr("501 5.5.2 BY= requires a value");
4061 			/* NOTREACHED */
4062 		}
4063 		errno = 0;
4064 		e->e_deliver_by = strtol(vp, &s, 10);
4065 		if (e->e_deliver_by == LONG_MIN ||
4066 		    e->e_deliver_by == LONG_MAX ||
4067 		    e->e_deliver_by > 999999999l ||
4068 		    e->e_deliver_by < -999999999l)
4069 		{
4070 			usrerr("501 5.5.2 BY=%s out of range", vp);
4071 			/* NOTREACHED */
4072 		}
4073 		if (s == NULL || *s != ';')
4074 		{
4075 			usrerr("501 5.5.2 BY= missing ';'");
4076 			/* NOTREACHED */
4077 		}
4078 		e->e_dlvr_flag = 0;
4079 		++s;	/* XXX: spaces allowed? */
4080 		SKIP_SPACE(s);
4081 		switch (tolower(*s))
4082 		{
4083 		  case 'n':
4084 			e->e_dlvr_flag = DLVR_NOTIFY;
4085 			break;
4086 		  case 'r':
4087 			e->e_dlvr_flag = DLVR_RETURN;
4088 			if (e->e_deliver_by <= 0)
4089 			{
4090 				usrerr("501 5.5.4 mode R requires BY time > 0");
4091 				/* NOTREACHED */
4092 			}
4093 			if (DeliverByMin > 0 && e->e_deliver_by > 0 &&
4094 			    e->e_deliver_by < DeliverByMin)
4095 			{
4096 				usrerr("555 5.5.2 time %ld less than %ld",
4097 					e->e_deliver_by, (long) DeliverByMin);
4098 				/* NOTREACHED */
4099 			}
4100 			break;
4101 		  default:
4102 			usrerr("501 5.5.2 illegal by-mode '%c'", PRTCHAR(*s));
4103 			/* NOTREACHED */
4104 		}
4105 		++s;	/* XXX: spaces allowed? */
4106 		SKIP_SPACE(s);
4107 		switch (tolower(*s))
4108 		{
4109 		  case 't':
4110 			e->e_dlvr_flag |= DLVR_TRACE;
4111 			break;
4112 		  case '\0':
4113 			break;
4114 		  default:
4115 			usrerr("501 5.5.2 illegal by-trace '%c'", PRTCHAR(*s));
4116 			/* NOTREACHED */
4117 		}
4118 
4119 		/* XXX: check whether more characters follow? */
4120 	}
4121 	else
4122 	{
4123 		usrerr("555 5.5.4 %s parameter unrecognized", kp);
4124 		/* NOTREACHED */
4125 	}
4126 }
4127 /*
4128 **  RCPT_ESMTP_ARGS -- process ESMTP arguments from RCPT line
4129 **
4130 **	Parameters:
4131 **		a -- the address corresponding to the To: parameter.
4132 **		kp -- the parameter key.
4133 **		vp -- the value of that parameter.
4134 **		e -- the envelope.
4135 **
4136 **	Returns:
4137 **		none.
4138 */
4139 
4140 static void
4141 rcpt_esmtp_args(a, kp, vp, e)
4142 	ADDRESS *a;
4143 	char *kp;
4144 	char *vp;
4145 	ENVELOPE *e;
4146 {
4147 	if (sm_strcasecmp(kp, "notify") == 0)
4148 	{
4149 		char *p;
4150 
4151 		if (bitset(PRIV_NORECEIPTS, PrivacyFlags))
4152 		{
4153 			usrerr("504 5.7.0 Sorry, NOTIFY not supported, we do not allow DSN");
4154 			/* NOTREACHED */
4155 		}
4156 		if (vp == NULL)
4157 		{
4158 			usrerr("501 5.5.2 NOTIFY requires a value");
4159 			/* NOTREACHED */
4160 		}
4161 		a->q_flags &= ~(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY);
4162 		a->q_flags |= QHASNOTIFY;
4163 		macdefine(&e->e_macro, A_TEMP, macid("{dsn_notify}"), vp);
4164 
4165 		if (sm_strcasecmp(vp, "never") == 0)
4166 			return;
4167 		for (p = vp; p != NULL; vp = p)
4168 		{
4169 			char *s;
4170 
4171 			s = p = strchr(p, ',');
4172 			if (p != NULL)
4173 				*p++ = '\0';
4174 			if (sm_strcasecmp(vp, "success") == 0)
4175 				a->q_flags |= QPINGONSUCCESS;
4176 			else if (sm_strcasecmp(vp, "failure") == 0)
4177 				a->q_flags |= QPINGONFAILURE;
4178 			else if (sm_strcasecmp(vp, "delay") == 0)
4179 				a->q_flags |= QPINGONDELAY;
4180 			else
4181 			{
4182 				usrerr("501 5.5.4 Bad argument \"%s\"  to NOTIFY",
4183 					vp);
4184 				/* NOTREACHED */
4185 			}
4186 			if (s != NULL)
4187 				*s = ',';
4188 		}
4189 	}
4190 	else if (sm_strcasecmp(kp, "orcpt") == 0)
4191 	{
4192 		if (bitset(PRIV_NORECEIPTS, PrivacyFlags))
4193 		{
4194 			usrerr("504 5.7.0 Sorry, ORCPT not supported, we do not allow DSN");
4195 			/* NOTREACHED */
4196 		}
4197 		if (vp == NULL)
4198 		{
4199 			usrerr("501 5.5.2 ORCPT requires a value");
4200 			/* NOTREACHED */
4201 		}
4202 		if (strchr(vp, ';') == NULL || !xtextok(vp))
4203 		{
4204 			usrerr("501 5.5.4 Syntax error in ORCPT parameter value");
4205 			/* NOTREACHED */
4206 		}
4207 		if (a->q_orcpt != NULL)
4208 		{
4209 			usrerr("501 5.5.0 Duplicate ORCPT parameter");
4210 			/* NOTREACHED */
4211 		}
4212 		a->q_orcpt = sm_rpool_strdup_x(e->e_rpool, vp);
4213 	}
4214 	else
4215 	{
4216 		usrerr("555 5.5.4 %s parameter unrecognized", kp);
4217 		/* NOTREACHED */
4218 	}
4219 }
4220 /*
4221 **  PRINTVRFYADDR -- print an entry in the verify queue
4222 **
4223 **	Parameters:
4224 **		a -- the address to print.
4225 **		last -- set if this is the last one.
4226 **		vrfy -- set if this is a VRFY command.
4227 **
4228 **	Returns:
4229 **		none.
4230 **
4231 **	Side Effects:
4232 **		Prints the appropriate 250 codes.
4233 */
4234 #define OFFF	(3 + 1 + 5 + 1)	/* offset in fmt: SMTP reply + enh. code */
4235 
4236 static void
4237 printvrfyaddr(a, last, vrfy)
4238 	register ADDRESS *a;
4239 	bool last;
4240 	bool vrfy;
4241 {
4242 	char fmtbuf[30];
4243 
4244 	if (vrfy && a->q_mailer != NULL &&
4245 	    !bitnset(M_VRFY250, a->q_mailer->m_flags))
4246 		(void) sm_strlcpy(fmtbuf, "252", sizeof fmtbuf);
4247 	else
4248 		(void) sm_strlcpy(fmtbuf, "250", sizeof fmtbuf);
4249 	fmtbuf[3] = last ? ' ' : '-';
4250 	(void) sm_strlcpy(&fmtbuf[4], "2.1.5 ", sizeof fmtbuf - 4);
4251 	if (a->q_fullname == NULL)
4252 	{
4253 		if ((a->q_mailer == NULL ||
4254 		     a->q_mailer->m_addrtype == NULL ||
4255 		     sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4256 		    strchr(a->q_user, '@') == NULL)
4257 			(void) sm_strlcpy(&fmtbuf[OFFF], "<%s@%s>",
4258 				       sizeof fmtbuf - OFFF);
4259 		else
4260 			(void) sm_strlcpy(&fmtbuf[OFFF], "<%s>",
4261 				       sizeof fmtbuf - OFFF);
4262 		message(fmtbuf, a->q_user, MyHostName);
4263 	}
4264 	else
4265 	{
4266 		if ((a->q_mailer == NULL ||
4267 		     a->q_mailer->m_addrtype == NULL ||
4268 		     sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4269 		    strchr(a->q_user, '@') == NULL)
4270 			(void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s@%s>",
4271 				       sizeof fmtbuf - OFFF);
4272 		else
4273 			(void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s>",
4274 				       sizeof fmtbuf - OFFF);
4275 		message(fmtbuf, a->q_fullname, a->q_user, MyHostName);
4276 	}
4277 }
4278 
4279 #if SASL
4280 /*
4281 **  SASLMECHS -- get list of possible AUTH mechanisms
4282 **
4283 **	Parameters:
4284 **		conn -- SASL connection info.
4285 **		mechlist -- output parameter for list of mechanisms.
4286 **
4287 **	Returns:
4288 **		number of mechs.
4289 */
4290 
4291 static int
4292 saslmechs(conn, mechlist)
4293 	sasl_conn_t *conn;
4294 	char **mechlist;
4295 {
4296 	int len, num, result;
4297 
4298 	/* "user" is currently unused */
4299 # if SASL >= 20000
4300 	result = sasl_listmech(conn, NULL,
4301 			       "", " ", "", (const char **) mechlist,
4302 			       (unsigned int *)&len, &num);
4303 # else /* SASL >= 20000 */
4304 	result = sasl_listmech(conn, "user", /* XXX */
4305 			       "", " ", "", mechlist,
4306 			       (unsigned int *)&len, (unsigned int *)&num);
4307 # endif /* SASL >= 20000 */
4308 	if (result != SASL_OK)
4309 	{
4310 		if (LogLevel > 9)
4311 			sm_syslog(LOG_WARNING, NOQID,
4312 				  "AUTH error: listmech=%d, num=%d",
4313 				  result, num);
4314 		num = 0;
4315 	}
4316 	if (num > 0)
4317 	{
4318 		if (LogLevel > 11)
4319 			sm_syslog(LOG_INFO, NOQID,
4320 				  "AUTH: available mech=%s, allowed mech=%s",
4321 				  *mechlist, AuthMechanisms);
4322 		*mechlist = intersect(AuthMechanisms, *mechlist, NULL);
4323 	}
4324 	else
4325 	{
4326 		*mechlist = NULL;	/* be paranoid... */
4327 		if (result == SASL_OK && LogLevel > 9)
4328 			sm_syslog(LOG_WARNING, NOQID,
4329 				  "AUTH warning: no mechanisms");
4330 	}
4331 	return num;
4332 }
4333 
4334 # if SASL >= 20000
4335 /*
4336 **  PROXY_POLICY -- define proxy policy for AUTH
4337 **
4338 **	Parameters:
4339 **		conn -- unused.
4340 **		context -- unused.
4341 **		requested_user -- authorization identity.
4342 **		rlen -- authorization identity length.
4343 **		auth_identity -- authentication identity.
4344 **		alen -- authentication identity length.
4345 **		def_realm -- default user realm.
4346 **		urlen -- user realm length.
4347 **		propctx -- unused.
4348 **
4349 **	Returns:
4350 **		ok?
4351 **
4352 **	Side Effects:
4353 **		sets {auth_authen} macro.
4354 */
4355 
4356 int
4357 proxy_policy(conn, context, requested_user, rlen, auth_identity, alen,
4358 	     def_realm, urlen, propctx)
4359 	sasl_conn_t *conn;
4360 	void *context;
4361 	const char *requested_user;
4362 	unsigned rlen;
4363 	const char *auth_identity;
4364 	unsigned alen;
4365 	const char *def_realm;
4366 	unsigned urlen;
4367 	struct propctx *propctx;
4368 {
4369 	if (auth_identity == NULL)
4370 		return SASL_FAIL;
4371 
4372 	macdefine(&BlankEnvelope.e_macro, A_TEMP,
4373 		  macid("{auth_authen}"), (char *) auth_identity);
4374 
4375 	return SASL_OK;
4376 }
4377 # else /* SASL >= 20000 */
4378 
4379 /*
4380 **  PROXY_POLICY -- define proxy policy for AUTH
4381 **
4382 **	Parameters:
4383 **		context -- unused.
4384 **		auth_identity -- authentication identity.
4385 **		requested_user -- authorization identity.
4386 **		user -- allowed user (output).
4387 **		errstr -- possible error string (output).
4388 **
4389 **	Returns:
4390 **		ok?
4391 */
4392 
4393 int
4394 proxy_policy(context, auth_identity, requested_user, user, errstr)
4395 	void *context;
4396 	const char *auth_identity;
4397 	const char *requested_user;
4398 	const char **user;
4399 	const char **errstr;
4400 {
4401 	if (user == NULL || auth_identity == NULL)
4402 		return SASL_FAIL;
4403 	*user = newstr(auth_identity);
4404 	return SASL_OK;
4405 }
4406 # endif /* SASL >= 20000 */
4407 #endif /* SASL */
4408 
4409 #if STARTTLS
4410 /*
4411 **  INITSRVTLS -- initialize server side TLS
4412 **
4413 **	Parameters:
4414 **		tls_ok -- should tls initialization be done?
4415 **
4416 **	Returns:
4417 **		succeeded?
4418 **
4419 **	Side Effects:
4420 **		sets tls_ok_srv which is a static variable in this module.
4421 **		Do NOT remove assignments to it!
4422 */
4423 
4424 bool
4425 initsrvtls(tls_ok)
4426 	bool tls_ok;
4427 {
4428 	if (!tls_ok)
4429 		return false;
4430 
4431 	/* do NOT remove assignment */
4432 	tls_ok_srv = inittls(&srv_ctx, TLS_Srv_Opts, true, SrvCertFile,
4433 			     SrvKeyFile, CACertPath, CACertFile, DHParams);
4434 	return tls_ok_srv;
4435 }
4436 #endif /* STARTTLS */
4437 /*
4438 **  SRVFEATURES -- get features for SMTP server
4439 **
4440 **	Parameters:
4441 **		e -- envelope (should be session context).
4442 **		clientname -- name of client.
4443 **		features -- default features for this invocation.
4444 **
4445 **	Returns:
4446 **		server features.
4447 */
4448 
4449 /* table with options: it uses just one character, how about strings? */
4450 static struct
4451 {
4452 	char		srvf_opt;
4453 	unsigned int	srvf_flag;
4454 } srv_feat_table[] =
4455 {
4456 	{ 'A',	SRV_OFFER_AUTH	},
4457 	{ 'B',	SRV_OFFER_VERB	},
4458 	{ 'C',	SRV_REQ_SEC	},
4459 	{ 'D',	SRV_OFFER_DSN	},
4460 	{ 'E',	SRV_OFFER_ETRN	},
4461 	{ 'L',	SRV_REQ_AUTH	},
4462 #if PIPELINING
4463 # if _FFR_NO_PIPE
4464 	{ 'N',	SRV_NO_PIPE	},
4465 # endif /* _FFR_NO_PIPE */
4466 	{ 'P',	SRV_OFFER_PIPE	},
4467 #endif /* PIPELINING */
4468 	{ 'R',	SRV_VRFY_CLT	},	/* same as V; not documented */
4469 	{ 'S',	SRV_OFFER_TLS	},
4470 /*	{ 'T',	SRV_TMP_FAIL	},	*/
4471 	{ 'V',	SRV_VRFY_CLT	},
4472 	{ 'X',	SRV_OFFER_EXPN	},
4473 /*	{ 'Y',	SRV_OFFER_VRFY	},	*/
4474 	{ '\0',	SRV_NONE	}
4475 };
4476 
4477 static unsigned int
4478 srvfeatures(e, clientname, features)
4479 	ENVELOPE *e;
4480 	char *clientname;
4481 	unsigned int features;
4482 {
4483 	int r, i, j;
4484 	char **pvp, c, opt;
4485 	char pvpbuf[PSBUFSIZE];
4486 
4487 	pvp = NULL;
4488 	r = rscap("srv_features", clientname, "", e, &pvp, pvpbuf,
4489 		  sizeof(pvpbuf));
4490 	if (r != EX_OK)
4491 		return features;
4492 	if (pvp == NULL || pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
4493 		return features;
4494 	if (pvp[1] != NULL && sm_strncasecmp(pvp[1], "temp", 4) == 0)
4495 		return SRV_TMP_FAIL;
4496 
4497 	/*
4498 	**  General rule (see sendmail.h, d_flags):
4499 	**  lower case: required/offered, upper case: Not required/available
4500 	**
4501 	**  Since we can change some features per daemon, we have both
4502 	**  cases here: turn on/off a feature.
4503 	*/
4504 
4505 	for (i = 1; pvp[i] != NULL; i++)
4506 	{
4507 		c = pvp[i][0];
4508 		j = 0;
4509 		for (;;)
4510 		{
4511 			if ((opt = srv_feat_table[j].srvf_opt) == '\0')
4512 			{
4513 				if (LogLevel > 9)
4514 					sm_syslog(LOG_WARNING, e->e_id,
4515 						  "srvfeatures: unknown feature %s",
4516 						  pvp[i]);
4517 				break;
4518 			}
4519 			if (c == opt)
4520 			{
4521 				features &= ~(srv_feat_table[j].srvf_flag);
4522 				break;
4523 			}
4524 			if (c == tolower(opt))
4525 			{
4526 				features |= srv_feat_table[j].srvf_flag;
4527 				break;
4528 			}
4529 			++j;
4530 		}
4531 	}
4532 	return features;
4533 }
4534 
4535 /*
4536 **  HELP -- implement the HELP command.
4537 **
4538 **	Parameters:
4539 **		topic -- the topic we want help for.
4540 **		e -- envelope.
4541 **
4542 **	Returns:
4543 **		none.
4544 **
4545 **	Side Effects:
4546 **		outputs the help file to message output.
4547 */
4548 #define HELPVSTR	"#vers	"
4549 #define HELPVERSION	2
4550 
4551 void
4552 help(topic, e)
4553 	char *topic;
4554 	ENVELOPE *e;
4555 {
4556 	register SM_FILE_T *hf;
4557 	register char *p;
4558 	int len;
4559 	bool noinfo;
4560 	bool first = true;
4561 	long sff = SFF_OPENASROOT|SFF_REGONLY;
4562 	char buf[MAXLINE];
4563 	char inp[MAXLINE];
4564 	static int foundvers = -1;
4565 	extern char Version[];
4566 
4567 	if (DontLockReadFiles)
4568 		sff |= SFF_NOLOCK;
4569 	if (!bitnset(DBS_HELPFILEINUNSAFEDIRPATH, DontBlameSendmail))
4570 		sff |= SFF_SAFEDIRPATH;
4571 
4572 	if (HelpFile == NULL ||
4573 	    (hf = safefopen(HelpFile, O_RDONLY, 0444, sff)) == NULL)
4574 	{
4575 		/* no help */
4576 		errno = 0;
4577 		message("502 5.3.0 Sendmail %s -- HELP not implemented",
4578 			Version);
4579 		return;
4580 	}
4581 
4582 	if (topic == NULL || *topic == '\0')
4583 	{
4584 		topic = "smtp";
4585 		noinfo = false;
4586 	}
4587 	else
4588 	{
4589 		makelower(topic);
4590 		noinfo = true;
4591 	}
4592 
4593 	len = strlen(topic);
4594 
4595 	while (sm_io_fgets(hf, SM_TIME_DEFAULT, buf, sizeof buf) != NULL)
4596 	{
4597 		if (buf[0] == '#')
4598 		{
4599 			if (foundvers < 0 &&
4600 			    strncmp(buf, HELPVSTR, strlen(HELPVSTR)) == 0)
4601 			{
4602 				int h;
4603 
4604 				if (sm_io_sscanf(buf + strlen(HELPVSTR), "%d",
4605 						 &h) == 1)
4606 					foundvers = h;
4607 			}
4608 			continue;
4609 		}
4610 		if (strncmp(buf, topic, len) == 0)
4611 		{
4612 			if (first)
4613 			{
4614 				first = false;
4615 
4616 				/* print version if no/old vers# in file */
4617 				if (foundvers < 2 && !noinfo)
4618 					message("214-2.0.0 This is Sendmail version %s", Version);
4619 			}
4620 			p = strpbrk(buf, " \t");
4621 			if (p == NULL)
4622 				p = buf + strlen(buf) - 1;
4623 			else
4624 				p++;
4625 			fixcrlf(p, true);
4626 			if (foundvers >= 2)
4627 			{
4628 				translate_dollars(p);
4629 				expand(p, inp, sizeof inp, e);
4630 				p = inp;
4631 			}
4632 			message("214-2.0.0 %s", p);
4633 			noinfo = false;
4634 		}
4635 	}
4636 
4637 	if (noinfo)
4638 		message("504 5.3.0 HELP topic \"%.10s\" unknown", topic);
4639 	else
4640 		message("214 2.0.0 End of HELP info");
4641 
4642 	if (foundvers != 0 && foundvers < HELPVERSION)
4643 	{
4644 		if (LogLevel > 1)
4645 			sm_syslog(LOG_WARNING, e->e_id,
4646 				  "%s too old (require version %d)",
4647 				  HelpFile, HELPVERSION);
4648 
4649 		/* avoid log next time */
4650 		foundvers = 0;
4651 	}
4652 
4653 	(void) sm_io_close(hf, SM_TIME_DEFAULT);
4654 }
4655 
4656 #if SASL
4657 /*
4658 **  RESET_SASLCONN -- reset SASL connection data
4659 **
4660 **	Parameters:
4661 **		conn -- SASL connection context
4662 **		hostname -- host name
4663 **		various connection data
4664 **
4665 **	Returns:
4666 **		SASL result
4667 */
4668 
4669 static int
4670 reset_saslconn(sasl_conn_t **conn, char *hostname,
4671 # if SASL >= 20000
4672 	       char *remoteip, char *localip,
4673 	       char *auth_id, sasl_ssf_t * ext_ssf)
4674 # else /* SASL >= 20000 */
4675 	       struct sockaddr_in *saddr_r, struct sockaddr_in *saddr_l,
4676 	       sasl_external_properties_t * ext_ssf)
4677 # endif /* SASL >= 20000 */
4678 {
4679 	int result;
4680 
4681 	sasl_dispose(conn);
4682 # if SASL >= 20000
4683 	result = sasl_server_new("smtp", hostname, NULL, NULL, NULL,
4684 				 NULL, 0, conn);
4685 # elif SASL > 10505
4686 	/* use empty realm: only works in SASL > 1.5.5 */
4687 	result = sasl_server_new("smtp", hostname, "", NULL, 0, conn);
4688 # else /* SASL >= 20000 */
4689 	/* use no realm -> realm is set to hostname by SASL lib */
4690 	result = sasl_server_new("smtp", hostname, NULL, NULL, 0,
4691 				 conn);
4692 # endif /* SASL >= 20000 */
4693 	if (result != SASL_OK)
4694 		return result;
4695 
4696 # if SASL >= 20000
4697 #  if NETINET || NETINET6
4698 	if (remoteip != NULL && *remoteip != '\0')
4699 		result = sasl_setprop(*conn, SASL_IPREMOTEPORT, remoteip);
4700 	if (result != SASL_OK)
4701 		return result;
4702 
4703 	if (localip != NULL && *localip != '\0')
4704 		result = sasl_setprop(*conn, SASL_IPLOCALPORT, localip);
4705 	if (result != SASL_OK)
4706 		return result;
4707 #  endif /* NETINET || NETINET6 */
4708 
4709 	result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
4710 	if (result != SASL_OK)
4711 		return result;
4712 
4713 	result = sasl_setprop(*conn, SASL_AUTH_EXTERNAL, auth_id);
4714 	if (result != SASL_OK)
4715 		return result;
4716 # else /* SASL >= 20000 */
4717 #  if NETINET
4718 	if (saddr_r != NULL)
4719 		result = sasl_setprop(*conn, SASL_IP_REMOTE, saddr_r);
4720 	if (result != SASL_OK)
4721 		return result;
4722 
4723 	if (saddr_l != NULL)
4724 		result = sasl_setprop(*conn, SASL_IP_LOCAL, saddr_l);
4725 	if (result != SASL_OK)
4726 		return result;
4727 #  endif /* NETINET */
4728 
4729 	result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
4730 	if (result != SASL_OK)
4731 		return result;
4732 # endif /* SASL >= 20000 */
4733 	return SASL_OK;
4734 }
4735 #endif /* SASL */
4736