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