xref: /freebsd/contrib/sendmail/libmilter/engine.c (revision a96ef4501919d7ac08e94e98dc34b0bdd744802b)
1 /*
2  *  Copyright (c) 1999-2004, 2006-2008 Proofpoint, Inc. and its suppliers.
3  *	All rights reserved.
4  *
5  * By using this file, you agree to the terms and conditions set
6  * forth in the LICENSE file which can be found at the top level of
7  * the sendmail distribution.
8  *
9  */
10 
11 #include <sm/gen.h>
12 SM_RCSID("@(#)$Id: engine.c,v 8.168 2013-11-22 20:51:36 ca Exp $")
13 
14 #include "libmilter.h"
15 
16 #if NETINET || NETINET6
17 # include <arpa/inet.h>
18 #endif
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_BUF	0
46 #define	CM_NULLOK 1
47 
48 /* possible values for cm_todo */
49 #define	CT_CONT		0x0000	/* continue reading commands */
50 #define	CT_IGNO		0x0001	/* continue even when error  */
51 
52 /* not needed right now, done via return code instead */
53 #define	CT_KEEP		0x0004	/* keep buffer (contains symbols) */
54 #define	CT_END		0x0008	/* last command of session, stop replying */
55 
56 /* index in macro array: macros only for these commands */
57 #define	CI_NONE		(-1)
58 #define	CI_CONN		0
59 #define	CI_HELO		1
60 #define	CI_MAIL		2
61 #define CI_RCPT		3
62 #define CI_DATA		4
63 #define CI_EOM		5
64 #define CI_EOH		6
65 #define CI_LAST		CI_EOH
66 #if CI_LAST < CI_DATA
67 ERROR: do not compile with CI_LAST < CI_DATA
68 #endif
69 #if CI_LAST < CI_EOM
70 ERROR: do not compile with CI_LAST < CI_EOM
71 #endif
72 #if CI_LAST < CI_EOH
73 ERROR: do not compile with CI_LAST < CI_EOH
74 #endif
75 #if CI_LAST < CI_RCPT
76 ERROR: do not compile with CI_LAST < CI_RCPT
77 #endif
78 #if CI_LAST < CI_MAIL
79 ERROR: do not compile with CI_LAST < CI_MAIL
80 #endif
81 #if CI_LAST < CI_HELO
82 ERROR: do not compile with CI_LAST < CI_HELO
83 #endif
84 #if CI_LAST < CI_CONN
85 ERROR: do not compile with CI_LAST < CI_CONN
86 #endif
87 #if CI_LAST >= MAX_MACROS_ENTRIES
88 ERROR: do not compile with CI_LAST >= MAX_MACROS_ENTRIES
89 #endif
90 
91 /* function prototypes */
92 static int	st_abortfct __P((genarg *));
93 static int	st_macros __P((genarg *));
94 static int	st_optionneg __P((genarg *));
95 static int	st_bodychunk __P((genarg *));
96 static int	st_connectinfo __P((genarg *));
97 static int	st_bodyend __P((genarg *));
98 static int	st_helo __P((genarg *));
99 static int	st_header __P((genarg *));
100 static int	st_sender __P((genarg *));
101 static int	st_rcpt __P((genarg *));
102 static int	st_unknown __P((genarg *));
103 static int	st_data __P((genarg *));
104 static int	st_eoh __P((genarg *));
105 static int	st_quit __P((genarg *));
106 static int	sendreply __P((sfsistat, socket_t, struct timeval *, SMFICTX_PTR));
107 static void	fix_stm __P((SMFICTX_PTR));
108 static bool	trans_ok __P((int, int));
109 static char	**dec_argv __P((char *, size_t));
110 static int	dec_arg2 __P((char *, size_t, char **, char **));
111 static void	mi_clr_symlist __P((SMFICTX_PTR));
112 
113 #if _FFR_WORKERS_POOL
114 static bool     mi_rd_socket_ready __P((int));
115 #endif
116 
117 /* states */
118 #define ST_NONE	(-1)
119 #define ST_INIT	0	/* initial state */
120 #define ST_OPTS	1	/* option negotiation */
121 #define ST_CONN	2	/* connection info */
122 #define ST_HELO	3	/* helo */
123 #define ST_MAIL	4	/* mail from */
124 #define ST_RCPT	5	/* rcpt to */
125 #define ST_DATA	6	/* data */
126 #define ST_HDRS	7	/* headers */
127 #define ST_EOHS	8	/* end of headers */
128 #define ST_BODY	9	/* body */
129 #define ST_ENDM	10	/* end of message */
130 #define ST_QUIT	11	/* quit */
131 #define ST_ABRT	12	/* abort */
132 #define ST_UNKN 13	/* unknown SMTP command */
133 #define ST_Q_NC	14	/* quit, new connection follows */
134 #define ST_LAST	ST_Q_NC	/* last valid state */
135 #define ST_SKIP	16	/* not a state but required for the state table */
136 
137 /* in a mail transaction? must be before eom according to spec. */
138 #define ST_IN_MAIL(st)	((st) >= ST_MAIL && (st) < ST_ENDM)
139 
140 /*
141 **  set of next states
142 **  each state (ST_*) corresponds to bit in an int value (1 << state)
143 **  each state has a set of allowed transitions ('or' of bits of states)
144 **  so a state transition is valid if the mask of the next state
145 **  is set in the NX_* value
146 **  this function is coded in trans_ok(), see below.
147 */
148 
149 #define MI_MASK(x)	(0x0001 << (x))	/* generate a bit "mask" for a state */
150 #define NX_INIT	(MI_MASK(ST_OPTS))
151 #define NX_OPTS	(MI_MASK(ST_CONN) | MI_MASK(ST_UNKN))
152 #define NX_CONN	(MI_MASK(ST_HELO) | MI_MASK(ST_MAIL) | MI_MASK(ST_UNKN))
153 #define NX_HELO	(MI_MASK(ST_HELO) | MI_MASK(ST_MAIL) | MI_MASK(ST_UNKN))
154 #define NX_MAIL	(MI_MASK(ST_RCPT) | MI_MASK(ST_ABRT) | MI_MASK(ST_UNKN))
155 #define NX_RCPT	(MI_MASK(ST_HDRS) | MI_MASK(ST_EOHS) | MI_MASK(ST_DATA) | \
156 		 MI_MASK(ST_BODY) | MI_MASK(ST_ENDM) | \
157 		 MI_MASK(ST_RCPT) | MI_MASK(ST_ABRT) | MI_MASK(ST_UNKN))
158 #define NX_DATA	(MI_MASK(ST_EOHS) | MI_MASK(ST_HDRS) | MI_MASK(ST_ABRT))
159 #define NX_HDRS	(MI_MASK(ST_EOHS) | MI_MASK(ST_HDRS) | MI_MASK(ST_ABRT))
160 #define NX_EOHS	(MI_MASK(ST_BODY) | MI_MASK(ST_ENDM) | MI_MASK(ST_ABRT))
161 #define NX_BODY	(MI_MASK(ST_ENDM) | MI_MASK(ST_BODY) | MI_MASK(ST_ABRT))
162 #define NX_ENDM	(MI_MASK(ST_QUIT) | MI_MASK(ST_MAIL) | MI_MASK(ST_UNKN) | \
163 		MI_MASK(ST_Q_NC))
164 #define NX_QUIT	0
165 #define NX_ABRT	0
166 #define NX_UNKN (MI_MASK(ST_HELO) | MI_MASK(ST_MAIL) | \
167 		 MI_MASK(ST_RCPT) | MI_MASK(ST_ABRT) | \
168 		 MI_MASK(ST_DATA) | \
169 		 MI_MASK(ST_BODY) | MI_MASK(ST_UNKN) | \
170 		 MI_MASK(ST_ABRT) | MI_MASK(ST_QUIT) | MI_MASK(ST_Q_NC))
171 #define NX_Q_NC	(MI_MASK(ST_CONN) | MI_MASK(ST_UNKN))
172 #define NX_SKIP MI_MASK(ST_SKIP)
173 
174 static int next_states[] =
175 {
176 	  NX_INIT
177 	, NX_OPTS
178 	, NX_CONN
179 	, NX_HELO
180 	, NX_MAIL
181 	, NX_RCPT
182 	, NX_DATA
183 	, NX_HDRS
184 	, NX_EOHS
185 	, NX_BODY
186 	, NX_ENDM
187 	, NX_QUIT
188 	, NX_ABRT
189 	, NX_UNKN
190 	, NX_Q_NC
191 };
192 
193 #define SIZE_NEXT_STATES	(sizeof(next_states) / sizeof(next_states[0]))
194 
195 /* commands received by milter */
196 static cmdfct cmds[] =
197 {
198   {SMFIC_ABORT,		CM_NULLOK,	ST_ABRT,  CT_CONT,  CI_NONE, st_abortfct}
199 , {SMFIC_MACRO,		CM_BUF,		ST_NONE,  CT_KEEP,  CI_NONE, st_macros	}
200 , {SMFIC_BODY,		CM_BUF,		ST_BODY,  CT_CONT,  CI_NONE, st_bodychunk}
201 , {SMFIC_CONNECT,	CM_BUF,		ST_CONN,  CT_CONT,  CI_CONN, st_connectinfo}
202 , {SMFIC_BODYEOB,	CM_NULLOK,	ST_ENDM,  CT_CONT,  CI_EOM,  st_bodyend	}
203 , {SMFIC_HELO,		CM_BUF,		ST_HELO,  CT_CONT,  CI_HELO, st_helo	}
204 , {SMFIC_HEADER,	CM_BUF,		ST_HDRS,  CT_CONT,  CI_NONE, st_header	}
205 , {SMFIC_MAIL,		CM_BUF,		ST_MAIL,  CT_CONT,  CI_MAIL, st_sender	}
206 , {SMFIC_OPTNEG,	CM_BUF,		ST_OPTS,  CT_CONT,  CI_NONE, st_optionneg}
207 , {SMFIC_EOH,		CM_NULLOK,	ST_EOHS,  CT_CONT,  CI_EOH,  st_eoh	}
208 , {SMFIC_QUIT,		CM_NULLOK,	ST_QUIT,  CT_END,   CI_NONE, st_quit	}
209 , {SMFIC_DATA,		CM_NULLOK,	ST_DATA,  CT_CONT,  CI_DATA, st_data	}
210 , {SMFIC_RCPT,		CM_BUF,		ST_RCPT,  CT_IGNO,  CI_RCPT, st_rcpt	}
211 , {SMFIC_UNKNOWN,	CM_BUF,		ST_UNKN,  CT_IGNO,  CI_NONE, st_unknown	}
212 , {SMFIC_QUIT_NC,	CM_NULLOK,	ST_Q_NC,  CT_CONT,  CI_NONE, st_quit	}
213 };
214 
215 /*
216 **  Additional (internal) reply codes;
217 **  must be coordinated wit libmilter/mfapi.h
218 */
219 
220 #define _SMFIS_KEEP	20
221 #define _SMFIS_ABORT	21
222 #define _SMFIS_OPTIONS	22
223 #define _SMFIS_NOREPLY	SMFIS_NOREPLY
224 #define _SMFIS_FAIL	(-1)
225 #define _SMFIS_NONE	(-2)
226 
227 /*
228 **  MI_ENGINE -- receive commands and process them
229 **
230 **	Parameters:
231 **		ctx -- context structure
232 **
233 **	Returns:
234 **		MI_FAILURE/MI_SUCCESS
235 */
236 
237 int
238 mi_engine(ctx)
239 	SMFICTX_PTR ctx;
240 {
241 	size_t len;
242 	int i;
243 	socket_t sd;
244 	int ret = MI_SUCCESS;
245 	int ncmds = sizeof(cmds) / sizeof(cmdfct);
246 	int curstate = ST_INIT;
247 	int newstate;
248 	bool call_abort;
249 	sfsistat r;
250 	char cmd;
251 	char *buf = NULL;
252 	genarg arg;
253 	struct timeval timeout;
254 	int (*f) __P((genarg *));
255 	sfsistat (*fi_abort) __P((SMFICTX *));
256 	sfsistat (*fi_close) __P((SMFICTX *));
257 
258 	arg.a_ctx = ctx;
259 	sd = ctx->ctx_sd;
260 	fi_abort = ctx->ctx_smfi->xxfi_abort;
261 #if _FFR_WORKERS_POOL
262 	curstate = ctx->ctx_state;
263 	if (curstate == ST_INIT)
264 	{
265 		mi_clr_macros(ctx, 0);
266 		fix_stm(ctx);
267 	}
268 #else   /* _FFR_WORKERS_POOL */
269 	mi_clr_macros(ctx, 0);
270 	fix_stm(ctx);
271 #endif  /* _FFR_WORKERS_POOL */
272 	r = _SMFIS_NONE;
273 	do
274 	{
275 		/* call abort only if in a mail transaction */
276 		call_abort = ST_IN_MAIL(curstate);
277 		timeout.tv_sec = ctx->ctx_timeout;
278 		timeout.tv_usec = 0;
279 		if (mi_stop() == MILTER_ABRT)
280 		{
281 			if (ctx->ctx_dbg > 3)
282 				sm_dprintf("[%lu] milter_abort\n",
283 					(long) ctx->ctx_id);
284 			ret = MI_FAILURE;
285 			break;
286 		}
287 
288 		/*
289 		**  Notice: buf is allocated by mi_rd_cmd() and it will
290 		**  usually be free()d after it has been used in f().
291 		**  However, if the function returns _SMFIS_KEEP then buf
292 		**  contains macros and will not be free()d.
293 		**  Hence r must be set to _SMFIS_NONE if a new buf is
294 		**  allocated to avoid problem with housekeeping, esp.
295 		**  if the code "break"s out of the loop.
296 		*/
297 
298 #if _FFR_WORKERS_POOL
299 		/* Is the socket ready to be read ??? */
300 		if (!mi_rd_socket_ready(sd))
301 		{
302 			ret = MI_CONTINUE;
303 			break;
304 		}
305 #endif  /* _FFR_WORKERS_POOL */
306 
307 		r = _SMFIS_NONE;
308 		if ((buf = mi_rd_cmd(sd, &timeout, &cmd, &len,
309 				     ctx->ctx_smfi->xxfi_name)) == NULL &&
310 		    cmd < SMFIC_VALIDCMD)
311 		{
312 			if (ctx->ctx_dbg > 5)
313 				sm_dprintf("[%lu] mi_engine: mi_rd_cmd error (%x)\n",
314 					(long) ctx->ctx_id, (int) cmd);
315 
316 			/*
317 			**  eof is currently treated as failure ->
318 			**  abort() instead of close(), otherwise use:
319 			**  if (cmd != SMFIC_EOF)
320 			*/
321 
322 			ret = MI_FAILURE;
323 			break;
324 		}
325 		if (ctx->ctx_dbg > 4)
326 			sm_dprintf("[%lu] got cmd '%c' len %d\n",
327 				(long) ctx->ctx_id, cmd, (int) len);
328 		for (i = 0; i < ncmds; i++)
329 		{
330 			if (cmd == cmds[i].cm_cmd)
331 				break;
332 		}
333 		if (i >= ncmds)
334 		{
335 			/* unknown command */
336 			if (ctx->ctx_dbg > 1)
337 				sm_dprintf("[%lu] cmd '%c' unknown\n",
338 					(long) ctx->ctx_id, cmd);
339 			ret = MI_FAILURE;
340 			break;
341 		}
342 		if ((f = cmds[i].cm_fct) == NULL)
343 		{
344 			/* stop for now */
345 			if (ctx->ctx_dbg > 1)
346 				sm_dprintf("[%lu] cmd '%c' not impl\n",
347 					(long) ctx->ctx_id, cmd);
348 			ret = MI_FAILURE;
349 			break;
350 		}
351 
352 		/* is new state ok? */
353 		newstate = cmds[i].cm_next;
354 		if (ctx->ctx_dbg > 5)
355 			sm_dprintf("[%lu] cur %x new %x nextmask %x\n",
356 				(long) ctx->ctx_id,
357 				curstate, newstate, next_states[curstate]);
358 
359 		if (newstate != ST_NONE && !trans_ok(curstate, newstate))
360 		{
361 			if (ctx->ctx_dbg > 1)
362 				sm_dprintf("[%lu] abort: cur %d (%x) new %d (%x) next %x\n",
363 					(long) ctx->ctx_id,
364 					curstate, MI_MASK(curstate),
365 					newstate, MI_MASK(newstate),
366 					next_states[curstate]);
367 
368 			/* call abort only if in a mail transaction */
369 			if (fi_abort != NULL && call_abort)
370 				(void) (*fi_abort)(ctx);
371 
372 			/*
373 			**  try to reach the new state from HELO
374 			**  if it can't be reached, ignore the command.
375 			*/
376 
377 			curstate = ST_HELO;
378 			if (!trans_ok(curstate, newstate))
379 			{
380 				if (buf != NULL)
381 				{
382 					free(buf);
383 					buf = NULL;
384 				}
385 				continue;
386 			}
387 		}
388 		if (cmds[i].cm_argt != CM_NULLOK && buf == NULL)
389 		{
390 			/* stop for now */
391 			if (ctx->ctx_dbg > 1)
392 				sm_dprintf("[%lu] cmd='%c', buf=NULL\n",
393 					(long) ctx->ctx_id, cmd);
394 			ret = MI_FAILURE;
395 			break;
396 		}
397 		arg.a_len = len;
398 		arg.a_buf = buf;
399 		if (newstate != ST_NONE)
400 		{
401 			curstate = newstate;
402 			ctx->ctx_state = curstate;
403 		}
404 		arg.a_idx = cmds[i].cm_macros;
405 		call_abort = ST_IN_MAIL(curstate);
406 
407 		/* call function to deal with command */
408 		MI_MONITOR_BEGIN(ctx, cmd);
409 		r = (*f)(&arg);
410 		MI_MONITOR_END(ctx, cmd);
411 		if (r != _SMFIS_KEEP && buf != NULL)
412 		{
413 			free(buf);
414 			buf = NULL;
415 		}
416 		if (sendreply(r, sd, &timeout, ctx) != MI_SUCCESS)
417 		{
418 			ret = MI_FAILURE;
419 			break;
420 		}
421 
422 		if (r == SMFIS_ACCEPT)
423 		{
424 			/* accept mail, no further actions taken */
425 			curstate = ST_HELO;
426 		}
427 		else if (r == SMFIS_REJECT || r == SMFIS_DISCARD ||
428 			 r ==  SMFIS_TEMPFAIL)
429 		{
430 			/*
431 			**  further actions depend on current state
432 			**  if the IGNO bit is set: "ignore" the error,
433 			**  i.e., stay in the current state
434 			*/
435 			if (!bitset(CT_IGNO, cmds[i].cm_todo))
436 				curstate = ST_HELO;
437 		}
438 		else if (r == _SMFIS_ABORT)
439 		{
440 			if (ctx->ctx_dbg > 5)
441 				sm_dprintf("[%lu] function returned abort\n",
442 					(long) ctx->ctx_id);
443 			ret = MI_FAILURE;
444 			break;
445 		}
446 	} while (!bitset(CT_END, cmds[i].cm_todo));
447 
448 	ctx->ctx_state = curstate;
449 
450 	if (ret == MI_FAILURE)
451 	{
452 		/* call abort only if in a mail transaction */
453 		if (fi_abort != NULL && call_abort)
454 			(void) (*fi_abort)(ctx);
455 	}
456 
457 	/* has close been called? */
458 	if (ctx->ctx_state != ST_QUIT
459 #if _FFR_WORKERS_POOL
460 	   && ret != MI_CONTINUE
461 #endif
462 	   )
463 	{
464 		if ((fi_close = ctx->ctx_smfi->xxfi_close) != NULL)
465 			(void) (*fi_close)(ctx);
466 	}
467 	if (r != _SMFIS_KEEP && buf != NULL)
468 		free(buf);
469 #if !_FFR_WORKERS_POOL
470 	mi_clr_macros(ctx, 0);
471 #endif
472 	return ret;
473 }
474 
475 static size_t milter_addsymlist __P((SMFICTX_PTR, char *, char **));
476 
477 static size_t
478 milter_addsymlist(ctx, buf, newbuf)
479 	SMFICTX_PTR ctx;
480 	char *buf;
481 	char **newbuf;
482 {
483 	size_t len;
484 	int i;
485 	mi_int32 v;
486 	char *buffer;
487 
488 	SM_ASSERT(ctx != NULL);
489 	SM_ASSERT(buf != NULL);
490 	SM_ASSERT(newbuf != NULL);
491 	len = 0;
492 	for (i = 0; i < MAX_MACROS_ENTRIES; i++)
493 	{
494 		if (ctx->ctx_mac_list[i] != NULL)
495 		{
496 			len += strlen(ctx->ctx_mac_list[i]) + 1 +
497 				MILTER_LEN_BYTES;
498 		}
499 	}
500 	if (len > 0)
501 	{
502 		size_t offset;
503 
504 		SM_ASSERT(len + MILTER_OPTLEN > len);
505 		len += MILTER_OPTLEN;
506 		buffer = malloc(len);
507 		if (buffer != NULL)
508 		{
509 			(void) memcpy(buffer, buf, MILTER_OPTLEN);
510 			offset = MILTER_OPTLEN;
511 			for (i = 0; i < MAX_MACROS_ENTRIES; i++)
512 			{
513 				size_t l;
514 
515 				if (ctx->ctx_mac_list[i] == NULL)
516 					continue;
517 
518 				SM_ASSERT(offset + MILTER_LEN_BYTES < len);
519 				v = htonl(i);
520 				(void) memcpy(buffer + offset, (void *) &v,
521 						MILTER_LEN_BYTES);
522 				offset += MILTER_LEN_BYTES;
523 				l = strlen(ctx->ctx_mac_list[i]) + 1;
524 				SM_ASSERT(offset + l <= len);
525 				(void) memcpy(buffer + offset,
526 						ctx->ctx_mac_list[i], l);
527 				offset += l;
528 			}
529 		}
530 		else
531 		{
532 			/* oops ... */
533 		}
534 	}
535 	else
536 	{
537 		len = MILTER_OPTLEN;
538 		buffer = buf;
539 	}
540 	*newbuf = buffer;
541 	return len;
542 }
543 
544 /*
545 **  GET_NR_BIT -- get "no reply" bit matching state
546 **
547 **	Parameters:
548 **		state -- current protocol stage
549 **
550 **	Returns:
551 **		0: no matching bit
552 **		>0: the matching "no reply" bit
553 */
554 
555 static unsigned long get_nr_bit __P((int));
556 
557 static unsigned long
558 get_nr_bit(state)
559 	int state;
560 {
561 	unsigned long bit;
562 
563 	switch (state)
564 	{
565 	  case ST_CONN:
566 		bit = SMFIP_NR_CONN;
567 		break;
568 	  case ST_HELO:
569 		bit = SMFIP_NR_HELO;
570 		break;
571 	  case ST_MAIL:
572 		bit = SMFIP_NR_MAIL;
573 		break;
574 	  case ST_RCPT:
575 		bit = SMFIP_NR_RCPT;
576 		break;
577 	  case ST_DATA:
578 		bit = SMFIP_NR_DATA;
579 		break;
580 	  case ST_UNKN:
581 		bit = SMFIP_NR_UNKN;
582 		break;
583 	  case ST_HDRS:
584 		bit = SMFIP_NR_HDR;
585 		break;
586 	  case ST_EOHS:
587 		bit = SMFIP_NR_EOH;
588 		break;
589 	  case ST_BODY:
590 		bit = SMFIP_NR_BODY;
591 		break;
592 	  default:
593 		bit = 0;
594 		break;
595 	}
596 	return bit;
597 }
598 
599 /*
600 **  SENDREPLY -- send a reply to the MTA
601 **
602 **	Parameters:
603 **		r -- reply code
604 **		sd -- socket descriptor
605 **		timeout_ptr -- (ptr to) timeout to use for sending
606 **		ctx -- context structure
607 **
608 **	Returns:
609 **		MI_SUCCESS/MI_FAILURE
610 */
611 
612 static int
613 sendreply(r, sd, timeout_ptr, ctx)
614 	sfsistat r;
615 	socket_t sd;
616 	struct timeval *timeout_ptr;
617 	SMFICTX_PTR ctx;
618 {
619 	int ret;
620 	unsigned long bit;
621 
622 	ret = MI_SUCCESS;
623 
624 	bit = get_nr_bit(ctx->ctx_state);
625 	if (bit != 0 && (ctx->ctx_pflags & bit) != 0 && r != SMFIS_NOREPLY)
626 	{
627 		if (r >= SMFIS_CONTINUE && r < _SMFIS_KEEP)
628 		{
629 			/* milter said it wouldn't reply, but it lied... */
630 			smi_log(SMI_LOG_ERR,
631 				"%s: milter claimed not to reply in state %d but did anyway %d",
632 				ctx->ctx_smfi->xxfi_name,
633 				ctx->ctx_state, r);
634 
635 		}
636 
637 		/*
638 		**  Force specified behavior, otherwise libmilter
639 		**  and MTA will fail to communicate properly.
640 		*/
641 
642 		switch (r)
643 		{
644 		  case SMFIS_CONTINUE:
645 		  case SMFIS_TEMPFAIL:
646 		  case SMFIS_REJECT:
647 		  case SMFIS_DISCARD:
648 		  case SMFIS_ACCEPT:
649 		  case SMFIS_SKIP:
650 		  case _SMFIS_OPTIONS:
651 			r = SMFIS_NOREPLY;
652 			break;
653 		}
654 	}
655 
656 	switch (r)
657 	{
658 	  case SMFIS_CONTINUE:
659 		ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_CONTINUE, NULL, 0);
660 		break;
661 	  case SMFIS_TEMPFAIL:
662 	  case SMFIS_REJECT:
663 		if (ctx->ctx_reply != NULL &&
664 		    ((r == SMFIS_TEMPFAIL && *ctx->ctx_reply == '4') ||
665 		     (r == SMFIS_REJECT && *ctx->ctx_reply == '5')))
666 		{
667 			ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_REPLYCODE,
668 					ctx->ctx_reply,
669 					strlen(ctx->ctx_reply) + 1);
670 			free(ctx->ctx_reply);
671 			ctx->ctx_reply = NULL;
672 		}
673 		else
674 		{
675 			ret = mi_wr_cmd(sd, timeout_ptr, r == SMFIS_REJECT ?
676 					SMFIR_REJECT : SMFIR_TEMPFAIL, NULL, 0);
677 		}
678 		break;
679 	  case SMFIS_DISCARD:
680 		ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_DISCARD, NULL, 0);
681 		break;
682 	  case SMFIS_ACCEPT:
683 		ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_ACCEPT, NULL, 0);
684 		break;
685 	  case SMFIS_SKIP:
686 		ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_SKIP, NULL, 0);
687 		break;
688 	  case _SMFIS_OPTIONS:
689 		{
690 			mi_int32 v;
691 			size_t len;
692 			char *buffer;
693 			char buf[MILTER_OPTLEN];
694 
695 			v = htonl(ctx->ctx_prot_vers2mta);
696 			(void) memcpy(&(buf[0]), (void *) &v,
697 				      MILTER_LEN_BYTES);
698 			v = htonl(ctx->ctx_aflags);
699 			(void) memcpy(&(buf[MILTER_LEN_BYTES]), (void *) &v,
700 				      MILTER_LEN_BYTES);
701 			v = htonl(ctx->ctx_pflags2mta);
702 			(void) memcpy(&(buf[MILTER_LEN_BYTES * 2]),
703 				      (void *) &v, MILTER_LEN_BYTES);
704 			len = milter_addsymlist(ctx, buf, &buffer);
705 			if (buffer != NULL)
706 			{
707 				ret = mi_wr_cmd(sd, timeout_ptr, SMFIC_OPTNEG,
708 						buffer, len);
709 				if (buffer != buf)
710 					free(buffer);
711 			}
712 			else
713 				ret = MI_FAILURE;
714 		}
715 		break;
716 	  case SMFIS_NOREPLY:
717 		if (bit != 0 &&
718 		    (ctx->ctx_pflags & bit) != 0 &&
719 		    (ctx->ctx_mta_pflags & bit) == 0)
720 		{
721 			/*
722 			**  milter doesn't want to send a reply,
723 			**  but the MTA doesn't have that feature: fake it.
724 			*/
725 
726 			ret = mi_wr_cmd(sd, timeout_ptr, SMFIR_CONTINUE, NULL,
727 					0);
728 		}
729 		break;
730 	  default:	/* don't send a reply */
731 		break;
732 	}
733 	return ret;
734 }
735 
736 /*
737 **  MI_CLR_MACROS -- clear set of macros starting from a given index
738 **
739 **	Parameters:
740 **		ctx -- context structure
741 **		m -- index from which to clear all macros
742 **
743 **	Returns:
744 **		None.
745 */
746 
747 void
748 mi_clr_macros(ctx, m)
749 	SMFICTX_PTR ctx;
750 	int m;
751 {
752 	int i;
753 
754 	for (i = m; i < MAX_MACROS_ENTRIES; i++)
755 	{
756 		if (ctx->ctx_mac_ptr[i] != NULL)
757 		{
758 			free(ctx->ctx_mac_ptr[i]);
759 			ctx->ctx_mac_ptr[i] = NULL;
760 		}
761 		if (ctx->ctx_mac_buf[i] != NULL)
762 		{
763 			free(ctx->ctx_mac_buf[i]);
764 			ctx->ctx_mac_buf[i] = NULL;
765 		}
766 	}
767 }
768 
769 /*
770 **  MI_CLR_SYMLIST -- clear list of macros
771 **
772 **	Parameters:
773 **		ctx -- context structure
774 **
775 **	Returns:
776 **		None.
777 */
778 
779 static void
780 mi_clr_symlist(ctx)
781 	SMFICTX *ctx;
782 {
783 	int i;
784 
785 	SM_ASSERT(ctx != NULL);
786 	for (i = SMFIM_FIRST; i <= SMFIM_LAST; i++)
787 	{
788 		if (ctx->ctx_mac_list[i] != NULL)
789 		{
790 			free(ctx->ctx_mac_list[i]);
791 			ctx->ctx_mac_list[i] = NULL;
792 		}
793 	}
794 }
795 
796 /*
797 **  MI_CLR_CTX -- clear context
798 **
799 **	Parameters:
800 **		ctx -- context structure
801 **
802 **	Returns:
803 **		None.
804 */
805 
806 void
807 mi_clr_ctx(ctx)
808 	SMFICTX *ctx;
809 {
810 	SM_ASSERT(ctx != NULL);
811 	if (ValidSocket(ctx->ctx_sd))
812 	{
813 		(void) closesocket(ctx->ctx_sd);
814 		ctx->ctx_sd = INVALID_SOCKET;
815 	}
816 	if (ctx->ctx_reply != NULL)
817 	{
818 		free(ctx->ctx_reply);
819 		ctx->ctx_reply = NULL;
820 	}
821 	if (ctx->ctx_privdata != NULL)
822 	{
823 		smi_log(SMI_LOG_WARN,
824 			"%s: private data not NULL",
825 			ctx->ctx_smfi->xxfi_name);
826 	}
827 	mi_clr_macros(ctx, 0);
828 	mi_clr_symlist(ctx);
829 	free(ctx);
830 }
831 
832 /*
833 **  ST_OPTIONNEG -- negotiate options
834 **
835 **	Parameters:
836 **		g -- generic argument structure
837 **
838 **	Returns:
839 **		abort/send options/continue
840 */
841 
842 static int
843 st_optionneg(g)
844 	genarg *g;
845 {
846 	mi_int32 i, v, fake_pflags, internal_pflags;
847 	SMFICTX_PTR ctx;
848 #if _FFR_MILTER_CHECK
849 	bool testmode = false;
850 #endif
851 	int (*fi_negotiate) __P((SMFICTX *,
852 					unsigned long, unsigned long,
853 					unsigned long, unsigned long,
854 					unsigned long *, unsigned long *,
855 					unsigned long *, unsigned long *));
856 
857 	if (g == NULL || g->a_ctx->ctx_smfi == NULL)
858 		return SMFIS_CONTINUE;
859 	ctx = g->a_ctx;
860 	mi_clr_macros(ctx, g->a_idx + 1);
861 	ctx->ctx_prot_vers = SMFI_PROT_VERSION;
862 
863 	/* check for minimum length */
864 	if (g->a_len < MILTER_OPTLEN)
865 	{
866 		smi_log(SMI_LOG_ERR,
867 			"%s: st_optionneg[%ld]: len too short %d < %d",
868 			ctx->ctx_smfi->xxfi_name,
869 			(long) ctx->ctx_id, (int) g->a_len,
870 			MILTER_OPTLEN);
871 		return _SMFIS_ABORT;
872 	}
873 
874 	/* protocol version */
875 	(void) memcpy((void *) &i, (void *) &(g->a_buf[0]), MILTER_LEN_BYTES);
876 	v = ntohl(i);
877 
878 #define SMFI_PROT_VERSION_MIN	2
879 
880 	/* check for minimum version */
881 	if (v < SMFI_PROT_VERSION_MIN)
882 	{
883 		smi_log(SMI_LOG_ERR,
884 			"%s: st_optionneg[%ld]: protocol version too old %d < %d",
885 			ctx->ctx_smfi->xxfi_name,
886 			(long) ctx->ctx_id, v, SMFI_PROT_VERSION_MIN);
887 		return _SMFIS_ABORT;
888 	}
889 	ctx->ctx_mta_prot_vers = v;
890 	if (ctx->ctx_prot_vers < ctx->ctx_mta_prot_vers)
891 		ctx->ctx_prot_vers2mta = ctx->ctx_prot_vers;
892 	else
893 		ctx->ctx_prot_vers2mta = ctx->ctx_mta_prot_vers;
894 
895 	(void) memcpy((void *) &i, (void *) &(g->a_buf[MILTER_LEN_BYTES]),
896 		      MILTER_LEN_BYTES);
897 	v = ntohl(i);
898 
899 	/* no flags? set to default value for V1 actions */
900 	if (v == 0)
901 		v = SMFI_V1_ACTS;
902 	ctx->ctx_mta_aflags = v;	/* MTA action flags */
903 
904 	internal_pflags = 0;
905 	(void) memcpy((void *) &i, (void *) &(g->a_buf[MILTER_LEN_BYTES * 2]),
906 		      MILTER_LEN_BYTES);
907 	v = ntohl(i);
908 
909 	/* no flags? set to default value for V1 protocol */
910 	if (v == 0)
911 		v = SMFI_V1_PROT;
912 #if _FFR_MDS_NEGOTIATE
913 	else if (ctx->ctx_smfi->xxfi_version >= SMFI_VERSION_MDS)
914 	{
915 		/*
916 		**  Allow changing the size only if milter is compiled
917 		**  against a version that supports this.
918 		**  If a milter is dynamically linked against a newer
919 		**  libmilter version, we don't want to "surprise"
920 		**  it with a larger buffer as it may rely on it
921 		**  even though it is not documented as a limit.
922 		*/
923 
924 		if (bitset(SMFIP_MDS_1M, v))
925 		{
926 			internal_pflags |= SMFIP_MDS_1M;
927 			(void) smfi_setmaxdatasize(MILTER_MDS_1M);
928 		}
929 		else if (bitset(SMFIP_MDS_256K, v))
930 		{
931 			internal_pflags |= SMFIP_MDS_256K;
932 			(void) smfi_setmaxdatasize(MILTER_MDS_256K);
933 		}
934 	}
935 # if 0
936 	/* don't log this for now... */
937 	else if (ctx->ctx_smfi->xxfi_version < SMFI_VERSION_MDS &&
938 		 bitset(SMFIP_MDS_1M|SMFIP_MDS_256K, v))
939 	{
940 		smi_log(SMI_LOG_WARN,
941 			"%s: st_optionneg[%ld]: milter version=%X, trying flags=%X",
942 			ctx->ctx_smfi->xxfi_name,
943 			(long) ctx->ctx_id, ctx->ctx_smfi->xxfi_version, v);
944 	}
945 # endif /* 0 */
946 #endif /* _FFR_MDS_NEGOTIATE */
947 
948 	/*
949 	**  MTA protocol flags.
950 	**  We pass the internal flags to the milter as "read only",
951 	**  i.e., a milter can read them so it knows which size
952 	**  will be used, but any changes by a milter will be ignored
953 	**  (see below, search for SMFI_INTERNAL).
954 	*/
955 
956 	ctx->ctx_mta_pflags = (v & ~SMFI_INTERNAL) | internal_pflags;
957 
958 	/*
959 	**  Copy flags from milter struct into libmilter context;
960 	**  this variable will be used later on to check whether
961 	**  the MTA "actions" can fulfill the milter requirements,
962 	**  but it may be overwritten by the negotiate callback.
963 	*/
964 
965 	ctx->ctx_aflags = ctx->ctx_smfi->xxfi_flags;
966 	fake_pflags = SMFIP_NR_CONN
967 			|SMFIP_NR_HELO
968 			|SMFIP_NR_MAIL
969 			|SMFIP_NR_RCPT
970 			|SMFIP_NR_DATA
971 			|SMFIP_NR_UNKN
972 			|SMFIP_NR_HDR
973 			|SMFIP_NR_EOH
974 			|SMFIP_NR_BODY
975 			;
976 
977 	if (g->a_ctx->ctx_smfi != NULL &&
978 	    g->a_ctx->ctx_smfi->xxfi_version > 4 &&
979 	    (fi_negotiate = g->a_ctx->ctx_smfi->xxfi_negotiate) != NULL)
980 	{
981 		int r;
982 		unsigned long m_aflags, m_pflags, m_f2, m_f3;
983 
984 		/*
985 		**  let milter decide whether the features offered by the
986 		**  MTA are "good enough".
987 		**  Notes:
988 		**  - libmilter can "fake" some features (e.g., SMFIP_NR_HDR)
989 		**  - m_f2, m_f3 are for future extensions
990 		*/
991 
992 		m_f2 = m_f3 = 0;
993 		m_aflags = ctx->ctx_mta_aflags;
994 		m_pflags = ctx->ctx_pflags;
995 		if ((SMFIP_SKIP & ctx->ctx_mta_pflags) != 0)
996 			m_pflags |= SMFIP_SKIP;
997 		r = fi_negotiate(g->a_ctx,
998 				ctx->ctx_mta_aflags,
999 				ctx->ctx_mta_pflags|fake_pflags,
1000 				0, 0,
1001 				&m_aflags, &m_pflags, &m_f2, &m_f3);
1002 
1003 #if _FFR_MILTER_CHECK
1004 		testmode = bitset(SMFIP_TEST, m_pflags);
1005 		if (testmode)
1006 			m_pflags &= ~SMFIP_TEST;
1007 #endif
1008 
1009 		/*
1010 		**  Types of protocol flags (pflags):
1011 		**  1. do NOT send protocol step X
1012 		**  2. MTA can do/understand something extra (SKIP,
1013 		**	send unknown RCPTs)
1014 		**  3. MTA can deal with "no reply" for various protocol steps
1015 		**  Note: this mean that it isn't possible to simply set all
1016 		**	flags to get "everything":
1017 		**	setting a flag of type 1 turns off a step
1018 		**		(it should be the other way around:
1019 		**		a flag means a protocol step can be sent)
1020 		**	setting a flag of type 3 requires that milter
1021 		**	never sends a reply for the corresponding step.
1022 		**  Summary: the "negation" of protocol flags is causing
1023 		**	problems, but at least for type 3 there is no simple
1024 		**	solution.
1025 		**
1026 		**  What should "all options" mean?
1027 		**  send all protocol steps _except_ those for which there is
1028 		**	no callback (currently registered in ctx_pflags)
1029 		**  expect SKIP as return code?		Yes
1030 		**  send unknown RCPTs?			No,
1031 		**				must be explicitly requested?
1032 		**  "no reply" for some protocol steps?	No,
1033 		**				must be explicitly requested.
1034 		*/
1035 
1036 		if (SMFIS_ALL_OPTS == r)
1037 		{
1038 			ctx->ctx_aflags = ctx->ctx_mta_aflags;
1039 			ctx->ctx_pflags2mta = ctx->ctx_pflags;
1040 			if ((SMFIP_SKIP & ctx->ctx_mta_pflags) != 0)
1041 				ctx->ctx_pflags2mta |= SMFIP_SKIP;
1042 		}
1043 		else if (r != SMFIS_CONTINUE)
1044 		{
1045 			smi_log(SMI_LOG_ERR,
1046 				"%s: st_optionneg[%ld]: xxfi_negotiate returned %d (protocol options=0x%lx, actions=0x%lx)",
1047 				ctx->ctx_smfi->xxfi_name,
1048 				(long) ctx->ctx_id, r, ctx->ctx_mta_pflags,
1049 				ctx->ctx_mta_aflags);
1050 			return _SMFIS_ABORT;
1051 		}
1052 		else
1053 		{
1054 			ctx->ctx_aflags = m_aflags;
1055 			ctx->ctx_pflags = m_pflags;
1056 			ctx->ctx_pflags2mta = m_pflags;
1057 		}
1058 
1059 		/* check whether some flags need to be "faked" */
1060 		i = ctx->ctx_pflags2mta;
1061 		if ((ctx->ctx_mta_pflags & i) != i)
1062 		{
1063 			unsigned int idx;
1064 			unsigned long b;
1065 
1066 			/*
1067 			**  If some behavior can be faked (set in fake_pflags),
1068 			**  but the MTA doesn't support it, then unset
1069 			**  that flag in the value that is sent to the MTA.
1070 			*/
1071 
1072 			for (idx = 0; idx < 32; idx++)
1073 			{
1074 				b = 1 << idx;
1075 				if ((ctx->ctx_mta_pflags & b) != b &&
1076 				    (fake_pflags & b) == b)
1077 					ctx->ctx_pflags2mta &= ~b;
1078 			}
1079 		}
1080 	}
1081 	else
1082 	{
1083 		/*
1084 		**  Set the protocol flags based on the values determined
1085 		**  in mi_listener() which checked the defined callbacks.
1086 		*/
1087 
1088 		ctx->ctx_pflags2mta = ctx->ctx_pflags;
1089 	}
1090 
1091 	/* check whether actions and protocol requirements can be satisfied */
1092 	i = ctx->ctx_aflags;
1093 	if ((i & ctx->ctx_mta_aflags) != i)
1094 	{
1095 		smi_log(SMI_LOG_ERR,
1096 			"%s: st_optionneg[%ld]: 0x%lx does not fulfill action requirements 0x%x",
1097 			ctx->ctx_smfi->xxfi_name,
1098 			(long) ctx->ctx_id, ctx->ctx_mta_aflags, i);
1099 		return _SMFIS_ABORT;
1100 	}
1101 
1102 	i = ctx->ctx_pflags2mta;
1103 	if ((ctx->ctx_mta_pflags & i) != i)
1104 	{
1105 		/*
1106 		**  Older MTAs do not support some protocol steps.
1107 		**  As this protocol is a bit "weird" (it asks for steps
1108 		**  NOT to be taken/sent) we have to check whether we
1109 		**  should turn off those "negative" requests.
1110 		**  Currently these are only SMFIP_NODATA and SMFIP_NOUNKNOWN.
1111 		*/
1112 
1113 		if (bitset(SMFIP_NODATA, ctx->ctx_pflags2mta) &&
1114 		    !bitset(SMFIP_NODATA, ctx->ctx_mta_pflags))
1115 			ctx->ctx_pflags2mta &= ~SMFIP_NODATA;
1116 		if (bitset(SMFIP_NOUNKNOWN, ctx->ctx_pflags2mta) &&
1117 		    !bitset(SMFIP_NOUNKNOWN, ctx->ctx_mta_pflags))
1118 			ctx->ctx_pflags2mta &= ~SMFIP_NOUNKNOWN;
1119 		i = ctx->ctx_pflags2mta;
1120 	}
1121 
1122 	if ((ctx->ctx_mta_pflags & i) != i)
1123 	{
1124 		smi_log(SMI_LOG_ERR,
1125 			"%s: st_optionneg[%ld]: 0x%lx does not fulfill protocol requirements 0x%x",
1126 			ctx->ctx_smfi->xxfi_name,
1127 			(long) ctx->ctx_id, ctx->ctx_mta_pflags, i);
1128 		return _SMFIS_ABORT;
1129 	}
1130 	fix_stm(ctx);
1131 
1132 	if (ctx->ctx_dbg > 3)
1133 		sm_dprintf("[%lu] milter_negotiate:"
1134 			" mta_actions=0x%lx, mta_flags=0x%lx"
1135 			" actions=0x%lx, flags=0x%lx\n"
1136 			, (long) ctx->ctx_id
1137 			, ctx->ctx_mta_aflags, ctx->ctx_mta_pflags
1138 			, ctx->ctx_aflags, ctx->ctx_pflags);
1139 
1140 #if _FFR_MILTER_CHECK
1141 	if (ctx->ctx_dbg > 3)
1142 		sm_dprintf("[%lu] milter_negotiate:"
1143 			" testmode=%d, pflags2mta=%X, internal_pflags=%X\n"
1144 			, (long) ctx->ctx_id, testmode
1145 			, ctx->ctx_pflags2mta, internal_pflags);
1146 
1147 	/* in test mode: take flags without further modifications */
1148 	if (!testmode)
1149 		/* Warning: check statement below! */
1150 #endif /* _FFR_MILTER_CHECK */
1151 
1152 	/*
1153 	**  Remove the internal flags that might have been set by a milter
1154 	**  and set only those determined above.
1155 	*/
1156 
1157 	ctx->ctx_pflags2mta = (ctx->ctx_pflags2mta & ~SMFI_INTERNAL)
1158 			      | internal_pflags;
1159 	return _SMFIS_OPTIONS;
1160 }
1161 
1162 /*
1163 **  ST_CONNECTINFO -- receive connection information
1164 **
1165 **	Parameters:
1166 **		g -- generic argument structure
1167 **
1168 **	Returns:
1169 **		continue or filter-specified value
1170 */
1171 
1172 static int
1173 st_connectinfo(g)
1174 	genarg *g;
1175 {
1176 	size_t l;
1177 	size_t i;
1178 	char *s, family;
1179 	unsigned short port = 0;
1180 	_SOCK_ADDR sockaddr;
1181 	sfsistat (*fi_connect) __P((SMFICTX *, char *, _SOCK_ADDR *));
1182 
1183 	if (g == NULL)
1184 		return _SMFIS_ABORT;
1185 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
1186 	if (g->a_ctx->ctx_smfi == NULL ||
1187 	    (fi_connect = g->a_ctx->ctx_smfi->xxfi_connect) == NULL)
1188 		return SMFIS_CONTINUE;
1189 
1190 	s = g->a_buf;
1191 	i = 0;
1192 	l = g->a_len;
1193 	while (i <= l && s[i] != '\0')
1194 		++i;
1195 	if (i + 1 >= l)
1196 		return _SMFIS_ABORT;
1197 
1198 	/* Move past trailing \0 in host string */
1199 	i++;
1200 	family = s[i++];
1201 	(void) memset(&sockaddr, '\0', sizeof sockaddr);
1202 	if (family != SMFIA_UNKNOWN)
1203 	{
1204 		if (i + sizeof port >= l)
1205 		{
1206 			smi_log(SMI_LOG_ERR,
1207 				"%s: connect[%ld]: wrong len %d >= %d",
1208 				g->a_ctx->ctx_smfi->xxfi_name,
1209 				(long) g->a_ctx->ctx_id, (int) i, (int) l);
1210 			return _SMFIS_ABORT;
1211 		}
1212 		(void) memcpy((void *) &port, (void *) (s + i),
1213 			      sizeof port);
1214 		i += sizeof port;
1215 
1216 		/* make sure string is terminated */
1217 		if (s[l - 1] != '\0')
1218 			return _SMFIS_ABORT;
1219 # if NETINET
1220 		if (family == SMFIA_INET)
1221 		{
1222 			if (inet_aton(s + i, (struct in_addr *) &sockaddr.sin.sin_addr)
1223 			    != 1)
1224 			{
1225 				smi_log(SMI_LOG_ERR,
1226 					"%s: connect[%ld]: inet_aton failed",
1227 					g->a_ctx->ctx_smfi->xxfi_name,
1228 					(long) g->a_ctx->ctx_id);
1229 				return _SMFIS_ABORT;
1230 			}
1231 			sockaddr.sa.sa_family = AF_INET;
1232 			if (port > 0)
1233 				sockaddr.sin.sin_port = port;
1234 		}
1235 		else
1236 # endif /* NETINET */
1237 # if NETINET6
1238 		if (family == SMFIA_INET6)
1239 		{
1240 			if (mi_inet_pton(AF_INET6, s + i,
1241 					 &sockaddr.sin6.sin6_addr) != 1)
1242 			{
1243 				smi_log(SMI_LOG_ERR,
1244 					"%s: connect[%ld]: mi_inet_pton failed",
1245 					g->a_ctx->ctx_smfi->xxfi_name,
1246 					(long) g->a_ctx->ctx_id);
1247 				return _SMFIS_ABORT;
1248 			}
1249 			sockaddr.sa.sa_family = AF_INET6;
1250 			if (port > 0)
1251 				sockaddr.sin6.sin6_port = port;
1252 		}
1253 		else
1254 # endif /* NETINET6 */
1255 # if NETUNIX
1256 		if (family == SMFIA_UNIX)
1257 		{
1258 			if (sm_strlcpy(sockaddr.sunix.sun_path, s + i,
1259 			    sizeof sockaddr.sunix.sun_path) >=
1260 			    sizeof sockaddr.sunix.sun_path)
1261 			{
1262 				smi_log(SMI_LOG_ERR,
1263 					"%s: connect[%ld]: path too long",
1264 					g->a_ctx->ctx_smfi->xxfi_name,
1265 					(long) g->a_ctx->ctx_id);
1266 				return _SMFIS_ABORT;
1267 			}
1268 			sockaddr.sunix.sun_family = AF_UNIX;
1269 		}
1270 		else
1271 # endif /* NETUNIX */
1272 		{
1273 			smi_log(SMI_LOG_ERR,
1274 				"%s: connect[%ld]: unknown family %d",
1275 				g->a_ctx->ctx_smfi->xxfi_name,
1276 				(long) g->a_ctx->ctx_id, family);
1277 			return _SMFIS_ABORT;
1278 		}
1279 	}
1280 	return (*fi_connect)(g->a_ctx, g->a_buf,
1281 			     family != SMFIA_UNKNOWN ? &sockaddr : NULL);
1282 }
1283 
1284 /*
1285 **  ST_EOH -- end of headers
1286 **
1287 **	Parameters:
1288 **		g -- generic argument structure
1289 **
1290 **	Returns:
1291 **		continue or filter-specified value
1292 */
1293 
1294 static int
1295 st_eoh(g)
1296 	genarg *g;
1297 {
1298 	sfsistat (*fi_eoh) __P((SMFICTX *));
1299 
1300 	if (g == NULL)
1301 		return _SMFIS_ABORT;
1302 	if (g->a_ctx->ctx_smfi != NULL &&
1303 	    (fi_eoh = g->a_ctx->ctx_smfi->xxfi_eoh) != NULL)
1304 		return (*fi_eoh)(g->a_ctx);
1305 	return SMFIS_CONTINUE;
1306 }
1307 
1308 /*
1309 **  ST_DATA -- DATA command
1310 **
1311 **	Parameters:
1312 **		g -- generic argument structure
1313 **
1314 **	Returns:
1315 **		continue or filter-specified value
1316 */
1317 
1318 static int
1319 st_data(g)
1320 	genarg *g;
1321 {
1322 	sfsistat (*fi_data) __P((SMFICTX *));
1323 
1324 	if (g == NULL)
1325 		return _SMFIS_ABORT;
1326 	if (g->a_ctx->ctx_smfi != NULL &&
1327 	    g->a_ctx->ctx_smfi->xxfi_version > 3 &&
1328 	    (fi_data = g->a_ctx->ctx_smfi->xxfi_data) != NULL)
1329 		return (*fi_data)(g->a_ctx);
1330 	return SMFIS_CONTINUE;
1331 }
1332 
1333 /*
1334 **  ST_HELO -- helo/ehlo command
1335 **
1336 **	Parameters:
1337 **		g -- generic argument structure
1338 **
1339 **	Returns:
1340 **		continue or filter-specified value
1341 */
1342 
1343 static int
1344 st_helo(g)
1345 	genarg *g;
1346 {
1347 	sfsistat (*fi_helo) __P((SMFICTX *, char *));
1348 
1349 	if (g == NULL)
1350 		return _SMFIS_ABORT;
1351 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
1352 	if (g->a_ctx->ctx_smfi != NULL &&
1353 	    (fi_helo = g->a_ctx->ctx_smfi->xxfi_helo) != NULL)
1354 	{
1355 		/* paranoia: check for terminating '\0' */
1356 		if (g->a_len == 0 || g->a_buf[g->a_len - 1] != '\0')
1357 			return MI_FAILURE;
1358 		return (*fi_helo)(g->a_ctx, g->a_buf);
1359 	}
1360 	return SMFIS_CONTINUE;
1361 }
1362 
1363 /*
1364 **  ST_HEADER -- header line
1365 **
1366 **	Parameters:
1367 **		g -- generic argument structure
1368 **
1369 **	Returns:
1370 **		continue or filter-specified value
1371 */
1372 
1373 static int
1374 st_header(g)
1375 	genarg *g;
1376 {
1377 	char *hf, *hv;
1378 	sfsistat (*fi_header) __P((SMFICTX *, char *, char *));
1379 
1380 	if (g == NULL)
1381 		return _SMFIS_ABORT;
1382 	if (g->a_ctx->ctx_smfi == NULL ||
1383 	    (fi_header = g->a_ctx->ctx_smfi->xxfi_header) == NULL)
1384 		return SMFIS_CONTINUE;
1385 	if (dec_arg2(g->a_buf, g->a_len, &hf, &hv) == MI_SUCCESS)
1386 		return (*fi_header)(g->a_ctx, hf, hv);
1387 	else
1388 		return _SMFIS_ABORT;
1389 }
1390 
1391 #define ARGV_FCT(lf, rf, idx)					\
1392 	char **argv;						\
1393 	sfsistat (*lf) __P((SMFICTX *, char **));		\
1394 	int r;							\
1395 								\
1396 	if (g == NULL)						\
1397 		return _SMFIS_ABORT;				\
1398 	mi_clr_macros(g->a_ctx, g->a_idx + 1);			\
1399 	if (g->a_ctx->ctx_smfi == NULL ||			\
1400 	    (lf = g->a_ctx->ctx_smfi->rf) == NULL)		\
1401 		return SMFIS_CONTINUE;				\
1402 	if ((argv = dec_argv(g->a_buf, g->a_len)) == NULL)	\
1403 		return _SMFIS_ABORT;				\
1404 	r = (*lf)(g->a_ctx, argv);				\
1405 	free(argv);						\
1406 	return r;
1407 
1408 /*
1409 **  ST_SENDER -- MAIL FROM command
1410 **
1411 **	Parameters:
1412 **		g -- generic argument structure
1413 **
1414 **	Returns:
1415 **		continue or filter-specified value
1416 */
1417 
1418 static int
1419 st_sender(g)
1420 	genarg *g;
1421 {
1422 	ARGV_FCT(fi_envfrom, xxfi_envfrom, CI_MAIL)
1423 }
1424 
1425 /*
1426 **  ST_RCPT -- RCPT TO command
1427 **
1428 **	Parameters:
1429 **		g -- generic argument structure
1430 **
1431 **	Returns:
1432 **		continue or filter-specified value
1433 */
1434 
1435 static int
1436 st_rcpt(g)
1437 	genarg *g;
1438 {
1439 	ARGV_FCT(fi_envrcpt, xxfi_envrcpt, CI_RCPT)
1440 }
1441 
1442 /*
1443 **  ST_UNKNOWN -- unrecognized or unimplemented command
1444 **
1445 **	Parameters:
1446 **		g -- generic argument structure
1447 **
1448 **	Returns:
1449 **		continue or filter-specified value
1450 */
1451 
1452 static int
1453 st_unknown(g)
1454 	genarg *g;
1455 {
1456 	sfsistat (*fi_unknown) __P((SMFICTX *, const char *));
1457 
1458 	if (g == NULL)
1459 		return _SMFIS_ABORT;
1460 	if (g->a_ctx->ctx_smfi != NULL &&
1461 	    g->a_ctx->ctx_smfi->xxfi_version > 2 &&
1462 	    (fi_unknown = g->a_ctx->ctx_smfi->xxfi_unknown) != NULL)
1463 		return (*fi_unknown)(g->a_ctx, (const char *) g->a_buf);
1464 	return SMFIS_CONTINUE;
1465 }
1466 
1467 /*
1468 **  ST_MACROS -- deal with macros received from the MTA
1469 **
1470 **	Parameters:
1471 **		g -- generic argument structure
1472 **
1473 **	Returns:
1474 **		continue/keep
1475 **
1476 **	Side effects:
1477 **		set pointer in macro array to current values.
1478 */
1479 
1480 static int
1481 st_macros(g)
1482 	genarg *g;
1483 {
1484 	int i;
1485 	char **argv;
1486 
1487 	if (g == NULL || g->a_len < 1)
1488 		return _SMFIS_FAIL;
1489 	if ((argv = dec_argv(g->a_buf + 1, g->a_len - 1)) == NULL)
1490 		return _SMFIS_FAIL;
1491 	switch (g->a_buf[0])
1492 	{
1493 	  case SMFIC_CONNECT:
1494 		i = CI_CONN;
1495 		break;
1496 	  case SMFIC_HELO:
1497 		i = CI_HELO;
1498 		break;
1499 	  case SMFIC_MAIL:
1500 		i = CI_MAIL;
1501 		break;
1502 	  case SMFIC_RCPT:
1503 		i = CI_RCPT;
1504 		break;
1505 	  case SMFIC_DATA:
1506 		i = CI_DATA;
1507 		break;
1508 	  case SMFIC_BODYEOB:
1509 		i = CI_EOM;
1510 		break;
1511 	  case SMFIC_EOH:
1512 		i = CI_EOH;
1513 		break;
1514 	  default:
1515 		free(argv);
1516 		return _SMFIS_FAIL;
1517 	}
1518 	if (g->a_ctx->ctx_mac_ptr[i] != NULL)
1519 		free(g->a_ctx->ctx_mac_ptr[i]);
1520 	if (g->a_ctx->ctx_mac_buf[i] != NULL)
1521 		free(g->a_ctx->ctx_mac_buf[i]);
1522 	g->a_ctx->ctx_mac_ptr[i] = argv;
1523 	g->a_ctx->ctx_mac_buf[i] = g->a_buf;
1524 	return _SMFIS_KEEP;
1525 }
1526 
1527 /*
1528 **  ST_QUIT -- quit command
1529 **
1530 **	Parameters:
1531 **		g -- generic argument structure
1532 **
1533 **	Returns:
1534 **		noreply
1535 */
1536 
1537 /* ARGSUSED */
1538 static int
1539 st_quit(g)
1540 	genarg *g;
1541 {
1542 	sfsistat (*fi_close) __P((SMFICTX *));
1543 
1544 	if (g == NULL)
1545 		return _SMFIS_ABORT;
1546 	if (g->a_ctx->ctx_smfi != NULL &&
1547 	    (fi_close = g->a_ctx->ctx_smfi->xxfi_close) != NULL)
1548 		(void) (*fi_close)(g->a_ctx);
1549 	mi_clr_macros(g->a_ctx, 0);
1550 	return _SMFIS_NOREPLY;
1551 }
1552 
1553 /*
1554 **  ST_BODYCHUNK -- deal with a piece of the mail body
1555 **
1556 **	Parameters:
1557 **		g -- generic argument structure
1558 **
1559 **	Returns:
1560 **		continue or filter-specified value
1561 */
1562 
1563 static int
1564 st_bodychunk(g)
1565 	genarg *g;
1566 {
1567 	sfsistat (*fi_body) __P((SMFICTX *, unsigned char *, size_t));
1568 
1569 	if (g == NULL)
1570 		return _SMFIS_ABORT;
1571 	if (g->a_ctx->ctx_smfi != NULL &&
1572 	    (fi_body = g->a_ctx->ctx_smfi->xxfi_body) != NULL)
1573 		return (*fi_body)(g->a_ctx, (unsigned char *)g->a_buf,
1574 				  g->a_len);
1575 	return SMFIS_CONTINUE;
1576 }
1577 
1578 /*
1579 **  ST_BODYEND -- deal with the last piece of the mail body
1580 **
1581 **	Parameters:
1582 **		g -- generic argument structure
1583 **
1584 **	Returns:
1585 **		continue or filter-specified value
1586 **
1587 **	Side effects:
1588 **		sends a reply for the body part (if non-empty).
1589 */
1590 
1591 static int
1592 st_bodyend(g)
1593 	genarg *g;
1594 {
1595 	sfsistat r;
1596 	sfsistat (*fi_body) __P((SMFICTX *, unsigned char *, size_t));
1597 	sfsistat (*fi_eom) __P((SMFICTX *));
1598 
1599 	if (g == NULL)
1600 		return _SMFIS_ABORT;
1601 	r = SMFIS_CONTINUE;
1602 	if (g->a_ctx->ctx_smfi != NULL)
1603 	{
1604 		if ((fi_body = g->a_ctx->ctx_smfi->xxfi_body) != NULL &&
1605 		    g->a_len > 0)
1606 		{
1607 			socket_t sd;
1608 			struct timeval timeout;
1609 
1610 			timeout.tv_sec = g->a_ctx->ctx_timeout;
1611 			timeout.tv_usec = 0;
1612 			sd = g->a_ctx->ctx_sd;
1613 			r = (*fi_body)(g->a_ctx, (unsigned char *)g->a_buf,
1614 				       g->a_len);
1615 			if (r != SMFIS_CONTINUE &&
1616 			    sendreply(r, sd, &timeout, g->a_ctx) != MI_SUCCESS)
1617 				return _SMFIS_ABORT;
1618 		}
1619 	}
1620 	if (r == SMFIS_CONTINUE &&
1621 	    (fi_eom = g->a_ctx->ctx_smfi->xxfi_eom) != NULL)
1622 		return (*fi_eom)(g->a_ctx);
1623 	return r;
1624 }
1625 
1626 /*
1627 **  ST_ABORTFCT -- deal with aborts
1628 **
1629 **	Parameters:
1630 **		g -- generic argument structure
1631 **
1632 **	Returns:
1633 **		abort or filter-specified value
1634 */
1635 
1636 static int
1637 st_abortfct(g)
1638 	genarg *g;
1639 {
1640 	sfsistat (*fi_abort) __P((SMFICTX *));
1641 
1642 	if (g == NULL)
1643 		return _SMFIS_ABORT;
1644 	if (g != NULL && g->a_ctx->ctx_smfi != NULL &&
1645 	    (fi_abort = g->a_ctx->ctx_smfi->xxfi_abort) != NULL)
1646 		(void) (*fi_abort)(g->a_ctx);
1647 	return _SMFIS_NOREPLY;
1648 }
1649 
1650 /*
1651 **  TRANS_OK -- is the state transition ok?
1652 **
1653 **	Parameters:
1654 **		old -- old state
1655 **		new -- new state
1656 **
1657 **	Returns:
1658 **		state transition ok
1659 */
1660 
1661 static bool
1662 trans_ok(old, new)
1663 	int old, new;
1664 {
1665 	int s, n;
1666 
1667 	s = old;
1668 	if (s >= SIZE_NEXT_STATES)
1669 		return false;
1670 	do
1671 	{
1672 		/* is this state transition allowed? */
1673 		if ((MI_MASK(new) & next_states[s]) != 0)
1674 			return true;
1675 
1676 		/*
1677 		**  no: try next state;
1678 		**  this works since the relevant states are ordered
1679 		**  strict sequentially
1680 		*/
1681 
1682 		n = s + 1;
1683 		if (n >= SIZE_NEXT_STATES)
1684 			return false;
1685 
1686 		/*
1687 		**  can we actually "skip" this state?
1688 		**  see fix_stm() which sets this bit for those
1689 		**  states which the filter program is not interested in
1690 		*/
1691 
1692 		if (bitset(NX_SKIP, next_states[n]))
1693 			s = n;
1694 		else
1695 			return false;
1696 	} while (s < SIZE_NEXT_STATES);
1697 	return false;
1698 }
1699 
1700 /*
1701 **  FIX_STM -- add "skip" bits to the state transition table
1702 **
1703 **	Parameters:
1704 **		ctx -- context structure
1705 **
1706 **	Returns:
1707 **		None.
1708 **
1709 **	Side effects:
1710 **		may change state transition table.
1711 */
1712 
1713 static void
1714 fix_stm(ctx)
1715 	SMFICTX_PTR ctx;
1716 {
1717 	unsigned long fl;
1718 
1719 	if (ctx == NULL || ctx->ctx_smfi == NULL)
1720 		return;
1721 	fl = ctx->ctx_pflags;
1722 	if (bitset(SMFIP_NOCONNECT, fl))
1723 		next_states[ST_CONN] |= NX_SKIP;
1724 	if (bitset(SMFIP_NOHELO, fl))
1725 		next_states[ST_HELO] |= NX_SKIP;
1726 	if (bitset(SMFIP_NOMAIL, fl))
1727 		next_states[ST_MAIL] |= NX_SKIP;
1728 	if (bitset(SMFIP_NORCPT, fl))
1729 		next_states[ST_RCPT] |= NX_SKIP;
1730 	if (bitset(SMFIP_NOHDRS, fl))
1731 		next_states[ST_HDRS] |= NX_SKIP;
1732 	if (bitset(SMFIP_NOEOH, fl))
1733 		next_states[ST_EOHS] |= NX_SKIP;
1734 	if (bitset(SMFIP_NOBODY, fl))
1735 		next_states[ST_BODY] |= NX_SKIP;
1736 	if (bitset(SMFIP_NODATA, fl))
1737 		next_states[ST_DATA] |= NX_SKIP;
1738 	if (bitset(SMFIP_NOUNKNOWN, fl))
1739 		next_states[ST_UNKN] |= NX_SKIP;
1740 }
1741 
1742 /*
1743 **  DEC_ARGV -- split a buffer into a list of strings, NULL terminated
1744 **
1745 **	Parameters:
1746 **		buf -- buffer with several strings
1747 **		len -- length of buffer
1748 **
1749 **	Returns:
1750 **		array of pointers to the individual strings
1751 */
1752 
1753 static char **
1754 dec_argv(buf, len)
1755 	char *buf;
1756 	size_t len;
1757 {
1758 	char **s;
1759 	size_t i;
1760 	int elem, nelem;
1761 
1762 	nelem = 0;
1763 	for (i = 0; i < len; i++)
1764 	{
1765 		if (buf[i] == '\0')
1766 			++nelem;
1767 	}
1768 	if (nelem == 0)
1769 		return NULL;
1770 
1771 	/* last entry is only for the name */
1772 	s = (char **)malloc((nelem + 1) * (sizeof *s));
1773 	if (s == NULL)
1774 		return NULL;
1775 	s[0] = buf;
1776 	for (i = 0, elem = 0; i < len && elem < nelem; i++)
1777 	{
1778 		if (buf[i] == '\0')
1779 		{
1780 			++elem;
1781 			if (i + 1 >= len)
1782 				s[elem] = NULL;
1783 			else
1784 				s[elem] = &(buf[i + 1]);
1785 		}
1786 	}
1787 
1788 	/* overwrite last entry (already done above, just paranoia) */
1789 	s[elem] = NULL;
1790 	return s;
1791 }
1792 
1793 /*
1794 **  DEC_ARG2 -- split a buffer into two strings
1795 **
1796 **	Parameters:
1797 **		buf -- buffer with two strings
1798 **		len -- length of buffer
1799 **		s1,s2 -- pointer to result strings
1800 **
1801 **	Returns:
1802 **		MI_FAILURE/MI_SUCCESS
1803 */
1804 
1805 static int
1806 dec_arg2(buf, len, s1, s2)
1807 	char *buf;
1808 	size_t len;
1809 	char **s1;
1810 	char **s2;
1811 {
1812 	size_t i;
1813 
1814 	/* paranoia: check for terminating '\0' */
1815 	if (len == 0 || buf[len - 1] != '\0')
1816 		return MI_FAILURE;
1817 	*s1 = buf;
1818 	for (i = 1; i < len && buf[i] != '\0'; i++)
1819 		continue;
1820 	if (i >= len - 1)
1821 		return MI_FAILURE;
1822 	*s2 = buf + i + 1;
1823 	return MI_SUCCESS;
1824 }
1825 
1826 /*
1827 **  MI_SENDOK -- is it ok for the filter to send stuff to the MTA?
1828 **
1829 **	Parameters:
1830 **		ctx -- context structure
1831 **		flag -- flag to check
1832 **
1833 **	Returns:
1834 **		sending allowed (in current state)
1835 */
1836 
1837 bool
1838 mi_sendok(ctx, flag)
1839 	SMFICTX_PTR ctx;
1840 	int flag;
1841 {
1842 	if (ctx == NULL || ctx->ctx_smfi == NULL)
1843 		return false;
1844 
1845 	/* did the milter request this operation? */
1846 	if (flag != 0 && !bitset(flag, ctx->ctx_aflags))
1847 		return false;
1848 
1849 	/* are we in the correct state? It must be "End of Message". */
1850 	return ctx->ctx_state == ST_ENDM;
1851 }
1852 
1853 #if _FFR_WORKERS_POOL
1854 /*
1855 **  MI_RD_SOCKET_READY - checks if the socket is ready for read(2)
1856 **
1857 **	Parameters:
1858 **		sd -- socket_t
1859 **
1860 **	Returns:
1861 **		true iff socket is ready for read(2)
1862 */
1863 
1864 #define MI_RD_CMD_TO  1
1865 #define MI_RD_MAX_ERR 16
1866 
1867 static bool
1868 mi_rd_socket_ready (sd)
1869 	socket_t sd;
1870 {
1871 	int n;
1872 	int nerr = 0;
1873 #if SM_CONF_POLL
1874 	struct pollfd pfd;
1875 #else
1876 	fd_set	rd_set, exc_set;
1877 #endif
1878 
1879 	do
1880 	{
1881 #if SM_CONF_POLL
1882 		pfd.fd = sd;
1883 		pfd.events = POLLIN;
1884 		pfd.revents = 0;
1885 
1886 		n = poll(&pfd, 1, MI_RD_CMD_TO);
1887 #else /* SM_CONF_POLL */
1888 		struct timeval timeout;
1889 
1890 		FD_ZERO(&rd_set);
1891 		FD_ZERO(&exc_set);
1892 		FD_SET(sd, &rd_set);
1893 		FD_SET(sd, &exc_set);
1894 
1895 		timeout.tv_sec = MI_RD_CMD_TO / 1000;
1896 		timeout.tv_usec = 0;
1897 		n = select(sd + 1, &rd_set, NULL, &exc_set, &timeout);
1898 #endif /* SM_CONF_POLL */
1899 
1900 		if (n < 0)
1901 		{
1902 			if (errno == EINTR)
1903 			{
1904 				nerr++;
1905 				continue;
1906 			}
1907 			return true;
1908 		}
1909 
1910 		if (n == 0)
1911 			return false;
1912 		break;
1913 	} while (nerr < MI_RD_MAX_ERR);
1914 	if (nerr >= MI_RD_MAX_ERR)
1915 		return false;
1916 
1917 #if SM_CONF_POLL
1918 	return (pfd.revents != 0);
1919 #else
1920 	return FD_ISSET(sd, &rd_set) || FD_ISSET(sd, &exc_set);
1921 #endif
1922 }
1923 #endif /* _FFR_WORKERS_POOL */
1924