1/*
2 * Copyright (c) 1999-2009, 2012, 2013 Proofpoint, Inc. and its suppliers.
3 *	All rights reserved.
4 *
5 * By using this file, you agree to the terms and conditions set
6 * forth in the LICENSE file which can be found at the top level of
7 * the sendmail distribution.
8 *
9 */
10
11#include <sendmail.h>
12
13SM_RCSID("@(#)$Id: milter.c,v 8.281 2013-11-22 20:51:56 ca Exp $")
14
15#if MILTER
16# include <sm/sendmail.h>
17# include <libmilter/mfapi.h>
18# include <libmilter/mfdef.h>
19
20# include <errno.h>
21# include <sm/time.h>
22# include <sys/uio.h>
23
24# if NETINET || NETINET6
25#  include <arpa/inet.h>
26#  if MILTER_NO_NAGLE
27#   include <netinet/tcp.h>
28#  endif /* MILTER_NO_NAGLE */
29# endif /* NETINET || NETINET6 */
30
31# include <sm/fdset.h>
32
33static void	milter_connect_timeout __P((int));
34static void	milter_error __P((struct milter *, ENVELOPE *));
35static int	milter_open __P((struct milter *, bool, ENVELOPE *));
36static void	milter_parse_timeouts __P((char *, struct milter *));
37static char	*milter_sysread __P((struct milter *, char *, ssize_t, time_t,
38			ENVELOPE *, const char *));
39static char	*milter_read __P((struct milter *, char *, ssize_t *, time_t,
40			ENVELOPE *, const char *));
41static char	*milter_write __P((struct milter *, int, char *, ssize_t,
42			time_t, ENVELOPE *, const char *));
43static char	*milter_send_command __P((struct milter *, int, void *,
44			ssize_t, ENVELOPE *, char *, const char *));
45static char	*milter_command __P((int, void *, ssize_t, int,
46			ENVELOPE *, char *, const char *, bool));
47static char	*milter_body __P((struct milter *, ENVELOPE *, char *));
48static int	milter_reopen_df __P((ENVELOPE *));
49static int	milter_reset_df __P((ENVELOPE *));
50static void	milter_quit_filter __P((struct milter *, ENVELOPE *));
51static void	milter_abort_filter __P((struct milter *, ENVELOPE *));
52static void	milter_send_macros __P((struct milter *, char **, int,
53			ENVELOPE *));
54static int	milter_negotiate __P((struct milter *, ENVELOPE *,
55			milters_T *));
56static void	milter_per_connection_check __P((ENVELOPE *));
57static char	*milter_headers __P((struct milter *, ENVELOPE *, char *));
58static void	milter_addheader __P((struct milter *, char *, ssize_t,
59			ENVELOPE *));
60static void	milter_insheader __P((struct milter *, char *, ssize_t,
61			ENVELOPE *));
62static void	milter_changeheader __P((struct milter *, char *, ssize_t,
63			ENVELOPE *));
64static void	milter_chgfrom __P((char *, ssize_t, ENVELOPE *));
65static void	milter_addrcpt __P((char *, ssize_t, ENVELOPE *));
66static void	milter_addrcpt_par __P((char *, ssize_t, ENVELOPE *));
67static void	milter_delrcpt __P((char *, ssize_t, ENVELOPE *));
68static int	milter_replbody __P((char *, ssize_t, bool, ENVELOPE *));
69static int	milter_set_macros __P((char *, char **, char *, int));
70
71
72/* milter states */
73# define SMFS_CLOSED		'C'	/* closed for all further actions */
74# define SMFS_OPEN		'O'	/* connected to remote milter filter */
75# define SMFS_INMSG		'M'	/* currently servicing a message */
76# define SMFS_DONE		'D'	/* done with current message */
77# define SMFS_CLOSABLE		'Q'	/* done with current connection */
78# define SMFS_ERROR		'E'	/* error state */
79# define SMFS_READY		'R'	/* ready for action */
80# define SMFS_SKIP		'S'	/* skip body */
81
82/*
83**  MilterMacros contains the milter macros for each milter and each stage.
84**  indices are (in order): stages, milter-index, macro
85**  milter-index == 0: "global" macros (not for a specific milter).
86*/
87
88static char *MilterMacros[SMFIM_LAST + 1][MAXFILTERS + 1][MAXFILTERMACROS + 1];
89static size_t MilterMaxDataSize = MILTER_MAX_DATA_SIZE;
90
91# define MILTER_CHECK_DONE_MSG() \
92	if (*state == SMFIR_REPLYCODE || \
93	    *state == SMFIR_REJECT || \
94	    *state == SMFIR_DISCARD || \
95	    *state == SMFIR_TEMPFAIL) \
96	{ \
97		/* Abort the filters to let them know we are done with msg */ \
98		milter_abort(e); \
99	}
100
101/* set state in case of an error */
102# define MILTER_SET_STATE	\
103	if (bitnset(SMF_TEMPFAIL, m->mf_flags)) \
104		*state = SMFIR_TEMPFAIL; \
105	else if (bitnset(SMF_TEMPDROP, m->mf_flags)) \
106		*state = SMFIR_SHUTDOWN; \
107	else if (bitnset(SMF_REJECT, m->mf_flags)) \
108		*state = SMFIR_REJECT
109
110/* flow through code maybe using continue; don't wrap in do {} while */
111# define MILTER_CHECK_ERROR(initial, action) \
112	if (!initial && tTd(71, 100)) \
113	{ \
114		if (e->e_quarmsg == NULL) \
115		{ \
116			e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \
117							 "filter failure"); \
118			macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \
119				  e->e_quarmsg); \
120		} \
121	} \
122	else if (tTd(71, 101)) \
123	{ \
124		if (e->e_quarmsg == NULL) \
125		{ \
126			e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \
127							 "filter failure"); \
128			macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \
129				  e->e_quarmsg); \
130		} \
131	} \
132	else MILTER_SET_STATE;	\
133	else \
134		action;
135
136# define MILTER_CHECK_REPLYCODE(default) \
137	if (response == NULL || \
138	    strlen(response) + 1 != (size_t) rlen || \
139	    rlen < 3 || \
140	    (response[0] != '4' && response[0] != '5') || \
141	    !isascii(response[1]) || !isdigit(response[1]) || \
142	    !isascii(response[2]) || !isdigit(response[2])) \
143	{ \
144		if (response != NULL) \
145			sm_free(response); /* XXX */ \
146		response = newstr(default); \
147	} \
148	else \
149	{ \
150		char *ptr = response; \
151 \
152		/* Check for unprotected %'s in the string */ \
153		while (*ptr != '\0') \
154		{ \
155			if (*ptr == '%' && *++ptr != '%') \
156			{ \
157				sm_free(response); /* XXX */ \
158				response = newstr(default); \
159				break; \
160			} \
161			ptr++; \
162		} \
163	}
164
165# define MILTER_DF_ERROR(msg) \
166{ \
167	int save_errno = errno; \
168 \
169	if (tTd(64, 5)) \
170	{ \
171		sm_dprintf(msg, dfname, sm_errstring(save_errno)); \
172		sm_dprintf("\n"); \
173	} \
174	if (MilterLogLevel > 0) \
175		sm_syslog(LOG_ERR, e->e_id, msg, dfname, sm_errstring(save_errno)); \
176	if (SuperSafe == SAFE_REALLY) \
177	{ \
178		if (e->e_dfp != NULL) \
179		{ \
180			(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT); \
181			e->e_dfp = NULL; \
182		} \
183		e->e_flags &= ~EF_HAS_DF; \
184	} \
185	errno = save_errno; \
186}
187
188/*
189**  MILTER_TIMEOUT -- make sure socket is ready in time
190**
191**	Parameters:
192**		routine -- routine name for debug/logging
193**		secs -- number of seconds in timeout
194**		write -- waiting to read or write?
195**		started -- whether this is part of a previous sequence
196**
197**	Assumes 'm' is a milter structure for the current socket.
198*/
199
200# define MILTER_TIMEOUT(routine, secs, write, started, function) \
201{ \
202	int ret; \
203	int save_errno; \
204	fd_set fds; \
205	struct timeval tv; \
206 \
207	if (!SM_FD_OK_SELECT(m->mf_sock)) \
208	{ \
209		if (tTd(64, 5)) \
210			sm_dprintf("milter_%s(%s): socket %d is larger than FD_SETSIZE %d\n", \
211				   (routine), m->mf_name, m->mf_sock, \
212				   SM_FD_SETSIZE); \
213		if (MilterLogLevel > 0) \
214			sm_syslog(LOG_ERR, e->e_id, \
215				  "Milter (%s): socket(%s) %d is larger than FD_SETSIZE %d", \
216				  m->mf_name, (routine), m->mf_sock, \
217				  SM_FD_SETSIZE); \
218		milter_error(m, e); \
219		return NULL; \
220	} \
221 \
222	do \
223	{ \
224		FD_ZERO(&fds); \
225		SM_FD_SET(m->mf_sock, &fds); \
226		tv.tv_sec = (secs); \
227		tv.tv_usec = 0; \
228		ret = select(m->mf_sock + 1, \
229			     (write) ? NULL : &fds, \
230			     (write) ? &fds : NULL, \
231			     NULL, &tv); \
232	} while (ret < 0 && errno == EINTR); \
233 \
234	switch (ret) \
235	{ \
236	  case 0: \
237		if (tTd(64, 5)) \
238			sm_dprintf("milter_%s(%s): timeout, where=%s\n", \
239				(routine), m->mf_name, (function)); \
240		if (MilterLogLevel > 0) \
241			sm_syslog(LOG_ERR, e->e_id, \
242				  "Milter (%s): timeout %s data %s, where=%s", \
243				  m->mf_name, \
244				  started ? "during" : "before", \
245				  (routine), (function)); \
246		milter_error(m, e); \
247		return NULL; \
248 \
249	  case -1: \
250		save_errno = errno; \
251		if (tTd(64, 5)) \
252			sm_dprintf("milter_%s(%s): select: %s\n", (routine), \
253				   m->mf_name, sm_errstring(save_errno)); \
254		if (MilterLogLevel > 0) \
255		{ \
256			sm_syslog(LOG_ERR, e->e_id, \
257				  "Milter (%s): select(%s): %s", \
258				  m->mf_name, (routine), \
259				  sm_errstring(save_errno)); \
260		} \
261		milter_error(m, e); \
262		return NULL; \
263 \
264	  default: \
265		if (SM_FD_ISSET(m->mf_sock, &fds)) \
266			break; \
267		if (tTd(64, 5)) \
268			sm_dprintf("milter_%s(%s): socket not ready\n", \
269				(routine), m->mf_name); \
270		if (MilterLogLevel > 0) \
271		{ \
272			sm_syslog(LOG_ERR, e->e_id, \
273				  "Milter (%s): socket(%s) not ready", \
274				  m->mf_name, (routine)); \
275		} \
276		milter_error(m, e); \
277		return NULL; \
278	} \
279}
280
281/*
282**  Low level functions
283*/
284
285/*
286**  MILTER_READ -- read from a remote milter filter
287**
288**	Parameters:
289**		m -- milter to read from.
290**		cmd -- return param for command read.
291**		rlen -- return length of response string.
292**		to -- timeout in seconds.
293**		e -- current envelope.
294**
295**	Returns:
296**		response string (may be NULL)
297*/
298
299static char *
300milter_sysread(m, buf, sz, to, e, where)
301	struct milter *m;
302	char *buf;
303	ssize_t sz;
304	time_t to;
305	ENVELOPE *e;
306	const char *where;
307{
308	time_t readstart = 0;
309	ssize_t len, curl;
310	bool started = false;
311
312	curl = 0;
313
314	if (to > 0)
315		readstart = curtime();
316
317	for (;;)
318	{
319		if (to > 0)
320		{
321			time_t now;
322
323			now = curtime();
324			if (now - readstart >= to)
325			{
326				if (tTd(64, 5))
327					sm_dprintf("milter_sys_read (%s): timeout %s data read in %s",
328						  m->mf_name,
329						  started ? "during" : "before",
330						  where);
331				if (MilterLogLevel > 0)
332					sm_syslog(LOG_ERR, e->e_id,
333						  "Milter (%s): timeout %s data read in %s",
334						  m->mf_name,
335						  started ? "during" : "before",
336						  where);
337				milter_error(m, e);
338				return NULL;
339			}
340			to -= now - readstart;
341			readstart = now;
342			MILTER_TIMEOUT("read", to, false, started, where);
343		}
344
345		len = read(m->mf_sock, buf + curl, sz - curl);
346
347		if (len < 0)
348		{
349			int save_errno = errno;
350
351			if (tTd(64, 5))
352				sm_dprintf("milter_sys_read(%s): read returned %ld: %s\n",
353					m->mf_name, (long) len,
354					sm_errstring(save_errno));
355			if (MilterLogLevel > 0)
356				sm_syslog(LOG_ERR, e->e_id,
357					  "Milter (%s): read returned %ld: %s",
358					  m->mf_name, (long) len,
359					  sm_errstring(save_errno));
360			milter_error(m, e);
361			return NULL;
362		}
363
364		started = true;
365		curl += len;
366		if (len == 0 || curl >= sz)
367			break;
368
369	}
370
371	if (curl != sz)
372	{
373		if (tTd(64, 5))
374			sm_dprintf("milter_sys_read(%s): cmd read returned %ld, expecting %ld\n",
375				m->mf_name, (long) curl, (long) sz);
376		if (MilterLogLevel > 0)
377			sm_syslog(LOG_ERR, e->e_id,
378				  "milter_sys_read(%s): cmd read returned %ld, expecting %ld",
379				  m->mf_name, (long) curl, (long) sz);
380		milter_error(m, e);
381		return NULL;
382	}
383	return buf;
384}
385
386static char *
387milter_read(m, cmd, rlen, to, e, where)
388	struct milter *m;
389	char *cmd;
390	ssize_t *rlen;
391	time_t to;
392	ENVELOPE *e;
393	const char *where;
394{
395	time_t readstart = 0;
396	ssize_t expl;
397	mi_int32 i;
398# if MILTER_NO_NAGLE && defined(TCP_CORK)
399	int cork = 0;
400# endif /* MILTER_NO_NAGLE && defined(TCP_CORK) */
401	char *buf;
402	char data[MILTER_LEN_BYTES + 1];
403
404	if (m->mf_sock < 0)
405	{
406		if (MilterLogLevel > 0)
407			sm_syslog(LOG_ERR, e->e_id,
408				  "milter_read(%s): socket closed, where=%s",
409				  m->mf_name, where);
410		milter_error(m, e);
411		return NULL;
412	}
413
414	*rlen = 0;
415	*cmd = '\0';
416
417	if (to > 0)
418		readstart = curtime();
419
420# if MILTER_NO_NAGLE && defined(TCP_CORK)
421	setsockopt(m->mf_sock, IPPROTO_TCP, TCP_CORK, (char *)&cork,
422		   sizeof(cork));
423# endif /* MILTER_NO_NAGLE && defined(TCP_CORK) */
424
425	if (milter_sysread(m, data, sizeof(data), to, e, where) == NULL)
426		return NULL;
427
428# if MILTER_NO_NAGLE && defined(TCP_CORK)
429	cork = 1;
430	setsockopt(m->mf_sock, IPPROTO_TCP, TCP_CORK, (char *)&cork,
431		   sizeof(cork));
432# endif /* MILTER_NO_NAGLE && defined(TCP_CORK) */
433
434	/* reset timeout */
435	if (to > 0)
436	{
437		time_t now;
438
439		now = curtime();
440		if (now - readstart >= to)
441		{
442			if (tTd(64, 5))
443				sm_dprintf("milter_read(%s): timeout before data read, where=%s\n",
444					m->mf_name, where);
445			if (MilterLogLevel > 0)
446				sm_syslog(LOG_ERR, e->e_id,
447					  "Milter read(%s): timeout before data read, where=%s",
448					  m->mf_name, where);
449			milter_error(m, e);
450			return NULL;
451		}
452		to -= now - readstart;
453	}
454
455	*cmd = data[MILTER_LEN_BYTES];
456	data[MILTER_LEN_BYTES] = '\0';
457	(void) memcpy(&i, data, MILTER_LEN_BYTES);
458	expl = ntohl(i) - 1;
459
460	if (tTd(64, 25))
461		sm_dprintf("milter_read(%s): expecting %ld bytes\n",
462			m->mf_name, (long) expl);
463
464	if (expl < 0)
465	{
466		if (tTd(64, 5))
467			sm_dprintf("milter_read(%s): read size %ld out of range, where=%s\n",
468				m->mf_name, (long) expl, where);
469		if (MilterLogLevel > 0)
470			sm_syslog(LOG_ERR, e->e_id,
471				  "milter_read(%s): read size %ld out of range, where=%s",
472				  m->mf_name, (long) expl, where);
473		milter_error(m, e);
474		return NULL;
475	}
476
477	if (expl == 0)
478		return NULL;
479
480	buf = (char *) xalloc(expl);
481
482	if (milter_sysread(m, buf, expl, to, e, where) == NULL)
483	{
484		sm_free(buf); /* XXX */
485		return NULL;
486	}
487
488	if (tTd(64, 50))
489		sm_dprintf("milter_read(%s): Returning %*s\n",
490			m->mf_name, (int) expl, buf);
491	*rlen = expl;
492	return buf;
493}
494
495/*
496**  MILTER_WRITE -- write to a remote milter filter
497**
498**	Parameters:
499**		m -- milter to read from.
500**		cmd -- command to send.
501**		buf -- optional command data.
502**		len -- length of buf.
503**		to -- timeout in seconds.
504**		e -- current envelope.
505**
506**	Returns:
507**		buf if successful, NULL otherwise
508**		Not actually used anywhere but function prototype
509**			must match milter_read()
510*/
511
512static char *
513milter_write(m, cmd, buf, len, to, e, where)
514	struct milter *m;
515	int cmd;
516	char *buf;
517	ssize_t len;
518	time_t to;
519	ENVELOPE *e;
520	const char *where;
521{
522	ssize_t sl, i;
523	int num_vectors;
524	mi_int32 nl;
525	char command = (char) cmd;
526	char data[MILTER_LEN_BYTES + 1];
527	bool started = false;
528	struct iovec vector[2];
529
530	/*
531	**  At most two buffers will be written, though
532	**  only one may actually be used (see num_vectors).
533	**  The first is the size/command and the second is the command data.
534	*/
535
536	if (len < 0 || len > MilterMaxDataSize)
537	{
538		if (tTd(64, 5))
539		{
540			sm_dprintf("milter_write(%s): length %ld out of range, cmd=%c\n",
541				m->mf_name, (long) len, command);
542			sm_dprintf("milter_write(%s): buf=%s\n",
543				m->mf_name, str2prt(buf));
544		}
545		if (MilterLogLevel > 0)
546			sm_syslog(LOG_ERR, e->e_id,
547				  "milter_write(%s): length %ld out of range, cmd=%c",
548				  m->mf_name, (long) len, command);
549		milter_error(m, e);
550		return NULL;
551	}
552	if (m->mf_sock < 0)
553	{
554		if (MilterLogLevel > 0)
555			sm_syslog(LOG_ERR, e->e_id,
556				  "milter_write(%s): socket closed",
557				  m->mf_name);
558		milter_error(m, e);
559		return NULL;
560	}
561
562	if (tTd(64, 20))
563		sm_dprintf("milter_write(%s): cmd %c, len %ld\n",
564			   m->mf_name, command, (long) len);
565
566	nl = htonl(len + 1);	/* add 1 for the command char */
567	(void) memcpy(data, (char *) &nl, MILTER_LEN_BYTES);
568	data[MILTER_LEN_BYTES] = command;
569	sl = MILTER_LEN_BYTES + 1;
570
571	/* set up the vector for the size / command */
572	vector[0].iov_base = (void *) data;
573	vector[0].iov_len  = sl;
574
575	/*
576	**  Determine if there is command data.  If so, there will be two
577	**  vectors.  If not, there will be only one.  The vectors are set
578	**  up here and 'num_vectors' and 'sl' are set appropriately.
579	*/
580
581	/* NOTE:  len<0 has already been checked for.  Pedantic */
582	if (len <= 0 || buf == NULL)
583	{
584		/* There is no command data -- only a size / command data */
585		num_vectors = 1;
586	}
587	else
588	{
589		/*
590		**  There is both size / command and command data.
591		**  Set up the vector for the command data.
592		*/
593
594		num_vectors = 2;
595		sl += len;
596		vector[1].iov_base = (void *) buf;
597		vector[1].iov_len  = len;
598
599		if (tTd(64, 50))
600			sm_dprintf("milter_write(%s): Sending %*s\n",
601				   m->mf_name, (int) len, buf);
602	}
603
604	if (to > 0)
605		MILTER_TIMEOUT("write", to, true, started, where);
606
607	/* write the vector(s) */
608	i = writev(m->mf_sock, vector, num_vectors);
609	if (i != sl)
610	{
611		int save_errno = errno;
612
613		if (tTd(64, 5))
614			sm_dprintf("milter_write(%s): write(%c) returned %ld, expected %ld: %s\n",
615				   m->mf_name, command, (long) i, (long) sl,
616				   sm_errstring(save_errno));
617		if (MilterLogLevel > 0)
618			sm_syslog(LOG_ERR, e->e_id,
619				  "Milter (%s): write(%c) returned %ld, expected %ld: %s",
620				  m->mf_name, command, (long) i, (long) sl,
621				  sm_errstring(save_errno));
622		milter_error(m, e);
623		return NULL;
624	}
625	return buf;
626}
627
628/*
629**  Utility functions
630*/
631
632/*
633**  MILTER_OPEN -- connect to remote milter filter
634**
635**	Parameters:
636**		m -- milter to connect to.
637**		parseonly -- parse but don't connect.
638**		e -- current envelope.
639**
640**	Returns:
641**		connected socket if successful && !parseonly,
642**		0 upon parse success if parseonly,
643**		-1 otherwise.
644*/
645
646static jmp_buf	MilterConnectTimeout;
647
648static int
649milter_open(m, parseonly, e)
650	struct milter *m;
651	bool parseonly;
652	ENVELOPE *e;
653{
654	int sock = 0;
655	SOCKADDR_LEN_T addrlen = 0;
656	int addrno = 0;
657	int save_errno;
658	char *p;
659	char *colon;
660	char *at;
661	struct hostent *hp = NULL;
662	SOCKADDR addr;
663
664	if (m->mf_conn == NULL || m->mf_conn[0] == '\0')
665	{
666		if (tTd(64, 5))
667			sm_dprintf("X%s: empty or missing socket information\n",
668				   m->mf_name);
669		if (parseonly)
670			syserr("X%s: empty or missing socket information",
671			       m->mf_name);
672		else if (MilterLogLevel > 0)
673			sm_syslog(LOG_ERR, e->e_id,
674				  "Milter (%s): empty or missing socket information",
675				  m->mf_name);
676		milter_error(m, e);
677		return -1;
678	}
679
680	/* protocol:filename or protocol:port@host */
681	memset(&addr, '\0', sizeof(addr));
682	p = m->mf_conn;
683	colon = strchr(p, ':');
684	if (colon != NULL)
685	{
686		*colon = '\0';
687
688		if (*p == '\0')
689		{
690# if NETUNIX
691			/* default to AF_UNIX */
692			addr.sa.sa_family = AF_UNIX;
693# else /* NETUNIX */
694#  if NETINET
695			/* default to AF_INET */
696			addr.sa.sa_family = AF_INET;
697#  else /* NETINET */
698#   if NETINET6
699			/* default to AF_INET6 */
700			addr.sa.sa_family = AF_INET6;
701#   else /* NETINET6 */
702			/* no protocols available */
703			if (MilterLogLevel > 0)
704				sm_syslog(LOG_ERR, e->e_id,
705					  "Milter (%s): no valid socket protocols available",
706					  m->mf_name);
707			milter_error(m, e);
708			return -1;
709#   endif /* NETINET6 */
710#  endif /* NETINET */
711# endif /* NETUNIX */
712		}
713# if NETUNIX
714		else if (sm_strcasecmp(p, "unix") == 0 ||
715			 sm_strcasecmp(p, "local") == 0)
716			addr.sa.sa_family = AF_UNIX;
717# endif /* NETUNIX */
718# if NETINET
719		else if (sm_strcasecmp(p, "inet") == 0)
720			addr.sa.sa_family = AF_INET;
721# endif /* NETINET */
722# if NETINET6
723		else if (sm_strcasecmp(p, "inet6") == 0)
724			addr.sa.sa_family = AF_INET6;
725# endif /* NETINET6 */
726		else
727		{
728# ifdef EPROTONOSUPPORT
729			errno = EPROTONOSUPPORT;
730# else /* EPROTONOSUPPORT */
731			errno = EINVAL;
732# endif /* EPROTONOSUPPORT */
733			if (tTd(64, 5))
734				sm_dprintf("X%s: unknown socket type %s\n",
735					m->mf_name, p);
736			if (parseonly)
737				syserr("X%s: unknown socket type %s",
738				       m->mf_name, p);
739			else if (MilterLogLevel > 0)
740				sm_syslog(LOG_ERR, e->e_id,
741					  "Milter (%s): unknown socket type %s",
742					  m->mf_name, p);
743			milter_error(m, e);
744			return -1;
745		}
746		*colon++ = ':';
747	}
748	else
749	{
750		/* default to AF_UNIX */
751		addr.sa.sa_family = AF_UNIX;
752		colon = p;
753	}
754
755# if NETUNIX
756	if (addr.sa.sa_family == AF_UNIX)
757	{
758		long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_EXECOK;
759
760		at = colon;
761		if (strlen(colon) >= sizeof(addr.sunix.sun_path))
762		{
763			if (tTd(64, 5))
764				sm_dprintf("X%s: local socket name %s too long\n",
765					m->mf_name, colon);
766			errno = EINVAL;
767			if (parseonly)
768				syserr("X%s: local socket name %s too long",
769				       m->mf_name, colon);
770			else if (MilterLogLevel > 0)
771				sm_syslog(LOG_ERR, e->e_id,
772					  "Milter (%s): local socket name %s too long",
773					  m->mf_name, colon);
774			milter_error(m, e);
775			return -1;
776		}
777		errno = safefile(colon, RunAsUid, RunAsGid, RunAsUserName, sff,
778				 S_IRUSR|S_IWUSR, NULL);
779
780		/* if just parsing .cf file, socket doesn't need to exist */
781		if (parseonly && errno == ENOENT)
782		{
783			if (OpMode == MD_DAEMON ||
784			    OpMode == MD_FGDAEMON)
785				(void) sm_io_fprintf(smioerr, SM_TIME_DEFAULT,
786						     "WARNING: X%s: local socket name %s missing\n",
787						     m->mf_name, colon);
788		}
789		else if (errno != 0)
790		{
791			/* if not safe, don't create */
792			save_errno = errno;
793			if (tTd(64, 5))
794				sm_dprintf("X%s: local socket name %s unsafe\n",
795					m->mf_name, colon);
796			errno = save_errno;
797			if (parseonly)
798			{
799				if (OpMode == MD_DAEMON ||
800				    OpMode == MD_FGDAEMON ||
801				    OpMode == MD_SMTP)
802					syserr("X%s: local socket name %s unsafe",
803					       m->mf_name, colon);
804			}
805			else if (MilterLogLevel > 0)
806				sm_syslog(LOG_ERR, e->e_id,
807					  "Milter (%s): local socket name %s unsafe",
808					  m->mf_name, colon);
809			milter_error(m, e);
810			return -1;
811		}
812
813		(void) sm_strlcpy(addr.sunix.sun_path, colon,
814			       sizeof(addr.sunix.sun_path));
815		addrlen = sizeof(struct sockaddr_un);
816	}
817	else
818# endif /* NETUNIX */
819# if NETINET || NETINET6
820	if (false
821#  if NETINET
822		 || addr.sa.sa_family == AF_INET
823#  endif /* NETINET */
824#  if NETINET6
825		 || addr.sa.sa_family == AF_INET6
826#  endif /* NETINET6 */
827		 )
828	{
829		unsigned short port;
830
831		/* Parse port@host */
832		at = strchr(colon, '@');
833		if (at == NULL)
834		{
835			if (tTd(64, 5))
836				sm_dprintf("X%s: bad address %s (expected port@host)\n",
837					m->mf_name, colon);
838			if (parseonly)
839				syserr("X%s: bad address %s (expected port@host)",
840				       m->mf_name, colon);
841			else if (MilterLogLevel > 0)
842				sm_syslog(LOG_ERR, e->e_id,
843					  "Milter (%s): bad address %s (expected port@host)",
844					  m->mf_name, colon);
845			milter_error(m, e);
846			return -1;
847		}
848		*at = '\0';
849		if (isascii(*colon) && isdigit(*colon))
850			port = htons((unsigned short) atoi(colon));
851		else
852		{
853#  ifdef NO_GETSERVBYNAME
854			if (tTd(64, 5))
855				sm_dprintf("X%s: invalid port number %s\n",
856					m->mf_name, colon);
857			if (parseonly)
858				syserr("X%s: invalid port number %s",
859				       m->mf_name, colon);
860			else if (MilterLogLevel > 0)
861				sm_syslog(LOG_ERR, e->e_id,
862					  "Milter (%s): invalid port number %s",
863					  m->mf_name, colon);
864			milter_error(m, e);
865			return -1;
866#  else /* NO_GETSERVBYNAME */
867			struct servent *sp;
868
869			sp = getservbyname(colon, "tcp");
870			if (sp == NULL)
871			{
872				save_errno = errno;
873				if (tTd(64, 5))
874					sm_dprintf("X%s: unknown port name %s\n",
875						m->mf_name, colon);
876				errno = save_errno;
877				if (parseonly)
878					syserr("X%s: unknown port name %s",
879					       m->mf_name, colon);
880				else if (MilterLogLevel > 0)
881					sm_syslog(LOG_ERR, e->e_id,
882						  "Milter (%s): unknown port name %s",
883						  m->mf_name, colon);
884				milter_error(m, e);
885				return -1;
886			}
887			port = sp->s_port;
888#  endif /* NO_GETSERVBYNAME */
889		}
890		*at++ = '@';
891		if (*at == '[')
892		{
893			char *end;
894
895			end = strchr(at, ']');
896			if (end != NULL)
897			{
898				bool found = false;
899#  if NETINET
900				unsigned long hid = INADDR_NONE;
901#  endif /* NETINET */
902#  if NETINET6
903				struct sockaddr_in6 hid6;
904#  endif /* NETINET6 */
905
906				*end = '\0';
907#  if NETINET
908				if (addr.sa.sa_family == AF_INET &&
909				    (hid = inet_addr(&at[1])) != INADDR_NONE)
910				{
911					addr.sin.sin_addr.s_addr = hid;
912					addr.sin.sin_port = port;
913					found = true;
914				}
915#  endif /* NETINET */
916#  if NETINET6
917				(void) memset(&hid6, '\0', sizeof(hid6));
918				if (addr.sa.sa_family == AF_INET6 &&
919				    anynet_pton(AF_INET6, &at[1],
920						&hid6.sin6_addr) == 1)
921				{
922					addr.sin6.sin6_addr = hid6.sin6_addr;
923					addr.sin6.sin6_port = port;
924					found = true;
925				}
926#  endif /* NETINET6 */
927				*end = ']';
928				if (!found)
929				{
930					if (tTd(64, 5))
931						sm_dprintf("X%s: Invalid numeric domain spec \"%s\"\n",
932							m->mf_name, at);
933					if (parseonly)
934						syserr("X%s: Invalid numeric domain spec \"%s\"",
935						       m->mf_name, at);
936					else if (MilterLogLevel > 0)
937						sm_syslog(LOG_ERR, e->e_id,
938							  "Milter (%s): Invalid numeric domain spec \"%s\"",
939							  m->mf_name, at);
940					milter_error(m, e);
941					return -1;
942				}
943			}
944			else
945			{
946				if (tTd(64, 5))
947					sm_dprintf("X%s: Invalid numeric domain spec \"%s\"\n",
948						m->mf_name, at);
949				if (parseonly)
950					syserr("X%s: Invalid numeric domain spec \"%s\"",
951					       m->mf_name, at);
952				else if (MilterLogLevel > 0)
953					sm_syslog(LOG_ERR, e->e_id,
954						  "Milter (%s): Invalid numeric domain spec \"%s\"",
955						  m->mf_name, at);
956				milter_error(m, e);
957				return -1;
958			}
959		}
960		else
961		{
962			hp = sm_gethostbyname(at, addr.sa.sa_family);
963			if (hp == NULL)
964			{
965				save_errno = errno;
966				if (tTd(64, 5))
967					sm_dprintf("X%s: Unknown host name %s\n",
968						   m->mf_name, at);
969				errno = save_errno;
970				if (parseonly)
971					syserr("X%s: Unknown host name %s",
972					       m->mf_name, at);
973				else if (MilterLogLevel > 0)
974					sm_syslog(LOG_ERR, e->e_id,
975						  "Milter (%s): Unknown host name %s",
976						  m->mf_name, at);
977				milter_error(m, e);
978				return -1;
979			}
980			addr.sa.sa_family = hp->h_addrtype;
981			switch (hp->h_addrtype)
982			{
983#  if NETINET
984			  case AF_INET:
985				memmove(&addr.sin.sin_addr,
986					hp->h_addr, INADDRSZ);
987				addr.sin.sin_port = port;
988				addrlen = sizeof(struct sockaddr_in);
989				addrno = 1;
990				break;
991#  endif /* NETINET */
992
993#  if NETINET6
994			  case AF_INET6:
995				memmove(&addr.sin6.sin6_addr,
996					hp->h_addr, IN6ADDRSZ);
997				addr.sin6.sin6_port = port;
998				addrlen = sizeof(struct sockaddr_in6);
999				addrno = 1;
1000				break;
1001#  endif /* NETINET6 */
1002
1003			  default:
1004				if (tTd(64, 5))
1005					sm_dprintf("X%s: Unknown protocol for %s (%d)\n",
1006						   m->mf_name, at,
1007						   hp->h_addrtype);
1008				if (parseonly)
1009					syserr("X%s: Unknown protocol for %s (%d)",
1010					       m->mf_name, at, hp->h_addrtype);
1011				else if (MilterLogLevel > 0)
1012					sm_syslog(LOG_ERR, e->e_id,
1013						  "Milter (%s): Unknown protocol for %s (%d)",
1014						  m->mf_name, at,
1015						  hp->h_addrtype);
1016				milter_error(m, e);
1017#  if NETINET6
1018				freehostent(hp);
1019#  endif /* NETINET6 */
1020				return -1;
1021			}
1022		}
1023	}
1024	else
1025# endif /* NETINET || NETINET6 */
1026	{
1027		if (tTd(64, 5))
1028			sm_dprintf("X%s: unknown socket protocol\n",
1029				   m->mf_name);
1030		if (parseonly)
1031			syserr("X%s: unknown socket protocol", m->mf_name);
1032		else if (MilterLogLevel > 0)
1033			sm_syslog(LOG_ERR, e->e_id,
1034				  "Milter (%s): unknown socket protocol",
1035				  m->mf_name);
1036		milter_error(m, e);
1037		return -1;
1038	}
1039
1040	/* just parsing through? */
1041	if (parseonly)
1042	{
1043		m->mf_state = SMFS_READY;
1044# if NETINET6
1045		if (hp != NULL)
1046			freehostent(hp);
1047# endif /* NETINET6 */
1048		return 0;
1049	}
1050
1051	/* sanity check */
1052	if (m->mf_state != SMFS_READY &&
1053	    m->mf_state != SMFS_CLOSED)
1054	{
1055		/* shouldn't happen */
1056		if (tTd(64, 1))
1057			sm_dprintf("Milter (%s): Trying to open filter in state %c\n",
1058				   m->mf_name, (char) m->mf_state);
1059		milter_error(m, e);
1060# if NETINET6
1061		if (hp != NULL)
1062			freehostent(hp);
1063# endif /* NETINET6 */
1064		return -1;
1065	}
1066
1067	/* nope, actually connecting */
1068	for (;;)
1069	{
1070		sock = socket(addr.sa.sa_family, SOCK_STREAM, 0);
1071		if (sock < 0)
1072		{
1073			save_errno = errno;
1074			if (tTd(64, 5))
1075				sm_dprintf("Milter (%s): error creating socket: %s\n",
1076					   m->mf_name,
1077					   sm_errstring(save_errno));
1078			if (MilterLogLevel > 0)
1079				sm_syslog(LOG_ERR, e->e_id,
1080					  "Milter (%s): error creating socket: %s",
1081					  m->mf_name, sm_errstring(save_errno));
1082			milter_error(m, e);
1083# if NETINET6
1084			if (hp != NULL)
1085				freehostent(hp);
1086# endif /* NETINET6 */
1087			return -1;
1088		}
1089
1090		if (setjmp(MilterConnectTimeout) == 0)
1091		{
1092			SM_EVENT *ev = NULL;
1093			int i;
1094
1095			if (m->mf_timeout[SMFTO_CONNECT] > 0)
1096				ev = sm_setevent(m->mf_timeout[SMFTO_CONNECT],
1097						 milter_connect_timeout, 0);
1098
1099			i = connect(sock, (struct sockaddr *) &addr, addrlen);
1100			save_errno = errno;
1101			if (ev != NULL)
1102				sm_clrevent(ev);
1103			errno = save_errno;
1104			if (i >= 0)
1105				break;
1106		}
1107
1108		/* couldn't connect.... try next address */
1109		save_errno = errno;
1110		p = CurHostName;
1111		CurHostName = at;
1112		if (tTd(64, 5))
1113			sm_dprintf("milter_open (%s): open %s failed: %s\n",
1114				   m->mf_name, at, sm_errstring(save_errno));
1115		if (MilterLogLevel > 13)
1116			sm_syslog(LOG_INFO, e->e_id,
1117				  "Milter (%s): open %s failed: %s",
1118				  m->mf_name, at, sm_errstring(save_errno));
1119		CurHostName = p;
1120		(void) close(sock);
1121
1122		/* try next address */
1123		if (hp != NULL && hp->h_addr_list[addrno] != NULL)
1124		{
1125			switch (addr.sa.sa_family)
1126			{
1127# if NETINET
1128			  case AF_INET:
1129				memmove(&addr.sin.sin_addr,
1130					hp->h_addr_list[addrno++],
1131					INADDRSZ);
1132				break;
1133# endif /* NETINET */
1134
1135# if NETINET6
1136			  case AF_INET6:
1137				memmove(&addr.sin6.sin6_addr,
1138					hp->h_addr_list[addrno++],
1139					IN6ADDRSZ);
1140				break;
1141# endif /* NETINET6 */
1142
1143			  default:
1144				if (tTd(64, 5))
1145					sm_dprintf("X%s: Unknown protocol for %s (%d)\n",
1146						   m->mf_name, at,
1147						   hp->h_addrtype);
1148				if (MilterLogLevel > 0)
1149					sm_syslog(LOG_ERR, e->e_id,
1150						  "Milter (%s): Unknown protocol for %s (%d)",
1151						  m->mf_name, at,
1152						  hp->h_addrtype);
1153				milter_error(m, e);
1154# if NETINET6
1155				freehostent(hp);
1156# endif /* NETINET6 */
1157				return -1;
1158			}
1159			continue;
1160		}
1161		p = CurHostName;
1162		CurHostName = at;
1163		if (tTd(64, 5))
1164			sm_dprintf("X%s: error connecting to filter: %s\n",
1165				   m->mf_name, sm_errstring(save_errno));
1166		if (MilterLogLevel > 0)
1167			sm_syslog(LOG_ERR, e->e_id,
1168				  "Milter (%s): error connecting to filter: %s",
1169				  m->mf_name, sm_errstring(save_errno));
1170		CurHostName = p;
1171		milter_error(m, e);
1172# if NETINET6
1173		if (hp != NULL)
1174			freehostent(hp);
1175# endif /* NETINET6 */
1176		return -1;
1177	}
1178	m->mf_state = SMFS_OPEN;
1179# if NETINET6
1180	if (hp != NULL)
1181	{
1182		freehostent(hp);
1183		hp = NULL;
1184	}
1185# endif /* NETINET6 */
1186# if MILTER_NO_NAGLE && !defined(TCP_CORK)
1187	{
1188		int nodelay = 1;
1189
1190		setsockopt(m->mf_sock, IPPROTO_TCP, TCP_NODELAY,
1191			   (char *)&nodelay, sizeof(nodelay));
1192	}
1193# endif /* MILTER_NO_NAGLE && !defined(TCP_CORK) */
1194	return sock;
1195}
1196
1197static void
1198milter_connect_timeout(ignore)
1199	int ignore;
1200{
1201	/*
1202	**  NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
1203	**	ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
1204	**	DOING.
1205	*/
1206
1207	errno = ETIMEDOUT;
1208	longjmp(MilterConnectTimeout, 1);
1209}
1210
1211/*
1212**  MILTER_SETUP -- setup structure for a mail filter
1213**
1214**	Parameters:
1215**		line -- the options line.
1216**
1217**	Returns:
1218**		none
1219*/
1220
1221void
1222milter_setup(line)
1223	char *line;
1224{
1225	char fcode;
1226	char *p;
1227	struct milter *m;
1228	STAB *s;
1229	static int idx = 0;
1230
1231	/* collect the filter name */
1232	for (p = line;
1233	     *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p));
1234	     p++)
1235		continue;
1236	if (*p != '\0')
1237		*p++ = '\0';
1238	if (line[0] == '\0')
1239	{
1240		syserr("name required for mail filter");
1241		return;
1242	}
1243	m = (struct milter *) xalloc(sizeof(*m));
1244	memset((char *) m, '\0', sizeof(*m));
1245	m->mf_name = newstr(line);
1246	m->mf_state = SMFS_READY;
1247	m->mf_sock = -1;
1248	m->mf_timeout[SMFTO_CONNECT] = (time_t) 300;
1249	m->mf_timeout[SMFTO_WRITE] = (time_t) 10;
1250	m->mf_timeout[SMFTO_READ] = (time_t) 10;
1251	m->mf_timeout[SMFTO_EOM] = (time_t) 300;
1252#if _FFR_MILTER_CHECK
1253	m->mf_mta_prot_version = SMFI_PROT_VERSION;
1254	m->mf_mta_prot_flags = SMFI_CURR_PROT;
1255	m->mf_mta_actions = SMFI_CURR_ACTS;
1256#endif /* _FFR_MILTER_CHECK */
1257
1258	/* now scan through and assign info from the fields */
1259	while (*p != '\0')
1260	{
1261		char *delimptr;
1262
1263		while (*p != '\0' &&
1264		       (*p == ',' || (isascii(*p) && isspace(*p))))
1265			p++;
1266
1267		/* p now points to field code */
1268		fcode = *p;
1269		while (*p != '\0' && *p != '=' && *p != ',')
1270			p++;
1271		if (*p++ != '=')
1272		{
1273			syserr("X%s: `=' expected", m->mf_name);
1274			return;
1275		}
1276		while (isascii(*p) && isspace(*p))
1277			p++;
1278
1279		/* p now points to the field body */
1280		p = munchstring(p, &delimptr, ',');
1281
1282		/* install the field into the filter struct */
1283		switch (fcode)
1284		{
1285		  case 'S':		/* socket */
1286			if (p == NULL)
1287				m->mf_conn = NULL;
1288			else
1289				m->mf_conn = newstr(p);
1290			break;
1291
1292		  case 'F':		/* Milter flags configured on MTA */
1293			for (; *p != '\0'; p++)
1294			{
1295				if (!(isascii(*p) && isspace(*p)))
1296					setbitn(bitidx(*p), m->mf_flags);
1297			}
1298			break;
1299
1300		  case 'T':		/* timeouts */
1301			milter_parse_timeouts(p, m);
1302			break;
1303
1304#if _FFR_MILTER_CHECK
1305		  case 'a':
1306			m->mf_mta_actions = strtoul(p, NULL, 0);
1307			break;
1308		  case 'f':
1309			m->mf_mta_prot_flags = strtoul(p, NULL, 0);
1310			break;
1311		  case 'v':
1312			m->mf_mta_prot_version = strtoul(p, NULL, 0);
1313			break;
1314#endif /* _FFR_MILTER_CHECK */
1315
1316		  default:
1317			syserr("X%s: unknown filter equate %c=",
1318			       m->mf_name, fcode);
1319			break;
1320		}
1321		p = delimptr;
1322	}
1323
1324	/* early check for errors */
1325	(void) milter_open(m, true, CurEnv);
1326
1327	/* enter the filter into the symbol table */
1328	s = stab(m->mf_name, ST_MILTER, ST_ENTER);
1329	if (s->s_milter != NULL)
1330		syserr("X%s: duplicate filter definition", m->mf_name);
1331	else
1332	{
1333		s->s_milter = m;
1334		m->mf_idx = ++idx;
1335	}
1336}
1337
1338/*
1339**  MILTER_CONFIG -- parse option list into an array and check config
1340**
1341**	Called when reading configuration file.
1342**
1343**	Parameters:
1344**		spec -- the filter list.
1345**		list -- the array to fill in.
1346**		max -- the maximum number of entries in list.
1347**
1348**	Returns:
1349**		none
1350*/
1351
1352void
1353milter_config(spec, list, max)
1354	char *spec;
1355	struct milter **list;
1356	int max;
1357{
1358	int numitems = 0;
1359	char *p;
1360
1361	/* leave one for the NULL signifying the end of the list */
1362	max--;
1363
1364	for (p = spec; p != NULL; )
1365	{
1366		STAB *s;
1367
1368		while (isascii(*p) && isspace(*p))
1369			p++;
1370		if (*p == '\0')
1371			break;
1372		spec = p;
1373
1374		if (numitems >= max)
1375		{
1376			syserr("Too many filters defined, %d max", max);
1377			if (max > 0)
1378				list[0] = NULL;
1379			return;
1380		}
1381		p = strpbrk(p, ";,");
1382		if (p != NULL)
1383			*p++ = '\0';
1384
1385		s = stab(spec, ST_MILTER, ST_FIND);
1386		if (s == NULL)
1387		{
1388			syserr("InputFilter %s not defined", spec);
1389			ExitStat = EX_CONFIG;
1390			return;
1391		}
1392		list[numitems++] = s->s_milter;
1393	}
1394	list[numitems] = NULL;
1395
1396	/* if not set, set to LogLevel */
1397	if (MilterLogLevel == -1)
1398		MilterLogLevel = LogLevel;
1399}
1400
1401/*
1402**  MILTER_PARSE_TIMEOUTS -- parse timeout list
1403**
1404**	Called when reading configuration file.
1405**
1406**	Parameters:
1407**		spec -- the timeout list.
1408**		m -- milter to set.
1409**
1410**	Returns:
1411**		none
1412*/
1413
1414static void
1415milter_parse_timeouts(spec, m)
1416	char *spec;
1417	struct milter *m;
1418{
1419	char fcode;
1420	int tcode;
1421	char *p;
1422
1423	p = spec;
1424
1425	/* now scan through and assign info from the fields */
1426	while (*p != '\0')
1427	{
1428		char *delimptr;
1429
1430		while (*p != '\0' &&
1431		       (*p == ';' || (isascii(*p) && isspace(*p))))
1432			p++;
1433
1434		/* p now points to field code */
1435		fcode = *p;
1436		while (*p != '\0' && *p != ':')
1437			p++;
1438		if (*p++ != ':')
1439		{
1440			syserr("X%s, T=: `:' expected", m->mf_name);
1441			return;
1442		}
1443		while (isascii(*p) && isspace(*p))
1444			p++;
1445
1446		/* p now points to the field body */
1447		p = munchstring(p, &delimptr, ';');
1448		tcode = -1;
1449
1450		/* install the field into the filter struct */
1451		switch (fcode)
1452		{
1453		  case 'C':
1454			tcode = SMFTO_CONNECT;
1455			break;
1456
1457		  case 'S':
1458			tcode = SMFTO_WRITE;
1459			break;
1460
1461		  case 'R':
1462			tcode = SMFTO_READ;
1463			break;
1464
1465		  case 'E':
1466			tcode = SMFTO_EOM;
1467			break;
1468
1469		  default:
1470			if (tTd(64, 5))
1471				sm_dprintf("X%s: %c unknown\n",
1472					   m->mf_name, fcode);
1473			syserr("X%s: unknown filter timeout %c",
1474			       m->mf_name, fcode);
1475			break;
1476		}
1477		if (tcode >= 0)
1478		{
1479			m->mf_timeout[tcode] = convtime(p, 's');
1480			if (tTd(64, 5))
1481				sm_dprintf("X%s: %c=%ld\n",
1482					   m->mf_name, fcode,
1483					   (u_long) m->mf_timeout[tcode]);
1484		}
1485		p = delimptr;
1486	}
1487}
1488
1489/*
1490**  MILTER_SET_MACROS -- set milter macros
1491**
1492**	Parameters:
1493**		name -- name of milter.
1494**		macros -- where to store macros.
1495**		val -- the value of the option.
1496**		nummac -- current number of macros
1497**
1498**	Returns:
1499**		new number of macros
1500*/
1501
1502static int
1503milter_set_macros(name, macros, val, nummac)
1504	char *name;
1505	char **macros;
1506	char *val;
1507	int nummac;
1508{
1509	char *p;
1510
1511	p = newstr(val);
1512	while (*p != '\0')
1513	{
1514		char *macro;
1515
1516		/* Skip leading commas, spaces */
1517		while (*p != '\0' &&
1518		       (*p == ',' || (isascii(*p) && isspace(*p))))
1519			p++;
1520
1521		if (*p == '\0')
1522			break;
1523
1524		/* Find end of macro */
1525		macro = p;
1526		while (*p != '\0' && *p != ',' &&
1527		       isascii(*p) && !isspace(*p))
1528			p++;
1529		if (*p != '\0')
1530			*p++ = '\0';
1531
1532		if (nummac >= MAXFILTERMACROS)
1533		{
1534			syserr("milter_set_option: too many macros in Milter.%s (max %d)",
1535			       name, MAXFILTERMACROS);
1536			macros[nummac] = NULL;
1537			return -1;
1538		}
1539		macros[nummac++] = macro;
1540	}
1541	macros[nummac] = NULL;
1542	return nummac;
1543}
1544
1545/*
1546**  MILTER_SET_OPTION -- set an individual milter option
1547**
1548**	Parameters:
1549**		name -- the name of the option.
1550**		val -- the value of the option.
1551**		sticky -- if set, don't let other setoptions override
1552**			this value.
1553**
1554**	Returns:
1555**		none.
1556*/
1557
1558/* set if Milter sub-option is stuck */
1559static BITMAP256	StickyMilterOpt;
1560
1561static struct milteropt
1562{
1563	char		*mo_name;	/* long name of milter option */
1564	unsigned char	mo_code;	/* code for option */
1565} MilterOptTab[] =
1566{
1567	{ "macros.connect",		SMFIM_CONNECT			},
1568	{ "macros.helo",		SMFIM_HELO			},
1569	{ "macros.envfrom",		SMFIM_ENVFROM			},
1570	{ "macros.envrcpt",		SMFIM_ENVRCPT			},
1571	{ "macros.data",		SMFIM_DATA			},
1572	{ "macros.eom",			SMFIM_EOM			},
1573	{ "macros.eoh",			SMFIM_EOH			},
1574
1575# define MO_LOGLEVEL			0x07
1576	{ "loglevel",			MO_LOGLEVEL			},
1577# if _FFR_MAXDATASIZE || _FFR_MDS_NEGOTIATE
1578#  define MO_MAXDATASIZE		0x08
1579	{ "maxdatasize",		MO_MAXDATASIZE			},
1580# endif /* _FFR_MAXDATASIZE || _FFR_MDS_NEGOTIATE */
1581	{ NULL,				(unsigned char)-1		},
1582};
1583
1584void
1585milter_set_option(name, val, sticky)
1586	char *name;
1587	char *val;
1588	bool sticky;
1589{
1590	int nummac, r;
1591	struct milteropt *mo;
1592	char **macros = NULL;
1593
1594	nummac = 0;
1595	if (tTd(37, 2) || tTd(64, 5))
1596		sm_dprintf("milter_set_option(%s = %s)", name, val);
1597
1598	if (name == NULL)
1599	{
1600		syserr("milter_set_option: invalid Milter option, must specify suboption");
1601		return;
1602	}
1603
1604	for (mo = MilterOptTab; mo->mo_name != NULL; mo++)
1605	{
1606		if (sm_strcasecmp(mo->mo_name, name) == 0)
1607			break;
1608	}
1609
1610	if (mo->mo_name == NULL)
1611	{
1612		syserr("milter_set_option: invalid Milter option %s", name);
1613		return;
1614	}
1615
1616	/*
1617	**  See if this option is preset for us.
1618	*/
1619
1620	if (!sticky && bitnset(mo->mo_code, StickyMilterOpt))
1621	{
1622		if (tTd(37, 2) || tTd(64,5))
1623			sm_dprintf(" (ignored)\n");
1624		return;
1625	}
1626
1627	if (tTd(37, 2) || tTd(64,5))
1628		sm_dprintf("\n");
1629
1630	switch (mo->mo_code)
1631	{
1632	  case MO_LOGLEVEL:
1633		MilterLogLevel = atoi(val);
1634		break;
1635
1636# if _FFR_MAXDATASIZE || _FFR_MDS_NEGOTIATE
1637	  case MO_MAXDATASIZE:
1638#  if _FFR_MDS_NEGOTIATE
1639		MilterMaxDataSize = (size_t)atol(val);
1640		if (MilterMaxDataSize != MILTER_MDS_64K &&
1641		    MilterMaxDataSize != MILTER_MDS_256K &&
1642		    MilterMaxDataSize != MILTER_MDS_1M)
1643		{
1644			sm_syslog(LOG_WARNING, NOQID,
1645				"WARNING: Milter.%s=%lu, allowed are only %d, %d, and %d",
1646				name, (unsigned long) MilterMaxDataSize,
1647				MILTER_MDS_64K, MILTER_MDS_256K,
1648				MILTER_MDS_1M);
1649			if (MilterMaxDataSize < MILTER_MDS_64K)
1650				MilterMaxDataSize = MILTER_MDS_64K;
1651			else if (MilterMaxDataSize < MILTER_MDS_256K)
1652				MilterMaxDataSize = MILTER_MDS_256K;
1653			else
1654				MilterMaxDataSize = MILTER_MDS_1M;
1655		}
1656#  endif /* _FFR_MDS_NEGOTIATE */
1657		break;
1658# endif /* _FFR_MAXDATASIZE || _FFR_MDS_NEGOTIATE */
1659
1660	  case SMFIM_CONNECT:
1661	  case SMFIM_HELO:
1662	  case SMFIM_ENVFROM:
1663	  case SMFIM_ENVRCPT:
1664	  case SMFIM_EOH:
1665	  case SMFIM_EOM:
1666	  case SMFIM_DATA:
1667		macros = MilterMacros[mo->mo_code][0];
1668
1669		r = milter_set_macros(name, macros, val, nummac);
1670		if (r >= 0)
1671			nummac = r;
1672		break;
1673
1674	  default:
1675		syserr("milter_set_option: invalid Milter option %s", name);
1676		break;
1677	}
1678	if (sticky)
1679		setbitn(mo->mo_code, StickyMilterOpt);
1680}
1681
1682/*
1683**  MILTER_REOPEN_DF -- open & truncate the data file (for replbody)
1684**
1685**	Parameters:
1686**		e -- current envelope.
1687**
1688**	Returns:
1689**		0 if succesful, -1 otherwise
1690*/
1691
1692static int
1693milter_reopen_df(e)
1694	ENVELOPE *e;
1695{
1696	char dfname[MAXPATHLEN];
1697
1698	(void) sm_strlcpy(dfname, queuename(e, DATAFL_LETTER), sizeof(dfname));
1699
1700	/*
1701	**  In SuperSafe == SAFE_REALLY mode, e->e_dfp is a read-only FP so
1702	**  close and reopen writable (later close and reopen
1703	**  read only again).
1704	**
1705	**  In SuperSafe != SAFE_REALLY mode, e->e_dfp still points at the
1706	**  buffered file I/O descriptor, still open for writing so there
1707	**  isn't any work to do here (except checking for consistency).
1708	*/
1709
1710	if (SuperSafe == SAFE_REALLY)
1711	{
1712		/* close read-only data file */
1713		if (bitset(EF_HAS_DF, e->e_flags) && e->e_dfp != NULL)
1714		{
1715			(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
1716			e->e_flags &= ~EF_HAS_DF;
1717		}
1718
1719		/* open writable */
1720		if ((e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname,
1721					   SM_IO_RDWR_B, NULL)) == NULL)
1722		{
1723			MILTER_DF_ERROR("milter_reopen_df: sm_io_open %s: %s");
1724			return -1;
1725		}
1726	}
1727	else if (e->e_dfp == NULL)
1728	{
1729		/* shouldn't happen */
1730		errno = ENOENT;
1731		MILTER_DF_ERROR("milter_reopen_df: NULL e_dfp (%s: %s)");
1732		return -1;
1733	}
1734	return 0;
1735}
1736
1737/*
1738**  MILTER_RESET_DF -- re-open read-only the data file (for replbody)
1739**
1740**	Parameters:
1741**		e -- current envelope.
1742**
1743**	Returns:
1744**		0 if succesful, -1 otherwise
1745*/
1746
1747static int
1748milter_reset_df(e)
1749	ENVELOPE *e;
1750{
1751	int afd;
1752	char dfname[MAXPATHLEN];
1753
1754	(void) sm_strlcpy(dfname, queuename(e, DATAFL_LETTER), sizeof(dfname));
1755
1756	if (sm_io_flush(e->e_dfp, SM_TIME_DEFAULT) != 0 ||
1757	    sm_io_error(e->e_dfp))
1758	{
1759		MILTER_DF_ERROR("milter_reset_df: error writing/flushing %s: %s");
1760		return -1;
1761	}
1762	else if (SuperSafe != SAFE_REALLY)
1763	{
1764		/* skip next few clauses */
1765		/* EMPTY */
1766	}
1767	else if ((afd = sm_io_getinfo(e->e_dfp, SM_IO_WHAT_FD, NULL)) >= 0
1768		 && fsync(afd) < 0)
1769	{
1770		MILTER_DF_ERROR("milter_reset_df: error sync'ing %s: %s");
1771		return -1;
1772	}
1773	else if (sm_io_close(e->e_dfp, SM_TIME_DEFAULT) < 0)
1774	{
1775		MILTER_DF_ERROR("milter_reset_df: error closing %s: %s");
1776		return -1;
1777	}
1778	else if ((e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname,
1779					SM_IO_RDONLY_B, NULL)) == NULL)
1780	{
1781		MILTER_DF_ERROR("milter_reset_df: error reopening %s: %s");
1782		return -1;
1783	}
1784	else
1785		e->e_flags |= EF_HAS_DF;
1786	return 0;
1787}
1788
1789/*
1790**  MILTER_QUIT_FILTER -- close down a single filter
1791**
1792**	Parameters:
1793**		m -- milter structure of filter to close down.
1794**		e -- current envelope.
1795**
1796**	Returns:
1797**		none
1798*/
1799
1800static void
1801milter_quit_filter(m, e)
1802	struct milter *m;
1803	ENVELOPE *e;
1804{
1805	if (tTd(64, 10))
1806		sm_dprintf("milter_quit_filter(%s)\n", m->mf_name);
1807	if (MilterLogLevel > 18)
1808		sm_syslog(LOG_INFO, e->e_id, "Milter (%s): quit filter",
1809			  m->mf_name);
1810
1811	/* Never replace error state */
1812	if (m->mf_state == SMFS_ERROR)
1813		return;
1814
1815	if (m->mf_sock < 0 ||
1816	    m->mf_state == SMFS_CLOSED ||
1817	    m->mf_state == SMFS_READY)
1818	{
1819		m->mf_sock = -1;
1820		m->mf_state = SMFS_CLOSED;
1821		return;
1822	}
1823
1824	(void) milter_write(m, SMFIC_QUIT, (char *) NULL, 0,
1825			    m->mf_timeout[SMFTO_WRITE], e, "quit_filter");
1826	if (m->mf_sock >= 0)
1827	{
1828		(void) close(m->mf_sock);
1829		m->mf_sock = -1;
1830	}
1831	if (m->mf_state != SMFS_ERROR)
1832		m->mf_state = SMFS_CLOSED;
1833}
1834
1835/*
1836**  MILTER_ABORT_FILTER -- tell filter to abort current message
1837**
1838**	Parameters:
1839**		m -- milter structure of filter to abort.
1840**		e -- current envelope.
1841**
1842**	Returns:
1843**		none
1844*/
1845
1846static void
1847milter_abort_filter(m, e)
1848	struct milter *m;
1849	ENVELOPE *e;
1850{
1851	if (tTd(64, 10))
1852		sm_dprintf("milter_abort_filter(%s)\n", m->mf_name);
1853	if (MilterLogLevel > 10)
1854		sm_syslog(LOG_INFO, e->e_id, "Milter (%s): abort filter",
1855			  m->mf_name);
1856
1857	if (m->mf_sock < 0 ||
1858	    m->mf_state != SMFS_INMSG)
1859		return;
1860
1861	(void) milter_write(m, SMFIC_ABORT, (char *) NULL, 0,
1862			    m->mf_timeout[SMFTO_WRITE], e, "abort_filter");
1863	if (m->mf_state != SMFS_ERROR)
1864		m->mf_state = SMFS_DONE;
1865}
1866
1867/*
1868**  MILTER_SEND_MACROS -- provide macros to the filters
1869**
1870**	Parameters:
1871**		m -- milter to send macros to.
1872**		macros -- macros to send for filter smfi_getsymval().
1873**		cmd -- which command the macros are associated with.
1874**		e -- current envelope (for macro access).
1875**
1876**	Returns:
1877**		none
1878*/
1879
1880static void
1881milter_send_macros(m, macros, cmd, e)
1882	struct milter *m;
1883	char **macros;
1884	int cmd;
1885	ENVELOPE *e;
1886{
1887	int i;
1888	int mid;
1889	char command = (char) cmd;
1890	char *v;
1891	char *buf, *bp;
1892	char exp[MAXLINE];
1893	ssize_t s;
1894
1895	/* sanity check */
1896	if (macros == NULL || macros[0] == NULL)
1897		return;
1898
1899	/* put together data */
1900	s = 1;			/* for the command character */
1901	for (i = 0; macros[i] != NULL; i++)
1902	{
1903		mid = macid(macros[i]);
1904		if (mid == 0)
1905			continue;
1906		v = macvalue(mid, e);
1907		if (v == NULL)
1908			continue;
1909		expand(v, exp, sizeof(exp), e);
1910		s += strlen(macros[i]) + 1 + strlen(exp) + 1;
1911	}
1912
1913	if (s < 0)
1914		return;
1915
1916	buf = (char *) xalloc(s);
1917	bp = buf;
1918	*bp++ = command;
1919	for (i = 0; macros[i] != NULL; i++)
1920	{
1921		mid = macid(macros[i]);
1922		if (mid == 0)
1923			continue;
1924		v = macvalue(mid, e);
1925		if (v == NULL)
1926			continue;
1927		expand(v, exp, sizeof(exp), e);
1928
1929		if (tTd(64, 10))
1930			sm_dprintf("milter_send_macros(%s, %c): %s=%s\n",
1931				m->mf_name, command, macros[i], exp);
1932
1933		(void) sm_strlcpy(bp, macros[i], s - (bp - buf));
1934		bp += strlen(bp) + 1;
1935		(void) sm_strlcpy(bp, exp, s - (bp - buf));
1936		bp += strlen(bp) + 1;
1937	}
1938	(void) milter_write(m, SMFIC_MACRO, buf, s,
1939			    m->mf_timeout[SMFTO_WRITE], e, "send_macros");
1940	sm_free(buf);
1941}
1942
1943/*
1944**  MILTER_SEND_COMMAND -- send a command and return the response for a filter
1945**
1946**	Parameters:
1947**		m -- current milter filter
1948**		cmd -- command to send.
1949**		data -- optional command data.
1950**		sz -- length of buf.
1951**		e -- current envelope (for e->e_id).
1952**		state -- return state word.
1953**
1954**	Returns:
1955**		response string (may be NULL)
1956*/
1957
1958static char *
1959milter_send_command(m, cmd, data, sz, e, state, where)
1960	struct milter *m;
1961	int cmd;
1962	void *data;
1963	ssize_t sz;
1964	ENVELOPE *e;
1965	char *state;
1966	const char *where;
1967{
1968	char rcmd;
1969	ssize_t rlen;
1970	unsigned long skipflag;
1971	unsigned long norespflag = 0;
1972	char command = (char) cmd;
1973	char *action;
1974	char *defresponse;
1975	char *response;
1976
1977	if (tTd(64, 10))
1978		sm_dprintf("milter_send_command(%s): cmd %c len %ld\n",
1979			m->mf_name, (char) command, (long) sz);
1980
1981	/* find skip flag and default failure */
1982	switch (command)
1983	{
1984	  case SMFIC_CONNECT:
1985		skipflag = SMFIP_NOCONNECT;
1986		norespflag = SMFIP_NR_CONN;
1987		action = "connect";
1988		defresponse = "554 Command rejected";
1989		break;
1990
1991	  case SMFIC_HELO:
1992		skipflag = SMFIP_NOHELO;
1993		norespflag = SMFIP_NR_HELO;
1994		action = "helo";
1995		defresponse = "550 Command rejected";
1996		break;
1997
1998	  case SMFIC_MAIL:
1999		skipflag = SMFIP_NOMAIL;
2000		norespflag = SMFIP_NR_MAIL;
2001		action = "mail";
2002		defresponse = "550 5.7.1 Command rejected";
2003		break;
2004
2005	  case SMFIC_RCPT:
2006		skipflag = SMFIP_NORCPT;
2007		norespflag = SMFIP_NR_RCPT;
2008		action = "rcpt";
2009		defresponse = "550 5.7.1 Command rejected";
2010		break;
2011
2012	  case SMFIC_HEADER:
2013		skipflag = SMFIP_NOHDRS;
2014		norespflag = SMFIP_NR_HDR;
2015		action = "header";
2016		defresponse = "550 5.7.1 Command rejected";
2017		break;
2018
2019	  case SMFIC_BODY:
2020		skipflag = SMFIP_NOBODY;
2021		norespflag = SMFIP_NR_BODY;
2022		action = "body";
2023		defresponse = "554 5.7.1 Command rejected";
2024		break;
2025
2026	  case SMFIC_EOH:
2027		skipflag = SMFIP_NOEOH;
2028		norespflag = SMFIP_NR_EOH;
2029		action = "eoh";
2030		defresponse = "550 5.7.1 Command rejected";
2031		break;
2032
2033	  case SMFIC_UNKNOWN:
2034		skipflag = SMFIP_NOUNKNOWN;
2035		norespflag = SMFIP_NR_UNKN;
2036		action = "unknown";
2037		defresponse = "550 5.7.1 Command rejected";
2038		break;
2039
2040	  case SMFIC_DATA:
2041		skipflag = SMFIP_NODATA;
2042		norespflag = SMFIP_NR_DATA;
2043		action = "data";
2044		defresponse = "550 5.7.1 Command rejected";
2045		break;
2046
2047	  case SMFIC_BODYEOB:
2048	  case SMFIC_OPTNEG:
2049	  case SMFIC_MACRO:
2050	  case SMFIC_ABORT:
2051	  case SMFIC_QUIT:
2052		/* NOTE: not handled by milter_send_command() */
2053		/* FALLTHROUGH */
2054
2055	  default:
2056		skipflag = 0;
2057		action = "default";
2058		defresponse = "550 5.7.1 Command rejected";
2059		break;
2060	}
2061
2062	if (tTd(64, 10))
2063		sm_dprintf("milter_send_command(%s): skip=%lx, pflags=%x\n",
2064			m->mf_name, skipflag, m->mf_pflags);
2065
2066	/* check if filter wants this command */
2067	if (skipflag != 0 && bitset(skipflag, m->mf_pflags))
2068		return NULL;
2069
2070	/* send the command to the filter */
2071	(void) milter_write(m, command, data, sz,
2072			    m->mf_timeout[SMFTO_WRITE], e, where);
2073	if (m->mf_state == SMFS_ERROR)
2074	{
2075		MILTER_CHECK_ERROR(false, return NULL);
2076		return NULL;
2077	}
2078
2079	/* check if filter sends response to this command */
2080	if (norespflag != 0 && bitset(norespflag, m->mf_pflags))
2081		return NULL;
2082
2083	/* get the response from the filter */
2084	response = milter_read(m, &rcmd, &rlen,
2085			       m->mf_timeout[SMFTO_READ], e, where);
2086	if (m->mf_state == SMFS_ERROR)
2087	{
2088		MILTER_CHECK_ERROR(false, return NULL);
2089		return NULL;
2090	}
2091
2092	if (tTd(64, 10))
2093		sm_dprintf("milter_send_command(%s): returned %c\n",
2094			   m->mf_name, (char) rcmd);
2095
2096	switch (rcmd)
2097	{
2098	  case SMFIR_REPLYCODE:
2099		MILTER_CHECK_REPLYCODE(defresponse);
2100		if (MilterLogLevel > 10)
2101			sm_syslog(LOG_INFO, e->e_id,
2102				  "milter=%s, action=%s, reject=%s",
2103				  m->mf_name, action, response);
2104		*state = rcmd;
2105		break;
2106
2107	  case SMFIR_REJECT:
2108		if (MilterLogLevel > 10)
2109			sm_syslog(LOG_INFO, e->e_id,
2110				  "milter=%s, action=%s, reject",
2111				  m->mf_name, action);
2112		*state = rcmd;
2113		break;
2114
2115	  case SMFIR_DISCARD:
2116		if (MilterLogLevel > 10)
2117			sm_syslog(LOG_INFO, e->e_id,
2118				  "milter=%s, action=%s, discard",
2119				  m->mf_name, action);
2120		*state = rcmd;
2121		break;
2122
2123	  case SMFIR_TEMPFAIL:
2124		if (MilterLogLevel > 10)
2125			sm_syslog(LOG_INFO, e->e_id,
2126				  "milter=%s, action=%s, tempfail",
2127				  m->mf_name, action);
2128		*state = rcmd;
2129		break;
2130
2131	  case SMFIR_ACCEPT:
2132		/* this filter is done with message/connection */
2133		if (command == SMFIC_HELO ||
2134		    command == SMFIC_CONNECT)
2135			m->mf_state = SMFS_CLOSABLE;
2136		else
2137			m->mf_state = SMFS_DONE;
2138		if (MilterLogLevel > 10)
2139			sm_syslog(LOG_INFO, e->e_id,
2140				  "milter=%s, action=%s, accepted",
2141				  m->mf_name, action);
2142		break;
2143
2144	  case SMFIR_CONTINUE:
2145		/* if MAIL command is ok, filter is in message state */
2146		if (command == SMFIC_MAIL)
2147			m->mf_state = SMFS_INMSG;
2148		if (MilterLogLevel > 12)
2149			sm_syslog(LOG_INFO, e->e_id,
2150				  "milter=%s, action=%s, continue",
2151				  m->mf_name, action);
2152		break;
2153
2154	  case SMFIR_SKIP:
2155		if (MilterLogLevel > 12)
2156			sm_syslog(LOG_INFO, e->e_id,
2157				  "milter=%s, action=%s, skip",
2158				  m->mf_name, action);
2159		m->mf_state = SMFS_SKIP;
2160		break;
2161
2162	  default:
2163		/* Invalid response to command */
2164		if (MilterLogLevel > 0)
2165			sm_syslog(LOG_ERR, e->e_id,
2166				  "milter_send_command(%s): action=%s returned bogus response %c",
2167				  m->mf_name, action, rcmd);
2168		milter_error(m, e); /* NO ERROR CHECK? */
2169		break;
2170	}
2171
2172	if (*state != SMFIR_REPLYCODE && response != NULL)
2173	{
2174		sm_free(response); /* XXX */
2175		response = NULL;
2176	}
2177	return response;
2178}
2179
2180/*
2181**  MILTER_COMMAND -- send a command and return the response for each filter
2182**
2183**	Parameters:
2184**		cmd -- command to send.
2185**		data -- optional command data.
2186**		sz -- length of buf.
2187**		stage -- index of macros to send for filter smfi_getsymval().
2188**		e -- current envelope (for macro access).
2189**		state -- return state word.
2190**		where -- description of calling function (logging).
2191**		cmd_error -- did the SMTP command cause an error?
2192**
2193**	Returns:
2194**		response string (may be NULL)
2195*/
2196
2197static char *
2198milter_command(cmd, data, sz, stage, e, state, where, cmd_error)
2199	int cmd;
2200	void *data;
2201	ssize_t sz;
2202	int stage;
2203	ENVELOPE *e;
2204	char *state;
2205	const char *where;
2206	bool cmd_error;
2207{
2208	int i;
2209	char command = (char) cmd;
2210	char *response = NULL;
2211	time_t tn = 0;
2212
2213	if (tTd(64, 10))
2214		sm_dprintf("milter_command: cmd %c len %ld\n",
2215			command, (long) sz);
2216
2217	*state = SMFIR_CONTINUE;
2218	for (i = 0; InputFilters[i] != NULL; i++)
2219	{
2220		struct milter *m = InputFilters[i];
2221
2222		/* previous problem? */
2223		if (m->mf_state == SMFS_ERROR)
2224		{
2225			MILTER_CHECK_ERROR(false, continue);
2226			break;
2227		}
2228
2229		/* sanity check */
2230		if (m->mf_sock < 0 ||
2231		    (m->mf_state != SMFS_OPEN && m->mf_state != SMFS_INMSG))
2232			continue;
2233
2234		if (stage >= SMFIM_FIRST && stage <= SMFIM_LAST)
2235		{
2236			int idx;
2237			char **macros;
2238
2239			if ((m->mf_lflags & MI_LFLAGS_SYM(stage)) != 0)
2240				idx = m->mf_idx;
2241			else
2242				idx = 0;
2243			SM_ASSERT(idx >= 0 && idx <= MAXFILTERS);
2244			macros = MilterMacros[stage][idx];
2245
2246			/* send macros (regardless of whether we send cmd) */
2247			if (macros != NULL && macros[0] != NULL)
2248			{
2249				milter_send_macros(m, macros, command, e);
2250				if (m->mf_state == SMFS_ERROR)
2251				{
2252					MILTER_CHECK_ERROR(false, continue);
2253					break;
2254				}
2255			}
2256		}
2257
2258		if (MilterLogLevel > 21)
2259			tn = curtime();
2260
2261		/*
2262		**  send the command if
2263		**	there is no error
2264		**	or it's RCPT and the client asked for it:
2265		**	!cmd_error ||
2266		**	where == "rcpt" && m->mf_pflags & SMFIP_RCPT_REJ != 0
2267		**  negate that condition and use continue
2268		*/
2269
2270		if (cmd_error &&
2271		    (strcmp(where, "rcpt") != 0 ||
2272		     (m->mf_pflags & SMFIP_RCPT_REJ) == 0))
2273			continue;
2274
2275		response = milter_send_command(m, command, data, sz, e, state,
2276						where);
2277
2278		if (MilterLogLevel > 21)
2279		{
2280			/* log the time it took for the command per filter */
2281			sm_syslog(LOG_INFO, e->e_id,
2282				  "Milter (%s): time command (%c), %d",
2283				  m->mf_name, command, (int) (tn - curtime()));
2284		}
2285
2286		if (*state != SMFIR_CONTINUE)
2287			break;
2288	}
2289	return response;
2290}
2291
2292static int milter_getsymlist __P((struct milter *, char *, int, int));
2293
2294static int
2295milter_getsymlist(m, buf, rlen, offset)
2296	struct milter *m;
2297	char *buf;
2298	int rlen;
2299	int offset;
2300{
2301	int i, r, nummac;
2302	mi_int32 v;
2303
2304	SM_ASSERT(m != NULL);
2305	SM_ASSERT(buf != NULL);
2306
2307	while (offset + MILTER_LEN_BYTES < rlen)
2308	{
2309		size_t len;
2310		char **macros;
2311
2312		nummac = 0;
2313		(void) memcpy((char *) &v, buf + offset, MILTER_LEN_BYTES);
2314		i = ntohl(v);
2315		if (i < SMFIM_FIRST || i > SMFIM_LAST)
2316			return -1;
2317		offset += MILTER_LEN_BYTES;
2318		macros = NULL;
2319
2320#define SM_M_MACRO_NAME(i) (((i) < SM_ARRAY_SIZE(MilterOptTab) && (i) >= 0) \
2321				?  MilterOptTab[i].mo_name : "?")
2322		switch (i)
2323		{
2324		  case SMFIM_CONNECT:
2325		  case SMFIM_HELO:
2326		  case SMFIM_ENVFROM:
2327		  case SMFIM_ENVRCPT:
2328		  case SMFIM_EOH:
2329		  case SMFIM_EOM:
2330		  case SMFIM_DATA:
2331			SM_ASSERT(m->mf_idx > 0 && m->mf_idx < MAXFILTERS);
2332			macros = MilterMacros[i][m->mf_idx];
2333			m->mf_lflags |= MI_LFLAGS_SYM(i);
2334			len = strlen(buf + offset);
2335			if (len >= 0)
2336			{
2337				r = milter_set_macros(m->mf_name, macros,
2338						buf + offset, nummac);
2339				if (r >= 0)
2340					nummac = r;
2341				if (tTd(64, 5))
2342					sm_dprintf("milter_getsymlist(%s, %s, \"%s\")=%d\n",
2343						m->mf_name,
2344						SM_M_MACRO_NAME(i),
2345						buf + offset, r);
2346			}
2347			break;
2348
2349		  default:
2350			return -1;
2351		}
2352		offset += len + 1;
2353	}
2354
2355	return 0;
2356}
2357
2358/*
2359**  MILTER_NEGOTIATE -- get version and flags from filter
2360**
2361**	Parameters:
2362**		m -- milter filter structure.
2363**		e -- current envelope.
2364**		milters -- milters structure.
2365**
2366**	Returns:
2367**		0 on success, -1 otherwise
2368*/
2369
2370static int
2371milter_negotiate(m, e, milters)
2372	struct milter *m;
2373	ENVELOPE *e;
2374	milters_T *milters;
2375{
2376	char rcmd;
2377	mi_int32 fvers, fflags, pflags;
2378	mi_int32 mta_prot_vers, mta_prot_flags, mta_actions;
2379	ssize_t rlen;
2380	char *response;
2381	char data[MILTER_OPTLEN];
2382
2383	/* sanity check */
2384	if (m->mf_sock < 0 || m->mf_state != SMFS_OPEN)
2385	{
2386		if (MilterLogLevel > 0)
2387			sm_syslog(LOG_ERR, e->e_id,
2388				  "Milter (%s): negotiate, impossible state",
2389				  m->mf_name);
2390		milter_error(m, e);
2391		return -1;
2392	}
2393
2394#if _FFR_MILTER_CHECK
2395	mta_prot_vers = m->mf_mta_prot_version;
2396	mta_prot_flags = m->mf_mta_prot_flags;
2397	mta_actions = m->mf_mta_actions;
2398#else /* _FFR_MILTER_CHECK */
2399	mta_prot_vers = SMFI_PROT_VERSION;
2400	mta_prot_flags = SMFI_CURR_PROT;
2401	mta_actions = SMFI_CURR_ACTS;
2402#endif /* _FFR_MILTER_CHECK */
2403#if _FFR_MDS_NEGOTIATE
2404	if (MilterMaxDataSize == MILTER_MDS_256K)
2405		mta_prot_flags |= SMFIP_MDS_256K;
2406	else if (MilterMaxDataSize == MILTER_MDS_1M)
2407		mta_prot_flags |= SMFIP_MDS_1M;
2408#endif /* _FFR_MDS_NEGOTIATE */
2409
2410	fvers = htonl(mta_prot_vers);
2411	pflags = htonl(mta_prot_flags);
2412	fflags = htonl(mta_actions);
2413	(void) memcpy(data, (char *) &fvers, MILTER_LEN_BYTES);
2414	(void) memcpy(data + MILTER_LEN_BYTES,
2415		      (char *) &fflags, MILTER_LEN_BYTES);
2416	(void) memcpy(data + (MILTER_LEN_BYTES * 2),
2417		      (char *) &pflags, MILTER_LEN_BYTES);
2418	(void) milter_write(m, SMFIC_OPTNEG, data, sizeof(data),
2419			    m->mf_timeout[SMFTO_WRITE], e, "negotiate");
2420
2421	if (m->mf_state == SMFS_ERROR)
2422		return -1;
2423
2424	if (tTd(64, 5))
2425		sm_dprintf("milter_negotiate(%s): send: version %lu, fflags 0x%lx, pflags 0x%lx\n",
2426			m->mf_name, (unsigned long) ntohl(fvers),
2427			(unsigned long) ntohl(fflags),
2428			(unsigned long) ntohl(pflags));
2429
2430	response = milter_read(m, &rcmd, &rlen, m->mf_timeout[SMFTO_READ], e,
2431				"negotiate");
2432	if (m->mf_state == SMFS_ERROR)
2433		return -1;
2434
2435	if (rcmd != SMFIC_OPTNEG)
2436	{
2437		if (tTd(64, 5))
2438			sm_dprintf("milter_negotiate(%s): returned %c instead of %c\n",
2439				m->mf_name, rcmd, SMFIC_OPTNEG);
2440		if (MilterLogLevel > 0)
2441			sm_syslog(LOG_ERR, e->e_id,
2442				  "Milter (%s): negotiate: returned %c instead of %c",
2443				  m->mf_name, rcmd, SMFIC_OPTNEG);
2444		if (response != NULL)
2445			sm_free(response); /* XXX */
2446		milter_error(m, e);
2447		return -1;
2448	}
2449
2450	/* Make sure we have enough bytes for the version */
2451	if (response == NULL || rlen < MILTER_LEN_BYTES)
2452	{
2453		if (tTd(64, 5))
2454			sm_dprintf("milter_negotiate(%s): did not return valid info\n",
2455				m->mf_name);
2456		if (MilterLogLevel > 0)
2457			sm_syslog(LOG_ERR, e->e_id,
2458				  "Milter (%s): negotiate: did not return valid info",
2459				  m->mf_name);
2460		if (response != NULL)
2461			sm_free(response); /* XXX */
2462		milter_error(m, e);
2463		return -1;
2464	}
2465
2466	/* extract information */
2467	(void) memcpy((char *) &fvers, response, MILTER_LEN_BYTES);
2468
2469	/* Now make sure we have enough for the feature bitmap */
2470	if (rlen < MILTER_OPTLEN)
2471	{
2472		if (tTd(64, 5))
2473			sm_dprintf("milter_negotiate(%s): did not return enough info\n",
2474				m->mf_name);
2475		if (MilterLogLevel > 0)
2476			sm_syslog(LOG_ERR, e->e_id,
2477				  "Milter (%s): negotiate: did not return enough info",
2478				  m->mf_name);
2479		if (response != NULL)
2480			sm_free(response); /* XXX */
2481		milter_error(m, e);
2482		return -1;
2483	}
2484
2485	(void) memcpy((char *) &fflags, response + MILTER_LEN_BYTES,
2486		      MILTER_LEN_BYTES);
2487	(void) memcpy((char *) &pflags, response + (MILTER_LEN_BYTES * 2),
2488		      MILTER_LEN_BYTES);
2489
2490	m->mf_fvers = ntohl(fvers);
2491	m->mf_fflags = ntohl(fflags);
2492	m->mf_pflags = ntohl(pflags);
2493
2494	/* check for version compatibility */
2495	if (m->mf_fvers == 1 ||
2496	    m->mf_fvers > SMFI_VERSION)
2497	{
2498		if (tTd(64, 5))
2499			sm_dprintf("milter_negotiate(%s): version %d != MTA milter version %d\n",
2500				m->mf_name, m->mf_fvers, SMFI_VERSION);
2501		if (MilterLogLevel > 0)
2502			sm_syslog(LOG_ERR, e->e_id,
2503				  "Milter (%s): negotiate: version %d != MTA milter version %d",
2504				  m->mf_name, m->mf_fvers, SMFI_VERSION);
2505		milter_error(m, e);
2506		goto error;
2507	}
2508
2509	/* check for filter feature mismatch */
2510	if ((m->mf_fflags & mta_actions) != m->mf_fflags)
2511	{
2512		if (tTd(64, 5))
2513			sm_dprintf("milter_negotiate(%s): filter abilities 0x%x != MTA milter abilities 0x%lx\n",
2514				m->mf_name, m->mf_fflags,
2515				(unsigned long) mta_actions);
2516		if (MilterLogLevel > 0)
2517			sm_syslog(LOG_ERR, e->e_id,
2518				  "Milter (%s): negotiate: filter abilities 0x%x != MTA milter abilities 0x%lx",
2519				  m->mf_name, m->mf_fflags,
2520				  (unsigned long) mta_actions);
2521		milter_error(m, e);
2522		goto error;
2523	}
2524
2525#if _FFR_MDS_NEGOTIATE
2526	/* use a table instead of sequence? */
2527	if (bitset(SMFIP_MDS_1M, m->mf_pflags))
2528	{
2529		if (MilterMaxDataSize != MILTER_MDS_1M)
2530		{
2531			/* this should not happen... */
2532			sm_syslog(LOG_WARNING, NOQID,
2533				  "WARNING: Milter.maxdatasize: configured=%lu, set by libmilter=%d",
2534				  (unsigned long) MilterMaxDataSize,
2535				  MILTER_MDS_1M);
2536			MilterMaxDataSize = MILTER_MDS_1M;
2537		}
2538	}
2539	else if (bitset(SMFIP_MDS_256K, m->mf_pflags))
2540	{
2541		if (MilterMaxDataSize != MILTER_MDS_256K)
2542		{
2543			sm_syslog(LOG_WARNING, NOQID,
2544				  "WARNING: Milter.maxdatasize: configured=%lu, set by libmilter=%d",
2545				  (unsigned long) MilterMaxDataSize,
2546				  MILTER_MDS_256K);
2547			MilterMaxDataSize = MILTER_MDS_256K;
2548		}
2549	}
2550	else if (MilterMaxDataSize != MILTER_MDS_64K)
2551	{
2552		sm_syslog(LOG_WARNING, NOQID,
2553			  "WARNING: Milter.maxdatasize: configured=%lu, set by libmilter=%d",
2554			  (unsigned long) MilterMaxDataSize,
2555			  MILTER_MDS_64K);
2556		MilterMaxDataSize = MILTER_MDS_64K;
2557	}
2558	m->mf_pflags &= ~SMFI_INTERNAL;
2559#endif /* _FFR_MDS_NEGOTIATE */
2560
2561	/* check for protocol feature mismatch */
2562	if ((m->mf_pflags & mta_prot_flags) != m->mf_pflags)
2563	{
2564		if (tTd(64, 5))
2565			sm_dprintf("milter_negotiate(%s): protocol abilities 0x%x != MTA milter abilities 0x%lx\n",
2566				m->mf_name, m->mf_pflags,
2567				(unsigned long) mta_prot_flags);
2568		if (MilterLogLevel > 0)
2569			sm_syslog(LOG_ERR, e->e_id,
2570				  "Milter (%s): negotiate: protocol abilities 0x%x != MTA milter abilities 0x%lx",
2571				  m->mf_name, m->mf_pflags,
2572				  (unsigned long) mta_prot_flags);
2573		milter_error(m, e);
2574		goto error;
2575	}
2576
2577	if (m->mf_fvers <= 2)
2578		m->mf_pflags |= SMFIP_NOUNKNOWN;
2579	if (m->mf_fvers <= 3)
2580		m->mf_pflags |= SMFIP_NODATA;
2581
2582	if (rlen > MILTER_OPTLEN)
2583	{
2584		milter_getsymlist(m, response, rlen, MILTER_OPTLEN);
2585	}
2586
2587	if (bitset(SMFIF_DELRCPT, m->mf_fflags))
2588		milters->mis_flags |= MIS_FL_DEL_RCPT;
2589	if (!bitset(SMFIP_NORCPT, m->mf_pflags) &&
2590	    !bitset(SMFIP_NR_RCPT, m->mf_pflags))
2591		milters->mis_flags |= MIS_FL_REJ_RCPT;
2592
2593	if (tTd(64, 5))
2594		sm_dprintf("milter_negotiate(%s): received: version %u, fflags 0x%x, pflags 0x%x\n",
2595			m->mf_name, m->mf_fvers, m->mf_fflags, m->mf_pflags);
2596	return 0;
2597
2598  error:
2599	if (response != NULL)
2600		sm_free(response); /* XXX */
2601	return -1;
2602}
2603
2604/*
2605**  MILTER_PER_CONNECTION_CHECK -- checks on per-connection commands
2606**
2607**	Reduce code duplication by putting these checks in one place
2608**
2609**	Parameters:
2610**		e -- current envelope.
2611**
2612**	Returns:
2613**		none
2614*/
2615
2616static void
2617milter_per_connection_check(e)
2618	ENVELOPE *e;
2619{
2620	int i;
2621
2622	/* see if we are done with any of the filters */
2623	for (i = 0; InputFilters[i] != NULL; i++)
2624	{
2625		struct milter *m = InputFilters[i];
2626
2627		if (m->mf_state == SMFS_CLOSABLE)
2628			milter_quit_filter(m, e);
2629	}
2630}
2631
2632/*
2633**  MILTER_ERROR -- Put a milter filter into error state
2634**
2635**	Parameters:
2636**		m -- the broken filter.
2637**		e -- current envelope.
2638**
2639**	Returns:
2640**		none
2641*/
2642
2643static void
2644milter_error(m, e)
2645	struct milter *m;
2646	ENVELOPE *e;
2647{
2648	/*
2649	**  We could send a quit here but we may have gotten here due to
2650	**  an I/O error so we don't want to try to make things worse.
2651	*/
2652
2653	if (m->mf_sock >= 0)
2654	{
2655		(void) close(m->mf_sock);
2656		m->mf_sock = -1;
2657	}
2658	m->mf_state = SMFS_ERROR;
2659
2660	if (MilterLogLevel > 0)
2661		sm_syslog(LOG_INFO, e->e_id, "Milter (%s): to error state",
2662			  m->mf_name);
2663}
2664
2665/*
2666**  MILTER_HEADERS -- send headers to a single milter filter
2667**
2668**	Parameters:
2669**		m -- current filter.
2670**		e -- current envelope.
2671**		state -- return state from response.
2672**
2673**	Returns:
2674**		response string (may be NULL)
2675*/
2676
2677static char *
2678milter_headers(m, e, state)
2679	struct milter *m;
2680	ENVELOPE *e;
2681	char *state;
2682{
2683	char *response = NULL;
2684	HDR *h;
2685
2686	if (MilterLogLevel > 17)
2687		sm_syslog(LOG_INFO, e->e_id, "Milter (%s): headers, send",
2688			  m->mf_name);
2689
2690	for (h = e->e_header; h != NULL; h = h->h_link)
2691	{
2692		int len_n, len_v, len_t, len_f;
2693		char *buf, *hv;
2694
2695		/* don't send over deleted headers */
2696		if (h->h_value == NULL)
2697		{
2698			/* strip H_USER so not counted in milter_changeheader() */
2699			h->h_flags &= ~H_USER;
2700			continue;
2701		}
2702
2703		/* skip auto-generated */
2704		if (!bitset(H_USER, h->h_flags))
2705			continue;
2706
2707		if (tTd(64, 10))
2708			sm_dprintf("milter_headers: %s:%s\n",
2709				h->h_field, h->h_value);
2710		if (MilterLogLevel > 21)
2711			sm_syslog(LOG_INFO, e->e_id, "Milter (%s): header, %s",
2712				  m->mf_name, h->h_field);
2713
2714		if (bitset(SMFIP_HDR_LEADSPC, m->mf_pflags)
2715		    || *(h->h_value) != ' ')
2716			hv = h->h_value;
2717		else
2718			hv = h->h_value + 1;
2719		len_f = strlen(h->h_field) + 1;
2720		len_t = len_f + strlen(hv) + 1;
2721		if (len_t < 0)
2722			continue;
2723		buf = (char *) xalloc(len_t);
2724
2725		/*
2726		**  Note: currently the call to dequote_internal_chars()
2727		**  is not required as h_field is supposed to be 7-bit US-ASCII.
2728		*/
2729
2730		len_n = dequote_internal_chars(h->h_field, buf, len_f);
2731		SM_ASSERT(len_n < len_f);
2732		len_v = dequote_internal_chars(hv, buf + len_n + 1,
2733						len_t - len_n - 1);
2734		SM_ASSERT(len_t >= len_n + 1 + len_v + 1);
2735		len_t = len_n + 1 + len_v + 1;
2736
2737		/* send it over */
2738		response = milter_send_command(m, SMFIC_HEADER, buf,
2739					       len_t, e, state, "header");
2740		sm_free(buf);
2741		if (m->mf_state == SMFS_ERROR ||
2742		    m->mf_state == SMFS_DONE ||
2743		    *state != SMFIR_CONTINUE)
2744			break;
2745	}
2746	if (MilterLogLevel > 17)
2747		sm_syslog(LOG_INFO, e->e_id, "Milter (%s): headers, sent",
2748			  m->mf_name);
2749	return response;
2750}
2751
2752/*
2753**  MILTER_BODY -- send the body to a filter
2754**
2755**	Parameters:
2756**		m -- current filter.
2757**		e -- current envelope.
2758**		state -- return state from response.
2759**
2760**	Returns:
2761**		response string (may be NULL)
2762*/
2763
2764static char *
2765milter_body(m, e, state)
2766	struct milter *m;
2767	ENVELOPE *e;
2768	char *state;
2769{
2770	char bufchar = '\0';
2771	char prevchar = '\0';
2772	int c;
2773	char *response = NULL;
2774	char *bp;
2775	char buf[MILTER_CHUNK_SIZE];
2776
2777	if (tTd(64, 10))
2778		sm_dprintf("milter_body\n");
2779
2780	if (bfrewind(e->e_dfp) < 0)
2781	{
2782		ExitStat = EX_IOERR;
2783		*state = SMFIR_TEMPFAIL;
2784		syserr("milter_body: %s/%cf%s: rewind error",
2785		       qid_printqueue(e->e_qgrp, e->e_qdir),
2786		       DATAFL_LETTER, e->e_id);
2787		return NULL;
2788	}
2789
2790	if (MilterLogLevel > 17)
2791		sm_syslog(LOG_INFO, e->e_id, "Milter (%s): body, send",
2792			  m->mf_name);
2793	bp = buf;
2794	while ((c = sm_io_getc(e->e_dfp, SM_TIME_DEFAULT)) != SM_IO_EOF)
2795	{
2796		/*  Change LF to CRLF */
2797		if (c == '\n')
2798		{
2799#if !_FFR_MILTER_CONVERT_ALL_LF_TO_CRLF
2800			/* Not a CRLF already? */
2801			if (prevchar != '\r')
2802#endif /* !_FFR_MILTER_CONVERT_ALL_LF_TO_CRLF */
2803			{
2804				/* Room for CR now? */
2805				if (bp + 2 > &buf[sizeof(buf)])
2806				{
2807					/* No room, buffer LF */
2808					bufchar = c;
2809
2810					/* and send CR now */
2811					c = '\r';
2812				}
2813				else
2814				{
2815					/* Room to do it now */
2816					*bp++ = '\r';
2817					prevchar = '\r';
2818				}
2819			}
2820		}
2821		*bp++ = (char) c;
2822		prevchar = c;
2823		if (bp >= &buf[sizeof(buf)])
2824		{
2825			/* send chunk */
2826			response = milter_send_command(m, SMFIC_BODY, buf,
2827						       bp - buf, e, state,
2828							"body chunk");
2829			bp = buf;
2830			if (bufchar != '\0')
2831			{
2832				*bp++ = bufchar;
2833				bufchar = '\0';
2834				prevchar = bufchar;
2835			}
2836		}
2837		if (m->mf_state == SMFS_ERROR ||
2838		    m->mf_state == SMFS_DONE ||
2839		    m->mf_state == SMFS_SKIP ||
2840		    *state != SMFIR_CONTINUE)
2841			break;
2842	}
2843
2844	/* check for read errors */
2845	if (sm_io_error(e->e_dfp))
2846	{
2847		ExitStat = EX_IOERR;
2848		if (*state == SMFIR_CONTINUE ||
2849		    *state == SMFIR_ACCEPT ||
2850		    m->mf_state == SMFS_SKIP)
2851		{
2852			*state = SMFIR_TEMPFAIL;
2853			if (response != NULL)
2854			{
2855				sm_free(response); /* XXX */
2856				response = NULL;
2857			}
2858		}
2859		syserr("milter_body: %s/%cf%s: read error",
2860		       qid_printqueue(e->e_qgrp, e->e_qdir),
2861		       DATAFL_LETTER, e->e_id);
2862		return response;
2863	}
2864
2865	/* send last body chunk */
2866	if (bp > buf &&
2867	    m->mf_state != SMFS_ERROR &&
2868	    m->mf_state != SMFS_DONE &&
2869	    m->mf_state != SMFS_SKIP &&
2870	    *state == SMFIR_CONTINUE)
2871	{
2872		/* send chunk */
2873		response = milter_send_command(m, SMFIC_BODY, buf, bp - buf,
2874					       e, state, "last body chunk");
2875		bp = buf;
2876	}
2877	if (MilterLogLevel > 17)
2878		sm_syslog(LOG_INFO, e->e_id, "Milter (%s): body, sent",
2879			  m->mf_name);
2880	if (m->mf_state == SMFS_SKIP)
2881	{
2882		*state = SMFIR_CONTINUE;
2883		m->mf_state = SMFS_READY;
2884	}
2885
2886	return response;
2887}
2888
2889/*
2890**  Actions
2891*/
2892
2893/*
2894**  ADDLEADINGSPACE -- Add a leading space to a string
2895**
2896**	Parameters:
2897**		str -- string
2898**		rp -- resource pool for allocations
2899**
2900**	Returns:
2901**		pointer to new string
2902*/
2903
2904static char *addleadingspace __P((char *, SM_RPOOL_T *));
2905
2906static char *
2907addleadingspace(str, rp)
2908	char *str;
2909	SM_RPOOL_T *rp;
2910{
2911	size_t l;
2912	char *new;
2913
2914	SM_ASSERT(str != NULL);
2915	l = strlen(str);
2916	SM_ASSERT(l + 2 > l);
2917	new = sm_rpool_malloc_x(rp, l + 2);
2918	new[0] = ' ';
2919	new[1] = '\0';
2920	sm_strlcpy(new + 1, str, l + 1);
2921	return new;
2922}
2923
2924/*
2925**  MILTER_ADDHEADER -- Add the supplied header to the message
2926**
2927**	Parameters:
2928**		m -- current filter.
2929**		response -- encoded form of header/value.
2930**		rlen -- length of response.
2931**		e -- current envelope.
2932**
2933**	Returns:
2934**		none
2935*/
2936
2937static void
2938milter_addheader(m, response, rlen, e)
2939	struct milter *m;
2940	char *response;
2941	ssize_t rlen;
2942	ENVELOPE *e;
2943{
2944	int mh_v_len;
2945	char *val, *mh_value;
2946	HDR *h;
2947
2948	if (tTd(64, 10))
2949		sm_dprintf("milter_addheader: ");
2950
2951	/* sanity checks */
2952	if (response == NULL)
2953	{
2954		if (tTd(64, 10))
2955			sm_dprintf("NULL response\n");
2956		return;
2957	}
2958
2959	if (rlen < 2 || strlen(response) + 1 >= (size_t) rlen)
2960	{
2961		if (tTd(64, 10))
2962			sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n",
2963				   (int) strlen(response), (int) (rlen - 1));
2964		return;
2965	}
2966
2967	/* Find separating NUL */
2968	val = response + strlen(response) + 1;
2969
2970	/* another sanity check */
2971	if (strlen(response) + strlen(val) + 2 != (size_t) rlen)
2972	{
2973		if (tTd(64, 10))
2974			sm_dprintf("didn't follow protocol (part len)\n");
2975		return;
2976	}
2977
2978	if (*response == '\0')
2979	{
2980		if (tTd(64, 10))
2981			sm_dprintf("empty field name\n");
2982		return;
2983	}
2984
2985	for (h = e->e_header; h != NULL; h = h->h_link)
2986	{
2987		if (sm_strcasecmp(h->h_field, response) == 0 &&
2988		    !bitset(H_USER, h->h_flags) &&
2989		    !bitset(H_TRACE, h->h_flags))
2990			break;
2991	}
2992
2993	mh_v_len = 0;
2994	mh_value = quote_internal_chars(val, NULL, &mh_v_len);
2995
2996	/* add to e_msgsize */
2997	e->e_msgsize += strlen(response) + 2 + strlen(val);
2998
2999	if (h != NULL)
3000	{
3001		if (tTd(64, 10))
3002			sm_dprintf("Replace default header %s value with %s\n",
3003				   h->h_field, mh_value);
3004		if (MilterLogLevel > 8)
3005			sm_syslog(LOG_INFO, e->e_id,
3006				  "Milter change: default header %s value with %s",
3007				  h->h_field, mh_value);
3008		if (bitset(SMFIP_HDR_LEADSPC, m->mf_pflags))
3009			h->h_value = mh_value;
3010		else
3011		{
3012			h->h_value = addleadingspace(mh_value, e->e_rpool);
3013			SM_FREE(mh_value);
3014		}
3015		h->h_flags |= H_USER;
3016	}
3017	else
3018	{
3019		if (tTd(64, 10))
3020			sm_dprintf("Add %s: %s\n", response, mh_value);
3021		if (MilterLogLevel > 8)
3022			sm_syslog(LOG_INFO, e->e_id,
3023				  "Milter add: header: %s: %s",
3024				  response, mh_value);
3025		addheader(newstr(response), mh_value, H_USER, e,
3026			!bitset(SMFIP_HDR_LEADSPC, m->mf_pflags));
3027		SM_FREE(mh_value);
3028	}
3029}
3030
3031/*
3032**  MILTER_INSHEADER -- Insert the supplied header
3033**
3034**	Parameters:
3035**		m -- current filter.
3036**		response -- encoded form of header/value.
3037**		rlen -- length of response.
3038**		e -- current envelope.
3039**
3040**	Returns:
3041**		none
3042**
3043**	Notes:
3044**		Unlike milter_addheader(), this does not attempt to determine
3045**		if the header already exists in the envelope, even a
3046**		deleted version.  It just blindly inserts.
3047*/
3048
3049static void
3050milter_insheader(m, response, rlen, e)
3051	struct milter *m;
3052	char *response;
3053	ssize_t rlen;
3054	ENVELOPE *e;
3055{
3056	mi_int32 idx, i;
3057	int mh_v_len;
3058	char *field, *val, *mh_value;
3059
3060	if (tTd(64, 10))
3061		sm_dprintf("milter_insheader: ");
3062
3063	/* sanity checks */
3064	if (response == NULL)
3065	{
3066		if (tTd(64, 10))
3067			sm_dprintf("NULL response\n");
3068		return;
3069	}
3070
3071	if (rlen < 2 || strlen(response) + 1 >= (size_t) rlen)
3072	{
3073		if (tTd(64, 10))
3074			sm_dprintf("didn't follow protocol (total len)\n");
3075		return;
3076	}
3077
3078	/* decode */
3079	(void) memcpy((char *) &i, response, MILTER_LEN_BYTES);
3080	idx = ntohl(i);
3081	field = response + MILTER_LEN_BYTES;
3082	val = field + strlen(field) + 1;
3083
3084	/* another sanity check */
3085	if (MILTER_LEN_BYTES + strlen(field) + 1 +
3086	    strlen(val) + 1 != (size_t) rlen)
3087	{
3088		if (tTd(64, 10))
3089			sm_dprintf("didn't follow protocol (part len)\n");
3090		return;
3091	}
3092
3093	if (*field == '\0')
3094	{
3095		if (tTd(64, 10))
3096			sm_dprintf("empty field name\n");
3097		return;
3098	}
3099
3100	/* add to e_msgsize */
3101	e->e_msgsize += strlen(response) + 2 + strlen(val);
3102
3103	if (tTd(64, 10))
3104		sm_dprintf("Insert (%d) %s: %s\n", idx, field, val);
3105	if (MilterLogLevel > 8)
3106		sm_syslog(LOG_INFO, e->e_id,
3107			  "Milter insert (%d): header: %s: %s",
3108			  idx, field, val);
3109	mh_v_len = 0;
3110	mh_value = quote_internal_chars(val, NULL, &mh_v_len);
3111	insheader(idx, newstr(field), mh_value, H_USER, e,
3112		!bitset(SMFIP_HDR_LEADSPC, m->mf_pflags));
3113	SM_FREE(mh_value);
3114}
3115
3116/*
3117**  MILTER_CHANGEHEADER -- Change the supplied header in the message
3118**
3119**	Parameters:
3120**		m -- current filter.
3121**		response -- encoded form of header/index/value.
3122**		rlen -- length of response.
3123**		e -- current envelope.
3124**
3125**	Returns:
3126**		none
3127*/
3128
3129static void
3130milter_changeheader(m, response, rlen, e)
3131	struct milter *m;
3132	char *response;
3133	ssize_t rlen;
3134	ENVELOPE *e;
3135{
3136	mi_int32 i, index;
3137	int mh_v_len;
3138	char *field, *val, *mh_value;
3139	HDR *h, *sysheader;
3140
3141	if (tTd(64, 10))
3142		sm_dprintf("milter_changeheader: ");
3143
3144	/* sanity checks */
3145	if (response == NULL)
3146	{
3147		if (tTd(64, 10))
3148			sm_dprintf("NULL response\n");
3149		return;
3150	}
3151
3152	if (rlen < 2 || strlen(response) + 1 >= (size_t) rlen)
3153	{
3154		if (tTd(64, 10))
3155			sm_dprintf("didn't follow protocol (total len)\n");
3156		return;
3157	}
3158
3159	/* Find separating NUL */
3160	(void) memcpy((char *) &i, response, MILTER_LEN_BYTES);
3161	index = ntohl(i);
3162	field = response + MILTER_LEN_BYTES;
3163	val = field + strlen(field) + 1;
3164
3165	/* another sanity check */
3166	if (MILTER_LEN_BYTES + strlen(field) + 1 +
3167	    strlen(val) + 1 != (size_t) rlen)
3168	{
3169		if (tTd(64, 10))
3170			sm_dprintf("didn't follow protocol (part len)\n");
3171		return;
3172	}
3173
3174	if (*field == '\0')
3175	{
3176		if (tTd(64, 10))
3177			sm_dprintf("empty field name\n");
3178		return;
3179	}
3180
3181	mh_v_len = 0;
3182	mh_value = quote_internal_chars(val, NULL, &mh_v_len);
3183
3184	sysheader = NULL;
3185	for (h = e->e_header; h != NULL; h = h->h_link)
3186	{
3187		if (sm_strcasecmp(h->h_field, field) == 0)
3188		{
3189			if (bitset(H_USER, h->h_flags) && --index <= 0)
3190			{
3191				sysheader = NULL;
3192				break;
3193			}
3194			else if (!bitset(H_USER, h->h_flags) &&
3195				 !bitset(H_TRACE, h->h_flags))
3196			{
3197				/*
3198				**  DRUMS msg-fmt draft says can only have
3199				**  multiple occurences of trace fields,
3200				**  so make sure we replace any non-trace,
3201				**  non-user field.
3202				*/
3203
3204				sysheader = h;
3205			}
3206		}
3207	}
3208
3209	/* if not found as user-provided header at index, use sysheader */
3210	if (h == NULL)
3211		h = sysheader;
3212
3213	if (h == NULL)
3214	{
3215		if (*val == '\0')
3216		{
3217			if (tTd(64, 10))
3218				sm_dprintf("Delete (noop) %s\n", field);
3219			if (MilterLogLevel > 8)
3220				sm_syslog(LOG_INFO, e->e_id,
3221					"Milter delete (noop): header: %s"
3222					, field);
3223		}
3224		else
3225		{
3226			/* treat modify value with no existing header as add */
3227			if (tTd(64, 10))
3228				sm_dprintf("Add %s: %s\n", field, mh_value);
3229			if (MilterLogLevel > 8)
3230				sm_syslog(LOG_INFO, e->e_id,
3231					"Milter change (add): header: %s: %s"
3232					, field, mh_value);
3233			addheader(newstr(field), mh_value, H_USER, e,
3234				!bitset(SMFIP_HDR_LEADSPC, m->mf_pflags));
3235		}
3236		return;
3237	}
3238
3239	if (tTd(64, 10))
3240	{
3241		if (*val == '\0')
3242		{
3243			sm_dprintf("Delete%s %s:%s\n",
3244				   h == sysheader ? " (default header)" : "",
3245				   field,
3246				   h->h_value == NULL ? "<NULL>" : h->h_value);
3247		}
3248		else
3249		{
3250			sm_dprintf("Change%s %s: from %s to %s\n",
3251				   h == sysheader ? " (default header)" : "",
3252				   field,
3253				   h->h_value == NULL ? "<NULL>" : h->h_value,
3254				   mh_value);
3255		}
3256	}
3257
3258	if (MilterLogLevel > 8)
3259	{
3260		if (*val == '\0')
3261		{
3262			sm_syslog(LOG_INFO, e->e_id,
3263				  "Milter delete: header%s %s:%s",
3264				  h == sysheader ? " (default header)" : "",
3265				  field,
3266				  h->h_value == NULL ? "<NULL>" : h->h_value);
3267		}
3268		else
3269		{
3270			sm_syslog(LOG_INFO, e->e_id,
3271				  "Milter change: header%s %s: from %s to %s",
3272				  h == sysheader ? " (default header)" : "",
3273				  field,
3274				  h->h_value == NULL ? "<NULL>" : h->h_value,
3275				  mh_value);
3276		}
3277	}
3278
3279	if (h != sysheader && h->h_value != NULL)
3280	{
3281		size_t l;
3282
3283		l = strlen(h->h_value);
3284		if (l > e->e_msgsize)
3285			e->e_msgsize = 0;
3286		else
3287			e->e_msgsize -= l;
3288		/* rpool, don't free: sm_free(h->h_value); XXX */
3289	}
3290
3291	if (*val == '\0')
3292	{
3293		/* Remove "Field: " from message size */
3294		if (h != sysheader)
3295		{
3296			size_t l;
3297
3298			l = strlen(h->h_field) + 2;
3299			if (l > e->e_msgsize)
3300				e->e_msgsize = 0;
3301			else
3302				e->e_msgsize -= l;
3303		}
3304		h->h_value = NULL;
3305		SM_FREE(mh_value);
3306	}
3307	else
3308	{
3309		if (bitset(SMFIP_HDR_LEADSPC, m->mf_pflags))
3310			h->h_value = mh_value;
3311		else
3312		{
3313			h->h_value = addleadingspace(mh_value, e->e_rpool);
3314			SM_FREE(mh_value);
3315		}
3316		h->h_flags |= H_USER;
3317		e->e_msgsize += strlen(h->h_value);
3318	}
3319}
3320
3321/*
3322**  MILTER_SPLIT_RESPONSE -- Split response into fields.
3323**
3324**	Parameters:
3325**		response -- encoded repsonse.
3326**		rlen -- length of response.
3327**		pargc -- number of arguments (ouput)
3328**
3329**	Returns:
3330**		array of pointers to the individual strings
3331*/
3332
3333static char **milter_split_response __P((char *, ssize_t, int *));
3334
3335static char **
3336milter_split_response(response, rlen, pargc)
3337	char *response;
3338	ssize_t rlen;
3339	int *pargc;
3340{
3341	char **s;
3342	size_t i;
3343	int elem, nelem;
3344
3345	SM_ASSERT(response != NULL);
3346	SM_ASSERT(pargc != NULL);
3347	*pargc = 0;
3348	if (rlen < 2 || strlen(response) >= (size_t) rlen)
3349	{
3350		if (tTd(64, 10))
3351			sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n",
3352				   (int) strlen(response), (int) (rlen - 1));
3353		return NULL;
3354	}
3355
3356	nelem = 0;
3357	for (i = 0; i < rlen; i++)
3358	{
3359		if (response[i] == '\0')
3360			++nelem;
3361	}
3362	if (nelem == 0)
3363		return NULL;
3364
3365	/* last entry is only for the name */
3366	s = (char **)malloc((nelem + 1) * (sizeof(*s)));
3367	if (s == NULL)
3368		return NULL;
3369	s[0] = response;
3370	for (i = 0, elem = 0; i < rlen && elem < nelem; i++)
3371	{
3372		if (response[i] == '\0')
3373		{
3374			++elem;
3375			if (i + 1 >= rlen)
3376				s[elem] = NULL;
3377			else
3378				s[elem] = &(response[i + 1]);
3379		}
3380	}
3381	*pargc = nelem;
3382
3383	if (tTd(64, 10))
3384	{
3385		for (elem = 0; elem < nelem; elem++)
3386			sm_dprintf("argv[%d]=\"%s\"\n", elem, s[elem]);
3387	}
3388
3389	/* overwrite last entry (already done above, just paranoia) */
3390	s[elem] = NULL;
3391	return s;
3392}
3393
3394/*
3395**  MILTER_CHGFROM -- Change the envelope sender address
3396**
3397**	Parameters:
3398**		response -- encoded form of recipient address.
3399**		rlen -- length of response.
3400**		e -- current envelope.
3401**
3402**	Returns:
3403**		none
3404*/
3405
3406static void
3407milter_chgfrom(response, rlen, e)
3408	char *response;
3409	ssize_t rlen;
3410	ENVELOPE *e;
3411{
3412	int olderrors, argc;
3413	char **argv;
3414
3415	if (tTd(64, 10))
3416		sm_dprintf("milter_chgfrom: ");
3417
3418	/* sanity checks */
3419	if (response == NULL)
3420	{
3421		if (tTd(64, 10))
3422			sm_dprintf("NULL response\n");
3423		return;
3424	}
3425
3426	if (*response == '\0' ||
3427	    strlen(response) + 1 > (size_t) rlen)
3428	{
3429		if (tTd(64, 10))
3430			sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n",
3431				   (int) strlen(response), (int) (rlen - 1));
3432		return;
3433	}
3434
3435	if (tTd(64, 10))
3436		sm_dprintf("%s\n", response);
3437	if (MilterLogLevel > 8)
3438		sm_syslog(LOG_INFO, e->e_id, "Milter chgfrom: %s", response);
3439	argv = milter_split_response(response, rlen, &argc);
3440	if (argc < 1 || argc > 2)
3441	{
3442		if (tTd(64, 10))
3443			sm_dprintf("didn't follow protocol argc=%d\n", argc);
3444		return;
3445	}
3446
3447	olderrors = Errors;
3448	setsender(argv[0], e, NULL, '\0', false);
3449	if (argc == 2)
3450	{
3451		reset_mail_esmtp_args(e);
3452
3453		/*
3454		**  need "features" here: how to get those? via e?
3455		**  "fake" it for now: allow everything.
3456		*/
3457
3458		parse_esmtp_args(e, NULL, argv[0], argv[1], "MAIL", NULL,
3459				mail_esmtp_args);
3460	}
3461	Errors = olderrors;
3462	return;
3463}
3464
3465/*
3466**  MILTER_ADDRCPT_PAR -- Add the supplied recipient to the message
3467**
3468**	Parameters:
3469**		response -- encoded form of recipient address.
3470**		rlen -- length of response.
3471**		e -- current envelope.
3472**
3473**	Returns:
3474**		none
3475*/
3476
3477static void
3478milter_addrcpt_par(response, rlen, e)
3479	char *response;
3480	ssize_t rlen;
3481	ENVELOPE *e;
3482{
3483	int olderrors, argc;
3484	char *delimptr;
3485	char **argv;
3486	ADDRESS *a;
3487
3488	if (tTd(64, 10))
3489		sm_dprintf("milter_addrcpt_par: ");
3490
3491	/* sanity checks */
3492	if (response == NULL)
3493	{
3494		if (tTd(64, 10))
3495			sm_dprintf("NULL response\n");
3496		return;
3497	}
3498
3499	if (tTd(64, 10))
3500		sm_dprintf("%s\n", response);
3501	if (MilterLogLevel > 8)
3502		sm_syslog(LOG_INFO, e->e_id, "Milter add: rcpt: %s", response);
3503
3504	argv = milter_split_response(response, rlen, &argc);
3505	if (argc < 1 || argc > 2)
3506	{
3507		if (tTd(64, 10))
3508			sm_dprintf("didn't follow protocol argc=%d\n", argc);
3509		return;
3510	}
3511	olderrors = Errors;
3512
3513	/* how to set ESMTP arguments? */
3514	a = parseaddr(argv[0], NULLADDR, RF_COPYALL, ' ', &delimptr, e, true);
3515
3516	if (a != NULL && olderrors == Errors)
3517	{
3518		parse_esmtp_args(e, a, argv[0], argv[1], "RCPT", NULL,
3519				rcpt_esmtp_args);
3520		if (olderrors == Errors)
3521			a = recipient(a, &e->e_sendqueue, 0, e);
3522		else
3523			sm_dprintf("olderrors=%d, Errors=%d\n",
3524				olderrors, Errors);
3525	}
3526	else
3527	{
3528		sm_dprintf("a=%p, olderrors=%d, Errors=%d\n",
3529			a, olderrors, Errors);
3530	}
3531
3532	Errors = olderrors;
3533	return;
3534}
3535
3536/*
3537**  MILTER_ADDRCPT -- Add the supplied recipient to the message
3538**
3539**	Parameters:
3540**		response -- encoded form of recipient address.
3541**		rlen -- length of response.
3542**		e -- current envelope.
3543**
3544**	Returns:
3545**		none
3546*/
3547
3548static void
3549milter_addrcpt(response, rlen, e)
3550	char *response;
3551	ssize_t rlen;
3552	ENVELOPE *e;
3553{
3554	int olderrors;
3555
3556	if (tTd(64, 10))
3557		sm_dprintf("milter_addrcpt: ");
3558
3559	/* sanity checks */
3560	if (response == NULL)
3561	{
3562		if (tTd(64, 10))
3563			sm_dprintf("NULL response\n");
3564		return;
3565	}
3566
3567	if (*response == '\0' ||
3568	    strlen(response) + 1 != (size_t) rlen)
3569	{
3570		if (tTd(64, 10))
3571			sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n",
3572				   (int) strlen(response), (int) (rlen - 1));
3573		return;
3574	}
3575
3576	if (tTd(64, 10))
3577		sm_dprintf("%s\n", response);
3578	if (MilterLogLevel > 8)
3579		sm_syslog(LOG_INFO, e->e_id, "Milter add: rcpt: %s", response);
3580	olderrors = Errors;
3581	(void) sendtolist(response, NULLADDR, &e->e_sendqueue, 0, e);
3582	Errors = olderrors;
3583	return;
3584}
3585
3586/*
3587**  MILTER_DELRCPT -- Delete the supplied recipient from the message
3588**
3589**	Parameters:
3590**		response -- encoded form of recipient address.
3591**		rlen -- length of response.
3592**		e -- current envelope.
3593**
3594**	Returns:
3595**		none
3596*/
3597
3598static void
3599milter_delrcpt(response, rlen, e)
3600	char *response;
3601	ssize_t rlen;
3602	ENVELOPE *e;
3603{
3604	if (tTd(64, 10))
3605		sm_dprintf("milter_delrcpt: ");
3606
3607	/* sanity checks */
3608	if (response == NULL)
3609	{
3610		if (tTd(64, 10))
3611			sm_dprintf("NULL response\n");
3612		return;
3613	}
3614
3615	if (*response == '\0' ||
3616	    strlen(response) + 1 != (size_t) rlen)
3617	{
3618		if (tTd(64, 10))
3619			sm_dprintf("didn't follow protocol (total len %d != rlen %d)\n",
3620				   (int) strlen(response), (int) (rlen - 1));
3621		return;
3622	}
3623
3624	if (tTd(64, 10))
3625		sm_dprintf("%s\n", response);
3626	if (MilterLogLevel > 8)
3627		sm_syslog(LOG_INFO, e->e_id, "Milter delete: rcpt %s",
3628			  response);
3629	(void) removefromlist(response, &e->e_sendqueue, e);
3630	return;
3631}
3632
3633/*
3634**  MILTER_REPLBODY -- Replace the current data file with new body
3635**
3636**	Parameters:
3637**		response -- encoded form of new body.
3638**		rlen -- length of response.
3639**		newfilter -- if first time called by a new filter
3640**		e -- current envelope.
3641**
3642**	Returns:
3643**		0 upon success, -1 upon failure
3644*/
3645
3646static int
3647milter_replbody(response, rlen, newfilter, e)
3648	char *response;
3649	ssize_t rlen;
3650	bool newfilter;
3651	ENVELOPE *e;
3652{
3653	static char prevchar;
3654	int i;
3655
3656	if (tTd(64, 10))
3657		sm_dprintf("milter_replbody\n");
3658
3659	/* If a new filter, reset previous character and truncate data file */
3660	if (newfilter)
3661	{
3662		off_t prevsize;
3663		char dfname[MAXPATHLEN];
3664
3665		(void) sm_strlcpy(dfname, queuename(e, DATAFL_LETTER),
3666				  sizeof(dfname));
3667
3668		/* Reset prevchar */
3669		prevchar = '\0';
3670
3671		/* Get the current data file information */
3672		prevsize = sm_io_getinfo(e->e_dfp, SM_IO_WHAT_SIZE, NULL);
3673		if (prevsize < 0)
3674			prevsize = 0;
3675
3676		/* truncate current data file */
3677		if (sm_io_getinfo(e->e_dfp, SM_IO_WHAT_ISTYPE, BF_FILE_TYPE))
3678		{
3679			if (sm_io_setinfo(e->e_dfp, SM_BF_TRUNCATE, NULL) < 0)
3680			{
3681				MILTER_DF_ERROR("milter_replbody: sm_io truncate %s: %s");
3682				return -1;
3683			}
3684		}
3685		else
3686		{
3687			int err;
3688
3689			err = sm_io_error(e->e_dfp);
3690			(void) sm_io_flush(e->e_dfp, SM_TIME_DEFAULT);
3691
3692			/*
3693			**  Clear error if tried to fflush()
3694			**  a read-only file pointer and
3695			**  there wasn't a previous error.
3696			*/
3697
3698			if (err == 0)
3699				sm_io_clearerr(e->e_dfp);
3700
3701			/* errno is set implicitly by fseek() before return */
3702			err = sm_io_seek(e->e_dfp, SM_TIME_DEFAULT,
3703					 0, SEEK_SET);
3704			if (err < 0)
3705			{
3706				MILTER_DF_ERROR("milter_replbody: sm_io_seek %s: %s");
3707				return -1;
3708			}
3709# if NOFTRUNCATE
3710			/* XXX: Not much we can do except rewind it */
3711			errno = EINVAL;
3712			MILTER_DF_ERROR("milter_replbody: ftruncate not available on this platform (%s:%s)");
3713			return -1;
3714# else /* NOFTRUNCATE */
3715			err = ftruncate(sm_io_getinfo(e->e_dfp,
3716						      SM_IO_WHAT_FD, NULL),
3717					0);
3718			if (err < 0)
3719			{
3720				MILTER_DF_ERROR("milter_replbody: sm_io ftruncate %s: %s");
3721				return -1;
3722			}
3723# endif /* NOFTRUNCATE */
3724		}
3725
3726		if (prevsize > e->e_msgsize)
3727			e->e_msgsize = 0;
3728		else
3729			e->e_msgsize -= prevsize;
3730	}
3731
3732	if (newfilter && MilterLogLevel > 8)
3733		sm_syslog(LOG_INFO, e->e_id, "Milter message: body replaced");
3734
3735	if (response == NULL)
3736	{
3737		/* Flush the buffered '\r' */
3738		if (prevchar == '\r')
3739		{
3740			(void) sm_io_putc(e->e_dfp, SM_TIME_DEFAULT, prevchar);
3741			e->e_msgsize++;
3742		}
3743		return 0;
3744	}
3745
3746	for (i = 0; i < rlen; i++)
3747	{
3748		/* Buffered char from last chunk */
3749		if (i == 0 && prevchar == '\r')
3750		{
3751			/* Not CRLF, output prevchar */
3752			if (response[i] != '\n')
3753			{
3754				(void) sm_io_putc(e->e_dfp, SM_TIME_DEFAULT,
3755						  prevchar);
3756				e->e_msgsize++;
3757			}
3758			prevchar = '\0';
3759		}
3760
3761		/* Turn CRLF into LF */
3762		if (response[i] == '\r')
3763		{
3764			/* check if at end of chunk */
3765			if (i + 1 < rlen)
3766			{
3767				/* If LF, strip CR */
3768				if (response[i + 1] == '\n')
3769					i++;
3770			}
3771			else
3772			{
3773				/* check next chunk */
3774				prevchar = '\r';
3775				continue;
3776			}
3777		}
3778		(void) sm_io_putc(e->e_dfp, SM_TIME_DEFAULT, response[i]);
3779		e->e_msgsize++;
3780	}
3781	return 0;
3782}
3783
3784/*
3785**  MTA callouts
3786*/
3787
3788/*
3789**  MILTER_INIT -- open and negotiate with all of the filters
3790**
3791**	Parameters:
3792**		e -- current envelope.
3793**		state -- return state from response.
3794**		milters -- milters structure.
3795**
3796**	Returns:
3797**		true iff at least one filter is active
3798*/
3799
3800/* ARGSUSED */
3801bool
3802milter_init(e, state, milters)
3803	ENVELOPE *e;
3804	char *state;
3805	milters_T *milters;
3806{
3807	int i;
3808
3809	if (tTd(64, 10))
3810		sm_dprintf("milter_init\n");
3811
3812	memset(milters, '\0', sizeof(*milters));
3813	*state = SMFIR_CONTINUE;
3814	if (InputFilters[0] == NULL)
3815	{
3816		if (MilterLogLevel > 10)
3817			sm_syslog(LOG_INFO, e->e_id,
3818				  "Milter: no active filter");
3819		return false;
3820	}
3821
3822	for (i = 0; InputFilters[i] != NULL; i++)
3823	{
3824		struct milter *m = InputFilters[i];
3825
3826		m->mf_sock = milter_open(m, false, e);
3827		if (m->mf_state == SMFS_ERROR)
3828		{
3829			MILTER_CHECK_ERROR(true, continue);
3830			break;
3831		}
3832
3833		if (m->mf_sock < 0 ||
3834		    milter_negotiate(m, e, milters) < 0 ||
3835		    m->mf_state == SMFS_ERROR)
3836		{
3837			if (tTd(64, 5))
3838				sm_dprintf("milter_init(%s): failed to %s\n",
3839					   m->mf_name,
3840					   m->mf_sock < 0 ? "open" :
3841							    "negotiate");
3842			if (MilterLogLevel > 0)
3843				sm_syslog(LOG_ERR, e->e_id,
3844					  "Milter (%s): init failed to %s",
3845					  m->mf_name,
3846					  m->mf_sock < 0 ? "open" :
3847							   "negotiate");
3848
3849			/* if negotiation failure, close socket */
3850			milter_error(m, e);
3851			MILTER_CHECK_ERROR(true, continue);
3852			continue;
3853		}
3854		if (MilterLogLevel > 9)
3855			sm_syslog(LOG_INFO, e->e_id,
3856				  "Milter (%s): init success to %s",
3857				  m->mf_name,
3858				  m->mf_sock < 0 ? "open" : "negotiate");
3859	}
3860
3861	/*
3862	**  If something temp/perm failed with one of the filters,
3863	**  we won't be using any of them, so clear any existing
3864	**  connections.
3865	*/
3866
3867	if (*state != SMFIR_CONTINUE)
3868		milter_quit(e);
3869
3870	return true;
3871}
3872
3873/*
3874**  MILTER_CONNECT -- send connection info to milter filters
3875**
3876**	Parameters:
3877**		hostname -- hostname of remote machine.
3878**		addr -- address of remote machine.
3879**		e -- current envelope.
3880**		state -- return state from response.
3881**
3882**	Returns:
3883**		response string (may be NULL)
3884*/
3885
3886char *
3887milter_connect(hostname, addr, e, state)
3888	char *hostname;
3889	SOCKADDR addr;
3890	ENVELOPE *e;
3891	char *state;
3892{
3893	char family;
3894	unsigned short port;
3895	char *buf, *bp;
3896	char *response;
3897	char *sockinfo = NULL;
3898	ssize_t s;
3899# if NETINET6
3900	char buf6[INET6_ADDRSTRLEN];
3901# endif /* NETINET6 */
3902
3903	if (tTd(64, 10))
3904		sm_dprintf("milter_connect(%s)\n", hostname);
3905	if (MilterLogLevel > 9)
3906		sm_syslog(LOG_INFO, e->e_id, "Milter: connect to filters");
3907
3908	/* gather data */
3909	switch (addr.sa.sa_family)
3910	{
3911# if NETUNIX
3912	  case AF_UNIX:
3913		family = SMFIA_UNIX;
3914		port = htons(0);
3915		sockinfo = addr.sunix.sun_path;
3916		break;
3917# endif /* NETUNIX */
3918
3919# if NETINET
3920	  case AF_INET:
3921		family = SMFIA_INET;
3922		port = addr.sin.sin_port;
3923		sockinfo = (char *) inet_ntoa(addr.sin.sin_addr);
3924		break;
3925# endif /* NETINET */
3926
3927# if NETINET6
3928	  case AF_INET6:
3929		if (IN6_IS_ADDR_V4MAPPED(&addr.sin6.sin6_addr))
3930			family = SMFIA_INET;
3931		else
3932			family = SMFIA_INET6;
3933		port = addr.sin6.sin6_port;
3934		sockinfo = anynet_ntop(&addr.sin6.sin6_addr, buf6,
3935				       sizeof(buf6));
3936		if (sockinfo == NULL)
3937			sockinfo = "";
3938		break;
3939# endif /* NETINET6 */
3940
3941	  default:
3942		family = SMFIA_UNKNOWN;
3943		break;
3944	}
3945
3946	s = strlen(hostname) + 1 + sizeof(family);
3947	if (family != SMFIA_UNKNOWN)
3948		s += sizeof(port) + strlen(sockinfo) + 1;
3949
3950	buf = (char *) xalloc(s);
3951	bp = buf;
3952
3953	/* put together data */
3954	(void) memcpy(bp, hostname, strlen(hostname));
3955	bp += strlen(hostname);
3956	*bp++ = '\0';
3957	(void) memcpy(bp, &family, sizeof(family));
3958	bp += sizeof(family);
3959	if (family != SMFIA_UNKNOWN)
3960	{
3961		(void) memcpy(bp, &port, sizeof(port));
3962		bp += sizeof(port);
3963
3964		/* include trailing '\0' */
3965		(void) memcpy(bp, sockinfo, strlen(sockinfo) + 1);
3966	}
3967
3968	response = milter_command(SMFIC_CONNECT, buf, s, SMFIM_CONNECT,
3969				e, state, "connect", false);
3970	sm_free(buf); /* XXX */
3971
3972	/*
3973	**  If this message connection is done for,
3974	**  close the filters.
3975	*/
3976
3977	if (*state != SMFIR_CONTINUE)
3978	{
3979		if (MilterLogLevel > 9)
3980			sm_syslog(LOG_INFO, e->e_id, "Milter: connect, ending");
3981		milter_quit(e);
3982	}
3983	else
3984		milter_per_connection_check(e);
3985
3986#if !_FFR_MILTER_CONNECT_REPLYCODE
3987	/*
3988	**  SMFIR_REPLYCODE can't work with connect due to
3989	**  the requirements of SMTP.  Therefore, ignore the
3990	**  reply code text but keep the state it would reflect.
3991	*/
3992
3993	if (*state == SMFIR_REPLYCODE)
3994	{
3995		if (response != NULL &&
3996		    *response == '4')
3997		{
3998			if (strncmp(response, "421 ", 4) == 0)
3999				*state = SMFIR_SHUTDOWN;
4000			else
4001				*state = SMFIR_TEMPFAIL;
4002		}
4003		else
4004			*state = SMFIR_REJECT;
4005		if (response != NULL)
4006		{
4007			sm_free(response); /* XXX */
4008			response = NULL;
4009		}
4010	}
4011#endif /* !_FFR_MILTER_CONNECT_REPLYCODE */
4012	return response;
4013}
4014
4015/*
4016**  MILTER_HELO -- send SMTP HELO/EHLO command info to milter filters
4017**
4018**	Parameters:
4019**		helo -- argument to SMTP HELO/EHLO command.
4020**		e -- current envelope.
4021**		state -- return state from response.
4022**
4023**	Returns:
4024**		response string (may be NULL)
4025*/
4026
4027char *
4028milter_helo(helo, e, state)
4029	char *helo;
4030	ENVELOPE *e;
4031	char *state;
4032{
4033	int i;
4034	char *response;
4035
4036	if (tTd(64, 10))
4037		sm_dprintf("milter_helo(%s)\n", helo);
4038
4039	/* HELO/EHLO can come at any point */
4040	for (i = 0; InputFilters[i] != NULL; i++)
4041	{
4042		struct milter *m = InputFilters[i];
4043
4044		switch (m->mf_state)
4045		{
4046		  case SMFS_INMSG:
4047			/* abort in message filters */
4048			milter_abort_filter(m, e);
4049			/* FALLTHROUGH */
4050
4051		  case SMFS_DONE:
4052			/* reset done filters */
4053			m->mf_state = SMFS_OPEN;
4054			break;
4055		}
4056	}
4057
4058	response = milter_command(SMFIC_HELO, helo, strlen(helo) + 1,
4059				  SMFIM_HELO, e, state, "helo", false);
4060	milter_per_connection_check(e);
4061	return response;
4062}
4063
4064/*
4065**  MILTER_ENVFROM -- send SMTP MAIL command info to milter filters
4066**
4067**	Parameters:
4068**		args -- SMTP MAIL command args (args[0] == sender).
4069**		e -- current envelope.
4070**		state -- return state from response.
4071**
4072**	Returns:
4073**		response string (may be NULL)
4074*/
4075
4076char *
4077milter_envfrom(args, e, state)
4078	char **args;
4079	ENVELOPE *e;
4080	char *state;
4081{
4082	int i;
4083	char *buf, *bp;
4084	char *response;
4085	ssize_t s;
4086
4087	if (tTd(64, 10))
4088	{
4089		sm_dprintf("milter_envfrom:");
4090		for (i = 0; args[i] != NULL; i++)
4091			sm_dprintf(" %s", args[i]);
4092		sm_dprintf("\n");
4093	}
4094
4095	/* sanity check */
4096	if (args[0] == NULL)
4097	{
4098		*state = SMFIR_REJECT;
4099		if (MilterLogLevel > 10)
4100			sm_syslog(LOG_INFO, e->e_id,
4101				  "Milter: reject, no sender");
4102		return NULL;
4103	}
4104
4105	/* new message, so ... */
4106	for (i = 0; InputFilters[i] != NULL; i++)
4107	{
4108		struct milter *m = InputFilters[i];
4109
4110		switch (m->mf_state)
4111		{
4112		  case SMFS_INMSG:
4113			/* abort in message filters */
4114			milter_abort_filter(m, e);
4115			/* FALLTHROUGH */
4116
4117		  case SMFS_DONE:
4118			/* reset done filters */
4119			m->mf_state = SMFS_OPEN;
4120			break;
4121		}
4122	}
4123
4124	/* put together data */
4125	s = 0;
4126	for (i = 0; args[i] != NULL; i++)
4127		s += strlen(args[i]) + 1;
4128
4129	if (s < 0)
4130	{
4131		*state = SMFIR_TEMPFAIL;
4132		return NULL;
4133	}
4134
4135	buf = (char *) xalloc(s);
4136	bp = buf;
4137	for (i = 0; args[i] != NULL; i++)
4138	{
4139		(void) sm_strlcpy(bp, args[i], s - (bp - buf));
4140		bp += strlen(bp) + 1;
4141	}
4142
4143	if (MilterLogLevel > 14)
4144		sm_syslog(LOG_INFO, e->e_id, "Milter: sender: %s", buf);
4145
4146	/* send it over */
4147	response = milter_command(SMFIC_MAIL, buf, s, SMFIM_ENVFROM,
4148				e, state, "mail", false);
4149	sm_free(buf); /* XXX */
4150
4151	/*
4152	**  If filter rejects/discards a per message command,
4153	**  abort the other filters since we are done with the
4154	**  current message.
4155	*/
4156
4157	MILTER_CHECK_DONE_MSG();
4158	if (MilterLogLevel > 10 && *state == SMFIR_REJECT)
4159		sm_syslog(LOG_INFO, e->e_id, "Milter: reject, sender");
4160	return response;
4161}
4162
4163/*
4164**  MILTER_ENVRCPT -- send SMTP RCPT command info to milter filters
4165**
4166**	Parameters:
4167**		args -- SMTP MAIL command args (args[0] == recipient).
4168**		e -- current envelope.
4169**		state -- return state from response.
4170**		rcpt_error -- does RCPT have an error?
4171**
4172**	Returns:
4173**		response string (may be NULL)
4174*/
4175
4176char *
4177milter_envrcpt(args, e, state, rcpt_error)
4178	char **args;
4179	ENVELOPE *e;
4180	char *state;
4181	bool rcpt_error;
4182{
4183	int i;
4184	char *buf, *bp;
4185	char *response;
4186	ssize_t s;
4187
4188	if (tTd(64, 10))
4189	{
4190		sm_dprintf("milter_envrcpt:");
4191		for (i = 0; args[i] != NULL; i++)
4192			sm_dprintf(" %s", args[i]);
4193		sm_dprintf("\n");
4194	}
4195
4196	/* sanity check */
4197	if (args[0] == NULL)
4198	{
4199		*state = SMFIR_REJECT;
4200		if (MilterLogLevel > 10)
4201			sm_syslog(LOG_INFO, e->e_id, "Milter: reject, no rcpt");
4202		return NULL;
4203	}
4204
4205	/* put together data */
4206	s = 0;
4207	for (i = 0; args[i] != NULL; i++)
4208		s += strlen(args[i]) + 1;
4209
4210	if (s < 0)
4211	{
4212		*state = SMFIR_TEMPFAIL;
4213		return NULL;
4214	}
4215
4216	buf = (char *) xalloc(s);
4217	bp = buf;
4218	for (i = 0; args[i] != NULL; i++)
4219	{
4220		(void) sm_strlcpy(bp, args[i], s - (bp - buf));
4221		bp += strlen(bp) + 1;
4222	}
4223
4224	if (MilterLogLevel > 14)
4225		sm_syslog(LOG_INFO, e->e_id, "Milter: rcpts: %s", buf);
4226
4227	/* send it over */
4228	response = milter_command(SMFIC_RCPT, buf, s, SMFIM_ENVRCPT,
4229				e, state, "rcpt", rcpt_error);
4230	sm_free(buf); /* XXX */
4231	return response;
4232}
4233
4234/*
4235**  MILTER_DATA_CMD -- send SMTP DATA command info to milter filters
4236**
4237**	Parameters:
4238**		e -- current envelope.
4239**		state -- return state from response.
4240**
4241**	Returns:
4242**		response string (may be NULL)
4243*/
4244
4245char *
4246milter_data_cmd(e, state)
4247	ENVELOPE *e;
4248	char *state;
4249{
4250	if (tTd(64, 10))
4251		sm_dprintf("milter_data_cmd\n");
4252
4253	/* send it over */
4254	return milter_command(SMFIC_DATA, NULL, 0, SMFIM_DATA,
4255				e, state, "data", false);
4256}
4257
4258/*
4259**  MILTER_DATA -- send message headers/body and gather final message results
4260**
4261**	Parameters:
4262**		e -- current envelope.
4263**		state -- return state from response.
4264**
4265**	Returns:
4266**		response string (may be NULL)
4267**
4268**	Side effects:
4269**		- Uses e->e_dfp for access to the body
4270**		- Can call the various milter action routines to
4271**		  modify the envelope or message.
4272*/
4273
4274/* flow through code using continue; don't wrap in do {} while */
4275# define MILTER_CHECK_RESULTS() \
4276	if (m->mf_state == SMFS_ERROR && *state == SMFIR_CONTINUE) \
4277	{ \
4278			MILTER_SET_STATE;	\
4279	} \
4280	if (*state == SMFIR_ACCEPT || \
4281	    m->mf_state == SMFS_DONE || \
4282	    m->mf_state == SMFS_ERROR) \
4283	{ \
4284		if (m->mf_state != SMFS_ERROR) \
4285			m->mf_state = SMFS_DONE; \
4286		continue;	/* to next filter */ \
4287	} \
4288	if (*state != SMFIR_CONTINUE) \
4289	{ \
4290		m->mf_state = SMFS_DONE; \
4291		goto finishup; \
4292	}
4293
4294char *
4295milter_data(e, state)
4296	ENVELOPE *e;
4297	char *state;
4298{
4299	bool replbody = false;		/* milter_replbody() called? */
4300	bool replfailed = false;	/* milter_replbody() failed? */
4301	bool rewind = false;		/* rewind data file? */
4302	bool dfopen = false;		/* data file open for writing? */
4303	bool newfilter;			/* reset on each new filter */
4304	char rcmd;
4305	int i;
4306	int save_errno;
4307	char *response = NULL;
4308	time_t eomsent;
4309	ssize_t rlen;
4310
4311	if (tTd(64, 10))
4312		sm_dprintf("milter_data\n");
4313
4314	*state = SMFIR_CONTINUE;
4315
4316	/*
4317	**  XXX: Should actually send body chunks to each filter
4318	**  a chunk at a time instead of sending the whole body to
4319	**  each filter in turn.  However, only if the filters don't
4320	**  change the body.
4321	*/
4322
4323	for (i = 0; InputFilters[i] != NULL; i++)
4324	{
4325		int idx;
4326		char **macros;
4327		struct milter *m = InputFilters[i];
4328
4329		if (*state != SMFIR_CONTINUE &&
4330		    *state != SMFIR_ACCEPT)
4331		{
4332			/*
4333			**  A previous filter has dealt with the message,
4334			**  safe to stop processing the filters.
4335			*/
4336
4337			break;
4338		}
4339
4340		/* Now reset state for later evaluation */
4341		*state = SMFIR_CONTINUE;
4342		newfilter = true;
4343
4344		/* previous problem? */
4345		if (m->mf_state == SMFS_ERROR)
4346		{
4347			MILTER_CHECK_ERROR(false, continue);
4348			break;
4349		}
4350
4351		/* sanity checks */
4352		if (m->mf_sock < 0 ||
4353		    (m->mf_state != SMFS_OPEN && m->mf_state != SMFS_INMSG))
4354			continue;
4355
4356		m->mf_state = SMFS_INMSG;
4357
4358		/* check if filter wants the headers */
4359		if (!bitset(SMFIP_NOHDRS, m->mf_pflags))
4360		{
4361			response = milter_headers(m, e, state);
4362			MILTER_CHECK_RESULTS();
4363		}
4364
4365		/* check if filter wants EOH */
4366		if (!bitset(SMFIP_NOEOH, m->mf_pflags))
4367		{
4368			if (tTd(64, 10))
4369				sm_dprintf("milter_data: eoh\n");
4370
4371			if ((m->mf_lflags & MI_LFLAGS_SYM(SMFIM_EOH)) != 0)
4372				idx = m->mf_idx;
4373			else
4374				idx = 0;
4375			SM_ASSERT(idx >= 0 && idx <= MAXFILTERS);
4376			macros = MilterMacros[SMFIM_EOH][idx];
4377
4378			if (macros != NULL)
4379			{
4380				milter_send_macros(m, macros, SMFIC_EOH, e);
4381				MILTER_CHECK_RESULTS();
4382			}
4383
4384			/* send it over */
4385			response = milter_send_command(m, SMFIC_EOH, NULL, 0,
4386						       e, state, "eoh");
4387			MILTER_CHECK_RESULTS();
4388		}
4389
4390		/* check if filter wants the body */
4391		if (!bitset(SMFIP_NOBODY, m->mf_pflags) &&
4392		    e->e_dfp != NULL)
4393		{
4394			rewind = true;
4395			response = milter_body(m, e, state);
4396			MILTER_CHECK_RESULTS();
4397		}
4398
4399		if ((m->mf_lflags & MI_LFLAGS_SYM(SMFIM_EOH)) != 0)
4400			idx = m->mf_idx;
4401		else
4402			idx = 0;
4403		SM_ASSERT(idx >= 0 && idx <= MAXFILTERS);
4404		macros = MilterMacros[SMFIM_EOM][idx];
4405		if (macros != NULL)
4406		{
4407			milter_send_macros(m, macros, SMFIC_BODYEOB, e);
4408			MILTER_CHECK_RESULTS();
4409		}
4410
4411		/* send the final body chunk */
4412		(void) milter_write(m, SMFIC_BODYEOB, NULL, 0,
4413				    m->mf_timeout[SMFTO_WRITE], e, "eom");
4414
4415		/* Get time EOM sent for timeout */
4416		eomsent = curtime();
4417
4418		/* deal with the possibility of multiple responses */
4419		while (*state == SMFIR_CONTINUE)
4420		{
4421			/* Check total timeout from EOM to final ACK/NAK */
4422			if (m->mf_timeout[SMFTO_EOM] > 0 &&
4423			    curtime() - eomsent >= m->mf_timeout[SMFTO_EOM])
4424			{
4425				if (tTd(64, 5))
4426					sm_dprintf("milter_data(%s): EOM ACK/NAK timeout\n",
4427						m->mf_name);
4428				if (MilterLogLevel > 0)
4429					sm_syslog(LOG_ERR, e->e_id,
4430						  "milter_data(%s): EOM ACK/NAK timeout",
4431						  m->mf_name);
4432				milter_error(m, e);
4433				MILTER_CHECK_ERROR(false, break);
4434				break;
4435			}
4436
4437			response = milter_read(m, &rcmd, &rlen,
4438					       m->mf_timeout[SMFTO_READ], e,
4439						"eom");
4440			if (m->mf_state == SMFS_ERROR)
4441				break;
4442
4443			if (tTd(64, 10))
4444				sm_dprintf("milter_data(%s): state %c\n",
4445					   m->mf_name, (char) rcmd);
4446
4447			switch (rcmd)
4448			{
4449			  case SMFIR_REPLYCODE:
4450				MILTER_CHECK_REPLYCODE("554 5.7.1 Command rejected");
4451				if (MilterLogLevel > 12)
4452					sm_syslog(LOG_INFO, e->e_id, "milter=%s, reject=%s",
4453						  m->mf_name, response);
4454				*state = rcmd;
4455				m->mf_state = SMFS_DONE;
4456				break;
4457
4458			  case SMFIR_REJECT: /* log msg at end of function */
4459				if (MilterLogLevel > 12)
4460					sm_syslog(LOG_INFO, e->e_id, "milter=%s, reject",
4461						  m->mf_name);
4462				*state = rcmd;
4463				m->mf_state = SMFS_DONE;
4464				break;
4465
4466			  case SMFIR_DISCARD:
4467				if (MilterLogLevel > 12)
4468					sm_syslog(LOG_INFO, e->e_id, "milter=%s, discard",
4469						  m->mf_name);
4470				*state = rcmd;
4471				m->mf_state = SMFS_DONE;
4472				break;
4473
4474			  case SMFIR_TEMPFAIL:
4475				if (MilterLogLevel > 12)
4476					sm_syslog(LOG_INFO, e->e_id, "milter=%s, tempfail",
4477						  m->mf_name);
4478				*state = rcmd;
4479				m->mf_state = SMFS_DONE;
4480				break;
4481
4482			  case SMFIR_CONTINUE:
4483			  case SMFIR_ACCEPT:
4484				/* this filter is done with message */
4485				if (replfailed)
4486					*state = SMFIR_TEMPFAIL;
4487				else
4488					*state = SMFIR_ACCEPT;
4489				m->mf_state = SMFS_DONE;
4490				break;
4491
4492			  case SMFIR_PROGRESS:
4493				break;
4494
4495			  case SMFIR_QUARANTINE:
4496				if (!bitset(SMFIF_QUARANTINE, m->mf_fflags))
4497				{
4498					if (MilterLogLevel > 9)
4499						sm_syslog(LOG_WARNING, e->e_id,
4500							  "milter_data(%s): lied about quarantining, honoring request anyway",
4501							  m->mf_name);
4502				}
4503				if (response == NULL)
4504					response = newstr("");
4505				if (MilterLogLevel > 3)
4506					sm_syslog(LOG_INFO, e->e_id,
4507						  "milter=%s, quarantine=%s",
4508						  m->mf_name, response);
4509				e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool,
4510								 response);
4511				macdefine(&e->e_macro, A_PERM,
4512					  macid("{quarantine}"), e->e_quarmsg);
4513				break;
4514
4515			  case SMFIR_ADDHEADER:
4516				if (!bitset(SMFIF_ADDHDRS, m->mf_fflags))
4517				{
4518					if (MilterLogLevel > 9)
4519						sm_syslog(LOG_WARNING, e->e_id,
4520							  "milter_data(%s): lied about adding headers, honoring request anyway",
4521							  m->mf_name);
4522				}
4523				milter_addheader(m, response, rlen, e);
4524				break;
4525
4526			  case SMFIR_INSHEADER:
4527				if (!bitset(SMFIF_ADDHDRS, m->mf_fflags))
4528				{
4529					if (MilterLogLevel > 9)
4530						sm_syslog(LOG_WARNING, e->e_id,
4531							  "milter_data(%s): lied about adding headers, honoring request anyway",
4532							  m->mf_name);
4533				}
4534				milter_insheader(m, response, rlen, e);
4535				break;
4536
4537			  case SMFIR_CHGHEADER:
4538				if (!bitset(SMFIF_CHGHDRS, m->mf_fflags))
4539				{
4540					if (MilterLogLevel > 9)
4541						sm_syslog(LOG_WARNING, e->e_id,
4542							  "milter_data(%s): lied about changing headers, honoring request anyway",
4543							  m->mf_name);
4544				}
4545				milter_changeheader(m, response, rlen, e);
4546				break;
4547
4548			  case SMFIR_CHGFROM:
4549				if (!bitset(SMFIF_CHGFROM, m->mf_fflags))
4550				{
4551					if (MilterLogLevel > 9)
4552						sm_syslog(LOG_WARNING, e->e_id,
4553							  "milter_data(%s) lied about changing sender, honoring request anyway",
4554							  m->mf_name);
4555				}
4556				milter_chgfrom(response, rlen, e);
4557				break;
4558
4559			  case SMFIR_ADDRCPT:
4560				if (!bitset(SMFIF_ADDRCPT, m->mf_fflags))
4561				{
4562					if (MilterLogLevel > 9)
4563						sm_syslog(LOG_WARNING, e->e_id,
4564							  "milter_data(%s) lied about adding recipients, honoring request anyway",
4565							  m->mf_name);
4566				}
4567				milter_addrcpt(response, rlen, e);
4568				break;
4569
4570			  case SMFIR_ADDRCPT_PAR:
4571				if (!bitset(SMFIF_ADDRCPT_PAR, m->mf_fflags))
4572				{
4573					if (MilterLogLevel > 9)
4574						sm_syslog(LOG_WARNING, e->e_id,
4575							  "milter_data(%s) lied about adding recipients with parameters, honoring request anyway",
4576							  m->mf_name);
4577				}
4578				milter_addrcpt_par(response, rlen, e);
4579				break;
4580
4581			  case SMFIR_DELRCPT:
4582				if (!bitset(SMFIF_DELRCPT, m->mf_fflags))
4583				{
4584					if (MilterLogLevel > 9)
4585						sm_syslog(LOG_WARNING, e->e_id,
4586							  "milter_data(%s): lied about removing recipients, honoring request anyway",
4587							  m->mf_name);
4588				}
4589				milter_delrcpt(response, rlen, e);
4590				break;
4591
4592			  case SMFIR_REPLBODY:
4593				if (!bitset(SMFIF_MODBODY, m->mf_fflags))
4594				{
4595					if (MilterLogLevel > 0)
4596						sm_syslog(LOG_ERR, e->e_id,
4597							  "milter_data(%s): lied about replacing body, rejecting request and tempfailing message",
4598							  m->mf_name);
4599					replfailed = true;
4600					break;
4601				}
4602
4603				/* already failed in attempt */
4604				if (replfailed)
4605					break;
4606
4607				if (!dfopen)
4608				{
4609					if (milter_reopen_df(e) < 0)
4610					{
4611						replfailed = true;
4612						break;
4613					}
4614					dfopen = true;
4615					rewind = true;
4616				}
4617
4618				if (milter_replbody(response, rlen,
4619						    newfilter, e) < 0)
4620					replfailed = true;
4621				newfilter = false;
4622				replbody = true;
4623				break;
4624
4625			  default:
4626				/* Invalid response to command */
4627				if (MilterLogLevel > 0)
4628					sm_syslog(LOG_ERR, e->e_id,
4629						  "milter_data(%s): returned bogus response %c",
4630						  m->mf_name, rcmd);
4631				milter_error(m, e);
4632				break;
4633			}
4634			if (rcmd != SMFIR_REPLYCODE && response != NULL)
4635			{
4636				sm_free(response); /* XXX */
4637				response = NULL;
4638			}
4639
4640			if (m->mf_state == SMFS_ERROR)
4641				break;
4642		}
4643
4644		if (replbody && !replfailed)
4645		{
4646			/* flush possible buffered character */
4647			milter_replbody(NULL, 0, !replbody, e);
4648			replbody = false;
4649		}
4650
4651		if (m->mf_state == SMFS_ERROR)
4652		{
4653			MILTER_CHECK_ERROR(false, continue);
4654			goto finishup;
4655		}
4656	}
4657
4658finishup:
4659	/* leave things in the expected state if we touched it */
4660	if (replfailed)
4661	{
4662		if (*state == SMFIR_CONTINUE ||
4663		    *state == SMFIR_ACCEPT)
4664		{
4665			*state = SMFIR_TEMPFAIL;
4666			SM_FREE_CLR(response);
4667		}
4668
4669		if (dfopen)
4670		{
4671			(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
4672			e->e_dfp = NULL;
4673			e->e_flags &= ~EF_HAS_DF;
4674			dfopen = false;
4675		}
4676		rewind = false;
4677	}
4678
4679	if ((dfopen && milter_reset_df(e) < 0) ||
4680	    (rewind && bfrewind(e->e_dfp) < 0))
4681	{
4682		save_errno = errno;
4683		ExitStat = EX_IOERR;
4684
4685		/*
4686		**  If filter told us to keep message but we had
4687		**  an error, we can't really keep it, tempfail it.
4688		*/
4689
4690		if (*state == SMFIR_CONTINUE ||
4691		    *state == SMFIR_ACCEPT)
4692		{
4693			*state = SMFIR_TEMPFAIL;
4694			SM_FREE_CLR(response);
4695		}
4696
4697		errno = save_errno;
4698		syserr("milter_data: %s/%cf%s: read error",
4699		       qid_printqueue(e->e_qgrp, e->e_qdir),
4700		       DATAFL_LETTER, e->e_id);
4701	}
4702
4703	MILTER_CHECK_DONE_MSG();
4704	if (MilterLogLevel > 10 && *state == SMFIR_REJECT)
4705		sm_syslog(LOG_INFO, e->e_id, "Milter: reject, data");
4706	return response;
4707}
4708
4709/*
4710**  MILTER_UNKNOWN -- send any unrecognized or unimplemented command
4711**			string to milter filters
4712**
4713**	Parameters:
4714**		smtpcmd -- the string itself.
4715**		e -- current envelope.
4716**		state -- return state from response.
4717**
4718**
4719**	Returns:
4720**		response string (may be NULL)
4721*/
4722
4723char *
4724milter_unknown(smtpcmd, e, state)
4725	char *smtpcmd;
4726	ENVELOPE *e;
4727	char *state;
4728{
4729	if (tTd(64, 10))
4730		sm_dprintf("milter_unknown(%s)\n", smtpcmd);
4731
4732	return milter_command(SMFIC_UNKNOWN, smtpcmd, strlen(smtpcmd) + 1,
4733				SMFIM_NOMACROS, e, state, "unknown", false);
4734}
4735
4736/*
4737**  MILTER_QUIT -- informs the filter(s) we are done and closes connection(s)
4738**
4739**	Parameters:
4740**		e -- current envelope.
4741**
4742**	Returns:
4743**		none
4744*/
4745
4746void
4747milter_quit(e)
4748	ENVELOPE *e;
4749{
4750	int i;
4751
4752	if (tTd(64, 10))
4753		sm_dprintf("milter_quit(%s)\n", e->e_id);
4754
4755	for (i = 0; InputFilters[i] != NULL; i++)
4756		milter_quit_filter(InputFilters[i], e);
4757}
4758
4759/*
4760**  MILTER_ABORT -- informs the filter(s) that we are aborting current message
4761**
4762**	Parameters:
4763**		e -- current envelope.
4764**
4765**	Returns:
4766**		none
4767*/
4768
4769void
4770milter_abort(e)
4771	ENVELOPE *e;
4772{
4773	int i;
4774
4775	if (tTd(64, 10))
4776		sm_dprintf("milter_abort\n");
4777
4778	for (i = 0; InputFilters[i] != NULL; i++)
4779	{
4780		struct milter *m = InputFilters[i];
4781
4782		/* sanity checks */
4783		if (m->mf_sock < 0 || m->mf_state != SMFS_INMSG)
4784			continue;
4785
4786		milter_abort_filter(m, e);
4787	}
4788}
4789#endif /* MILTER */
4790