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