xref: /freebsd/contrib/sendmail/src/milter.c (revision 817420dc8eac7df799c78f5309b75092b7f7cd40)
1 /*
2  * Copyright (c) 1999-2000 Sendmail, 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 #ifndef lint
12 static char id[] = "@(#)$Id: milter.c,v 8.50.4.33 2000/09/19 19:40:15 gshapiro Exp $";
13 #endif /* ! lint */
14 
15 #if _FFR_MILTER
16 
17 # include <sendmail.h>
18 # include <errno.h>
19 # include <sys/time.h>
20 
21 # if NETINET || NETINET6
22 #  include <arpa/inet.h>
23 # endif /* NETINET || NETINET6 */
24 
25 
26 static void	milter_error __P((struct milter *));
27 static int	milter_open __P((struct milter *, bool, ENVELOPE *));
28 static void	milter_parse_timeouts __P((char *, struct milter *));
29 
30 static char *MilterConnectMacros[MAXFILTERMACROS + 1];
31 static char *MilterHeloMacros[MAXFILTERMACROS + 1];
32 static char *MilterEnvFromMacros[MAXFILTERMACROS + 1];
33 static char *MilterEnvRcptMacros[MAXFILTERMACROS + 1];
34 
35 # define MILTER_CHECK_DONE_MSG() \
36 	if (*state == SMFIR_REPLYCODE || \
37 	    *state == SMFIR_REJECT || \
38 	    *state == SMFIR_DISCARD || \
39 	    *state == SMFIR_TEMPFAIL) \
40 	{ \
41 		/* Abort the filters to let them know we are done with msg */ \
42 		milter_abort(e); \
43 	}
44 
45 # define MILTER_CHECK_ERROR(action) \
46 	if (bitnset(SMF_TEMPFAIL, m->mf_flags)) \
47 		*state = SMFIR_TEMPFAIL; \
48 	else if (bitnset(SMF_REJECT, m->mf_flags)) \
49 		*state = SMFIR_REJECT; \
50 	else \
51 		action;
52 
53 # define MILTER_CHECK_REPLYCODE(default) \
54 	if (response == NULL || \
55 	    strlen(response) + 1 != (size_t) rlen || \
56 	    rlen < 3 || \
57 	    (response[0] != '4' && response[0] != '5') || \
58 	    !isascii(response[1]) || !isdigit(response[1]) || \
59 	    !isascii(response[2]) || !isdigit(response[2])) \
60 	{ \
61 		if (response != NULL) \
62 			free(response); \
63 		response = newstr(default); \
64 	} \
65 	else \
66 	{ \
67 		char *ptr = response; \
68  \
69 		/* Check for unprotected %'s in the string */ \
70 		while (*ptr != '\0') \
71 		{ \
72 			if (*ptr == '%' && *++ptr != '%') \
73 			{ \
74 				free(response); \
75 				response = newstr(default); \
76 				break; \
77 			} \
78 			ptr++; \
79 		} \
80 	}
81 
82 # define MILTER_DF_ERROR(msg) \
83 { \
84 	int save_errno = errno; \
85  \
86 	if (tTd(64, 5)) \
87 	{ \
88 		dprintf(msg, dfname, errstring(save_errno)); \
89 		dprintf("\n"); \
90 	} \
91 	if (LogLevel > 0) \
92 		sm_syslog(LOG_ERR, e->e_id, msg, dfname, errstring(save_errno)); \
93 	if (SuperSafe) \
94 	{ \
95 		if (e->e_dfp != NULL) \
96 		{ \
97 			(void) fclose(e->e_dfp); \
98 			e->e_dfp = NULL; \
99 		} \
100 		e->e_flags &= ~EF_HAS_DF; \
101 	} \
102 	errno = save_errno; \
103 }
104 
105 /*
106 **  MILTER_TIMEOUT -- make sure socket is ready in time
107 **
108 **	Parameters:
109 **		routine -- routine name for debug/logging
110 **		secs -- number of seconds in timeout
111 **		write -- waiting to read or write?
112 **
113 **	Assumes 'm' is a milter structure for the current socket.
114 */
115 
116 
117 #  define MILTER_TIMEOUT(routine, secs, write) \
118 { \
119 	int ret; \
120 	int save_errno; \
121 	fd_set fds; \
122 	struct timeval tv; \
123  \
124 	if (m->mf_sock >= FD_SETSIZE) \
125 	{ \
126 		if (tTd(64, 5)) \
127 			dprintf("%s(%s): socket %d is larger than FD_SETSIZE %d\n", \
128 				routine, m->mf_name, m->mf_sock, FD_SETSIZE); \
129 		if (LogLevel > 0) \
130 			sm_syslog(LOG_ERR, e->e_id, \
131 				  "%s(%s): socket %d is larger than FD_SETSIZE %d\n", \
132 				  routine, m->mf_name, m->mf_sock, FD_SETSIZE); \
133 		milter_error(m); \
134 		return NULL; \
135 	} \
136  \
137 	FD_ZERO(&fds); \
138 	FD_SET(m->mf_sock, &fds); \
139 	tv.tv_sec = secs; \
140 	tv.tv_usec = 0; \
141 	ret = select(m->mf_sock + 1, \
142 		     write ? NULL : &fds, \
143 		     write ? &fds : NULL, \
144 		     NULL, &tv); \
145  \
146 	switch (ret) \
147 	{ \
148 	  case 0: \
149 		if (tTd(64, 5)) \
150 			dprintf("%s(%s): timeout\n", routine, m->mf_name); \
151 		if (LogLevel > 0) \
152 			sm_syslog(LOG_ERR, e->e_id, "%s(%s): timeout\n", \
153 				  routine, m->mf_name); \
154 		milter_error(m); \
155 		return NULL; \
156  \
157 	  case -1: \
158 		save_errno = errno; \
159 		if (tTd(64, 5)) \
160 			dprintf("%s(%s): select: %s\n", \
161 				routine,  m->mf_name, errstring(save_errno)); \
162 		if (LogLevel > 0) \
163 			sm_syslog(LOG_ERR, e->e_id, \
164 				  "%s(%s): select: %s\n", \
165 				  routine, m->mf_name, errstring(save_errno)); \
166 		milter_error(m); \
167 		return NULL; \
168  \
169 	  default: \
170 		if (FD_ISSET(m->mf_sock, &fds)) \
171 			break; \
172 		if (tTd(64, 5)) \
173 			dprintf("%s(%s): socket not ready\n", \
174 				routine, m->mf_name); \
175 		if (LogLevel > 0) \
176 			sm_syslog(LOG_ERR, e->e_id, \
177 				  "%s(%s): socket not ready\n", \
178 				  m->mf_name, routine); \
179 		milter_error(m); \
180 		return NULL; \
181 	} \
182 }
183 
184 
185 /*
186 **  Low level functions
187 */
188 
189 /*
190 **  MILTER_READ -- read from a remote milter filter
191 **
192 **	Parameters:
193 **		m -- milter to read from.
194 **		cmd -- return param for command read.
195 **		rlen -- return length of response string.
196 **		to -- timeout in seconds.
197 **		e -- current envelope.
198 **
199 **	Returns:
200 **		response string (may be NULL)
201 */
202 
203 static char *
204 milter_sysread(m, buf, sz, to, e)
205 	struct milter *m;
206 	char *buf;
207 	ssize_t sz;
208 	time_t to;
209 	ENVELOPE *e;
210 {
211 	time_t readstart = 0;
212 	ssize_t len, curl;
213 
214 	curl = 0;
215 
216 	if (to > 0)
217 		readstart = curtime();
218 
219 	for (;;)
220 	{
221 		if (to > 0)
222 		{
223 			time_t now;
224 
225 			now = curtime();
226 			if (now - readstart >= to)
227 			{
228 				if (tTd(64, 5))
229 					dprintf("milter_read(%s): timeout before data read\n",
230 						m->mf_name);
231 				if (LogLevel > 0)
232 					sm_syslog(LOG_ERR, e->e_id,
233 						  "milter_read(%s): timeout before data read\n",
234 						  m->mf_name);
235 				milter_error(m);
236 				return NULL;
237 			}
238 			to -= now - readstart;
239 			readstart = now;
240 			MILTER_TIMEOUT("milter_read", to, FALSE);
241 		}
242 
243 		len = read(m->mf_sock, buf + curl, sz - curl);
244 
245 		if (len < 0)
246 		{
247 			int save_errno = errno;
248 
249 			if (tTd(64, 5))
250 				dprintf("milter_read(%s): read returned %ld: %s\n",
251 					m->mf_name, (long) len,
252 					errstring(save_errno));
253 			if (LogLevel > 0)
254 				sm_syslog(LOG_ERR, e->e_id,
255 					  "milter_read(%s): read returned %ld: %s",
256 					  m->mf_name, (long) len,
257 					  errstring(save_errno));
258 			milter_error(m);
259 			return NULL;
260 		}
261 
262 		curl += len;
263 		if (len == 0 || len >= sz)
264 			break;
265 
266 	}
267 
268 	if (curl != sz)
269 	{
270 		if (tTd(64, 5))
271 			dprintf("milter_read(%s): read returned %ld, expecting %ld\n",
272 				m->mf_name, (long) curl, (long) sz);
273 		if (LogLevel > 0)
274 			sm_syslog(LOG_ERR, e->e_id,
275 				  "milter_read(%s): read returned %ld, expecting %ld",
276 				  m->mf_name, (long) curl, (long) sz);
277 		milter_error(m);
278 		return NULL;
279 	}
280 	return buf;
281 }
282 
283 static char *
284 milter_read(m, cmd, rlen, to, e)
285 	struct milter *m;
286 	char *cmd;
287 	ssize_t *rlen;
288 	time_t to;
289 	ENVELOPE *e;
290 {
291 	time_t readstart = 0;
292 	ssize_t expl;
293 	mi_int32 i;
294 	char *buf;
295 	char data[MILTER_LEN_BYTES + 1];
296 
297 	*rlen = 0;
298 	*cmd = '\0';
299 
300 	if (to > 0)
301 		readstart = curtime();
302 
303 	if (milter_sysread(m, data, sizeof data, to, e) == NULL)
304 		return NULL;
305 
306 	/* reset timeout */
307 	if (to > 0)
308 	{
309 		time_t now;
310 
311 		now = curtime();
312 		if (now - readstart >= to)
313 		{
314 			if (tTd(64, 5))
315 				dprintf("milter_read(%s): timeout before data read\n",
316 					m->mf_name);
317 			if (LogLevel > 0)
318 				sm_syslog(LOG_ERR, e->e_id,
319 					  "milter_read(%s): timeout before data read\n",
320 					  m->mf_name);
321 			milter_error(m);
322 			return NULL;
323 		}
324 		to -= now - readstart;
325 	}
326 
327 	*cmd = data[MILTER_LEN_BYTES];
328 	data[MILTER_LEN_BYTES] = '\0';
329 	(void) memcpy(&i, data, MILTER_LEN_BYTES);
330 	expl = ntohl(i) - 1;
331 
332 	if (tTd(64, 25))
333 		dprintf("milter_read(%s): expecting %ld bytes\n",
334 			m->mf_name, (long) expl);
335 
336 	if (expl < 0)
337 	{
338 		if (tTd(64, 5))
339 			dprintf("milter_read(%s): read size %ld out of range\n",
340 				m->mf_name, (long) expl);
341 		if (LogLevel > 0)
342 			sm_syslog(LOG_ERR, e->e_id,
343 				  "milter_read(%s): read size %ld out of range",
344 				  m->mf_name, (long) expl);
345 		milter_error(m);
346 		return NULL;
347 	}
348 
349 	if (expl == 0)
350 		return NULL;
351 
352 	buf = (char *)xalloc(expl);
353 
354 	if (milter_sysread(m, buf, expl, to, e) == NULL)
355 	{
356 		free(buf);
357 		return NULL;
358 	}
359 
360 	if (tTd(64, 50))
361 		dprintf("milter_read(%s): Returning %*s\n",
362 			m->mf_name, (int) expl, buf);
363 	*rlen = expl;
364 	return buf;
365 }
366 /*
367 **  MILTER_WRITE -- write to a remote milter filter
368 **
369 **	Parameters:
370 **		m -- milter to read from.
371 **		cmd -- command to send.
372 **		buf -- optional command data.
373 **		len -- length of buf.
374 **		to -- timeout in seconds.
375 **		e -- current envelope.
376 **
377 **	Returns:
378 **		buf if successful, NULL otherwise
379 **		Not actually used anywhere but function prototype
380 **			must match milter_read()
381 */
382 
383 static char *
384 milter_write(m, cmd, buf, len, to, e)
385 	struct milter *m;
386 	char cmd;
387 	char *buf;
388 	ssize_t len;
389 	time_t to;
390 	ENVELOPE *e;
391 {
392 	time_t writestart = (time_t) 0;
393 	ssize_t sl, i;
394 	mi_int32 nl;
395 	char data[MILTER_LEN_BYTES + 1];
396 
397 	if (len < 0 || len > MILTER_CHUNK_SIZE)
398 	{
399 		if (tTd(64, 5))
400 			dprintf("milter_write(%s): length %ld out of range\n",
401 				m->mf_name, (long) len);
402 		if (LogLevel > 0)
403 			sm_syslog(LOG_ERR, e->e_id,
404 				  "milter_write(%s): length %ld out of range",
405 				  m->mf_name, (long) len);
406 		milter_error(m);
407 		return NULL;
408 	}
409 
410 	if (tTd(64, 20))
411 		dprintf("milter_write(%s): cmd %c, len %ld\n",
412 			m->mf_name, cmd, (long) len);
413 
414 	nl = htonl(len + 1);	/* add 1 for the cmd char */
415 	(void) memcpy(data, (char *) &nl, MILTER_LEN_BYTES);
416 	data[MILTER_LEN_BYTES] = cmd;
417 	sl = MILTER_LEN_BYTES + 1;
418 
419 	if (to > 0)
420 	{
421 		writestart = curtime();
422 		MILTER_TIMEOUT("milter_write", to, TRUE);
423 	}
424 
425 	/* use writev() instead to send the whole stuff at once? */
426 	i = write(m->mf_sock, (void *) data, sl);
427 	if (i != sl)
428 	{
429 		int save_errno = errno;
430 
431 		if (tTd(64, 5))
432 			dprintf("milter_write(%s): write(%c) returned %ld, expected %ld: %s\n",
433 				m->mf_name, cmd, (long) i, (long) sl,
434 				errstring(save_errno));
435 		if (LogLevel > 0)
436 			sm_syslog(LOG_ERR, e->e_id,
437 				  "milter_write(%s): write(%c) returned %ld, expected %ld: %s",
438 				  m->mf_name, cmd, (long) i, (long) sl,
439 				  errstring(save_errno));
440 		milter_error(m);
441 		return buf;
442 	}
443 
444 	if (len <= 0 || buf == NULL)
445 		return buf;
446 
447 	if (tTd(64, 50))
448 		dprintf("milter_write(%s): Sending %*s\n",
449 			m->mf_name, (int) len, buf);
450 
451 	if (to > 0)
452 	{
453 		time_t now;
454 
455 		now = curtime();
456 		if (now - writestart >= to)
457 		{
458 			if (tTd(64, 5))
459 				dprintf("milter_write(%s): timeout before data send\n",
460 					m->mf_name);
461 			if (LogLevel > 0)
462 				sm_syslog(LOG_ERR, e->e_id,
463 					  "milter_write(%s): timeout before data send\n",
464 					  m->mf_name);
465 			milter_error(m);
466 			return NULL;
467 		}
468 		else
469 		{
470 			to -= now - writestart;
471 			MILTER_TIMEOUT("milter_write", to, TRUE);
472 		}
473 	}
474 
475 	i = write(m->mf_sock, (void *) buf, len);
476 	if (i != len)
477 	{
478 		int save_errno = errno;
479 
480 		if (tTd(64, 5))
481 			dprintf("milter_write(%s): write(%c) returned %ld, expected %ld: %s\n",
482 				m->mf_name, cmd, (long) i, (long) sl,
483 				errstring(save_errno));
484 		if (LogLevel > 0)
485 			sm_syslog(LOG_ERR, e->e_id,
486 				  "milter_write(%s): write(%c) returned %ld, expected %ld: %s",
487 				  m->mf_name, cmd, (long) i, (long) len,
488 				  errstring(save_errno));
489 		milter_error(m);
490 		return NULL;
491 	}
492 	return buf;
493 }
494 
495 /*
496 **  Utility functions
497 */
498 
499 /*
500 **  MILTER_OPEN -- connect to remote milter filter
501 **
502 **	Parameters:
503 **		m -- milter to connect to.
504 **		parseonly -- parse but don't connect.
505 **		e -- current envelope.
506 **
507 **	Returns:
508 **		connected socket if sucessful && !parseonly,
509 **		0 upon parse success if parseonly,
510 **		-1 otherwise.
511 */
512 
513 static int
514 milter_open(m, parseonly, e)
515 	struct milter *m;
516 	bool parseonly;
517 	ENVELOPE *e;
518 {
519 	int sock = 0;
520 	SOCKADDR_LEN_T addrlen = 0;
521 	int addrno = 0;
522 	int save_errno;
523 	char *p;
524 	char *colon;
525 	char *at;
526 	struct hostent *hp = NULL;
527 	SOCKADDR addr;
528 
529 	if (m->mf_conn == NULL || m->mf_conn[0] == '\0')
530 	{
531 		if (tTd(64, 5))
532 			dprintf("X%s: empty or missing socket information\n",
533 				m->mf_name);
534 		if (parseonly)
535 			syserr("X%s: empty or missing socket information",
536 			       m->mf_name);
537 		else if (LogLevel > 10)
538 			sm_syslog(LOG_ERR, e->e_id,
539 				  "X%s: empty or missing socket information",
540 				  m->mf_name);
541 		milter_error(m);
542 		return -1;
543 	}
544 
545 	/* protocol:filename or protocol:port@host */
546 	p = m->mf_conn;
547 	colon = strchr(p, ':');
548 	if (colon != NULL)
549 	{
550 		*colon = '\0';
551 
552 		if (*p == '\0')
553 		{
554 # if NETUNIX
555 			/* default to AF_UNIX */
556 			addr.sa.sa_family = AF_UNIX;
557 # else /* NETUNIX */
558 #  if NETINET
559 			/* default to AF_INET */
560 			addr.sa.sa_family = AF_INET;
561 #  else /* NETINET */
562 #   if NETINET6
563 			/* default to AF_INET6 */
564 			addr.sa.sa_family = AF_INET6;
565 #   else /* NETINET6 */
566 			/* no protocols available */
567 			sm_syslog(LOG_ERR, e->e_id,
568 				  "X%s: no valid socket protocols available",
569 				  m->mf_name);
570 			milter_error(m);
571 			return -1;
572 #   endif /* NETINET6 */
573 #  endif /* NETINET */
574 # endif /* NETUNIX */
575 		}
576 # if NETUNIX
577 		else if (strcasecmp(p, "unix") == 0 ||
578 			 strcasecmp(p, "local") == 0)
579 			addr.sa.sa_family = AF_UNIX;
580 # endif /* NETUNIX */
581 # if NETINET
582 		else if (strcasecmp(p, "inet") == 0)
583 			addr.sa.sa_family = AF_INET;
584 # endif /* NETINET */
585 # if NETINET6
586 		else if (strcasecmp(p, "inet6") == 0)
587 			addr.sa.sa_family = AF_INET6;
588 # endif /* NETINET6 */
589 		else
590 		{
591 # ifdef EPROTONOSUPPORT
592 			errno = EPROTONOSUPPORT;
593 # else /* EPROTONOSUPPORT */
594 			errno = EINVAL;
595 # endif /* EPROTONOSUPPORT */
596 			if (tTd(64, 5))
597 				dprintf("X%s: unknown socket type %s\n",
598 					m->mf_name, p);
599 			if (parseonly)
600 				syserr("X%s: unknown socket type %s",
601 				       m->mf_name, p);
602 			else if (LogLevel > 10)
603 				sm_syslog(LOG_ERR, e->e_id,
604 					  "X%s: unknown socket type %s",
605 					  m->mf_name, p);
606 			milter_error(m);
607 			return -1;
608 		}
609 		*colon++ = ':';
610 	}
611 	else
612 	{
613 		/* default to AF_UNIX */
614 		addr.sa.sa_family = AF_UNIX;
615 		colon = p;
616 	}
617 
618 # if NETUNIX
619 	if (addr.sa.sa_family == AF_UNIX)
620 	{
621 		long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_EXECOK;
622 
623 		at = colon;
624 		if (strlen(colon) >= sizeof addr.sunix.sun_path)
625 		{
626 			if (tTd(64, 5))
627 				dprintf("X%s: local socket name %s too long\n",
628 					m->mf_name, colon);
629 			errno = EINVAL;
630 			if (parseonly)
631 				syserr("X%s: local socket name %s too long",
632 				       m->mf_name, colon);
633 			else if (LogLevel > 10)
634 				sm_syslog(LOG_ERR, e->e_id,
635 					  "X%s: local socket name %s too long",
636 					  m->mf_name, colon);
637 			milter_error(m);
638 			return -1;
639 		}
640 		errno = safefile(colon, RunAsUid, RunAsGid, RunAsUserName, sff,
641 				 S_IRUSR|S_IWUSR, NULL);
642 
643 		/* if just parsing .cf file, socket doesn't need to exist */
644 		if (parseonly && errno == ENOENT)
645 		{
646 			if (OpMode == MD_DAEMON ||
647 			    OpMode == MD_FGDAEMON)
648 				fprintf(stderr,
649 					"WARNING: X%s: local socket name %s missing\n",
650 					m->mf_name, colon);
651 		}
652 		else if (errno != 0)
653 		{
654 			/* if not safe, don't create */
655 			save_errno = errno;
656 			if (tTd(64, 5))
657 				dprintf("X%s: local socket name %s unsafe\n",
658 					m->mf_name, colon);
659 			errno = save_errno;
660 			if (parseonly)
661 			{
662 				if (OpMode == MD_DAEMON ||
663 				    OpMode == MD_FGDAEMON ||
664 				    OpMode == MD_SMTP)
665 					syserr("X%s: local socket name %s unsafe",
666 					       m->mf_name, colon);
667 			}
668 			else if (LogLevel > 10)
669 				sm_syslog(LOG_ERR, e->e_id,
670 					  "X%s: local socket name %s unsafe",
671 					  m->mf_name, colon);
672 			milter_error(m);
673 			return -1;
674 		}
675 
676 		(void) strlcpy(addr.sunix.sun_path, colon,
677 			       sizeof addr.sunix.sun_path);
678 		addrlen = sizeof (struct sockaddr_un);
679 	}
680 	else
681 # endif /* NETUNIX */
682 # if NETINET || NETINET6
683 	if (FALSE
684 #  if NETINET
685 		 || addr.sa.sa_family == AF_INET
686 #  endif /* NETINET */
687 #  if NETINET6
688 		 || addr.sa.sa_family == AF_INET6
689 #  endif /* NETINET6 */
690 		 )
691 	{
692 		u_short port;
693 
694 		/* Parse port@host */
695 		at = strchr(colon, '@');
696 		if (at == NULL)
697 		{
698 			if (tTd(64, 5))
699 				dprintf("X%s: bad address %s (expected port@host)\n",
700 					m->mf_name, colon);
701 			if (parseonly)
702 				syserr("X%s: bad address %s (expected port@host)",
703 				       m->mf_name, colon);
704 			else if (LogLevel > 10)
705 				sm_syslog(LOG_ERR, e->e_id,
706 					  "X%s: bad address %s (expected port@host)",
707 					  m->mf_name, colon);
708 			milter_error(m);
709 			return -1;
710 		}
711 		*at = '\0';
712 		if (isascii(*colon) && isdigit(*colon))
713 			port = htons((u_short) atoi(colon));
714 		else
715 		{
716 #  ifdef NO_GETSERVBYNAME
717 			if (tTd(64, 5))
718 				dprintf("X%s: invalid port number %s\n",
719 					m->mf_name, colon);
720 			if (parseonly)
721 				syserr("X%s: invalid port number %s",
722 				       m->mf_name, colon);
723 			else if (LogLevel > 10)
724 				sm_syslog(LOG_ERR, e->e_id,
725 					  "X%s: invalid port number %s",
726 					  m->mf_name, colon);
727 			milter_error(m);
728 			return -1;
729 #  else /* NO_GETSERVBYNAME */
730 			register struct servent *sp;
731 
732 			sp = getservbyname(colon, "tcp");
733 			if (sp == NULL)
734 			{
735 				save_errno = errno;
736 				if (tTd(64, 5))
737 					dprintf("X%s: unknown port name %s\n",
738 						m->mf_name, colon);
739 				errno = save_errno;
740 				if (parseonly)
741 					syserr("X%s: unknown port name %s",
742 					       m->mf_name, colon);
743 				else if (LogLevel > 10)
744 					sm_syslog(LOG_ERR, e->e_id,
745 						  "X%s: unknown port name %s",
746 						  m->mf_name, colon);
747 				milter_error(m);
748 				return -1;
749 			}
750 			port = sp->s_port;
751 #  endif /* NO_GETSERVBYNAME */
752 		}
753 		*at++ = '@';
754 		if (*at == '[')
755 		{
756 			char *end;
757 
758 			end = strchr(at, ']');
759 			if (end != NULL)
760 			{
761 				bool found = FALSE;
762 #  if NETINET
763 				unsigned long hid = INADDR_NONE;
764 #  endif /* NETINET */
765 #  if NETINET6
766 				struct sockaddr_in6 hid6;
767 #  endif /* NETINET6 */
768 
769 				*end = '\0';
770 #  if NETINET
771 				if (addr.sa.sa_family == AF_INET &&
772 				    (hid = inet_addr(&at[1])) != INADDR_NONE)
773 				{
774 					addr.sin.sin_addr.s_addr = hid;
775 					addr.sin.sin_port = port;
776 					found = TRUE;
777 				}
778 #  endif /* NETINET */
779 #  if NETINET6
780 				(void) memset(&hid6, '\0', sizeof hid6);
781 				if (addr.sa.sa_family == AF_INET6 &&
782 				    inet_pton(AF_INET6, &at[1],
783 					      &hid6.sin6_addr) == 1)
784 				{
785 					addr.sin6.sin6_addr = hid6.sin6_addr;
786 					addr.sin6.sin6_port = port;
787 					found = TRUE;
788 				}
789 #  endif /* NETINET6 */
790 				*end = ']';
791 				if (!found)
792 				{
793 					if (tTd(64, 5))
794 						dprintf("X%s: Invalid numeric domain spec \"%s\"\n",
795 							m->mf_name, at);
796 					if (parseonly)
797 						syserr("X%s: Invalid numeric domain spec \"%s\"",
798 						       m->mf_name, at);
799 					else if (LogLevel > 10)
800 						sm_syslog(LOG_ERR, e->e_id,
801 							  "X%s: Invalid numeric domain spec \"%s\"",
802 							  m->mf_name, at);
803 					milter_error(m);
804 					return -1;
805 				}
806 			}
807 			else
808 			{
809 				if (tTd(64, 5))
810 					dprintf("X%s: Invalid numeric domain spec \"%s\"\n",
811 						m->mf_name, at);
812 				if (parseonly)
813 					syserr("X%s: Invalid numeric domain spec \"%s\"",
814 					       m->mf_name, at);
815 				else if (LogLevel > 10)
816 					sm_syslog(LOG_ERR, e->e_id,
817 						  "X%s: Invalid numeric domain spec \"%s\"",
818 						  m->mf_name, at);
819 				milter_error(m);
820 				return -1;
821 			}
822 		}
823 		else
824 		{
825 			hp = sm_gethostbyname(at, addr.sa.sa_family);
826 			if (hp == NULL)
827 			{
828 				save_errno = errno;
829 				if (tTd(64, 5))
830 					dprintf("X%s: Unknown host name %s\n",
831 						m->mf_name, at);
832 				errno = save_errno;
833 				if (parseonly)
834 					syserr("X%s: Unknown host name %s",
835 					       m->mf_name, at);
836 				else if (LogLevel > 10)
837 					sm_syslog(LOG_ERR, e->e_id,
838 						  "X%s: Unknown host name %s",
839 						  m->mf_name, at);
840 				milter_error(m);
841 				return -1;
842 			}
843 			addr.sa.sa_family = hp->h_addrtype;
844 			switch (hp->h_addrtype)
845 			{
846 #  if NETINET
847 			  case AF_INET:
848 				memmove(&addr.sin.sin_addr,
849 					hp->h_addr,
850 					INADDRSZ);
851 				addr.sin.sin_port = port;
852 				addrlen = sizeof (struct sockaddr_in);
853 				addrno = 1;
854 				break;
855 #  endif /* NETINET */
856 
857 #  if NETINET6
858 			  case AF_INET6:
859 				memmove(&addr.sin6.sin6_addr,
860 					hp->h_addr,
861 					IN6ADDRSZ);
862 				addr.sin6.sin6_port = port;
863 				addrlen = sizeof (struct sockaddr_in6);
864 				addrno = 1;
865 				break;
866 #  endif /* NETINET6 */
867 
868 			  default:
869 				if (tTd(64, 5))
870 					dprintf("X%s: Unknown protocol for %s (%d)\n",
871 						m->mf_name, at,
872 						hp->h_addrtype);
873 				if (parseonly)
874 					syserr("X%s: Unknown protocol for %s (%d)",
875 					       m->mf_name, at, hp->h_addrtype);
876 				else if (LogLevel > 10)
877 					sm_syslog(LOG_ERR, e->e_id,
878 						  "X%s: Unknown protocol for %s (%d)",
879 						  m->mf_name, at,
880 						  hp->h_addrtype);
881 				milter_error(m);
882 				return -1;
883 			}
884 		}
885 	}
886 	else
887 # endif /* NETINET || NETINET6 */
888 	{
889 		if (tTd(64, 5))
890 			dprintf("X%s: unknown socket protocol\n", m->mf_name);
891 		if (parseonly)
892 			syserr("X%s: unknown socket protocol", m->mf_name);
893 		else if (LogLevel > 10)
894 			sm_syslog(LOG_ERR, e->e_id,
895 				  "X%s: unknown socket protocol", m->mf_name);
896 		milter_error(m);
897 		return -1;
898 	}
899 
900 	/* just parsing through? */
901 	if (parseonly)
902 	{
903 		m->mf_state = SMFS_READY;
904 		return 0;
905 	}
906 
907 	/* sanity check */
908 	if (m->mf_state != SMFS_READY &&
909 	    m->mf_state != SMFS_CLOSED)
910 	{
911 		/* shouldn't happen */
912 		if (tTd(64, 1))
913 			dprintf("milter_open(%s): Trying to open filter in state %c\n",
914 				m->mf_name, (char) m->mf_state);
915 		milter_error(m);
916 		return -1;
917 	}
918 
919 	/* nope, actually connecting */
920 	for (;;)
921 	{
922 		sock = socket(addr.sa.sa_family, SOCK_STREAM, 0);
923 		if (sock < 0)
924 		{
925 			save_errno = errno;
926 			if (tTd(64, 5))
927 				dprintf("X%s: error creating socket: %s\n",
928 					m->mf_name, errstring(save_errno));
929 			if (LogLevel > 0)
930 				sm_syslog(LOG_ERR, e->e_id,
931 					  "X%s: error creating socket: %s",
932 					  m->mf_name, errstring(save_errno));
933 			milter_error(m);
934 			return -1;
935 		}
936 
937 		if (connect(sock, (struct sockaddr *) &addr, addrlen) >= 0)
938 			break;
939 
940 		/* couldn't connect.... try next address */
941 		save_errno = errno;
942 		p = CurHostName;
943 		CurHostName = at;
944 		if (tTd(64, 5))
945 			dprintf("milter_open(%s): %s failed: %s\n",
946 				m->mf_name, at, errstring(save_errno));
947 		if (LogLevel >= 14)
948 			sm_syslog(LOG_INFO, e->e_id,
949 				  "milter_open(%s): %s failed: %s",
950 				  m->mf_name, at, errstring(save_errno));
951 		CurHostName = p;
952 		(void) close(sock);
953 
954 		/* try next address */
955 		if (hp != NULL && hp->h_addr_list[addrno] != NULL)
956 		{
957 			switch (addr.sa.sa_family)
958 			{
959 # if NETINET
960 			  case AF_INET:
961 				memmove(&addr.sin.sin_addr,
962 					hp->h_addr_list[addrno++],
963 					INADDRSZ);
964 				break;
965 # endif /* NETINET */
966 
967 # if NETINET6
968 			  case AF_INET6:
969 				memmove(&addr.sin6.sin6_addr,
970 					hp->h_addr_list[addrno++],
971 					IN6ADDRSZ);
972 				break;
973 # endif /* NETINET6 */
974 
975 			  default:
976 				if (tTd(64, 5))
977 					dprintf("X%s: Unknown protocol for %s (%d)\n",
978 						m->mf_name, at,
979 						hp->h_addrtype);
980 				if (LogLevel > 0)
981 					sm_syslog(LOG_ERR, e->e_id,
982 						  "X%s: Unknown protocol for %s (%d)",
983 						  m->mf_name, at,
984 						  hp->h_addrtype);
985 				milter_error(m);
986 				return -1;
987 			}
988 			continue;
989 		}
990 		if (tTd(64, 5))
991 			dprintf("X%s: error connecting to filter\n",
992 				m->mf_name);
993 		if (LogLevel > 0)
994 			sm_syslog(LOG_ERR, e->e_id,
995 				  "X%s: error connecting to filter",
996 				  m->mf_name);
997 		milter_error(m);
998 		return -1;
999 	}
1000 	m->mf_state = SMFS_OPEN;
1001 	return sock;
1002 }
1003 /*
1004 **  MILTER_SETUP -- setup structure for a mail filter
1005 **
1006 **	Parameters:
1007 **		line -- the options line.
1008 **
1009 **	Returns:
1010 **		none
1011 */
1012 
1013 void
1014 milter_setup(line)
1015 	char *line;
1016 {
1017 	char fcode;
1018 	register char *p;
1019 	register struct milter *m;
1020 	STAB *s;
1021 
1022 	/* collect the filter name */
1023 	for (p = line;
1024 	     *p != '\0' && *p != ',' && !(isascii(*p) && isspace(*p));
1025 	     p++)
1026 		continue;
1027 	if (*p != '\0')
1028 		*p++ = '\0';
1029 	if (line[0] == '\0')
1030 	{
1031 		syserr("name required for mail filter");
1032 		return;
1033 	}
1034 	m = (struct milter *)xalloc(sizeof *m);
1035 	memset((char *) m, '\0', sizeof *m);
1036 	m->mf_name = newstr(line);
1037 	m->mf_state = SMFS_READY;
1038 	m->mf_sock = -1;
1039 	m->mf_timeout[SMFTO_WRITE] = (time_t) 10;
1040 	m->mf_timeout[SMFTO_READ] = (time_t) 10;
1041 	m->mf_timeout[SMFTO_EOM] = (time_t) 300;
1042 
1043 	/* now scan through and assign info from the fields */
1044 	while (*p != '\0')
1045 	{
1046 		char *delimptr;
1047 
1048 		while (*p != '\0' &&
1049 		       (*p == ',' || (isascii(*p) && isspace(*p))))
1050 			p++;
1051 
1052 		/* p now points to field code */
1053 		fcode = *p;
1054 		while (*p != '\0' && *p != '=' && *p != ',')
1055 			p++;
1056 		if (*p++ != '=')
1057 		{
1058 			syserr("X%s: `=' expected", m->mf_name);
1059 			return;
1060 		}
1061 		while (isascii(*p) && isspace(*p))
1062 			p++;
1063 
1064 		/* p now points to the field body */
1065 		p = munchstring(p, &delimptr, ',');
1066 
1067 		/* install the field into the filter struct */
1068 		switch (fcode)
1069 		{
1070 		  case 'S':		/* socket */
1071 			if (p == NULL)
1072 				m->mf_conn = NULL;
1073 			else
1074 				m->mf_conn = newstr(p);
1075 			break;
1076 
1077 		  case 'F':		/* Milter flags configured on MTA */
1078 			for (; *p != '\0'; p++)
1079 			{
1080 				if (!(isascii(*p) && isspace(*p)))
1081 					setbitn(*p, m->mf_flags);
1082 			}
1083 			break;
1084 
1085 		  case 'T':		/* timeouts */
1086 			milter_parse_timeouts(p, m);
1087 			break;
1088 
1089 		  default:
1090 			syserr("X%s: unknown filter equate %c=",
1091 			       m->mf_name, fcode);
1092 			break;
1093 		}
1094 		p = delimptr;
1095 	}
1096 
1097 	/* early check for errors */
1098 	(void) milter_open(m, TRUE, CurEnv);
1099 
1100 	/* enter the filter into the symbol table */
1101 	s = stab(m->mf_name, ST_MILTER, ST_ENTER);
1102 	if (s->s_milter != NULL)
1103 		syserr("X%s: duplicate filter definition", m->mf_name);
1104 	else
1105 		s->s_milter = m;
1106 }
1107 /*
1108 **  MILTER_PARSE_LIST -- parse option list into an array
1109 **
1110 **	Called when reading configuration file.
1111 **
1112 **	Parameters:
1113 **		spec -- the filter list.
1114 **		list -- the array to fill in.
1115 **		max -- the maximum number of entries in list.
1116 **
1117 **	Returns:
1118 **		none
1119 */
1120 
1121 void
1122 milter_parse_list(spec, list, max)
1123 	char *spec;
1124 	struct milter **list;
1125 	int max;
1126 {
1127 	int numitems = 0;
1128 	register char *p;
1129 
1130 	/* leave one for the NULL signifying the end of the list */
1131 	max--;
1132 
1133 	for (p = spec; p != NULL; )
1134 	{
1135 		STAB *s;
1136 
1137 		while (isascii(*p) && isspace(*p))
1138 			p++;
1139 		if (*p == '\0')
1140 			break;
1141 		spec = p;
1142 
1143 		if (numitems >= max)
1144 		{
1145 			syserr("Too many filters defined, %d max", max);
1146 			if (max > 0)
1147 				list[0] = NULL;
1148 			return;
1149 		}
1150 		p = strpbrk(p, ",");
1151 		if (p != NULL)
1152 			*p++ = '\0';
1153 
1154 		s = stab(spec, ST_MILTER, ST_FIND);
1155 		if (s == NULL)
1156 		{
1157 			syserr("InputFilter %s not defined", spec);
1158 			ExitStat = EX_CONFIG;
1159 			return;
1160 		}
1161 		list[numitems++] = s->s_milter;
1162 	}
1163 	list[numitems] = NULL;
1164 }
1165 /*
1166 **  MILTER_PARSE_TIMEOUTS -- parse timeout list
1167 **
1168 **	Called when reading configuration file.
1169 **
1170 **	Parameters:
1171 **		spec -- the timeout list.
1172 **		m -- milter to set.
1173 **
1174 **	Returns:
1175 **		none
1176 */
1177 
1178 static void
1179 milter_parse_timeouts(spec, m)
1180 	char *spec;
1181 	struct milter *m;
1182 {
1183 	char fcode;
1184 	register char *p;
1185 
1186 	p = spec;
1187 
1188 	/* now scan through and assign info from the fields */
1189 	while (*p != '\0')
1190 	{
1191 		char *delimptr;
1192 
1193 		while (*p != '\0' &&
1194 		       (*p == ';' || (isascii(*p) && isspace(*p))))
1195 			p++;
1196 
1197 		/* p now points to field code */
1198 		fcode = *p;
1199 		while (*p != '\0' && *p != ':')
1200 			p++;
1201 		if (*p++ != ':')
1202 		{
1203 			syserr("X%s, T=: `:' expected", m->mf_name);
1204 			return;
1205 		}
1206 		while (isascii(*p) && isspace(*p))
1207 			p++;
1208 
1209 		/* p now points to the field body */
1210 		p = munchstring(p, &delimptr, ';');
1211 
1212 		/* install the field into the filter struct */
1213 		switch (fcode)
1214 		{
1215 		  case 'S':
1216 			m->mf_timeout[SMFTO_WRITE] = convtime(p, 's');
1217 			if (tTd(64, 5))
1218 				printf("X%s: %c=%ld\n",
1219 				       m->mf_name, fcode,
1220 				       (u_long) m->mf_timeout[SMFTO_WRITE]);
1221 			break;
1222 
1223 		  case 'R':
1224 			m->mf_timeout[SMFTO_READ] = convtime(p, 's');
1225 			if (tTd(64, 5))
1226 				printf("X%s: %c=%ld\n",
1227 				       m->mf_name, fcode,
1228 				       (u_long) m->mf_timeout[SMFTO_READ]);
1229 			break;
1230 
1231 		  case 'E':
1232 			m->mf_timeout[SMFTO_EOM] = convtime(p, 's');
1233 			if (tTd(64, 5))
1234 				printf("X%s: %c=%ld\n",
1235 				       m->mf_name, fcode,
1236 				       (u_long) m->mf_timeout[SMFTO_EOM]);
1237 			break;
1238 
1239 		  default:
1240 			if (tTd(64, 5))
1241 				printf("X%s: %c unknown\n",
1242 				       m->mf_name, fcode);
1243 			syserr("X%s: unknown filter timeout %c",
1244 			       m->mf_name, fcode);
1245 			break;
1246 		}
1247 		p = delimptr;
1248 	}
1249 }
1250 /*
1251 **  MILTER_SET_OPTION -- set an individual milter option
1252 **
1253 **	Parameters:
1254 **		name -- the name of the option.
1255 **		val -- the value of the option.
1256 **		sticky -- if set, don't let other setoptions override
1257 **			this value.
1258 **
1259 **	Returns:
1260 **		none.
1261 */
1262 
1263 /* set if Milter sub-option is stuck */
1264 static BITMAP256	StickyMilterOpt;
1265 
1266 static struct milteropt
1267 {
1268 	char	*mo_name;	/* long name of milter option */
1269 	u_char	mo_code;	/* code for option */
1270 } MilterOptTab[] =
1271 {
1272 # define MO_MACROS_CONNECT		0x01
1273 	{ "macros.connect",		MO_MACROS_CONNECT		},
1274 # define MO_MACROS_HELO			0x02
1275 	{ "macros.helo",		MO_MACROS_HELO			},
1276 # define MO_MACROS_ENVFROM		0x03
1277 	{ "macros.envfrom",		MO_MACROS_ENVFROM		},
1278 # define MO_MACROS_ENVRCPT		0x04
1279 	{ "macros.envrcpt",		MO_MACROS_ENVRCPT		},
1280 	{ NULL,				0				},
1281 };
1282 
1283 void
1284 milter_set_option(name, val, sticky)
1285 	char *name;
1286 	char *val;
1287 	bool sticky;
1288 {
1289 	int nummac = 0;
1290 	register struct milteropt *mo;
1291 	char *p;
1292 	char **macros = NULL;
1293 
1294 	if (tTd(37, 2) || tTd(64, 5))
1295 		dprintf("milter_set_option(%s = %s)", name, val);
1296 
1297 	for (mo = MilterOptTab; mo->mo_name != NULL; mo++)
1298 	{
1299 		if (strcasecmp(mo->mo_name, name) == 0)
1300 			break;
1301 	}
1302 
1303 	if (mo->mo_name == NULL)
1304 		syserr("milter_set_option: invalid Milter option %s", name);
1305 
1306 	/*
1307 	**  See if this option is preset for us.
1308 	*/
1309 
1310 	if (!sticky && bitnset(mo->mo_code, StickyMilterOpt))
1311 	{
1312 		if (tTd(37, 2) || tTd(64,5))
1313 			dprintf(" (ignored)\n");
1314 		return;
1315 	}
1316 
1317 	if (tTd(37, 2) || tTd(64,5))
1318 		dprintf("\n");
1319 
1320 	switch (mo->mo_code)
1321 	{
1322 	  case MO_MACROS_CONNECT:
1323 		if (macros == NULL)
1324 			macros = MilterConnectMacros;
1325 		/* FALLTHROUGH */
1326 
1327 	  case MO_MACROS_HELO:
1328 		if (macros == NULL)
1329 			macros = MilterHeloMacros;
1330 		/* FALLTHROUGH */
1331 
1332 	  case MO_MACROS_ENVFROM:
1333 		if (macros == NULL)
1334 			macros = MilterEnvFromMacros;
1335 		/* FALLTHROUGH */
1336 
1337 	  case MO_MACROS_ENVRCPT:
1338 		if (macros == NULL)
1339 			macros = MilterEnvRcptMacros;
1340 
1341 		p = newstr(val);
1342 		while (*p != '\0')
1343 		{
1344 			char *macro;
1345 
1346 			/* Skip leading commas, spaces */
1347 			while (*p != '\0' &&
1348 			       (*p == ',' || (isascii(*p) && isspace(*p))))
1349 				p++;
1350 
1351 			if (*p == '\0')
1352 				break;
1353 
1354 			/* Find end of macro */
1355 			macro = p;
1356 			while (*p != '\0' && *p != ',' &&
1357 			       isascii(*p) && !isspace(*p))
1358 				p++;
1359 			if (*p != '\0')
1360 				*p++ = '\0';
1361 
1362 			if (nummac >= MAXFILTERMACROS)
1363 			{
1364 				syserr("milter_set_option: too many macros in Milter.%s (max %d)",
1365 				       name, MAXFILTERMACROS);
1366 				macros[nummac] = NULL;
1367 				break;
1368 			}
1369 			macros[nummac++] = macro;
1370 		}
1371 		macros[nummac] = NULL;
1372 		break;
1373 
1374 	  default:
1375 		syserr("milter_set_option: invalid Milter option %s", name);
1376 		break;
1377 	}
1378 
1379 	if (sticky)
1380 		setbitn(mo->mo_code, StickyMilterOpt);
1381 }
1382 /*
1383 **  MILTER_REOPEN_DF -- open & truncate the df file (for replbody)
1384 **
1385 **	Parameters:
1386 **		e -- current envelope.
1387 **
1388 **	Returns:
1389 **		0 if succesful, -1 otherwise
1390 */
1391 
1392 static int
1393 milter_reopen_df(e)
1394 	ENVELOPE *e;
1395 {
1396 	char dfname[MAXPATHLEN];
1397 
1398 	(void) strlcpy(dfname, queuename(e, 'd'), sizeof dfname);
1399 
1400 	/*
1401 	**  In SuperSafe mode, e->e_dfp is a read-only FP so
1402 	**  close and reopen writable (later close and reopen
1403 	**  read only again).
1404 	**
1405 	**  In !SuperSafe mode, e->e_dfp still points at the
1406 	**  buffered file I/O descriptor, still open for writing
1407 	**  so there isn't as much work to do, just truncate it
1408 	**  and go.
1409 	*/
1410 
1411 	if (SuperSafe)
1412 	{
1413 		/* close read-only df */
1414 		if (bitset(EF_HAS_DF, e->e_flags) && e->e_dfp != NULL)
1415 		{
1416 			(void) fclose(e->e_dfp);
1417 			e->e_flags &= ~EF_HAS_DF;
1418 		}
1419 
1420 		/* open writable */
1421 		if ((e->e_dfp = fopen(dfname, "w+")) == NULL)
1422 		{
1423 			MILTER_DF_ERROR("milter_reopen_df: fopen %s: %s");
1424 			return -1;
1425 		}
1426 	}
1427 	else if (e->e_dfp == NULL)
1428 	{
1429 		/* shouldn't happen */
1430 		errno = ENOENT;
1431 		MILTER_DF_ERROR("milter_reopen_df: NULL e_dfp (%s: %s)");
1432 		return -1;
1433 	}
1434 	return 0;
1435 }
1436 /*
1437 **  MILTER_RESET_DF -- re-open read-only the df file (for replbody)
1438 **
1439 **	Parameters:
1440 **		e -- current envelope.
1441 **
1442 **	Returns:
1443 **		0 if succesful, -1 otherwise
1444 */
1445 
1446 static int
1447 milter_reset_df(e)
1448 	ENVELOPE *e;
1449 {
1450 	int afd;
1451 	char dfname[MAXPATHLEN];
1452 
1453 	(void) strlcpy(dfname, queuename(e, 'd'), sizeof dfname);
1454 
1455 	if (fflush(e->e_dfp) != 0 || ferror(e->e_dfp))
1456 	{
1457 		MILTER_DF_ERROR("milter_reset_df: error writing/flushing %s: %s");
1458 		return -1;
1459 	}
1460 	else if (!SuperSafe)
1461 	{
1462 		/* skip next few clauses */
1463 		/* EMPTY */
1464 	}
1465 	else if ((afd = fileno(e->e_dfp)) >= 0 && fsync(afd) < 0)
1466 	{
1467 		MILTER_DF_ERROR("milter_reset_df: error sync'ing %s: %s");
1468 		return -1;
1469 	}
1470 	else if (fclose(e->e_dfp) < 0)
1471 	{
1472 		MILTER_DF_ERROR("milter_reset_df: error closing %s: %s");
1473 		return -1;
1474 	}
1475 	else if ((e->e_dfp = fopen(dfname, "r")) == NULL)
1476 	{
1477 		MILTER_DF_ERROR("milter_reset_df: error reopening %s: %s");
1478 		return -1;
1479 	}
1480 	else
1481 		e->e_flags |= EF_HAS_DF;
1482 	return 0;
1483 }
1484 /*
1485 **  MILTER_CAN_DELRCPTS -- can any milter filters delete recipients?
1486 **
1487 **	Parameters:
1488 **		none
1489 **
1490 **	Returns:
1491 **		TRUE if any filter deletes recipients, FALSE otherwise
1492 */
1493 
1494 bool
1495 milter_can_delrcpts()
1496 {
1497 	bool can = FALSE;
1498 	int i;
1499 
1500 	if (tTd(64, 10))
1501 		dprintf("milter_can_delrcpts:");
1502 
1503 	for (i = 0; InputFilters[i] != NULL; i++)
1504 	{
1505 		struct milter *m = InputFilters[i];
1506 
1507 		if (bitset(SMFIF_DELRCPT, m->mf_fflags))
1508 		{
1509 			can = TRUE;
1510 			break;
1511 		}
1512 	}
1513 	if (tTd(64, 10))
1514 		dprintf("%s\n", can ? "TRUE" : "FALSE");
1515 
1516 	return can;
1517 }
1518 /*
1519 **  MILTER_QUIT_FILTER -- close down a single filter
1520 **
1521 **	Parameters:
1522 **		m -- milter structure of filter to close down.
1523 **		e -- current envelope.
1524 **
1525 **	Returns:
1526 **		none
1527 */
1528 
1529 static void
1530 milter_quit_filter(m, e)
1531 	struct milter *m;
1532 	ENVELOPE *e;
1533 {
1534 	if (tTd(64, 10))
1535 		dprintf("milter_quit_filter(%s)\n", m->mf_name);
1536 
1537 	/* Never replace error state */
1538 	if (m->mf_state == SMFS_ERROR)
1539 		return;
1540 
1541 	if (m->mf_sock < 0 ||
1542 	    m->mf_state == SMFS_CLOSED ||
1543 	    m->mf_state == SMFS_READY)
1544 	{
1545 		m->mf_sock = -1;
1546 		m->mf_state = SMFS_CLOSED;
1547 		return;
1548 	}
1549 
1550 	(void) milter_write(m, SMFIC_QUIT, (char *) NULL, 0,
1551 			    m->mf_timeout[SMFTO_WRITE], e);
1552 	(void) close(m->mf_sock);
1553 	m->mf_sock = -1;
1554 	if (m->mf_state != SMFS_ERROR)
1555 		m->mf_state = SMFS_CLOSED;
1556 }
1557 /*
1558 **  MILTER_ABORT_FILTER -- tell filter to abort current message
1559 **
1560 **	Parameters:
1561 **		m -- milter structure of filter to abort.
1562 **		e -- current envelope.
1563 **
1564 **	Returns:
1565 **		none
1566 */
1567 
1568 static void
1569 milter_abort_filter(m, e)
1570 	struct milter *m;
1571 	ENVELOPE *e;
1572 {
1573 	if (tTd(64, 10))
1574 		dprintf("milter_abort_filter(%s)\n", m->mf_name);
1575 
1576 	if (m->mf_sock < 0 ||
1577 	    m->mf_state != SMFS_INMSG)
1578 		return;
1579 
1580 	(void) milter_write(m, SMFIC_ABORT, (char *) NULL, 0,
1581 			    m->mf_timeout[SMFTO_WRITE], e);
1582 	if (m->mf_state != SMFS_ERROR)
1583 		m->mf_state = SMFS_DONE;
1584 }
1585 /*
1586 **  MILTER_SEND_MACROS -- provide macros to the filters
1587 **
1588 **	Parameters:
1589 **		m -- milter to send macros to.
1590 **		macros -- macros to send for filter smfi_getsymval().
1591 **		cmd -- which command the macros are associated with.
1592 **		e -- current envelope (for macro access).
1593 **
1594 **	Returns:
1595 **		none
1596 */
1597 
1598 static void
1599 milter_send_macros(m, macros, cmd, e)
1600 	struct milter *m;
1601 	char **macros;
1602 	char cmd;
1603 	ENVELOPE *e;
1604 {
1605 	int i;
1606 	int mid;
1607 	char *v;
1608 	char *buf, *bp;
1609 	ssize_t s;
1610 
1611 	/* sanity check */
1612 	if (macros == NULL || macros[0] == NULL)
1613 		return;
1614 
1615 	/* put together data */
1616 	s = 1;			/* for the command character */
1617 	for (i = 0; macros[i] != NULL; i++)
1618 	{
1619 		mid = macid(macros[i], NULL);
1620 		if (mid == '\0')
1621 			continue;
1622 		v = macvalue(mid, e);
1623 		if (v == NULL)
1624 			continue;
1625 		s += strlen(macros[i]) + 1 + strlen(v) + 1;
1626 	}
1627 
1628 	buf = (char *)xalloc(s);
1629 	bp = buf;
1630 	*bp++ = cmd;
1631 	for (i = 0; macros[i] != NULL; i++)
1632 	{
1633 		mid = macid(macros[i], NULL);
1634 		if (mid == '\0')
1635 			continue;
1636 		v = macvalue(mid, e);
1637 		if (v == NULL)
1638 			continue;
1639 
1640 		if (tTd(64, 10))
1641 			dprintf("milter_send_macros(%s, %c): %s=%s\n",
1642 				m->mf_name, cmd, macros[i], v);
1643 
1644 		(void) strlcpy(bp, macros[i], s - (bp - buf));
1645 		bp += strlen(bp) + 1;
1646 		(void) strlcpy(bp, v, s - (bp - buf));
1647 		bp += strlen(bp) + 1;
1648 	}
1649 	(void) milter_write(m, SMFIC_MACRO, buf, s,
1650 			    m->mf_timeout[SMFTO_WRITE], e);
1651 	free(buf);
1652 }
1653 
1654 /*
1655 **  MILTER_SEND_COMMAND -- send a command and return the response for a filter
1656 **
1657 **	Parameters:
1658 **		m -- current milter filter
1659 **		command -- command to send.
1660 **		data -- optional command data.
1661 **		sz -- length of buf.
1662 **		e -- current envelope (for e->e_id).
1663 **		state -- return state word.
1664 **
1665 **	Returns:
1666 **		response string (may be NULL)
1667 */
1668 
1669 static char *
1670 milter_send_command(m, command, data, sz, e, state)
1671 	struct milter *m;
1672 	char command;
1673 	void *data;
1674 	ssize_t sz;
1675 	ENVELOPE *e;
1676 	char *state;
1677 {
1678 	char rcmd;
1679 	ssize_t rlen;
1680 	u_long skipflag;
1681 	char *defresponse;
1682 	char *response;
1683 
1684 	if (tTd(64, 10))
1685 		dprintf("milter_send_command(%s): cmd %c len %ld\n",
1686 			m->mf_name, (char) command, (long) sz);
1687 
1688 	/* find skip flag and default failure */
1689 	switch (command)
1690 	{
1691 	  case SMFIC_CONNECT:
1692 		skipflag = SMFIP_NOCONNECT;
1693 		defresponse = "554 Command rejected";
1694 		break;
1695 
1696 	  case SMFIC_HELO:
1697 		skipflag = SMFIP_NOHELO;
1698 		defresponse = "550 Command rejected";
1699 		break;
1700 
1701 	  case SMFIC_MAIL:
1702 		skipflag = SMFIP_NOMAIL;
1703 		defresponse = "550 5.7.1 Command rejected";
1704 		break;
1705 
1706 	  case SMFIC_RCPT:
1707 		skipflag = SMFIP_NORCPT;
1708 		defresponse = "550 5.7.1 Command rejected";
1709 		break;
1710 
1711 	  case SMFIC_HEADER:
1712 		skipflag = SMFIP_NOHDRS;
1713 		defresponse = "550 5.7.1 Command rejected";
1714 		break;
1715 
1716 	  case SMFIC_BODY:
1717 		skipflag = SMFIP_NOBODY;
1718 		defresponse = "554 5.7.1 Command rejected";
1719 		break;
1720 
1721 	  case SMFIC_EOH:
1722 		skipflag = SMFIP_NOEOH;
1723 		defresponse = "550 5.7.1 Command rejected";
1724 		break;
1725 
1726 	  case SMFIC_BODYEOB:
1727 	  case SMFIC_OPTNEG:
1728 	  case SMFIC_MACRO:
1729 	  case SMFIC_ABORT:
1730 	  case SMFIC_QUIT:
1731 		/* NOTE: not handled by milter_send_command() */
1732 		/* FALLTHROUGH */
1733 
1734 	  default:
1735 		skipflag = 0;
1736 		defresponse = "550 5.7.1 Command rejected";
1737 		break;
1738 	}
1739 
1740 	/* check if filter wants this command */
1741 	if (skipflag != 0 &&
1742 	    bitset(skipflag, m->mf_pflags))
1743 		return NULL;
1744 
1745 
1746 	(void) milter_write(m, command, data, sz,
1747 			    m->mf_timeout[SMFTO_WRITE], e);
1748 	if (m->mf_state == SMFS_ERROR)
1749 	{
1750 		MILTER_CHECK_ERROR(/* EMPTY */;);
1751 		return NULL;
1752 	}
1753 
1754 	response = milter_read(m, &rcmd, &rlen,
1755 			       m->mf_timeout[SMFTO_READ], e);
1756 	if (m->mf_state == SMFS_ERROR)
1757 	{
1758 		MILTER_CHECK_ERROR(/* EMPTY */;);
1759 		return NULL;
1760 	}
1761 
1762 	if (tTd(64, 10))
1763 		dprintf("milter_send_command(%s): returned %c\n",
1764 			m->mf_name, (char) rcmd);
1765 
1766 	switch (rcmd)
1767 	{
1768 	  case SMFIR_REPLYCODE:
1769 		MILTER_CHECK_REPLYCODE(defresponse);
1770 		/* FALLTHROUGH */
1771 
1772 	  case SMFIR_REJECT:
1773 	  case SMFIR_DISCARD:
1774 	  case SMFIR_TEMPFAIL:
1775 		*state = rcmd;
1776 		break;
1777 
1778 	  case SMFIR_ACCEPT:
1779 		/* this filter is done with message/connection */
1780 		m->mf_state = SMFS_DONE;
1781 		break;
1782 
1783 	  case SMFIR_CONTINUE:
1784 		/* if MAIL command is ok, filter is in message state */
1785 		if (command == SMFIC_MAIL)
1786 			m->mf_state = SMFS_INMSG;
1787 		break;
1788 
1789 	  default:
1790 		/* Invalid response to command */
1791 		if (LogLevel > 0)
1792 			sm_syslog(LOG_ERR, e->e_id,
1793 				  "milter_send_command(%s): returned bogus response %c",
1794 				  m->mf_name, rcmd);
1795 		milter_error(m);
1796 		break;
1797 	}
1798 
1799 	if (*state != SMFIR_REPLYCODE &&
1800 	    response != NULL)
1801 	{
1802 		free(response);
1803 		response = NULL;
1804 	}
1805 	return response;
1806 }
1807 
1808 /*
1809 **  MILTER_COMMAND -- send a command and return the response for each filter
1810 **
1811 **	Parameters:
1812 **		command -- command to send.
1813 **		data -- optional command data.
1814 **		sz -- length of buf.
1815 **		macros -- macros to send for filter smfi_getsymval().
1816 **		e -- current envelope (for macro access).
1817 **		state -- return state word.
1818 **
1819 **	Returns:
1820 **		response string (may be NULL)
1821 */
1822 
1823 static char *
1824 milter_command(command, data, sz, macros, e, state)
1825 	char command;
1826 	void *data;
1827 	ssize_t sz;
1828 	char **macros;
1829 	ENVELOPE *e;
1830 	char *state;
1831 {
1832 	int i;
1833 	char *response = NULL;
1834 
1835 	if (tTd(64, 10))
1836 		dprintf("milter_command: cmd %c len %ld\n",
1837 			(char) command, (long) sz);
1838 
1839 	*state = SMFIR_CONTINUE;
1840 	for (i = 0; InputFilters[i] != NULL; i++)
1841 	{
1842 		struct milter *m = InputFilters[i];
1843 
1844 		/* sanity check */
1845 		if (m->mf_sock < 0 ||
1846 		    (m->mf_state != SMFS_OPEN && m->mf_state != SMFS_INMSG))
1847 			continue;
1848 
1849 		/* send macros (regardless of whether we send command) */
1850 		if (macros != NULL && macros[0] != NULL)
1851 		{
1852 			milter_send_macros(m, macros, command, e);
1853 			if (m->mf_state == SMFS_ERROR)
1854 			{
1855 				MILTER_CHECK_ERROR(continue);
1856 				break;
1857 			}
1858 		}
1859 
1860 		response = milter_send_command(m, command, data, sz, e, state);
1861 		if (*state != SMFIR_CONTINUE)
1862 			break;
1863 	}
1864 	return response;
1865 }
1866 /*
1867 **  MILTER_NEGOTIATE -- get version and flags from filter
1868 **
1869 **	Parameters:
1870 **		m -- milter filter structure.
1871 **		e -- current envelope.
1872 **
1873 **	Returns:
1874 **		0 on success, -1 otherwise
1875 */
1876 
1877 static int
1878 milter_negotiate(m, e)
1879 	struct milter *m;
1880 	ENVELOPE *e;
1881 {
1882 	char rcmd;
1883 	mi_int32 fvers;
1884 	mi_int32 fflags;
1885 	mi_int32 pflags;
1886 	char *response;
1887 	ssize_t rlen;
1888 	char data[MILTER_OPTLEN];
1889 
1890 	/* sanity check */
1891 	if (m->mf_sock < 0 || m->mf_state != SMFS_OPEN)
1892 	{
1893 		if (LogLevel > 0)
1894 			sm_syslog(LOG_ERR, e->e_id,
1895 				  "milter_negotiate(%s): impossible state",
1896 				  m->mf_name);
1897 		milter_error(m);
1898 		return -1;
1899 	}
1900 
1901 	fvers = htonl(SMFI_VERSION);
1902 	fflags = htonl(SMFI_CURR_ACTS);
1903 	pflags = htonl(SMFI_CURR_PROT);
1904 	(void) memcpy(data, (char *) &fvers, MILTER_LEN_BYTES);
1905 	(void) memcpy(data + MILTER_LEN_BYTES,
1906 		      (char *) &fflags, MILTER_LEN_BYTES);
1907 	(void) memcpy(data + (MILTER_LEN_BYTES * 2),
1908 		      (char *) &pflags, MILTER_LEN_BYTES);
1909 	(void) milter_write(m, SMFIC_OPTNEG, data, sizeof data,
1910 			    m->mf_timeout[SMFTO_WRITE], e);
1911 
1912 	if (m->mf_state == SMFS_ERROR)
1913 		return -1;
1914 
1915 	response = milter_read(m, &rcmd, &rlen, m->mf_timeout[SMFTO_READ], e);
1916 	if (m->mf_state == SMFS_ERROR)
1917 		return -1;
1918 
1919 	if (rcmd != SMFIC_OPTNEG)
1920 	{
1921 		if (tTd(64, 5))
1922 			dprintf("milter_negotiate(%s): returned %c instead of %c\n",
1923 				m->mf_name, rcmd, SMFIC_OPTNEG);
1924 		if (LogLevel > 0)
1925 			sm_syslog(LOG_ERR, e->e_id,
1926 				  "milter_negotiate(%s): returned %c instead of %c",
1927 				  m->mf_name, rcmd, SMFIC_OPTNEG);
1928 		if (response != NULL)
1929 			free(response);
1930 		milter_error(m);
1931 		return -1;
1932 	}
1933 
1934 	/* Make sure we have enough bytes for the version */
1935 	if (response == NULL || rlen < MILTER_LEN_BYTES)
1936 	{
1937 		if (tTd(64, 5))
1938 			dprintf("milter_negotiate(%s): did not return valid info\n",
1939 				m->mf_name);
1940 		if (LogLevel > 0)
1941 			sm_syslog(LOG_ERR, e->e_id,
1942 				  "milter_negotiate(%s): did not return valid info",
1943 				  m->mf_name);
1944 		if (response != NULL)
1945 			free(response);
1946 		milter_error(m);
1947 		return -1;
1948 	}
1949 
1950 	/* extract information */
1951 	(void) memcpy((char *) &fvers, response, MILTER_LEN_BYTES);
1952 
1953 	/* Now make sure we have enough for the feature bitmap */
1954 	if (rlen != MILTER_OPTLEN)
1955 	{
1956 		if (tTd(64, 5))
1957 			dprintf("milter_negotiate(%s): did not return enough info\n",
1958 				m->mf_name);
1959 		if (LogLevel > 0)
1960 			sm_syslog(LOG_ERR, e->e_id,
1961 				  "milter_negotiate(%s): did not return enough info",
1962 				  m->mf_name);
1963 		if (response != NULL)
1964 			free(response);
1965 		milter_error(m);
1966 		return -1;
1967 	}
1968 
1969 	(void) memcpy((char *) &fflags, response + MILTER_LEN_BYTES,
1970 		      MILTER_LEN_BYTES);
1971 	(void) memcpy((char *) &pflags, response + (MILTER_LEN_BYTES * 2),
1972 		      MILTER_LEN_BYTES);
1973 	free(response);
1974 	response = NULL;
1975 
1976 	m->mf_fvers = ntohl(fvers);
1977 	m->mf_fflags = ntohl(fflags);
1978 	m->mf_pflags = ntohl(pflags);
1979 
1980 	/* check for version compatibility */
1981 	if (m->mf_fvers == 1 ||
1982 	    m->mf_fvers > SMFI_VERSION)
1983 	{
1984 		if (tTd(64, 5))
1985 			dprintf("milter_negotiate(%s): version %lu != MTA milter version %d\n",
1986 				m->mf_name, m->mf_fvers, SMFI_VERSION);
1987 		if (LogLevel > 0)
1988 			sm_syslog(LOG_ERR, e->e_id,
1989 				  "milter_negotiate(%s): version %ld != MTA milter version %d",
1990 				  m->mf_name, m->mf_fvers, SMFI_VERSION);
1991 		milter_error(m);
1992 		return -1;
1993 	}
1994 
1995 	/* check for filter feature mismatch */
1996 	if ((m->mf_fflags & SMFI_CURR_ACTS) != m->mf_fflags)
1997 	{
1998 		if (tTd(64, 5))
1999 			dprintf("milter_negotiate(%s): filter abilities 0x%lx != MTA milter abilities 0x%lx\n",
2000 				m->mf_name, m->mf_fflags,
2001 				(u_long) SMFI_CURR_ACTS);
2002 		if (LogLevel > 0)
2003 			sm_syslog(LOG_ERR, e->e_id,
2004 				  "milter_negotiate(%s): filter abilities 0x%lx != MTA milter abilities 0x%lx\n",
2005 				  m->mf_name, m->mf_fflags,
2006 				  (u_long) SMFI_CURR_ACTS);
2007 		milter_error(m);
2008 		return -1;
2009 	}
2010 
2011 	/* check for protocol feature mismatch */
2012 	if ((m->mf_pflags & SMFI_CURR_PROT) != m->mf_pflags)
2013 	{
2014 		if (tTd(64, 5))
2015 			dprintf("milter_negotiate(%s): protocol abilities 0x%lx != MTA milter abilities 0x%lx\n",
2016 				m->mf_name, m->mf_pflags,
2017 				(u_long) SMFI_CURR_PROT);
2018 		if (LogLevel > 0)
2019 			sm_syslog(LOG_ERR, e->e_id,
2020 				  "milter_negotiate(%s): protocol abilities 0x%lx != MTA milter abilities 0x%lx\n",
2021 				  m->mf_name, m->mf_pflags,
2022 				  (u_long) SMFI_CURR_PROT);
2023 		milter_error(m);
2024 		return -1;
2025 	}
2026 
2027 	if (tTd(64, 5))
2028 		dprintf("milter_negotiate(%s): version %lu, fflags 0x%lx, pflags 0x%lx\n",
2029 			m->mf_name, m->mf_fvers, m->mf_fflags, m->mf_pflags);
2030 	return 0;
2031 }
2032 /*
2033 **  MILTER_PER_CONNECTION_CHECK -- checks on per-connection commands
2034 **
2035 **	Reduce code duplication by putting these checks in one place
2036 **
2037 **	Parameters:
2038 **		e -- current envelope.
2039 **
2040 **	Returns:
2041 **		none
2042 */
2043 
2044 static void
2045 milter_per_connection_check(e)
2046 	ENVELOPE *e;
2047 {
2048 	int i;
2049 
2050 	/* see if we are done with any of the filters */
2051 	for (i = 0; InputFilters[i] != NULL; i++)
2052 	{
2053 		struct milter *m = InputFilters[i];
2054 
2055 		if (m->mf_state == SMFS_DONE)
2056 			milter_quit_filter(m, e);
2057 	}
2058 }
2059 /*
2060 **  MILTER_ERROR -- Put a milter filter into error state
2061 **
2062 **	Parameters:
2063 **		m -- the broken filter.
2064 **
2065 **	Returns:
2066 **		none
2067 */
2068 
2069 static void
2070 milter_error(m)
2071 	struct milter *m;
2072 {
2073 	/*
2074 	**  We could send a quit here but
2075 	**  we may have gotten here due to
2076 	**  an I/O error so we don't want
2077 	**  to try to make things worse.
2078 	*/
2079 
2080 	if (m->mf_sock >= 0)
2081 	{
2082 		(void) close(m->mf_sock);
2083 		m->mf_sock = -1;
2084 	}
2085 	m->mf_state = SMFS_ERROR;
2086 }
2087 /*
2088 **  MILTER_HEADERS -- send headers to a single milter filter
2089 **
2090 **	Parameters:
2091 **		m -- current filter.
2092 **		e -- current envelope.
2093 **		state -- return state from response.
2094 **
2095 **	Returns:
2096 **		response string (may be NULL)
2097 */
2098 
2099 static char *
2100 milter_headers(m, e, state)
2101 	struct milter *m;
2102 	ENVELOPE *e;
2103 	char *state;
2104 {
2105 	char *response = NULL;
2106 	HDR *h;
2107 
2108 	for (h = e->e_header; h != NULL; h = h->h_link)
2109 	{
2110 		char *buf;
2111 		ssize_t s;
2112 
2113 		/* don't send over deleted headers */
2114 		if (h->h_value == NULL)
2115 		{
2116 			/* strip H_USER so not counted in milter_chgheader() */
2117 			h->h_flags &= ~H_USER;
2118 			continue;
2119 		}
2120 
2121 		/* skip auto-generated */
2122 		if (!bitset(H_USER, h->h_flags))
2123 			continue;
2124 
2125 		if (tTd(64, 10))
2126 			dprintf("milter_headers: %s: %s\n",
2127 				h->h_field, h->h_value);
2128 
2129 		s = strlen(h->h_field) + 1 +
2130 			strlen(h->h_value) + 1;
2131 		buf = (char *) xalloc(s);
2132 		snprintf(buf, s, "%s%c%s", h->h_field, '\0', h->h_value);
2133 
2134 		/* send it over */
2135 		response = milter_send_command(m, SMFIC_HEADER, buf,
2136 					       s, e, state);
2137 		free(buf);
2138 		if (m->mf_state == SMFS_ERROR ||
2139 		    m->mf_state == SMFS_DONE ||
2140 		    *state != SMFIR_CONTINUE)
2141 			break;
2142 	}
2143 	return response;
2144 }
2145 /*
2146 **  MILTER_BODY -- send the body to a filter
2147 **
2148 **	Parameters:
2149 **		m -- current filter.
2150 **		e -- current envelope.
2151 **		state -- return state from response.
2152 **
2153 **	Returns:
2154 **		response string (may be NULL)
2155 */
2156 
2157 static char *
2158 milter_body(m, e, state)
2159 	struct milter *m;
2160 	ENVELOPE *e;
2161 	char *state;
2162 {
2163 	char bufchar = '\0';
2164 	char prevchar = '\0';
2165 	int c;
2166 	char *response = NULL;
2167 	char *bp;
2168 	char buf[MILTER_CHUNK_SIZE];
2169 
2170 	if (tTd(64, 10))
2171 		dprintf("milter_body\n");
2172 
2173 	if (bfrewind(e->e_dfp) < 0)
2174 	{
2175 		ExitStat = EX_IOERR;
2176 		*state = SMFIR_TEMPFAIL;
2177 		syserr("milter_body: %s/df%s: rewind error",
2178 		       qid_printqueue(e->e_queuedir), e->e_id);
2179 		return NULL;
2180 	}
2181 
2182 	bp = buf;
2183 	while ((c = getc(e->e_dfp)) != EOF)
2184 	{
2185 		/*  Change LF to CRLF */
2186 		if (c == '\n')
2187 		{
2188 			/* Not a CRLF already? */
2189 			if (prevchar != '\r')
2190 			{
2191 				/* Room for CR now? */
2192 				if (bp + 2 > &buf[sizeof buf])
2193 				{
2194 					/* No room, buffer LF */
2195 					bufchar = c;
2196 
2197 					/* and send CR now */
2198 					c = '\r';
2199 				}
2200 				else
2201 				{
2202 					/* Room to do it now */
2203 					*bp++ = '\r';
2204 					prevchar = '\r';
2205 				}
2206 			}
2207 		}
2208 		*bp++ = (char) c;
2209 		prevchar = c;
2210 		if (bp >= &buf[sizeof buf])
2211 		{
2212 			/* send chunk */
2213 			response = milter_send_command(m, SMFIC_BODY, buf,
2214 						       bp - buf, e, state);
2215 			bp = buf;
2216 			if (bufchar != '\0')
2217 			{
2218 				*bp++ = bufchar;
2219 				bufchar = '\0';
2220 				prevchar = bufchar;
2221 			}
2222 		}
2223 		if (m->mf_state == SMFS_ERROR ||
2224 		    m->mf_state == SMFS_DONE ||
2225 		    *state != SMFIR_CONTINUE)
2226 			break;
2227 	}
2228 
2229 	/* check for read errors */
2230 	if (ferror(e->e_dfp))
2231 	{
2232 		ExitStat = EX_IOERR;
2233 		if (*state == SMFIR_CONTINUE ||
2234 		    *state == SMFIR_ACCEPT)
2235 		{
2236 			*state = SMFIR_TEMPFAIL;
2237 			if (response != NULL)
2238 			{
2239 				free(response);
2240 				response = NULL;
2241 			}
2242 		}
2243 		syserr("milter_body: %s/df%s: read error",
2244 		       qid_printqueue(e->e_queuedir), e->e_id);
2245 		return response;
2246 	}
2247 
2248 	/* send last body chunk */
2249 	if (bp > buf &&
2250 	    m->mf_state != SMFS_ERROR &&
2251 	    m->mf_state != SMFS_DONE &&
2252 	    *state == SMFIR_CONTINUE)
2253 	{
2254 		/* send chunk */
2255 		response = milter_send_command(m, SMFIC_BODY, buf, bp - buf,
2256 					       e, state);
2257 		bp = buf;
2258 	}
2259 	return response;
2260 }
2261 
2262 /*
2263 **  Actions
2264 */
2265 
2266 /*
2267 **  MILTER_ADDHEADER -- Add the supplied header to the message
2268 **
2269 **	Parameters:
2270 **		response -- encoded form of header/value.
2271 **		rlen -- length of response.
2272 **		e -- current envelope.
2273 **
2274 **	Returns:
2275 **		none
2276 */
2277 
2278 static void
2279 milter_addheader(response, rlen, e)
2280 	char *response;
2281 	ssize_t rlen;
2282 	ENVELOPE *e;
2283 {
2284 	char *val;
2285 
2286 	if (tTd(64, 10))
2287 		dprintf("milter_addheader: ");
2288 
2289 	/* sanity checks */
2290 	if (response == NULL)
2291 	{
2292 		if (tTd(64, 10))
2293 			dprintf("NULL response\n");
2294 		return;
2295 	}
2296 
2297 	if (rlen < 2 || strlen(response) + 1 >= (size_t) rlen)
2298 	{
2299 		if (tTd(64, 10))
2300 			dprintf("didn't follow protocol (total len)\n");
2301 		return;
2302 	}
2303 
2304 	/* Find separating NUL */
2305 	val = response + strlen(response) + 1;
2306 
2307 	/* another sanity check */
2308 	if (strlen(response) + strlen(val) + 2 != (size_t) rlen)
2309 	{
2310 		if (tTd(64, 10))
2311 			dprintf("didn't follow protocol (part len)\n");
2312 		return;
2313 	}
2314 
2315 	if (*response == '\0')
2316 	{
2317 		if (tTd(64, 10))
2318 			dprintf("empty field name\n");
2319 		return;
2320 	}
2321 
2322 	/* add to e_msgsize */
2323 	e->e_msgsize += strlen(response) + 2 + strlen(val);
2324 
2325 	if (tTd(64, 10))
2326 		dprintf("Add %s: %s\n", response, val);
2327 
2328 	addheader(newstr(response), val, H_USER, &e->e_header);
2329 }
2330 /*
2331 **  MILTER_CHANGEHEADER -- Change the supplied header in the message
2332 **
2333 **	Parameters:
2334 **		response -- encoded form of header/index/value.
2335 **		rlen -- length of response.
2336 **		e -- current envelope.
2337 **
2338 **	Returns:
2339 **		none
2340 */
2341 
2342 static void
2343 milter_changeheader(response, rlen, e)
2344 	char *response;
2345 	ssize_t rlen;
2346 	ENVELOPE *e;
2347 {
2348 	mi_int32 i, index;
2349 	char *field, *val;
2350 	HDR *h;
2351 
2352 	if (tTd(64, 10))
2353 		dprintf("milter_changeheader: ");
2354 
2355 	/* sanity checks */
2356 	if (response == NULL)
2357 	{
2358 		if (tTd(64, 10))
2359 			dprintf("NULL response\n");
2360 		return;
2361 	}
2362 
2363 	if (rlen < 2 || strlen(response) + 1 >= (size_t) rlen)
2364 	{
2365 		if (tTd(64, 10))
2366 			dprintf("didn't follow protocol (total len)\n");
2367 		return;
2368 	}
2369 
2370 	/* Find separating NUL */
2371 	(void) memcpy((char *) &i, response, MILTER_LEN_BYTES);
2372 	index = ntohl(i);
2373 	field = response + MILTER_LEN_BYTES;
2374 	val = field + strlen(field) + 1;
2375 
2376 	/* another sanity check */
2377 	if (MILTER_LEN_BYTES + strlen(field) + 1 +
2378 	    strlen(val) + 1 != (size_t) rlen)
2379 	{
2380 		if (tTd(64, 10))
2381 			dprintf("didn't follow protocol (part len)\n");
2382 		return;
2383 	}
2384 
2385 	if (*field == '\0')
2386 	{
2387 		if (tTd(64, 10))
2388 			dprintf("empty field name\n");
2389 		return;
2390 	}
2391 
2392 	for (h = e->e_header; h != NULL; h = h->h_link)
2393 	{
2394 		if (bitset(H_USER, h->h_flags) &&
2395 		    strcasecmp(h->h_field, field) == 0 &&
2396 		    --index <= 0)
2397 			break;
2398 	}
2399 
2400 	if (h == NULL)
2401 	{
2402 		if (*val == '\0')
2403 		{
2404 			if (tTd(64, 10))
2405 				dprintf("Delete (noop) %s:\n", field);
2406 		}
2407 		else
2408 		{
2409 			/* treat modify value with no existing header as add */
2410 			if (tTd(64, 10))
2411 				dprintf("Add %s: %s\n",	field, val);
2412 
2413 			addheader(newstr(field), val, H_USER, &e->e_header);
2414 		}
2415 		return;
2416 	}
2417 
2418 	if (tTd(64, 10))
2419 	{
2420 		if (*val == '\0')
2421 		{
2422 			dprintf("Delete %s: %s\n", field,
2423 				h->h_value == NULL ? "<NULL>" : h->h_value);
2424 		}
2425 		else
2426 		{
2427 			dprintf("Change %s: from %s to %s\n",
2428 				field,
2429 				h->h_value == NULL ? "<NULL>" : h->h_value,
2430 				val);
2431 		}
2432 	}
2433 
2434 	if (h->h_value != NULL)
2435 	{
2436 		e->e_msgsize -= strlen(h->h_value);
2437 		free(h->h_value);
2438 	}
2439 
2440 	if (*val == '\0')
2441 	{
2442 		/* Remove "Field: " from message size */
2443 		e->e_msgsize -= strlen(h->h_field) + 2;
2444 		h->h_value = NULL;
2445 	}
2446 	else
2447 	{
2448 		h->h_value = newstr(val);
2449 		e->e_msgsize += strlen(h->h_value);
2450 	}
2451 }
2452 /*
2453 **  MILTER_ADDRCPT -- Add the supplied recipient to the message
2454 **
2455 **	Parameters:
2456 **		response -- encoded form of recipient address.
2457 **		rlen -- length of response.
2458 **		e -- current envelope.
2459 **
2460 **	Returns:
2461 **		none
2462 */
2463 
2464 static void
2465 milter_addrcpt(response, rlen, e)
2466 	char *response;
2467 	ssize_t rlen;
2468 	ENVELOPE *e;
2469 {
2470 	if (tTd(64, 10))
2471 		dprintf("milter_addrcpt: ");
2472 
2473 	/* sanity checks */
2474 	if (response == NULL)
2475 	{
2476 		if (tTd(64, 10))
2477 			dprintf("NULL response\n");
2478 		return;
2479 	}
2480 
2481 	if (*response == '\0' ||
2482 	    strlen(response) + 1 != (size_t) rlen)
2483 	{
2484 		if (tTd(64, 10))
2485 			dprintf("didn't follow protocol (total len %d != rlen %d)\n",
2486 				strlen(response), rlen -1);
2487 		return;
2488 	}
2489 
2490 	if (tTd(64, 10))
2491 		dprintf("%s\n", response);
2492 	(void) sendtolist(response, NULLADDR, &e->e_sendqueue, 0, e);
2493 	return;
2494 }
2495 /*
2496 **  MILTER_DELRCPT -- Delete the supplied recipient from the message
2497 **
2498 **	Parameters:
2499 **		response -- encoded form of recipient address.
2500 **		rlen -- length of response.
2501 **		e -- current envelope.
2502 **
2503 **	Returns:
2504 **		none
2505 */
2506 
2507 static void
2508 milter_delrcpt(response, rlen, e)
2509 	char *response;
2510 	ssize_t rlen;
2511 	ENVELOPE *e;
2512 {
2513 	if (tTd(64, 10))
2514 		dprintf("milter_delrcpt: ");
2515 
2516 	/* sanity checks */
2517 	if (response == NULL)
2518 	{
2519 		if (tTd(64, 10))
2520 			dprintf("NULL response\n");
2521 		return;
2522 	}
2523 
2524 	if (*response == '\0' ||
2525 	    strlen(response) + 1 != (size_t) rlen)
2526 	{
2527 		if (tTd(64, 10))
2528 			dprintf("didn't follow protocol (total len)\n");
2529 		return;
2530 	}
2531 
2532 	if (tTd(64, 10))
2533 		dprintf("%s\n", response);
2534 	(void) removefromlist(response, &e->e_sendqueue, e);
2535 	return;
2536 }
2537 /*
2538 **  MILTER_REPLBODY -- Replace the current df file with new body
2539 **
2540 **	Parameters:
2541 **		response -- encoded form of new body.
2542 **		rlen -- length of response.
2543 **		newfilter -- if first time called by a new filter
2544 **		e -- current envelope.
2545 **
2546 **	Returns:
2547 **		0 upon success, -1 upon failure
2548 */
2549 
2550 static int
2551 milter_replbody(response, rlen, newfilter, e)
2552 	char *response;
2553 	ssize_t rlen;
2554 	bool newfilter;
2555 	ENVELOPE *e;
2556 {
2557 	static char prevchar;
2558 	int i;
2559 
2560 	if (tTd(64, 10))
2561 		dprintf("milter_replbody\n");
2562 
2563 	/* If a new filter, reset previous character and truncate df */
2564 	if (newfilter)
2565 	{
2566 		off_t prevsize = 0;
2567 		char dfname[MAXPATHLEN];
2568 
2569 		(void) strlcpy(dfname, queuename(e, 'd'), sizeof dfname);
2570 
2571 		/* Reset prevchar */
2572 		prevchar = '\0';
2573 
2574 		/* Get the current df information */
2575 		if (bitset(EF_HAS_DF, e->e_flags) && e->e_dfp != NULL)
2576 		{
2577 			int afd;
2578 			struct stat st;
2579 
2580 			afd = fileno(e->e_dfp);
2581 			if (afd > 0 && fstat(afd, &st) == 0)
2582 				prevsize = st.st_size;
2583 		}
2584 
2585 		/* truncate current df file */
2586 		if (bftruncate(e->e_dfp) < 0)
2587 		{
2588 			MILTER_DF_ERROR("milter_reopen_df: bftruncate %s: %s");
2589 			return -1;
2590 		}
2591 		else
2592 		{
2593 			if (prevsize > e->e_msgsize)
2594 				e->e_msgsize = 0;
2595 			else
2596 				e->e_msgsize -= prevsize;
2597 		}
2598 	}
2599 
2600 	if (response == NULL)
2601 	{
2602 		/* Flush the buffered '\r' */
2603 		if (prevchar == '\r')
2604 		{
2605 			(void) putc(prevchar, e->e_dfp);
2606 			e->e_msgsize++;
2607 		}
2608 		return 0;
2609 	}
2610 
2611 	for (i = 0; i < rlen; i++)
2612 	{
2613 		/* Buffered char from last chunk */
2614 		if (i == 0 && prevchar == '\r')
2615 		{
2616 			/* Not CRLF, output prevchar */
2617 			if (response[i] != '\n')
2618 			{
2619 				(void) putc(prevchar, e->e_dfp);
2620 				e->e_msgsize++;
2621 			}
2622 			prevchar = '\0';
2623 		}
2624 
2625 		/* Turn CRLF into LF */
2626 		if (response[i] == '\r')
2627 		{
2628 			/* check if at end of chunk */
2629 			if (i + 1 < rlen)
2630 			{
2631 				/* If LF, strip CR */
2632 				if (response[i + 1] == '\n')
2633 					i++;
2634 			}
2635 			else
2636 			{
2637 				/* check next chunk */
2638 				prevchar = '\r';
2639 				continue;
2640 			}
2641 		}
2642 		(void) putc(response[i], e->e_dfp);
2643 		e->e_msgsize++;
2644 	}
2645 	return 0;
2646 }
2647 
2648 /*
2649 **  MTA callouts
2650 */
2651 
2652 /*
2653 **  MILTER_INIT -- open and negotiate with all of the filters
2654 **
2655 **	Parameters:
2656 **		e -- current envelope.
2657 **		state -- return state from response.
2658 **
2659 **	Returns:
2660 **		none
2661 */
2662 
2663 /* ARGSUSED */
2664 void
2665 milter_init(e, state)
2666 	ENVELOPE *e;
2667 	char *state;
2668 {
2669 	int i;
2670 
2671 	if (tTd(64, 10))
2672 		dprintf("milter_init\n");
2673 
2674 	*state = SMFIR_CONTINUE;
2675 	for (i = 0; InputFilters[i] != NULL; i++)
2676 	{
2677 		struct milter *m = InputFilters[i];
2678 
2679 		m->mf_sock = milter_open(m, FALSE, e);
2680 		if (m->mf_state == SMFS_ERROR)
2681 		{
2682 			MILTER_CHECK_ERROR(continue);
2683 			break;
2684 		}
2685 
2686 		if (m->mf_sock < 0 ||
2687 		    milter_negotiate(m, e) < 0 ||
2688 		    m->mf_state == SMFS_ERROR)
2689 		{
2690 			if (tTd(64, 5))
2691 				dprintf("milter_init(%s): failed to %s\n",
2692 					m->mf_name,
2693 					m->mf_sock < 0 ? "open" : "negotiate");
2694 
2695 			/* if negotation failure, close socket */
2696 			if (m->mf_sock >= 0)
2697 			{
2698 				(void) close(m->mf_sock);
2699 				m->mf_sock = -1;
2700 			}
2701 			milter_error(m);
2702 			if (m->mf_state == SMFS_ERROR)
2703 			{
2704 				MILTER_CHECK_ERROR(continue);
2705 				break;
2706 			}
2707 		}
2708 	}
2709 
2710 	/*
2711 	**  If something temp/perm failed with one of the filters,
2712 	**  we won't be using any of them, so clear any existing
2713 	**  connections.
2714 	*/
2715 
2716 	if (*state != SMFIR_CONTINUE)
2717 		milter_quit(e);
2718 }
2719 /*
2720 **  MILTER_CONNECT -- send connection info to milter filters
2721 **
2722 **	Parameters:
2723 **		hostname -- hostname of remote machine.
2724 **		addr -- address of remote machine.
2725 **		e -- current envelope.
2726 **		state -- return state from response.
2727 **
2728 **	Returns:
2729 **		response string (may be NULL)
2730 */
2731 
2732 char *
2733 milter_connect(hostname, addr, e, state)
2734 	char *hostname;
2735 	SOCKADDR addr;
2736 	ENVELOPE *e;
2737 	char *state;
2738 {
2739 	char family;
2740 	u_short port;
2741 	char *buf, *bp;
2742 	char *response;
2743 	char *sockinfo = NULL;
2744 	ssize_t s;
2745 # if NETINET6
2746 	char buf6[INET6_ADDRSTRLEN];
2747 # endif /* NETINET6 */
2748 
2749 	if (tTd(64, 10))
2750 		dprintf("milter_connect(%s)\n", hostname);
2751 
2752 	/* gather data */
2753 	switch (addr.sa.sa_family)
2754 	{
2755 # if NETUNIX
2756 	  case AF_UNIX:
2757 		family = SMFIA_UNIX;
2758 		port = htons(0);
2759 		sockinfo = addr.sunix.sun_path;
2760 		break;
2761 # endif /* NETUNIX */
2762 
2763 # if NETINET
2764 	  case AF_INET:
2765 		family = SMFIA_INET;
2766 		port = htons(addr.sin.sin_port);
2767 		sockinfo = (char *) inet_ntoa(addr.sin.sin_addr);
2768 		break;
2769 # endif /* NETINET */
2770 
2771 # if NETINET6
2772 	  case AF_INET6:
2773 		family = SMFIA_INET6;
2774 		port = htons(addr.sin6.sin6_port);
2775 		sockinfo = anynet_ntop(&addr.sin6.sin6_addr, buf6,
2776 				       sizeof buf6);
2777 		if (sockinfo == NULL)
2778 			sockinfo = "";
2779 		break;
2780 # endif /* NETINET6 */
2781 
2782 	  default:
2783 		family = SMFIA_UNKNOWN;
2784 		break;
2785 	}
2786 
2787 	s = strlen(hostname) + 1 + sizeof(family);
2788 	if (family != SMFIA_UNKNOWN)
2789 		s += sizeof(port) + strlen(sockinfo) + 1;
2790 
2791 	buf = (char *)xalloc(s);
2792 	bp = buf;
2793 
2794 	/* put together data */
2795 	(void) memcpy(bp, hostname, strlen(hostname));
2796 	bp += strlen(hostname);
2797 	*bp++ = '\0';
2798 	(void) memcpy(bp, &family, sizeof family);
2799 	bp += sizeof family;
2800 	if (family != SMFIA_UNKNOWN)
2801 	{
2802 		(void) memcpy(bp, &port, sizeof port);
2803 		bp += sizeof port;
2804 
2805 		/* include trailing '\0' */
2806 		(void) memcpy(bp, sockinfo, strlen(sockinfo) + 1);
2807 	}
2808 
2809 	response = milter_command(SMFIC_CONNECT, buf, s,
2810 				  MilterConnectMacros, e, state);
2811 	free(buf);
2812 
2813 	/*
2814 	**  If this message connection is done for,
2815 	**  close the filters.
2816 	*/
2817 
2818 	if (*state != SMFIR_CONTINUE)
2819 		milter_quit(e);
2820 	else
2821 		milter_per_connection_check(e);
2822 
2823 	/*
2824 	**  SMFIR_REPLYCODE can't work with connect due to
2825 	**  the requirements of SMTP.  Therefore, ignore the
2826 	**  reply code text but keep the state it would reflect.
2827 	*/
2828 
2829 	if (*state == SMFIR_REPLYCODE)
2830 	{
2831 		if (response != NULL &&
2832 		    *response == '4')
2833 			*state = SMFIR_TEMPFAIL;
2834 		else
2835 			*state = SMFIR_REJECT;
2836 		if (response != NULL)
2837 		{
2838 			free(response);
2839 			response = NULL;
2840 		}
2841 	}
2842 	return response;
2843 }
2844 /*
2845 **  MILTER_HELO -- send SMTP HELO/EHLO command info to milter filters
2846 **
2847 **	Parameters:
2848 **		helo -- argument to SMTP HELO/EHLO command.
2849 **		e -- current envelope.
2850 **		state -- return state from response.
2851 **
2852 **	Returns:
2853 **		response string (may be NULL)
2854 */
2855 
2856 char *
2857 milter_helo(helo, e, state)
2858 	char *helo;
2859 	ENVELOPE *e;
2860 	char *state;
2861 {
2862 	char *response;
2863 
2864 	if (tTd(64, 10))
2865 		dprintf("milter_helo(%s)\n", helo);
2866 
2867 	response = milter_command(SMFIC_HELO, helo, strlen(helo) + 1,
2868 				  MilterHeloMacros, e, state);
2869 	milter_per_connection_check(e);
2870 	return response;
2871 }
2872 /*
2873 **  MILTER_ENVFROM -- send SMTP MAIL command info to milter filters
2874 **
2875 **	Parameters:
2876 **		args -- SMTP MAIL command args (args[0] == sender).
2877 **		e -- current envelope.
2878 **		state -- return state from response.
2879 **
2880 **	Returns:
2881 **		response string (may be NULL)
2882 */
2883 
2884 char *
2885 milter_envfrom(args, e, state)
2886 	char **args;
2887 	ENVELOPE *e;
2888 	char *state;
2889 {
2890 	int i;
2891 	char *buf, *bp;
2892 	char *response;
2893 	ssize_t s;
2894 
2895 	if (tTd(64, 10))
2896 	{
2897 		dprintf("milter_envfrom:");
2898 		for (i = 0; args[i] != NULL; i++)
2899 			dprintf(" %s", args[i]);
2900 		dprintf("\n");
2901 	}
2902 
2903 	/* sanity check */
2904 	if (args[0] == NULL)
2905 	{
2906 		*state = SMFIR_REJECT;
2907 		return NULL;
2908 	}
2909 
2910 	/* new message, so ... */
2911 	for (i = 0; InputFilters[i] != NULL; i++)
2912 	{
2913 		struct milter *m = InputFilters[i];
2914 
2915 		switch (m->mf_state)
2916 		{
2917 		  case SMFS_INMSG:
2918 			/* abort in message filters */
2919 			milter_abort_filter(m, e);
2920 			/* FALLTHROUGH */
2921 
2922 		  case SMFS_DONE:
2923 			/* reset done filters */
2924 			m->mf_state = SMFS_OPEN;
2925 			break;
2926 		}
2927 	}
2928 
2929 	/* put together data */
2930 	s = 0;
2931 	for (i = 0; args[i] != NULL; i++)
2932 		s += strlen(args[i]) + 1;
2933 	buf = (char *)xalloc(s);
2934 	bp = buf;
2935 	for (i = 0; args[i] != NULL; i++)
2936 	{
2937 		(void) strlcpy(bp, args[i], s - (bp - buf));
2938 		bp += strlen(bp) + 1;
2939 	}
2940 
2941 	/* send it over */
2942 	response = milter_command(SMFIC_MAIL, buf, s,
2943 				  MilterEnvFromMacros, e, state);
2944 	free(buf);
2945 
2946 	/*
2947 	**  If filter rejects/discards a per message command,
2948 	**  abort the other filters since we are done with the
2949 	**  current message.
2950 	*/
2951 
2952 	MILTER_CHECK_DONE_MSG();
2953 	return response;
2954 }
2955 /*
2956 **  MILTER_ENVRCPT -- send SMTP RCPT command info to milter filters
2957 **
2958 **	Parameters:
2959 **		args -- SMTP MAIL command args (args[0] == recipient).
2960 **		e -- current envelope.
2961 **		state -- return state from response.
2962 **
2963 **	Returns:
2964 **		response string (may be NULL)
2965 */
2966 
2967 char *
2968 milter_envrcpt(args, e, state)
2969 	char **args;
2970 	ENVELOPE *e;
2971 	char *state;
2972 {
2973 	int i;
2974 	char *buf, *bp;
2975 	char *response;
2976 	ssize_t s;
2977 
2978 	if (tTd(64, 10))
2979 	{
2980 		dprintf("milter_envrcpt:");
2981 		for (i = 0; args[i] != NULL; i++)
2982 			dprintf(" %s", args[i]);
2983 		dprintf("\n");
2984 	}
2985 
2986 	/* sanity check */
2987 	if (args[0] == NULL)
2988 	{
2989 		*state = SMFIR_REJECT;
2990 		return NULL;
2991 	}
2992 
2993 	/* put together data */
2994 	s = 0;
2995 	for (i = 0; args[i] != NULL; i++)
2996 		s += strlen(args[i]) + 1;
2997 	buf = (char *)xalloc(s);
2998 	bp = buf;
2999 	for (i = 0; args[i] != NULL; i++)
3000 	{
3001 		(void) strlcpy(bp, args[i], s - (bp - buf));
3002 		bp += strlen(bp) + 1;
3003 	}
3004 
3005 	/* send it over */
3006 	response = milter_command(SMFIC_RCPT, buf, s,
3007 				  MilterEnvRcptMacros, e, state);
3008 	free(buf);
3009 	return response;
3010 }
3011 /*
3012 **  MILTER_DATA -- send message headers/body and gather final message results
3013 **
3014 **	Parameters:
3015 **		e -- current envelope.
3016 **		state -- return state from response.
3017 **
3018 **	Returns:
3019 **		response string (may be NULL)
3020 **
3021 **	Side effects:
3022 **		- Uses e->e_dfp for access to the body
3023 **		- Can call the various milter action routines to
3024 **		  modify the envelope or message.
3025 */
3026 
3027 # define MILTER_CHECK_RESULTS() \
3028 	if (*state == SMFIR_ACCEPT || \
3029 	    m->mf_state == SMFS_DONE || \
3030 	    m->mf_state == SMFS_ERROR) \
3031 	{ \
3032 		if (m->mf_state != SMFS_ERROR) \
3033 			m->mf_state = SMFS_DONE; \
3034 		continue;	/* to next filter */ \
3035 	} \
3036 	if (*state != SMFIR_CONTINUE) \
3037 	{ \
3038 		m->mf_state = SMFS_DONE; \
3039 		goto finishup; \
3040 	}
3041 
3042 char *
3043 milter_data(e, state)
3044 	ENVELOPE *e;
3045 	char *state;
3046 {
3047 	bool replbody = FALSE;		/* milter_replbody() called? */
3048 	bool replfailed = FALSE;	/* milter_replbody() failed? */
3049 	bool rewind = FALSE;		/* rewind df file? */
3050 	bool dfopen = FALSE;		/* df open for writing? */
3051 	bool newfilter;			/* reset on each new filter */
3052 	char rcmd;
3053 	int i;
3054 	int save_errno;
3055 	char *response = NULL;
3056 	time_t eomsent;
3057 	ssize_t rlen;
3058 
3059 	if (tTd(64, 10))
3060 		dprintf("milter_data\n");
3061 
3062 	*state = SMFIR_CONTINUE;
3063 
3064 	/*
3065 	**  XXX: Should actually send body chunks to each filter
3066 	**  a chunk at a time instead of sending the whole body to
3067 	**  each filter in turn.  However, only if the filters don't
3068 	**  change the body.
3069 	*/
3070 
3071 	for (i = 0; InputFilters[i] != NULL; i++)
3072 	{
3073 		struct milter *m = InputFilters[i];
3074 
3075 		if (*state != SMFIR_CONTINUE &&
3076 		    *state != SMFIR_ACCEPT)
3077 		{
3078 			/*
3079 			**  A previous filter has dealt with the message,
3080 			**  safe to stop processing the filters.
3081 			*/
3082 
3083 			break;
3084 		}
3085 
3086 		/* Now reset state for later evaluation */
3087 		*state = SMFIR_CONTINUE;
3088 		newfilter = TRUE;
3089 
3090 		/* sanity checks */
3091 		if (m->mf_sock < 0 ||
3092 		    (m->mf_state != SMFS_OPEN && m->mf_state != SMFS_INMSG))
3093 			continue;
3094 
3095 		m->mf_state = SMFS_INMSG;
3096 
3097 		/* check if filter wants the headers */
3098 		if (!bitset(SMFIP_NOHDRS, m->mf_pflags))
3099 		{
3100 			response = milter_headers(m, e, state);
3101 			MILTER_CHECK_RESULTS();
3102 		}
3103 
3104 		/* check if filter wants EOH */
3105 		if (!bitset(SMFIP_NOEOH, m->mf_pflags))
3106 		{
3107 			if (tTd(64, 10))
3108 				dprintf("milter_data: eoh\n");
3109 
3110 			/* send it over */
3111 			response = milter_send_command(m, SMFIC_EOH, NULL, 0,
3112 						       e, state);
3113 			MILTER_CHECK_RESULTS();
3114 		}
3115 
3116 		/* check if filter wants the body */
3117 		if (!bitset(SMFIP_NOBODY, m->mf_pflags) &&
3118 		    e->e_dfp != NULL)
3119 		{
3120 			rewind = TRUE;
3121 			response = milter_body(m, e, state);
3122 			MILTER_CHECK_RESULTS();
3123 		}
3124 
3125 		/* send the final body chunk */
3126 		(void) milter_write(m, SMFIC_BODYEOB, NULL, 0,
3127 				    m->mf_timeout[SMFTO_WRITE], e);
3128 
3129 		/* Get time EOM sent for timeout */
3130 		eomsent = curtime();
3131 
3132 		/* deal with the possibility of multiple responses */
3133 		while (*state == SMFIR_CONTINUE)
3134 		{
3135 			/* Check total timeout from EOM to final ACK/NAK */
3136 			if (m->mf_timeout[SMFTO_EOM] > 0 &&
3137 			    curtime() - eomsent >= m->mf_timeout[SMFTO_EOM])
3138 			{
3139 				if (tTd(64, 5))
3140 					dprintf("milter_data(%s): EOM ACK/NAK timeout\n",
3141 						m->mf_name);
3142 				if (LogLevel > 0)
3143 					sm_syslog(LOG_ERR, e->e_id,
3144 						  "milter_data(%s): EOM ACK/NAK timeout\n",
3145 						  m->mf_name);
3146 				milter_error(m);
3147 				MILTER_CHECK_ERROR(continue);
3148 				break;
3149 			}
3150 
3151 			response = milter_read(m, &rcmd, &rlen,
3152 					       m->mf_timeout[SMFTO_READ], e);
3153 			if (m->mf_state == SMFS_ERROR)
3154 				break;
3155 
3156 			if (tTd(64, 10))
3157 				dprintf("milter_data(%s): state %c\n",
3158 					m->mf_name, (char) rcmd);
3159 
3160 			switch (rcmd)
3161 			{
3162 			  case SMFIR_REPLYCODE:
3163 				MILTER_CHECK_REPLYCODE("554 5.7.1 Command rejected");
3164 				*state = rcmd;
3165 				m->mf_state = SMFS_DONE;
3166 				break;
3167 
3168 			  case SMFIR_REJECT:
3169 			  case SMFIR_DISCARD:
3170 			  case SMFIR_TEMPFAIL:
3171 				*state = rcmd;
3172 				m->mf_state = SMFS_DONE;
3173 				break;
3174 
3175 			  case SMFIR_CONTINUE:
3176 			  case SMFIR_ACCEPT:
3177 				/* this filter is done with message */
3178 				if (replfailed)
3179 					*state = SMFIR_TEMPFAIL;
3180 				else
3181 					*state = SMFIR_ACCEPT;
3182 				m->mf_state = SMFS_DONE;
3183 				break;
3184 
3185 			  case SMFIR_PROGRESS:
3186 				break;
3187 
3188 			  case SMFIR_ADDHEADER:
3189 				if (!bitset(SMFIF_ADDHDRS, m->mf_fflags))
3190 				{
3191 					if (LogLevel > 9)
3192 						sm_syslog(LOG_WARNING, e->e_id,
3193 							  "milter_data(%s): lied about adding headers, honoring request anyway",
3194 							  m->mf_name);
3195 				}
3196 				milter_addheader(response, rlen, e);
3197 				break;
3198 
3199 			  case SMFIR_CHGHEADER:
3200 				if (!bitset(SMFIF_CHGHDRS, m->mf_fflags))
3201 				{
3202 					if (LogLevel > 9)
3203 						sm_syslog(LOG_WARNING, e->e_id,
3204 							  "milter_data(%s): lied about changing headers, honoring request anyway",
3205 							  m->mf_name);
3206 				}
3207 				milter_changeheader(response, rlen, e);
3208 				break;
3209 
3210 			  case SMFIR_ADDRCPT:
3211 				if (!bitset(SMFIF_ADDRCPT, m->mf_fflags))
3212 				{
3213 					if (LogLevel > 9)
3214 						sm_syslog(LOG_WARNING, e->e_id,
3215 							  "milter_data(%s) lied about adding recipients, honoring request anyway",
3216 							  m->mf_name);
3217 				}
3218 				milter_addrcpt(response, rlen, e);
3219 				break;
3220 
3221 			  case SMFIR_DELRCPT:
3222 				if (!bitset(SMFIF_DELRCPT, m->mf_fflags))
3223 				{
3224 					if (LogLevel > 9)
3225 						sm_syslog(LOG_WARNING, e->e_id,
3226 							  "milter_data(%s): lied about removing recipients, honoring request anyway",
3227 							  m->mf_name);
3228 				}
3229 				milter_delrcpt(response, rlen, e);
3230 				break;
3231 
3232 			  case SMFIR_REPLBODY:
3233 				if (!bitset(SMFIF_MODBODY, m->mf_fflags))
3234 				{
3235 					if (LogLevel > 0)
3236 						sm_syslog(LOG_ERR, e->e_id,
3237 							  "milter_data(%s): lied about replacing body, rejecting request and tempfailing message",
3238 							  m->mf_name);
3239 					replfailed = TRUE;
3240 					break;
3241 				}
3242 
3243 				/* already failed in attempt */
3244 				if (replfailed)
3245 					break;
3246 
3247 				if (!dfopen)
3248 				{
3249 					if (milter_reopen_df(e) < 0)
3250 					{
3251 						replfailed = TRUE;
3252 						break;
3253 					}
3254 					dfopen = TRUE;
3255 					rewind = TRUE;
3256 				}
3257 
3258 				if (milter_replbody(response, rlen,
3259 						    newfilter, e) < 0)
3260 					replfailed = TRUE;
3261 				newfilter = FALSE;
3262 				replbody = TRUE;
3263 				break;
3264 
3265 			  default:
3266 				/* Invalid response to command */
3267 				if (LogLevel > 0)
3268 					sm_syslog(LOG_ERR, e->e_id,
3269 						  "milter_data(%s): returned bogus response %c",
3270 						  m->mf_name, rcmd);
3271 				milter_error(m);
3272 				break;
3273 			}
3274 			if (rcmd != SMFIR_REPLYCODE &&
3275 			    response != NULL)
3276 			{
3277 				free(response);
3278 				response = NULL;
3279 			}
3280 
3281 			if (m->mf_state == SMFS_ERROR)
3282 				break;
3283 		}
3284 
3285 		if (replbody && !replfailed)
3286 		{
3287 			/* flush possible buffered character */
3288 			milter_replbody(NULL, 0, !replbody, e);
3289 			replbody = FALSE;
3290 		}
3291 
3292 		if (m->mf_state == SMFS_ERROR)
3293 		{
3294 			MILTER_CHECK_ERROR(continue);
3295 			goto finishup;
3296 		}
3297 	}
3298 
3299 finishup:
3300 	/* leave things in the expected state if we touched it */
3301 	if (replfailed)
3302 	{
3303 		if (*state == SMFIR_CONTINUE ||
3304 		    *state == SMFIR_ACCEPT)
3305 		{
3306 			*state = SMFIR_TEMPFAIL;
3307 			if (response != NULL)
3308 			{
3309 				free(response);
3310 				response = NULL;
3311 			}
3312 		}
3313 
3314 		if (dfopen)
3315 		{
3316 			(void) fclose(e->e_dfp);
3317 			e->e_dfp = NULL;
3318 			e->e_flags &= ~EF_HAS_DF;
3319 			dfopen = FALSE;
3320 		}
3321 		rewind = FALSE;
3322 	}
3323 
3324 	if ((dfopen && milter_reset_df(e) < 0) ||
3325 	    (rewind && bfrewind(e->e_dfp) < 0))
3326 	{
3327 		save_errno = errno;
3328 		ExitStat = EX_IOERR;
3329 
3330 		/*
3331 		**  If filter told us to keep message but we had
3332 		**  an error, we can't really keep it, tempfail it.
3333 		*/
3334 
3335 		if (*state == SMFIR_CONTINUE ||
3336 		    *state == SMFIR_ACCEPT)
3337 		{
3338 			*state = SMFIR_TEMPFAIL;
3339 			if (response != NULL)
3340 			{
3341 				free(response);
3342 				response = NULL;
3343 			}
3344 		}
3345 
3346 		errno = save_errno;
3347 		syserr("milter_data: %s/df%s: read error",
3348 		       qid_printqueue(e->e_queuedir), e->e_id);
3349 	}
3350 	MILTER_CHECK_DONE_MSG();
3351 	return response;
3352 }
3353 /*
3354 **  MILTER_QUIT -- informs the filter(s) we are done and closes connection(s)
3355 **
3356 **	Parameters:
3357 **		e -- current envelope.
3358 **
3359 **	Returns:
3360 **		none
3361 */
3362 
3363 void
3364 milter_quit(e)
3365 	ENVELOPE *e;
3366 {
3367 	int i;
3368 
3369 	if (tTd(64, 10))
3370 		dprintf("milter_quit\n");
3371 
3372 	for (i = 0; InputFilters[i] != NULL; i++)
3373 		milter_quit_filter(InputFilters[i], e);
3374 }
3375 /*
3376 **  MILTER_ABORT -- informs the filter(s) that we are aborting current message
3377 **
3378 **	Parameters:
3379 **		e -- current envelope.
3380 **
3381 **	Returns:
3382 **		none
3383 */
3384 
3385 void
3386 milter_abort(e)
3387 	ENVELOPE *e;
3388 {
3389 	int i;
3390 
3391 	if (tTd(64, 10))
3392 		dprintf("milter_abort\n");
3393 
3394 	for (i = 0; InputFilters[i] != NULL; i++)
3395 	{
3396 		struct milter *m = InputFilters[i];
3397 
3398 		/* sanity checks */
3399 		if (m->mf_sock < 0 || m->mf_state != SMFS_INMSG)
3400 			continue;
3401 
3402 		milter_abort_filter(m, e);
3403 	}
3404 }
3405 #endif /* _FFR_MILTER */
3406