xref: /freebsd/contrib/sendmail/libmilter/engine.c (revision eacee0ff7ec955b32e09515246bd97b6edcd2b0f)
1 /*
2  *  Copyright (c) 1999-2001 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 #include <sm/gen.h>
12 SM_RCSID("@(#)$Id: engine.c,v 8.102 2001/12/13 17:10:00 ca Exp $")
13 
14 #include "libmilter.h"
15 
16 #if NETINET || NETINET6
17 # include <arpa/inet.h>
18 #endif /* NETINET || NETINET6 */
19 
20 /* generic argument for functions in the command table */
21 struct arg_struct
22 {
23 	size_t		a_len;		/* length of buffer */
24 	char		*a_buf;		/* argument string */
25 	int		a_idx;		/* index for macro array */
26 	SMFICTX_PTR	a_ctx;		/* context */
27 };
28 
29 typedef struct arg_struct genarg;
30 
31 /* structure for commands received from MTA */
32 struct cmdfct_t
33 {
34 	char	cm_cmd;				/* command */
35 	int	cm_argt;			/* type of arguments expected */
36 	int	cm_next;			/* next state */
37 	int	cm_todo;			/* what to do next */
38 	int	cm_macros;			/* index for macros */
39 	int	(*cm_fct) __P((genarg *));	/* function to execute */
40 };
41 
42 typedef struct cmdfct_t cmdfct;
43 
44 /* possible values for cm_argt */
45 #define	CM_ARG0	0	/* no args */
46 #define	CM_ARG1	1	/* one arg (string) */
47 #define	CM_ARG2	2	/* two args (strings) */
48 #define	CM_ARGA	4	/* one string and _SOCK_ADDR */
49 #define	CM_ARGO	5	/* two integers */
50 #define	CM_ARGV	8	/* \0 separated list of args, NULL-terminated */
51 #define	CM_ARGN	9	/* \0 separated list of args (strings) */
52 
53 /* possible values for cm_todo */
54 #define	CT_CONT		0x0000	/* continue reading commands */
55 #define	CT_IGNO		0x0001	/* continue even when error  */
56 
57 /* not needed right now, done via return code instead */
58 #define	CT_KEEP		0x0004	/* keep buffer (contains symbols) */
59 #define	CT_END		0x0008	/* start replying */
60 
61 /* index in macro array: macros only for these commands */
62 #define	CI_NONE	(-1)
63 #define	CI_CONN	0
64 #define	CI_HELO	1
65 #define	CI_MAIL	2
66 #define	CI_RCPT	3
67 #if CI_RCPT >= MAX_MACROS_ENTRIES
68 ERROR: do not compile with CI_RCPT >= MAX_MACROS_ENTRIES
69 #endif
70 
71 /* function prototypes */
72 static int	st_abortfct __P((genarg *));
73 static int	st_macros __P((genarg *));
74 static int	st_optionneg __P((genarg *));
75 static int	st_bodychunk __P((genarg *));
76 static int	st_connectinfo __P((genarg *));
77 static int	st_bodyend __P((genarg *));
78 static int	st_helo __P((genarg *));
79 static int	st_header __P((genarg *));
80 static int	st_sender __P((genarg *));
81 static int	st_rcpt __P((genarg *));
82 static int	st_eoh __P((genarg *));
83 static int	st_quit __P((genarg *));
84 static int	sendreply __P((sfsistat, socket_t, struct timeval *, SMFICTX_PTR));
85 static void	fix_stm __P((SMFICTX_PTR));
86 static bool	trans_ok __P((int, int));
87 static char	**dec_argv __P((char *, size_t));
88 static int	dec_arg2 __P((char *, size_t, char **, char **));
89 
90 /* states */
91 #define ST_NONE	(-1)
92 #define ST_INIT	0	/* initial state */
93 #define ST_OPTS	1	/* option negotiation */
94 #define ST_CONN	2	/* connection info */
95 #define ST_HELO	3	/* helo */
96 #define ST_MAIL	4	/* mail from */
97 #define ST_RCPT	5	/* rcpt to */
98 #define ST_HDRS	6	/* headers */
99 #define ST_EOHS	7	/* end of headers */
100 #define ST_BODY	8	/* body */
101 #define ST_ENDM	9	/* end of message */
102 #define ST_QUIT	10	/* quit */
103 #define ST_ABRT	11	/* abort */
104 #define ST_LAST	ST_ABRT
105 #define ST_SKIP	15	/* not a state but required for the state table */
106 
107 /* in a mail transaction? must be before eom according to spec. */
108 #define ST_IN_MAIL(st)	((st) >= ST_MAIL && (st) < ST_ENDM)
109 
110 /*
111 **  set of next states
112 **  each state (ST_*) corresponds to bit in an int value (1 << state)
113 **  each state has a set of allowed transitions ('or' of bits of states)
114 **  so a state transition is valid if the mask of the next state
115 **  is set in the NX_* value
116 **  this function is coded in trans_ok(), see below.
117 */
118 
119 #define MASK(x)	(0x0001 << (x))	/* generate a bit "mask" for a state */
120 #define NX_INIT	(MASK(ST_OPTS))
121 #define NX_OPTS	(MASK(ST_CONN))
122 #define NX_CONN	(MASK(ST_HELO) | MASK(ST_MAIL))
123 #define NX_HELO	(MASK(ST_HELO) | MASK(ST_MAIL))
124 #define NX_MAIL	(MASK(ST_RCPT) | MASK(ST_ABRT))
125 #define NX_RCPT	(MASK(ST_HDRS) | MASK(ST_EOHS) | \
126 		 MASK(ST_BODY) | MASK(ST_ENDM) | \
127 		 MASK(ST_RCPT) | MASK(ST_ABRT))
128 #define NX_HDRS	(MASK(ST_EOHS) | MASK(ST_HDRS) | MASK(ST_ABRT))
129 #define NX_EOHS	(MASK(ST_BODY) | MASK(ST_ENDM) | MASK(ST_ABRT))
130 #define NX_BODY	(MASK(ST_ENDM) | MASK(ST_BODY) | MASK(ST_ABRT))
131 #define NX_ENDM	(MASK(ST_QUIT) | MASK(ST_MAIL))
132 #define NX_QUIT	0
133 #define NX_ABRT	0
134 #define NX_SKIP MASK(ST_SKIP)
135 
136 static int next_states[] =
137 {
138 	NX_INIT,
139 	NX_OPTS,
140 	NX_CONN,
141 	NX_HELO,
142 	NX_MAIL,
143 	NX_RCPT,
144 	NX_HDRS,
145 	NX_EOHS,
146 	NX_BODY,
147 	NX_ENDM,
148 	NX_QUIT,
149 	NX_ABRT
150 };
151 
152 /* commands received by milter */
153 static cmdfct cmds[] =
154 {
155 {SMFIC_ABORT,	CM_ARG0, ST_ABRT,  CT_CONT,	CI_NONE, st_abortfct	},
156 {SMFIC_MACRO,	CM_ARGV, ST_NONE,  CT_KEEP,	CI_NONE, st_macros	},
157 {SMFIC_BODY,	CM_ARG1, ST_BODY,  CT_CONT,	CI_NONE, st_bodychunk	},
158 {SMFIC_CONNECT,	CM_ARG2, ST_CONN,  CT_CONT,	CI_CONN, st_connectinfo	},
159 {SMFIC_BODYEOB,	CM_ARG1, ST_ENDM,  CT_CONT,	CI_NONE, st_bodyend	},
160 {SMFIC_HELO,	CM_ARG1, ST_HELO,  CT_CONT,	CI_HELO, st_helo	},
161 {SMFIC_HEADER,	CM_ARG2, ST_HDRS,  CT_CONT,	CI_NONE, st_header	},
162 {SMFIC_MAIL,	CM_ARGV, ST_MAIL,  CT_CONT,	CI_MAIL, st_sender	},
163 {SMFIC_OPTNEG,	CM_ARGO, ST_OPTS,  CT_CONT,	CI_NONE, st_optionneg	},
164 {SMFIC_EOH,	CM_ARG0, ST_EOHS,  CT_CONT,	CI_NONE, st_eoh		},
165 {SMFIC_QUIT,	CM_ARG0, ST_QUIT,  CT_END,	CI_NONE, st_quit	},
166 {SMFIC_RCPT,	CM_ARGV, ST_RCPT,  CT_IGNO,	CI_RCPT, st_rcpt	}
167 };
168 
169 /* additional (internal) reply codes */
170 #define _SMFIS_KEEP	20
171 #define _SMFIS_ABORT	21
172 #define _SMFIS_OPTIONS	22
173 #define _SMFIS_NOREPLY	23
174 #define _SMFIS_FAIL	(-1)
175 #define _SMFIS_NONE	(-2)
176 
177 /*
178 **  MI_ENGINE -- receive commands and process them
179 **
180 **	Parameters:
181 **		ctx -- context structure
182 **
183 **	Returns:
184 **		MI_FAILURE/MI_SUCCESS
185 */
186 int
187 mi_engine(ctx)
188 	SMFICTX_PTR ctx;
189 {
190 	size_t len;
191 	int i;
192 	socket_t sd;
193 	int ret = MI_SUCCESS;
194 	int ncmds = sizeof(cmds) / sizeof(cmdfct);
195 	int curstate = ST_INIT;
196 	int newstate;
197 	bool call_abort;
198 	sfsistat r;
199 	char cmd;
200 	char *buf = NULL;
201 	genarg arg;
202 	struct timeval timeout;
203 	int (*f) __P((genarg *));
204 	sfsistat (*fi_abort) __P((SMFICTX *));
205 	sfsistat (*fi_close) __P((SMFICTX *));
206 
207 	arg.a_ctx = ctx;
208 	sd = ctx->ctx_sd;
209 	fi_abort = ctx->ctx_smfi->xxfi_abort;
210 	mi_clr_macros(ctx, 0);
211 	fix_stm(ctx);
212 	r = _SMFIS_NONE;
213 	do
214 	{
215 		/* call abort only if in a mail transaction */
216 		call_abort = ST_IN_MAIL(curstate);
217 		timeout.tv_sec = ctx->ctx_timeout;
218 		timeout.tv_usec = 0;
219 		if (mi_stop() == MILTER_ABRT)
220 		{
221 			if (ctx->ctx_dbg > 3)
222 				sm_dprintf("[%d] milter_abort\n",
223 					(int) ctx->ctx_id);
224 			ret = MI_FAILURE;
225 			break;
226 		}
227 
228 		/*
229 		**  Notice: buf is allocated by mi_rd_cmd() and it will
230 		**  usually be free()d after it has been used in f().
231 		**  However, if the function returns _SMFIS_KEEP then buf
232 		**  contains macros and will not be free()d.
233 		**  Hence r must be set to _SMFIS_NONE if a new buf is
234 		**  allocated to avoid problem with housekeeping, esp.
235 		**  if the code "break"s out of the loop.
236 		*/
237 
238 		r = _SMFIS_NONE;
239 		if ((buf = mi_rd_cmd(sd, &timeout, &cmd, &len,
240 				     ctx->ctx_smfi->xxfi_name)) == NULL &&
241 		    cmd < SMFIC_VALIDCMD)
242 		{
243 			if (ctx->ctx_dbg > 5)
244 				sm_dprintf("[%d] mi_engine: mi_rd_cmd error (%x)\n",
245 					(int) ctx->ctx_id, (int) cmd);
246 
247 			/*
248 			**  eof is currently treated as failure ->
249 			**  abort() instead of close(), otherwise use:
250 			**  if (cmd != SMFIC_EOF)
251 			*/
252 
253 			ret = MI_FAILURE;
254 			break;
255 		}
256 		if (ctx->ctx_dbg > 4)
257 			sm_dprintf("[%d] got cmd '%c' len %d\n",
258 				(int) ctx->ctx_id, cmd, len);
259 		for (i = 0; i < ncmds; i++)
260 		{
261 			if (cmd == cmds[i].cm_cmd)
262 				break;
263 		}
264 		if (i >= ncmds)
265 		{
266 			/* unknown command */
267 			if (ctx->ctx_dbg > 1)
268 				sm_dprintf("[%d] cmd '%c' unknown\n",
269 					(int) ctx->ctx_id, cmd);
270 			ret = MI_FAILURE;
271 			break;
272 		}
273 		if ((f = cmds[i].cm_fct) == NULL)
274 		{
275 			/* stop for now */
276 			if (ctx->ctx_dbg > 1)
277 				sm_dprintf("[%d] cmd '%c' not impl\n",
278 					(int) ctx->ctx_id, cmd);
279 			ret = MI_FAILURE;
280 			break;
281 		}
282 
283 		/* is new state ok? */
284 		newstate = cmds[i].cm_next;
285 		if (ctx->ctx_dbg > 5)
286 			sm_dprintf("[%d] cur %x new %x nextmask %x\n",
287 				(int) ctx->ctx_id,
288 				curstate, newstate, next_states[curstate]);
289 
290 		if (newstate != ST_NONE && !trans_ok(curstate, newstate))
291 		{
292 			if (ctx->ctx_dbg > 1)
293 				sm_dprintf("[%d] abort: cur %d (%x) new %d (%x) next %x\n",
294 					(int) ctx->ctx_id,
295 					curstate, MASK(curstate),
296 					newstate, MASK(newstate),
297 					next_states[curstate]);
298 
299 			/* call abort only if in a mail transaction */
300 			if (fi_abort != NULL && call_abort)
301 				(void) (*fi_abort)(ctx);
302 
303 			/*
304 			**  try to reach the new state from HELO
305 			**  if it can't be reached, ignore the command.
306 			*/
307 
308 			curstate = ST_HELO;
309 			if (!trans_ok(curstate, newstate))
310 			{
311 				free(buf);
312 				buf = NULL;
313 				continue;
314 			}
315 		}
316 		arg.a_len = len;
317 		arg.a_buf = buf;
318 		if (newstate != ST_NONE)
319 		{
320 			curstate = newstate;
321 			ctx->ctx_state = curstate;
322 		}
323 		arg.a_idx = cmds[i].cm_macros;
324 
325 		/* call function to deal with command */
326 		r = (*f)(&arg);
327 		if (r != _SMFIS_KEEP && buf != NULL)
328 		{
329 			free(buf);
330 			buf = NULL;
331 		}
332 		if (sendreply(r, sd, &timeout, ctx) != MI_SUCCESS)
333 		{
334 			ret = MI_FAILURE;
335 			break;
336 		}
337 
338 		call_abort = ST_IN_MAIL(curstate);
339 		if (r == SMFIS_ACCEPT)
340 		{
341 			/* accept mail, no further actions taken */
342 			curstate = ST_HELO;
343 		}
344 		else if (r == SMFIS_REJECT || r == SMFIS_DISCARD ||
345 			 r ==  SMFIS_TEMPFAIL)
346 		{
347 			/*
348 			**  further actions depend on current state
349 			**  if the IGNO bit is set: "ignore" the error,
350 			**  i.e., stay in the current state
351 			*/
352 			if (!bitset(CT_IGNO, cmds[i].cm_todo))
353 				curstate = ST_HELO;
354 		}
355 		else if (r == _SMFIS_ABORT)
356 		{
357 			if (ctx->ctx_dbg > 5)
358 				sm_dprintf("[%d] function returned abort\n",
359 					(int) ctx->ctx_id);
360 			ret = MI_FAILURE;
361 			break;
362 		}
363 	} while (!bitset(CT_END, cmds[i].cm_todo));
364 
365 	if (ret != MI_SUCCESS)
366 	{
367 		/* call abort only if in a mail transaction */
368 		if (fi_abort != NULL && call_abort)
369 			(void) (*fi_abort)(ctx);
370 	}
371 
372 	/* close must always be called */
373 	if ((fi_close = ctx->ctx_smfi->xxfi_close) != NULL)
374 		(void) (*fi_close)(ctx);
375 	if (r != _SMFIS_KEEP && buf != NULL)
376 		free(buf);
377 	mi_clr_macros(ctx, 0);
378 	return ret;
379 }
380 /*
381 **  SENDREPLY -- send a reply to the MTA
382 **
383 **	Parameters:
384 **		r -- reply code
385 **		sd -- socket descriptor
386 **		timeout_ptr -- (ptr to) timeout to use for sending
387 **		ctx -- context structure
388 **
389 **	Returns:
390 **		MI_SUCCESS/MI_FAILURE
391 */
392 
393 static int
394 sendreply(r, sd, timeout_ptr, ctx)
395 	sfsistat r;
396 	socket_t sd;
397 	struct timeval *timeout_ptr;
398 	SMFICTX_PTR ctx;
399 {
400 	int ret = MI_SUCCESS;
401 
402 	switch (r)
403 	{
404 	  case SMFIS_CONTINUE:
405 		ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_CONTINUE, NULL, 0);
406 		break;
407 	  case SMFIS_TEMPFAIL:
408 	  case SMFIS_REJECT:
409 		if (ctx->ctx_reply != NULL)
410 		{
411 			ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_REPLYCODE,
412 					ctx->ctx_reply,
413 					strlen(ctx->ctx_reply) + 1);
414 			free(ctx->ctx_reply);
415 			ctx->ctx_reply = NULL;
416 		}
417 		else
418 		{
419 			ret = mi_wr_cmd(sd, timeout_ptr, r == SMFIS_REJECT ?
420 					SMFIR_REJECT : SMFIR_TEMPFAIL, NULL, 0);
421 		}
422 		break;
423 	  case SMFIS_DISCARD:
424 		ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_DISCARD, NULL, 0);
425 		break;
426 	  case SMFIS_ACCEPT:
427 		ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_ACCEPT, NULL, 0);
428 		break;
429 	  case _SMFIS_OPTIONS:
430 		{
431 			char buf[MILTER_OPTLEN];
432 			mi_int32 v;
433 
434 			v = htonl(ctx->ctx_smfi->xxfi_version);
435 			(void) memcpy(&(buf[0]), (void *) &v, MILTER_LEN_BYTES);
436 			v = htonl(ctx->ctx_smfi->xxfi_flags);
437 			(void) memcpy(&(buf[MILTER_LEN_BYTES]), (void *) &v,
438 				      MILTER_LEN_BYTES);
439 			v = htonl(ctx->ctx_pflags);
440 			(void) memcpy(&(buf[MILTER_LEN_BYTES * 2]), (void *) &v,
441 				      MILTER_LEN_BYTES);
442 			ret = mi_wr_cmd(sd, timeout_ptr, SMFIC_OPTNEG, buf,
443 				       MILTER_OPTLEN);
444 		}
445 		break;
446 	  default:	/* don't send a reply */
447 		break;
448 	}
449 	return ret;
450 }
451 
452 /*
453 **  CLR_MACROS -- clear set of macros starting from a given index
454 **
455 **	Parameters:
456 **		ctx -- context structure
457 **		m -- index from which to clear all macros
458 **
459 **	Returns:
460 **		None.
461 */
462 void
463 mi_clr_macros(ctx, m)
464 	SMFICTX_PTR ctx;
465 	int m;
466 {
467 	int i;
468 
469 	for (i = m; i < MAX_MACROS_ENTRIES; i++)
470 	{
471 		if (ctx->ctx_mac_ptr[i] != NULL)
472 		{
473 			free(ctx->ctx_mac_ptr[i]);
474 			ctx->ctx_mac_ptr[i] = NULL;
475 		}
476 		if (ctx->ctx_mac_buf[i] != NULL)
477 		{
478 			free(ctx->ctx_mac_buf[i]);
479 			ctx->ctx_mac_buf[i] = NULL;
480 		}
481 	}
482 }
483 /*
484 **  ST_OPTIONNEG -- negotiate options
485 **
486 **	Parameters:
487 **		g -- generic argument structure
488 **
489 **	Returns:
490 **		abort/send options/continue
491 */
492 
493 static int
494 st_optionneg(g)
495 	genarg *g;
496 {
497 	mi_int32 i, v;
498 
499 	if (g == NULL || g->a_ctx->ctx_smfi == NULL)
500 		return SMFIS_CONTINUE;
501 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
502 
503 	/* check for minimum length */
504 	if (g->a_len < MILTER_OPTLEN)
505 	{
506 		smi_log(SMI_LOG_ERR,
507 			"%s: st_optionneg[%d]: len too short %d < %d",
508 			g->a_ctx->ctx_smfi->xxfi_name,
509 			(int) g->a_ctx->ctx_id, g->a_len,
510 			MILTER_OPTLEN);
511 		return _SMFIS_ABORT;
512 	}
513 
514 	(void) memcpy((void *) &i, (void *) &(g->a_buf[0]),
515 		      MILTER_LEN_BYTES);
516 	v = ntohl(i);
517 	if (v < g->a_ctx->ctx_smfi->xxfi_version)
518 	{
519 		/* hard failure for now! */
520 		smi_log(SMI_LOG_ERR,
521 			"%s: st_optionneg[%d]: version mismatch MTA: %d < milter: %d",
522 			g->a_ctx->ctx_smfi->xxfi_name,
523 			(int) g->a_ctx->ctx_id, (int) v,
524 			g->a_ctx->ctx_smfi->xxfi_version);
525 		return _SMFIS_ABORT;
526 	}
527 
528 	(void) memcpy((void *) &i, (void *) &(g->a_buf[MILTER_LEN_BYTES]),
529 		      MILTER_LEN_BYTES);
530 	v = ntohl(i);
531 
532 	/* no flags? set to default value for V1 actions */
533 	if (v == 0)
534 		v = SMFI_V1_ACTS;
535 	i = g->a_ctx->ctx_smfi->xxfi_flags;
536 	if ((v & i) != i)
537 	{
538 		smi_log(SMI_LOG_ERR,
539 			"%s: st_optionneg[%d]: 0x%x does not fulfill action requirements 0x%x",
540 			g->a_ctx->ctx_smfi->xxfi_name,
541 			(int) g->a_ctx->ctx_id, v, i);
542 		return _SMFIS_ABORT;
543 	}
544 
545 	(void) memcpy((void *) &i, (void *) &(g->a_buf[MILTER_LEN_BYTES * 2]),
546 		      MILTER_LEN_BYTES);
547 	v = ntohl(i);
548 
549 	/* no flags? set to default value for V1 protocol */
550 	if (v == 0)
551 		v = SMFI_V1_PROT;
552 	i = g->a_ctx->ctx_pflags;
553 	if ((v & i) != i)
554 	{
555 		smi_log(SMI_LOG_ERR,
556 			"%s: st_optionneg[%d]: 0x%x does not fulfill protocol requirements 0x%x",
557 			g->a_ctx->ctx_smfi->xxfi_name,
558 			(int) g->a_ctx->ctx_id, v, i);
559 		return _SMFIS_ABORT;
560 	}
561 
562 	return _SMFIS_OPTIONS;
563 }
564 /*
565 **  ST_CONNECTINFO -- receive connection information
566 **
567 **	Parameters:
568 **		g -- generic argument structure
569 **
570 **	Returns:
571 **		continue or filter-specified value
572 */
573 
574 static int
575 st_connectinfo(g)
576 	genarg *g;
577 {
578 	size_t l;
579 	size_t i;
580 	char *s, family;
581 	unsigned short port = 0;
582 	_SOCK_ADDR sockaddr;
583 	sfsistat (*fi_connect) __P((SMFICTX *, char *, _SOCK_ADDR *));
584 
585 	if (g == NULL)
586 		return _SMFIS_ABORT;
587 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
588 	if (g->a_ctx->ctx_smfi == NULL ||
589 	    (fi_connect = g->a_ctx->ctx_smfi->xxfi_connect) == NULL)
590 		return SMFIS_CONTINUE;
591 
592 	s = g->a_buf;
593 	i = 0;
594 	l = g->a_len;
595 	while (s[i] != '\0' && i <= l)
596 		++i;
597 	if (i >= l)
598 		return _SMFIS_ABORT;
599 
600 	/* Move past trailing \0 in host string */
601 	i++;
602 	family = s[i++];
603 	memset(&sockaddr, '\0', sizeof sockaddr);
604 	if (family != SMFIA_UNKNOWN)
605 	{
606 		(void) memcpy((void *) &port, (void *) (s + i),
607 			      sizeof port);
608 		port = ntohs(port);
609 		if ((i += sizeof port) >= l)
610 		{
611 			smi_log(SMI_LOG_ERR,
612 				"%s: connect[%d]: wrong len %d >= %d",
613 				g->a_ctx->ctx_smfi->xxfi_name,
614 				(int) g->a_ctx->ctx_id, i, l);
615 			return _SMFIS_ABORT;
616 		}
617 # if NETINET
618 		if (family == SMFIA_INET)
619 		{
620 			if (inet_aton(s + i, (struct in_addr *) &sockaddr.sin.sin_addr)
621 			    == INADDR_NONE)
622 			{
623 				smi_log(SMI_LOG_ERR,
624 					"%s: connect[%d]: inet_aton failed",
625 					g->a_ctx->ctx_smfi->xxfi_name,
626 					(int) g->a_ctx->ctx_id);
627 				return _SMFIS_ABORT;
628 			}
629 			sockaddr.sa.sa_family = AF_INET;
630 			if (port > 0)
631 				sockaddr.sin.sin_port = port;
632 		}
633 		else
634 # endif /* NETINET */
635 # if NETINET6
636 		if (family == SMFIA_INET6)
637 		{
638 			if (mi_inet_pton(AF_INET6, s + i,
639 					 &sockaddr.sin6.sin6_addr) != 1)
640 			{
641 				smi_log(SMI_LOG_ERR,
642 					"%s: connect[%d]: mi_inet_pton failed",
643 					g->a_ctx->ctx_smfi->xxfi_name,
644 					(int) g->a_ctx->ctx_id);
645 				return _SMFIS_ABORT;
646 			}
647 			sockaddr.sa.sa_family = AF_INET6;
648 			if (port > 0)
649 				sockaddr.sin6.sin6_port = port;
650 		}
651 		else
652 # endif /* NETINET6 */
653 # if NETUNIX
654 		if (family == SMFIA_UNIX)
655 		{
656 			if (sm_strlcpy(sockaddr.sunix.sun_path, s + i,
657 			    sizeof sockaddr.sunix.sun_path) >=
658 			    sizeof sockaddr.sunix.sun_path)
659 			{
660 				smi_log(SMI_LOG_ERR,
661 					"%s: connect[%d]: path too long",
662 					g->a_ctx->ctx_smfi->xxfi_name,
663 					(int) g->a_ctx->ctx_id);
664 				return _SMFIS_ABORT;
665 			}
666 			sockaddr.sunix.sun_family = AF_UNIX;
667 		}
668 		else
669 # endif /* NETUNIX */
670 		{
671 			smi_log(SMI_LOG_ERR,
672 				"%s: connect[%d]: unknown family %d",
673 				g->a_ctx->ctx_smfi->xxfi_name,
674 				(int) g->a_ctx->ctx_id, family);
675 			return _SMFIS_ABORT;
676 		}
677 	}
678 	return (*fi_connect)(g->a_ctx, g->a_buf,
679 			     family != SMFIA_UNKNOWN ? &sockaddr : NULL);
680 }
681 /*
682 **  ST_EOH -- end of headers
683 **
684 **	Parameters:
685 **		g -- generic argument structure
686 **
687 **	Returns:
688 **		continue or filter-specified value
689 */
690 
691 static int
692 st_eoh(g)
693 	genarg *g;
694 {
695 	sfsistat (*fi_eoh) __P((SMFICTX *));
696 
697 	if (g == NULL)
698 		return _SMFIS_ABORT;
699 	if (g->a_ctx->ctx_smfi != NULL &&
700 	    (fi_eoh = g->a_ctx->ctx_smfi->xxfi_eoh) != NULL)
701 		return (*fi_eoh)(g->a_ctx);
702 	return SMFIS_CONTINUE;
703 }
704 /*
705 **  ST_HELO -- helo/ehlo command
706 **
707 **	Parameters:
708 **		g -- generic argument structure
709 **
710 **	Returns:
711 **		continue or filter-specified value
712 */
713 static int
714 st_helo(g)
715 	genarg *g;
716 {
717 	sfsistat (*fi_helo) __P((SMFICTX *, char *));
718 
719 	if (g == NULL)
720 		return _SMFIS_ABORT;
721 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
722 	if (g->a_ctx->ctx_smfi != NULL &&
723 	    (fi_helo = g->a_ctx->ctx_smfi->xxfi_helo) != NULL)
724 		return (*fi_helo)(g->a_ctx, g->a_buf);
725 	return SMFIS_CONTINUE;
726 }
727 /*
728 **  ST_HEADER -- header line
729 **
730 **	Parameters:
731 **		g -- generic argument structure
732 **
733 **	Returns:
734 **		continue or filter-specified value
735 */
736 
737 static int
738 st_header(g)
739 	genarg *g;
740 {
741 	char *hf, *hv;
742 	sfsistat (*fi_header) __P((SMFICTX *, char *, char *));
743 
744 	if (g == NULL)
745 		return _SMFIS_ABORT;
746 	if (g->a_ctx->ctx_smfi == NULL ||
747 	    (fi_header = g->a_ctx->ctx_smfi->xxfi_header) == NULL)
748 		return SMFIS_CONTINUE;
749 	if (dec_arg2(g->a_buf, g->a_len, &hf, &hv) == MI_SUCCESS)
750 		return (*fi_header)(g->a_ctx, hf, hv);
751 	else
752 		return _SMFIS_ABORT;
753 }
754 
755 #define ARGV_FCT(lf, rf, idx)					\
756 	char **argv;						\
757 	sfsistat (*lf) __P((SMFICTX *, char **));		\
758 	int r;							\
759 								\
760 	if (g == NULL)						\
761 		return _SMFIS_ABORT;				\
762 	mi_clr_macros(g->a_ctx, g->a_idx + 1);			\
763 	if (g->a_ctx->ctx_smfi == NULL ||			\
764 	    (lf = g->a_ctx->ctx_smfi->rf) == NULL)		\
765 		return SMFIS_CONTINUE;				\
766 	if ((argv = dec_argv(g->a_buf, g->a_len)) == NULL)	\
767 		return _SMFIS_ABORT;				\
768 	r = (*lf)(g->a_ctx, argv);				\
769 	free(argv);						\
770 	return r;
771 
772 /*
773 **  ST_SENDER -- MAIL FROM command
774 **
775 **	Parameters:
776 **		g -- generic argument structure
777 **
778 **	Returns:
779 **		continue or filter-specified value
780 */
781 
782 static int
783 st_sender(g)
784 	genarg *g;
785 {
786 	ARGV_FCT(fi_envfrom, xxfi_envfrom, CI_MAIL)
787 }
788 /*
789 **  ST_RCPT -- RCPT TO command
790 **
791 **	Parameters:
792 **		g -- generic argument structure
793 **
794 **	Returns:
795 **		continue or filter-specified value
796 */
797 
798 static int
799 st_rcpt(g)
800 	genarg *g;
801 {
802 	ARGV_FCT(fi_envrcpt, xxfi_envrcpt, CI_RCPT)
803 }
804 /*
805 **  ST_MACROS -- deal with macros received from the MTA
806 **
807 **	Parameters:
808 **		g -- generic argument structure
809 **
810 **	Returns:
811 **		continue/keep
812 **
813 **	Side effects:
814 **		set pointer in macro array to current values.
815 */
816 
817 static int
818 st_macros(g)
819 	genarg *g;
820 {
821 	int i;
822 	char **argv;
823 
824 	if (g == NULL || g->a_len < 1)
825 		return _SMFIS_FAIL;
826 	if ((argv = dec_argv(g->a_buf + 1, g->a_len - 1)) == NULL)
827 		return _SMFIS_FAIL;
828 	switch (g->a_buf[0])
829 	{
830 	  case SMFIC_CONNECT:
831 		i = CI_CONN;
832 		break;
833 	  case SMFIC_HELO:
834 		i = CI_HELO;
835 		break;
836 	  case SMFIC_MAIL:
837 		i = CI_MAIL;
838 		break;
839 	  case SMFIC_RCPT:
840 		i = CI_RCPT;
841 		break;
842 	  default:
843 		free(argv);
844 		return _SMFIS_FAIL;
845 	}
846 	if (g->a_ctx->ctx_mac_ptr[i] != NULL)
847 		free(g->a_ctx->ctx_mac_ptr[i]);
848 	if (g->a_ctx->ctx_mac_buf[i] != NULL)
849 		free(g->a_ctx->ctx_mac_buf[i]);
850 	g->a_ctx->ctx_mac_ptr[i] = argv;
851 	g->a_ctx->ctx_mac_buf[i] = g->a_buf;
852 	return _SMFIS_KEEP;
853 }
854 /*
855 **  ST_QUIT -- quit command
856 **
857 **	Parameters:
858 **		g -- generic argument structure
859 **
860 **	Returns:
861 **		noreply
862 */
863 
864 static int
865 st_quit(g)
866 	genarg *g;
867 {
868 	return _SMFIS_NOREPLY;
869 }
870 /*
871 **  ST_BODYCHUNK -- deal with a piece of the mail body
872 **
873 **	Parameters:
874 **		g -- generic argument structure
875 **
876 **	Returns:
877 **		continue or filter-specified value
878 */
879 
880 static int
881 st_bodychunk(g)
882 	genarg *g;
883 {
884 	sfsistat (*fi_body) __P((SMFICTX *, unsigned char *, size_t));
885 
886 	if (g == NULL)
887 		return _SMFIS_ABORT;
888 	if (g->a_ctx->ctx_smfi != NULL &&
889 	    (fi_body = g->a_ctx->ctx_smfi->xxfi_body) != NULL)
890 		return (*fi_body)(g->a_ctx, (unsigned char *)g->a_buf,
891 				  g->a_len);
892 	return SMFIS_CONTINUE;
893 }
894 /*
895 **  ST_BODYEND -- deal with the last piece of the mail body
896 **
897 **	Parameters:
898 **		g -- generic argument structure
899 **
900 **	Returns:
901 **		continue or filter-specified value
902 **
903 **	Side effects:
904 **		sends a reply for the body part (if non-empty).
905 */
906 
907 static int
908 st_bodyend(g)
909 	genarg *g;
910 {
911 	sfsistat r;
912 	sfsistat (*fi_body) __P((SMFICTX *, unsigned char *, size_t));
913 	sfsistat (*fi_eom) __P((SMFICTX *));
914 
915 	if (g == NULL)
916 		return _SMFIS_ABORT;
917 	r = SMFIS_CONTINUE;
918 	if (g->a_ctx->ctx_smfi != NULL)
919 	{
920 		if ((fi_body = g->a_ctx->ctx_smfi->xxfi_body) != NULL &&
921 		    g->a_len > 0)
922 		{
923 			socket_t sd;
924 			struct timeval timeout;
925 
926 			timeout.tv_sec = g->a_ctx->ctx_timeout;
927 			timeout.tv_usec = 0;
928 			sd = g->a_ctx->ctx_sd;
929 			r = (*fi_body)(g->a_ctx, (unsigned char *)g->a_buf,
930 				       g->a_len);
931 			if (r != SMFIS_CONTINUE &&
932 			    sendreply(r, sd, &timeout, g->a_ctx) != MI_SUCCESS)
933 				return _SMFIS_ABORT;
934 		}
935 	}
936 	if (r == SMFIS_CONTINUE &&
937 	    (fi_eom = g->a_ctx->ctx_smfi->xxfi_eom) != NULL)
938 		return (*fi_eom)(g->a_ctx);
939 	return r;
940 }
941 /*
942 **  ST_ABORTFCT -- deal with aborts
943 **
944 **	Parameters:
945 **		g -- generic argument structure
946 **
947 **	Returns:
948 **		abort or filter-specified value
949 */
950 
951 static int
952 st_abortfct(g)
953 	genarg *g;
954 {
955 	sfsistat (*fi_abort) __P((SMFICTX *));
956 
957 	if (g == NULL)
958 		return _SMFIS_ABORT;
959 	if (g != NULL && g->a_ctx->ctx_smfi != NULL &&
960 	    (fi_abort = g->a_ctx->ctx_smfi->xxfi_abort) != NULL)
961 		(void) (*fi_abort)(g->a_ctx);
962 	return _SMFIS_NOREPLY;
963 }
964 /*
965 **  TRANS_OK -- is the state transition ok?
966 **
967 **	Parameters:
968 **		old -- old state
969 **		new -- new state
970 **
971 **	Returns:
972 **		state transition ok
973 */
974 
975 static bool
976 trans_ok(old, new)
977 	int old, new;
978 {
979 	int s, n;
980 
981 	s = old;
982 	do
983 	{
984 		/* is this state transition allowed? */
985 		if ((MASK(new) & next_states[s]) != 0)
986 			return true;
987 
988 		/*
989 		**  no: try next state;
990 		**  this works since the relevant states are ordered
991 		**  strict sequentially
992 		*/
993 
994 		n = s + 1;
995 
996 		/*
997 		**  can we actually "skip" this state?
998 		**  see fix_stm() which sets this bit for those
999 		**  states which the filter program is not interested in
1000 		*/
1001 
1002 		if (bitset(NX_SKIP, next_states[n]))
1003 			s = n;
1004 		else
1005 			return false;
1006 	} while (s <= ST_LAST);
1007 	return false;
1008 }
1009 /*
1010 **  FIX_STM -- add "skip" bits to the state transition table
1011 **
1012 **	Parameters:
1013 **		ctx -- context structure
1014 **
1015 **	Returns:
1016 **		None.
1017 **
1018 **	Side effects:
1019 **		may change state transition table.
1020 */
1021 
1022 static void
1023 fix_stm(ctx)
1024 	SMFICTX_PTR ctx;
1025 {
1026 	unsigned long fl;
1027 
1028 	if (ctx == NULL || ctx->ctx_smfi == NULL)
1029 		return;
1030 	fl = ctx->ctx_pflags;
1031 	if (bitset(SMFIP_NOCONNECT, fl))
1032 		next_states[ST_CONN] |= NX_SKIP;
1033 	if (bitset(SMFIP_NOHELO, fl))
1034 		next_states[ST_HELO] |= NX_SKIP;
1035 	if (bitset(SMFIP_NOMAIL, fl))
1036 		next_states[ST_MAIL] |= NX_SKIP;
1037 	if (bitset(SMFIP_NORCPT, fl))
1038 		next_states[ST_RCPT] |= NX_SKIP;
1039 	if (bitset(SMFIP_NOHDRS, fl))
1040 		next_states[ST_HDRS] |= NX_SKIP;
1041 	if (bitset(SMFIP_NOEOH, fl))
1042 		next_states[ST_EOHS] |= NX_SKIP;
1043 	if (bitset(SMFIP_NOBODY, fl))
1044 		next_states[ST_BODY] |= NX_SKIP;
1045 }
1046 /*
1047 **  DEC_ARGV -- split a buffer into a list of strings, NULL terminated
1048 **
1049 **	Parameters:
1050 **		buf -- buffer with several strings
1051 **		len -- length of buffer
1052 **
1053 **	Returns:
1054 **		array of pointers to the individual strings
1055 */
1056 
1057 static char **
1058 dec_argv(buf, len)
1059 	char *buf;
1060 	size_t len;
1061 {
1062 	char **s;
1063 	size_t i;
1064 	int elem, nelem;
1065 
1066 	nelem = 0;
1067 	for (i = 0; i < len; i++)
1068 	{
1069 		if (buf[i] == '\0')
1070 			++nelem;
1071 	}
1072 	if (nelem == 0)
1073 		return NULL;
1074 
1075 	/* last entry is only for the name */
1076 	s = (char **)malloc((nelem + 1) * (sizeof *s));
1077 	if (s == NULL)
1078 		return NULL;
1079 	s[0] = buf;
1080 	for (i = 0, elem = 0; i < len && elem < nelem; i++)
1081 	{
1082 		if (buf[i] == '\0')
1083 			s[++elem] = &(buf[i + 1]);
1084 	}
1085 
1086 	/* overwrite last entry */
1087 	s[elem] = NULL;
1088 	return s;
1089 }
1090 /*
1091 **  DEC_ARG2 -- split a buffer into two strings
1092 **
1093 **	Parameters:
1094 **		buf -- buffer with two strings
1095 **		len -- length of buffer
1096 **		s1,s2 -- pointer to result strings
1097 **
1098 **	Returns:
1099 **		MI_FAILURE/MI_SUCCESS
1100 */
1101 
1102 static int
1103 dec_arg2(buf, len, s1, s2)
1104 	char *buf;
1105 	size_t len;
1106 	char **s1;
1107 	char **s2;
1108 {
1109 	size_t i;
1110 
1111 	*s1 = buf;
1112 	for (i = 1; i < len && buf[i] != '\0'; i++)
1113 		continue;
1114 	if (i >= len - 1)
1115 		return MI_FAILURE;
1116 	*s2 = buf + i + 1;
1117 	return MI_SUCCESS;
1118 }
1119 /*
1120 **  SENDOK -- is it ok for the filter to send stuff to the MTA?
1121 **
1122 **	Parameters:
1123 **		ctx -- context structure
1124 **		flag -- flag to check
1125 **
1126 **	Returns:
1127 **		sending allowed (in current state)
1128 */
1129 
1130 bool
1131 mi_sendok(ctx, flag)
1132 	SMFICTX_PTR ctx;
1133 	int flag;
1134 {
1135 	if (ctx == NULL || ctx->ctx_smfi == NULL)
1136 		return false;
1137 
1138 	/* did the milter request this operation? */
1139 	if (flag != 0 && !bitset(flag, ctx->ctx_smfi->xxfi_flags))
1140 		return false;
1141 
1142 	/* are we in the correct state? It must be "End of Message". */
1143 	return ctx->ctx_state == ST_ENDM;
1144 }
1145