xref: /titanic_44/usr/src/cmd/sendmail/libmilter/engine.c (revision 3289e1bdec732dbdf04517907516fd0d00f6a6f8)
1 /*
2  *  Copyright (c) 1999-2004, 2006-2008 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.162 2008/02/27 01:34:14 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 
740 void
741 mi_clr_macros(ctx, m)
742 	SMFICTX_PTR ctx;
743 	int m;
744 {
745 	int i;
746 
747 	for (i = m; i < MAX_MACROS_ENTRIES; i++)
748 	{
749 		if (ctx->ctx_mac_ptr[i] != NULL)
750 		{
751 			free(ctx->ctx_mac_ptr[i]);
752 			ctx->ctx_mac_ptr[i] = NULL;
753 		}
754 		if (ctx->ctx_mac_buf[i] != NULL)
755 		{
756 			free(ctx->ctx_mac_buf[i]);
757 			ctx->ctx_mac_buf[i] = NULL;
758 		}
759 	}
760 }
761 
762 /*
763 **  ST_OPTIONNEG -- negotiate options
764 **
765 **	Parameters:
766 **		g -- generic argument structure
767 **
768 **	Returns:
769 **		abort/send options/continue
770 */
771 
772 static int
773 st_optionneg(g)
774 	genarg *g;
775 {
776 	mi_int32 i, v, fake_pflags;
777 	SMFICTX_PTR ctx;
778 	int (*fi_negotiate) __P((SMFICTX *,
779 					unsigned long, unsigned long,
780 					unsigned long, unsigned long,
781 					unsigned long *, unsigned long *,
782 					unsigned long *, unsigned long *));
783 
784 	if (g == NULL || g->a_ctx->ctx_smfi == NULL)
785 		return SMFIS_CONTINUE;
786 	ctx = g->a_ctx;
787 	mi_clr_macros(ctx, g->a_idx + 1);
788 	ctx->ctx_prot_vers = SMFI_PROT_VERSION;
789 
790 	/* check for minimum length */
791 	if (g->a_len < MILTER_OPTLEN)
792 	{
793 		smi_log(SMI_LOG_ERR,
794 			"%s: st_optionneg[%ld]: len too short %d < %d",
795 			ctx->ctx_smfi->xxfi_name,
796 			(long) ctx->ctx_id, (int) g->a_len,
797 			MILTER_OPTLEN);
798 		return _SMFIS_ABORT;
799 	}
800 
801 	/* protocol version */
802 	(void) memcpy((void *) &i, (void *) &(g->a_buf[0]), MILTER_LEN_BYTES);
803 	v = ntohl(i);
804 
805 #define SMFI_PROT_VERSION_MIN	2
806 
807 	/* check for minimum version */
808 	if (v < SMFI_PROT_VERSION_MIN)
809 	{
810 		smi_log(SMI_LOG_ERR,
811 			"%s: st_optionneg[%ld]: protocol version too old %d < %d",
812 			ctx->ctx_smfi->xxfi_name,
813 			(long) ctx->ctx_id, v, SMFI_PROT_VERSION_MIN);
814 		return _SMFIS_ABORT;
815 	}
816 	ctx->ctx_mta_prot_vers = v;
817 	if (ctx->ctx_prot_vers < ctx->ctx_mta_prot_vers)
818 		ctx->ctx_prot_vers2mta = ctx->ctx_prot_vers;
819 	else
820 		ctx->ctx_prot_vers2mta = ctx->ctx_mta_prot_vers;
821 
822 	(void) memcpy((void *) &i, (void *) &(g->a_buf[MILTER_LEN_BYTES]),
823 		      MILTER_LEN_BYTES);
824 	v = ntohl(i);
825 
826 	/* no flags? set to default value for V1 actions */
827 	if (v == 0)
828 		v = SMFI_V1_ACTS;
829 	ctx->ctx_mta_aflags = v;	/* MTA action flags */
830 
831 	(void) memcpy((void *) &i, (void *) &(g->a_buf[MILTER_LEN_BYTES * 2]),
832 		      MILTER_LEN_BYTES);
833 	v = ntohl(i);
834 
835 	/* no flags? set to default value for V1 protocol */
836 	if (v == 0)
837 		v = SMFI_V1_PROT;
838 	ctx->ctx_mta_pflags = v;	/* MTA protocol flags */
839 
840 	/*
841 	**  Copy flags from milter struct into libmilter context;
842 	**  this variable will be used later on to check whether
843 	**  the MTA "actions" can fulfill the milter requirements,
844 	**  but it may be overwritten by the negotiate callback.
845 	*/
846 
847 	ctx->ctx_aflags = ctx->ctx_smfi->xxfi_flags;
848 	fake_pflags = SMFIP_NR_CONN
849 			|SMFIP_NR_HELO
850 			|SMFIP_NR_MAIL
851 			|SMFIP_NR_RCPT
852 			|SMFIP_NR_DATA
853 			|SMFIP_NR_UNKN
854 			|SMFIP_NR_HDR
855 			|SMFIP_NR_EOH
856 			|SMFIP_NR_BODY
857 			;
858 
859 	if (g->a_ctx->ctx_smfi != NULL &&
860 	    g->a_ctx->ctx_smfi->xxfi_version > 4 &&
861 	    (fi_negotiate = g->a_ctx->ctx_smfi->xxfi_negotiate) != NULL)
862 	{
863 		int r;
864 		unsigned long m_aflags, m_pflags, m_f2, m_f3;
865 
866 		/*
867 		**  let milter decide whether the features offered by the
868 		**  MTA are "good enough".
869 		**  Notes:
870 		**  - libmilter can "fake" some features (e.g., SMFIP_NR_HDR)
871 		**  - m_f2, m_f3 are for future extensions
872 		*/
873 
874 		m_f2 = m_f3 = 0;
875 		m_aflags = ctx->ctx_mta_aflags;
876 		m_pflags = ctx->ctx_pflags;
877 		if ((SMFIP_SKIP & ctx->ctx_mta_pflags) != 0)
878 			m_pflags |= SMFIP_SKIP;
879 		r = fi_negotiate(g->a_ctx,
880 				ctx->ctx_mta_aflags,
881 				ctx->ctx_mta_pflags|fake_pflags,
882 				0, 0,
883 				&m_aflags, &m_pflags, &m_f2, &m_f3);
884 
885 		/*
886 		**  Types of protocol flags (pflags):
887 		**  1. do NOT send protocol step X
888 		**  2. MTA can do/understand something extra (SKIP,
889 		**	send unknown RCPTs)
890 		**  3. MTA can deal with "no reply" for various protocol steps
891 		**  Note: this mean that it isn't possible to simply set all
892 		**	flags to get "everything":
893 		**	setting a flag of type 1 turns off a step
894 		**		(it should be the other way around:
895 		**		a flag means a protocol step can be sent)
896 		**	setting a flag of type 3 requires that milter
897 		**	never sends a reply for the corresponding step.
898 		**  Summary: the "negation" of protocol flags is causing
899 		**	problems, but at least for type 3 there is no simple
900 		**	solution.
901 		**
902 		**  What should "all options" mean?
903 		**  send all protocol steps _except_ those for which there is
904 		**	no callback (currently registered in ctx_pflags)
905 		**  expect SKIP as return code?		Yes
906 		**  send unknown RCPTs?			No,
907 		**				must be explicitly requested?
908 		**  "no reply" for some protocol steps?	No,
909 		**				must be explicitly requested.
910 		*/
911 
912 		if (SMFIS_ALL_OPTS == r)
913 		{
914 			ctx->ctx_aflags = ctx->ctx_mta_aflags;
915 			ctx->ctx_pflags2mta = ctx->ctx_pflags;
916 			if ((SMFIP_SKIP & ctx->ctx_mta_pflags) != 0)
917 				ctx->ctx_pflags2mta |= SMFIP_SKIP;
918 		}
919 		else if (r != SMFIS_CONTINUE)
920 		{
921 			smi_log(SMI_LOG_ERR,
922 				"%s: st_optionneg[%ld]: xxfi_negotiate returned %d (protocol options=0x%lx, actions=0x%lx)",
923 				ctx->ctx_smfi->xxfi_name,
924 				(long) ctx->ctx_id, r, ctx->ctx_mta_pflags,
925 				ctx->ctx_mta_aflags);
926 			return _SMFIS_ABORT;
927 		}
928 		else
929 		{
930 			ctx->ctx_aflags = m_aflags;
931 			ctx->ctx_pflags = m_pflags;
932 			ctx->ctx_pflags2mta = m_pflags;
933 		}
934 
935 		/* check whether some flags need to be "faked" */
936 		i = ctx->ctx_pflags2mta;
937 		if ((ctx->ctx_mta_pflags & i) != i)
938 		{
939 			unsigned int idx;
940 			unsigned long b;
941 
942 			/*
943 			**  If some behavior can be faked (set in fake_pflags),
944 			**  but the MTA doesn't support it, then unset
945 			**  that flag in the value that is sent to the MTA.
946 			*/
947 
948 			for (idx = 0; idx < 32; idx++)
949 			{
950 				b = 1 << idx;
951 				if ((ctx->ctx_mta_pflags & b) != b &&
952 				    (fake_pflags & b) == b)
953 					ctx->ctx_pflags2mta &= ~b;
954 			}
955 		}
956 	}
957 	else
958 	{
959 		/*
960 		**  Set the protocol flags based on the values determined
961 		**  in mi_listener() which checked the defined callbacks.
962 		*/
963 
964 		ctx->ctx_pflags2mta = ctx->ctx_pflags;
965 	}
966 
967 	/* check whether actions and protocol requirements can be satisfied */
968 	i = ctx->ctx_aflags;
969 	if ((i & ctx->ctx_mta_aflags) != i)
970 	{
971 		smi_log(SMI_LOG_ERR,
972 			"%s: st_optionneg[%ld]: 0x%lx does not fulfill action requirements 0x%x",
973 			ctx->ctx_smfi->xxfi_name,
974 			(long) ctx->ctx_id, ctx->ctx_mta_aflags, i);
975 		return _SMFIS_ABORT;
976 	}
977 
978 	i = ctx->ctx_pflags2mta;
979 	if ((ctx->ctx_mta_pflags & i) != i)
980 	{
981 		/*
982 		**  Older MTAs do not support some protocol steps.
983 		**  As this protocol is a bit "wierd" (it asks for steps
984 		**  NOT to be taken/sent) we have to check whether we
985 		**  should turn off those "negative" requests.
986 		**  Currently these are only SMFIP_NODATA and SMFIP_NOUNKNOWN.
987 		*/
988 
989 		if (bitset(SMFIP_NODATA, ctx->ctx_pflags2mta) &&
990 		    !bitset(SMFIP_NODATA, ctx->ctx_mta_pflags))
991 			ctx->ctx_pflags2mta &= ~SMFIP_NODATA;
992 		if (bitset(SMFIP_NOUNKNOWN, ctx->ctx_pflags2mta) &&
993 		    !bitset(SMFIP_NOUNKNOWN, ctx->ctx_mta_pflags))
994 			ctx->ctx_pflags2mta &= ~SMFIP_NOUNKNOWN;
995 		i = ctx->ctx_pflags2mta;
996 	}
997 
998 	if ((ctx->ctx_mta_pflags & i) != i)
999 	{
1000 		smi_log(SMI_LOG_ERR,
1001 			"%s: st_optionneg[%ld]: 0x%lx does not fulfill protocol requirements 0x%x",
1002 			ctx->ctx_smfi->xxfi_name,
1003 			(long) ctx->ctx_id, ctx->ctx_mta_pflags, i);
1004 		return _SMFIS_ABORT;
1005 	}
1006 	fix_stm(ctx);
1007 
1008 	if (ctx->ctx_dbg > 3)
1009 		sm_dprintf("[%ld] milter_negotiate:"
1010 			" mta_actions=0x%lx, mta_flags=0x%lx"
1011 			" actions=0x%lx, flags=0x%lx\n"
1012 			, (long) ctx->ctx_id
1013 			, ctx->ctx_mta_aflags, ctx->ctx_mta_pflags
1014 			, ctx->ctx_aflags, ctx->ctx_pflags);
1015 
1016 	return _SMFIS_OPTIONS;
1017 }
1018 
1019 /*
1020 **  ST_CONNECTINFO -- receive connection information
1021 **
1022 **	Parameters:
1023 **		g -- generic argument structure
1024 **
1025 **	Returns:
1026 **		continue or filter-specified value
1027 */
1028 
1029 static int
1030 st_connectinfo(g)
1031 	genarg *g;
1032 {
1033 	size_t l;
1034 	size_t i;
1035 	char *s, family;
1036 	unsigned short port = 0;
1037 	_SOCK_ADDR sockaddr;
1038 	sfsistat (*fi_connect) __P((SMFICTX *, char *, _SOCK_ADDR *));
1039 
1040 	if (g == NULL)
1041 		return _SMFIS_ABORT;
1042 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
1043 	if (g->a_ctx->ctx_smfi == NULL ||
1044 	    (fi_connect = g->a_ctx->ctx_smfi->xxfi_connect) == NULL)
1045 		return SMFIS_CONTINUE;
1046 
1047 	s = g->a_buf;
1048 	i = 0;
1049 	l = g->a_len;
1050 	while (s[i] != '\0' && i <= l)
1051 		++i;
1052 	if (i + 1 >= l)
1053 		return _SMFIS_ABORT;
1054 
1055 	/* Move past trailing \0 in host string */
1056 	i++;
1057 	family = s[i++];
1058 	(void) memset(&sockaddr, '\0', sizeof sockaddr);
1059 	if (family != SMFIA_UNKNOWN)
1060 	{
1061 		if (i + sizeof port >= l)
1062 		{
1063 			smi_log(SMI_LOG_ERR,
1064 				"%s: connect[%ld]: wrong len %d >= %d",
1065 				g->a_ctx->ctx_smfi->xxfi_name,
1066 				(long) g->a_ctx->ctx_id, (int) i, (int) l);
1067 			return _SMFIS_ABORT;
1068 		}
1069 		(void) memcpy((void *) &port, (void *) (s + i),
1070 			      sizeof port);
1071 		i += sizeof port;
1072 
1073 		/* make sure string is terminated */
1074 		if (s[l - 1] != '\0')
1075 			return _SMFIS_ABORT;
1076 # if NETINET
1077 		if (family == SMFIA_INET)
1078 		{
1079 			if (inet_aton(s + i, (struct in_addr *) &sockaddr.sin.sin_addr)
1080 			    != 1)
1081 			{
1082 				smi_log(SMI_LOG_ERR,
1083 					"%s: connect[%ld]: inet_aton failed",
1084 					g->a_ctx->ctx_smfi->xxfi_name,
1085 					(long) g->a_ctx->ctx_id);
1086 				return _SMFIS_ABORT;
1087 			}
1088 			sockaddr.sa.sa_family = AF_INET;
1089 			if (port > 0)
1090 				sockaddr.sin.sin_port = port;
1091 		}
1092 		else
1093 # endif /* NETINET */
1094 # if NETINET6
1095 		if (family == SMFIA_INET6)
1096 		{
1097 			if (mi_inet_pton(AF_INET6, s + i,
1098 					 &sockaddr.sin6.sin6_addr) != 1)
1099 			{
1100 				smi_log(SMI_LOG_ERR,
1101 					"%s: connect[%ld]: mi_inet_pton failed",
1102 					g->a_ctx->ctx_smfi->xxfi_name,
1103 					(long) g->a_ctx->ctx_id);
1104 				return _SMFIS_ABORT;
1105 			}
1106 			sockaddr.sa.sa_family = AF_INET6;
1107 			if (port > 0)
1108 				sockaddr.sin6.sin6_port = port;
1109 		}
1110 		else
1111 # endif /* NETINET6 */
1112 # if NETUNIX
1113 		if (family == SMFIA_UNIX)
1114 		{
1115 			if (sm_strlcpy(sockaddr.sunix.sun_path, s + i,
1116 			    sizeof sockaddr.sunix.sun_path) >=
1117 			    sizeof sockaddr.sunix.sun_path)
1118 			{
1119 				smi_log(SMI_LOG_ERR,
1120 					"%s: connect[%ld]: path too long",
1121 					g->a_ctx->ctx_smfi->xxfi_name,
1122 					(long) g->a_ctx->ctx_id);
1123 				return _SMFIS_ABORT;
1124 			}
1125 			sockaddr.sunix.sun_family = AF_UNIX;
1126 		}
1127 		else
1128 # endif /* NETUNIX */
1129 		{
1130 			smi_log(SMI_LOG_ERR,
1131 				"%s: connect[%ld]: unknown family %d",
1132 				g->a_ctx->ctx_smfi->xxfi_name,
1133 				(long) g->a_ctx->ctx_id, family);
1134 			return _SMFIS_ABORT;
1135 		}
1136 	}
1137 	return (*fi_connect)(g->a_ctx, g->a_buf,
1138 			     family != SMFIA_UNKNOWN ? &sockaddr : NULL);
1139 }
1140 
1141 /*
1142 **  ST_EOH -- end of headers
1143 **
1144 **	Parameters:
1145 **		g -- generic argument structure
1146 **
1147 **	Returns:
1148 **		continue or filter-specified value
1149 */
1150 
1151 static int
1152 st_eoh(g)
1153 	genarg *g;
1154 {
1155 	sfsistat (*fi_eoh) __P((SMFICTX *));
1156 
1157 	if (g == NULL)
1158 		return _SMFIS_ABORT;
1159 	if (g->a_ctx->ctx_smfi != NULL &&
1160 	    (fi_eoh = g->a_ctx->ctx_smfi->xxfi_eoh) != NULL)
1161 		return (*fi_eoh)(g->a_ctx);
1162 	return SMFIS_CONTINUE;
1163 }
1164 
1165 /*
1166 **  ST_DATA -- DATA command
1167 **
1168 **	Parameters:
1169 **		g -- generic argument structure
1170 **
1171 **	Returns:
1172 **		continue or filter-specified value
1173 */
1174 
1175 static int
1176 st_data(g)
1177 	genarg *g;
1178 {
1179 	sfsistat (*fi_data) __P((SMFICTX *));
1180 
1181 	if (g == NULL)
1182 		return _SMFIS_ABORT;
1183 	if (g->a_ctx->ctx_smfi != NULL &&
1184 	    g->a_ctx->ctx_smfi->xxfi_version > 3 &&
1185 	    (fi_data = g->a_ctx->ctx_smfi->xxfi_data) != NULL)
1186 		return (*fi_data)(g->a_ctx);
1187 	return SMFIS_CONTINUE;
1188 }
1189 
1190 /*
1191 **  ST_HELO -- helo/ehlo command
1192 **
1193 **	Parameters:
1194 **		g -- generic argument structure
1195 **
1196 **	Returns:
1197 **		continue or filter-specified value
1198 */
1199 
1200 static int
1201 st_helo(g)
1202 	genarg *g;
1203 {
1204 	sfsistat (*fi_helo) __P((SMFICTX *, char *));
1205 
1206 	if (g == NULL)
1207 		return _SMFIS_ABORT;
1208 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
1209 	if (g->a_ctx->ctx_smfi != NULL &&
1210 	    (fi_helo = g->a_ctx->ctx_smfi->xxfi_helo) != NULL)
1211 	{
1212 		/* paranoia: check for terminating '\0' */
1213 		if (g->a_len == 0 || g->a_buf[g->a_len - 1] != '\0')
1214 			return MI_FAILURE;
1215 		return (*fi_helo)(g->a_ctx, g->a_buf);
1216 	}
1217 	return SMFIS_CONTINUE;
1218 }
1219 
1220 /*
1221 **  ST_HEADER -- header line
1222 **
1223 **	Parameters:
1224 **		g -- generic argument structure
1225 **
1226 **	Returns:
1227 **		continue or filter-specified value
1228 */
1229 
1230 static int
1231 st_header(g)
1232 	genarg *g;
1233 {
1234 	char *hf, *hv;
1235 	sfsistat (*fi_header) __P((SMFICTX *, char *, char *));
1236 
1237 	if (g == NULL)
1238 		return _SMFIS_ABORT;
1239 	if (g->a_ctx->ctx_smfi == NULL ||
1240 	    (fi_header = g->a_ctx->ctx_smfi->xxfi_header) == NULL)
1241 		return SMFIS_CONTINUE;
1242 	if (dec_arg2(g->a_buf, g->a_len, &hf, &hv) == MI_SUCCESS)
1243 		return (*fi_header)(g->a_ctx, hf, hv);
1244 	else
1245 		return _SMFIS_ABORT;
1246 }
1247 
1248 #define ARGV_FCT(lf, rf, idx)					\
1249 	char **argv;						\
1250 	sfsistat (*lf) __P((SMFICTX *, char **));		\
1251 	int r;							\
1252 								\
1253 	if (g == NULL)						\
1254 		return _SMFIS_ABORT;				\
1255 	mi_clr_macros(g->a_ctx, g->a_idx + 1);			\
1256 	if (g->a_ctx->ctx_smfi == NULL ||			\
1257 	    (lf = g->a_ctx->ctx_smfi->rf) == NULL)		\
1258 		return SMFIS_CONTINUE;				\
1259 	if ((argv = dec_argv(g->a_buf, g->a_len)) == NULL)	\
1260 		return _SMFIS_ABORT;				\
1261 	r = (*lf)(g->a_ctx, argv);				\
1262 	free(argv);						\
1263 	return r;
1264 
1265 /*
1266 **  ST_SENDER -- MAIL FROM command
1267 **
1268 **	Parameters:
1269 **		g -- generic argument structure
1270 **
1271 **	Returns:
1272 **		continue or filter-specified value
1273 */
1274 
1275 static int
1276 st_sender(g)
1277 	genarg *g;
1278 {
1279 	ARGV_FCT(fi_envfrom, xxfi_envfrom, CI_MAIL)
1280 }
1281 
1282 /*
1283 **  ST_RCPT -- RCPT TO command
1284 **
1285 **	Parameters:
1286 **		g -- generic argument structure
1287 **
1288 **	Returns:
1289 **		continue or filter-specified value
1290 */
1291 
1292 static int
1293 st_rcpt(g)
1294 	genarg *g;
1295 {
1296 	ARGV_FCT(fi_envrcpt, xxfi_envrcpt, CI_RCPT)
1297 }
1298 
1299 /*
1300 **  ST_UNKNOWN -- unrecognized or unimplemented command
1301 **
1302 **	Parameters:
1303 **		g -- generic argument structure
1304 **
1305 **	Returns:
1306 **		continue or filter-specified value
1307 */
1308 
1309 static int
1310 st_unknown(g)
1311 	genarg *g;
1312 {
1313 	sfsistat (*fi_unknown) __P((SMFICTX *, const char *));
1314 
1315 	if (g == NULL)
1316 		return _SMFIS_ABORT;
1317 	if (g->a_ctx->ctx_smfi != NULL &&
1318 	    g->a_ctx->ctx_smfi->xxfi_version > 2 &&
1319 	    (fi_unknown = g->a_ctx->ctx_smfi->xxfi_unknown) != NULL)
1320 		return (*fi_unknown)(g->a_ctx, (const char *) g->a_buf);
1321 	return SMFIS_CONTINUE;
1322 }
1323 
1324 /*
1325 **  ST_MACROS -- deal with macros received from the MTA
1326 **
1327 **	Parameters:
1328 **		g -- generic argument structure
1329 **
1330 **	Returns:
1331 **		continue/keep
1332 **
1333 **	Side effects:
1334 **		set pointer in macro array to current values.
1335 */
1336 
1337 static int
1338 st_macros(g)
1339 	genarg *g;
1340 {
1341 	int i;
1342 	char **argv;
1343 
1344 	if (g == NULL || g->a_len < 1)
1345 		return _SMFIS_FAIL;
1346 	if ((argv = dec_argv(g->a_buf + 1, g->a_len - 1)) == NULL)
1347 		return _SMFIS_FAIL;
1348 	switch (g->a_buf[0])
1349 	{
1350 	  case SMFIC_CONNECT:
1351 		i = CI_CONN;
1352 		break;
1353 	  case SMFIC_HELO:
1354 		i = CI_HELO;
1355 		break;
1356 	  case SMFIC_MAIL:
1357 		i = CI_MAIL;
1358 		break;
1359 	  case SMFIC_RCPT:
1360 		i = CI_RCPT;
1361 		break;
1362 	  case SMFIC_DATA:
1363 		i = CI_DATA;
1364 		break;
1365 	  case SMFIC_BODYEOB:
1366 		i = CI_EOM;
1367 		break;
1368 	  case SMFIC_EOH:
1369 		i = CI_EOH;
1370 		break;
1371 	  default:
1372 		free(argv);
1373 		return _SMFIS_FAIL;
1374 	}
1375 	if (g->a_ctx->ctx_mac_ptr[i] != NULL)
1376 		free(g->a_ctx->ctx_mac_ptr[i]);
1377 	if (g->a_ctx->ctx_mac_buf[i] != NULL)
1378 		free(g->a_ctx->ctx_mac_buf[i]);
1379 	g->a_ctx->ctx_mac_ptr[i] = argv;
1380 	g->a_ctx->ctx_mac_buf[i] = g->a_buf;
1381 	return _SMFIS_KEEP;
1382 }
1383 
1384 /*
1385 **  ST_QUIT -- quit command
1386 **
1387 **	Parameters:
1388 **		g -- generic argument structure
1389 **
1390 **	Returns:
1391 **		noreply
1392 */
1393 
1394 /* ARGSUSED */
1395 static int
1396 st_quit(g)
1397 	genarg *g;
1398 {
1399 	sfsistat (*fi_close) __P((SMFICTX *));
1400 
1401 	if (g == NULL)
1402 		return _SMFIS_ABORT;
1403 	if (g->a_ctx->ctx_smfi != NULL &&
1404 	    (fi_close = g->a_ctx->ctx_smfi->xxfi_close) != NULL)
1405 		(void) (*fi_close)(g->a_ctx);
1406 	mi_clr_macros(g->a_ctx, 0);
1407 	return _SMFIS_NOREPLY;
1408 }
1409 
1410 /*
1411 **  ST_BODYCHUNK -- deal with a piece of the mail body
1412 **
1413 **	Parameters:
1414 **		g -- generic argument structure
1415 **
1416 **	Returns:
1417 **		continue or filter-specified value
1418 */
1419 
1420 static int
1421 st_bodychunk(g)
1422 	genarg *g;
1423 {
1424 	sfsistat (*fi_body) __P((SMFICTX *, unsigned char *, size_t));
1425 
1426 	if (g == NULL)
1427 		return _SMFIS_ABORT;
1428 	if (g->a_ctx->ctx_smfi != NULL &&
1429 	    (fi_body = g->a_ctx->ctx_smfi->xxfi_body) != NULL)
1430 		return (*fi_body)(g->a_ctx, (unsigned char *)g->a_buf,
1431 				  g->a_len);
1432 	return SMFIS_CONTINUE;
1433 }
1434 
1435 /*
1436 **  ST_BODYEND -- deal with the last piece of the mail body
1437 **
1438 **	Parameters:
1439 **		g -- generic argument structure
1440 **
1441 **	Returns:
1442 **		continue or filter-specified value
1443 **
1444 **	Side effects:
1445 **		sends a reply for the body part (if non-empty).
1446 */
1447 
1448 static int
1449 st_bodyend(g)
1450 	genarg *g;
1451 {
1452 	sfsistat r;
1453 	sfsistat (*fi_body) __P((SMFICTX *, unsigned char *, size_t));
1454 	sfsistat (*fi_eom) __P((SMFICTX *));
1455 
1456 	if (g == NULL)
1457 		return _SMFIS_ABORT;
1458 	r = SMFIS_CONTINUE;
1459 	if (g->a_ctx->ctx_smfi != NULL)
1460 	{
1461 		if ((fi_body = g->a_ctx->ctx_smfi->xxfi_body) != NULL &&
1462 		    g->a_len > 0)
1463 		{
1464 			socket_t sd;
1465 			struct timeval timeout;
1466 
1467 			timeout.tv_sec = g->a_ctx->ctx_timeout;
1468 			timeout.tv_usec = 0;
1469 			sd = g->a_ctx->ctx_sd;
1470 			r = (*fi_body)(g->a_ctx, (unsigned char *)g->a_buf,
1471 				       g->a_len);
1472 			if (r != SMFIS_CONTINUE &&
1473 			    sendreply(r, sd, &timeout, g->a_ctx) != MI_SUCCESS)
1474 				return _SMFIS_ABORT;
1475 		}
1476 	}
1477 	if (r == SMFIS_CONTINUE &&
1478 	    (fi_eom = g->a_ctx->ctx_smfi->xxfi_eom) != NULL)
1479 		return (*fi_eom)(g->a_ctx);
1480 	return r;
1481 }
1482 
1483 /*
1484 **  ST_ABORTFCT -- deal with aborts
1485 **
1486 **	Parameters:
1487 **		g -- generic argument structure
1488 **
1489 **	Returns:
1490 **		abort or filter-specified value
1491 */
1492 
1493 static int
1494 st_abortfct(g)
1495 	genarg *g;
1496 {
1497 	sfsistat (*fi_abort) __P((SMFICTX *));
1498 
1499 	if (g == NULL)
1500 		return _SMFIS_ABORT;
1501 	if (g != NULL && g->a_ctx->ctx_smfi != NULL &&
1502 	    (fi_abort = g->a_ctx->ctx_smfi->xxfi_abort) != NULL)
1503 		(void) (*fi_abort)(g->a_ctx);
1504 	return _SMFIS_NOREPLY;
1505 }
1506 
1507 /*
1508 **  TRANS_OK -- is the state transition ok?
1509 **
1510 **	Parameters:
1511 **		old -- old state
1512 **		new -- new state
1513 **
1514 **	Returns:
1515 **		state transition ok
1516 */
1517 
1518 static bool
1519 trans_ok(old, new)
1520 	int old, new;
1521 {
1522 	int s, n;
1523 
1524 	s = old;
1525 	if (s >= SIZE_NEXT_STATES)
1526 		return false;
1527 	do
1528 	{
1529 		/* is this state transition allowed? */
1530 		if ((MI_MASK(new) & next_states[s]) != 0)
1531 			return true;
1532 
1533 		/*
1534 		**  no: try next state;
1535 		**  this works since the relevant states are ordered
1536 		**  strict sequentially
1537 		*/
1538 
1539 		n = s + 1;
1540 		if (n >= SIZE_NEXT_STATES)
1541 			return false;
1542 
1543 		/*
1544 		**  can we actually "skip" this state?
1545 		**  see fix_stm() which sets this bit for those
1546 		**  states which the filter program is not interested in
1547 		*/
1548 
1549 		if (bitset(NX_SKIP, next_states[n]))
1550 			s = n;
1551 		else
1552 			return false;
1553 	} while (s < SIZE_NEXT_STATES);
1554 	return false;
1555 }
1556 
1557 /*
1558 **  FIX_STM -- add "skip" bits to the state transition table
1559 **
1560 **	Parameters:
1561 **		ctx -- context structure
1562 **
1563 **	Returns:
1564 **		None.
1565 **
1566 **	Side effects:
1567 **		may change state transition table.
1568 */
1569 
1570 static void
1571 fix_stm(ctx)
1572 	SMFICTX_PTR ctx;
1573 {
1574 	unsigned long fl;
1575 
1576 	if (ctx == NULL || ctx->ctx_smfi == NULL)
1577 		return;
1578 	fl = ctx->ctx_pflags;
1579 	if (bitset(SMFIP_NOCONNECT, fl))
1580 		next_states[ST_CONN] |= NX_SKIP;
1581 	if (bitset(SMFIP_NOHELO, fl))
1582 		next_states[ST_HELO] |= NX_SKIP;
1583 	if (bitset(SMFIP_NOMAIL, fl))
1584 		next_states[ST_MAIL] |= NX_SKIP;
1585 	if (bitset(SMFIP_NORCPT, fl))
1586 		next_states[ST_RCPT] |= NX_SKIP;
1587 	if (bitset(SMFIP_NOHDRS, fl))
1588 		next_states[ST_HDRS] |= NX_SKIP;
1589 	if (bitset(SMFIP_NOEOH, fl))
1590 		next_states[ST_EOHS] |= NX_SKIP;
1591 	if (bitset(SMFIP_NOBODY, fl))
1592 		next_states[ST_BODY] |= NX_SKIP;
1593 	if (bitset(SMFIP_NODATA, fl))
1594 		next_states[ST_DATA] |= NX_SKIP;
1595 	if (bitset(SMFIP_NOUNKNOWN, fl))
1596 		next_states[ST_UNKN] |= NX_SKIP;
1597 }
1598 
1599 /*
1600 **  DEC_ARGV -- split a buffer into a list of strings, NULL terminated
1601 **
1602 **	Parameters:
1603 **		buf -- buffer with several strings
1604 **		len -- length of buffer
1605 **
1606 **	Returns:
1607 **		array of pointers to the individual strings
1608 */
1609 
1610 static char **
1611 dec_argv(buf, len)
1612 	char *buf;
1613 	size_t len;
1614 {
1615 	char **s;
1616 	size_t i;
1617 	int elem, nelem;
1618 
1619 	nelem = 0;
1620 	for (i = 0; i < len; i++)
1621 	{
1622 		if (buf[i] == '\0')
1623 			++nelem;
1624 	}
1625 	if (nelem == 0)
1626 		return NULL;
1627 
1628 	/* last entry is only for the name */
1629 	s = (char **)malloc((nelem + 1) * (sizeof *s));
1630 	if (s == NULL)
1631 		return NULL;
1632 	s[0] = buf;
1633 	for (i = 0, elem = 0; i < len && elem < nelem; i++)
1634 	{
1635 		if (buf[i] == '\0')
1636 		{
1637 			++elem;
1638 			if (i + 1 >= len)
1639 				s[elem] = NULL;
1640 			else
1641 				s[elem] = &(buf[i + 1]);
1642 		}
1643 	}
1644 
1645 	/* overwrite last entry (already done above, just paranoia) */
1646 	s[elem] = NULL;
1647 	return s;
1648 }
1649 
1650 /*
1651 **  DEC_ARG2 -- split a buffer into two strings
1652 **
1653 **	Parameters:
1654 **		buf -- buffer with two strings
1655 **		len -- length of buffer
1656 **		s1,s2 -- pointer to result strings
1657 **
1658 **	Returns:
1659 **		MI_FAILURE/MI_SUCCESS
1660 */
1661 
1662 static int
1663 dec_arg2(buf, len, s1, s2)
1664 	char *buf;
1665 	size_t len;
1666 	char **s1;
1667 	char **s2;
1668 {
1669 	size_t i;
1670 
1671 	/* paranoia: check for terminating '\0' */
1672 	if (len == 0 || buf[len - 1] != '\0')
1673 		return MI_FAILURE;
1674 	*s1 = buf;
1675 	for (i = 1; i < len && buf[i] != '\0'; i++)
1676 		continue;
1677 	if (i >= len - 1)
1678 		return MI_FAILURE;
1679 	*s2 = buf + i + 1;
1680 	return MI_SUCCESS;
1681 }
1682 
1683 /*
1684 **  SENDOK -- is it ok for the filter to send stuff to the MTA?
1685 **
1686 **	Parameters:
1687 **		ctx -- context structure
1688 **		flag -- flag to check
1689 **
1690 **	Returns:
1691 **		sending allowed (in current state)
1692 */
1693 
1694 bool
1695 mi_sendok(ctx, flag)
1696 	SMFICTX_PTR ctx;
1697 	int flag;
1698 {
1699 	if (ctx == NULL || ctx->ctx_smfi == NULL)
1700 		return false;
1701 
1702 	/* did the milter request this operation? */
1703 	if (flag != 0 && !bitset(flag, ctx->ctx_aflags))
1704 		return false;
1705 
1706 	/* are we in the correct state? It must be "End of Message". */
1707 	return ctx->ctx_state == ST_ENDM;
1708 }
1709 
1710 #if _FFR_WORKERS_POOL
1711 /*
1712 **  MI_RD_SOCKET_READY - checks if the socket is ready for read(2)
1713 **
1714 **	Parameters:
1715 **		sd -- socket_t
1716 **
1717 **	Returns:
1718 **		true iff socket is ready for read(2)
1719 */
1720 
1721 #define MI_RD_CMD_TO  1
1722 #define MI_RD_MAX_ERR 16
1723 
1724 static bool
1725 mi_rd_socket_ready (sd)
1726 	socket_t sd;
1727 {
1728 	int n;
1729 	int nerr = 0;
1730 #if SM_CONF_POLL
1731 	struct pollfd pfd;
1732 #else /* SM_CONF_POLL */
1733 	fd_set	rd_set, exc_set;
1734 #endif /* SM_CONF_POLL */
1735 
1736 	do
1737 	{
1738 #if SM_CONF_POLL
1739 		pfd.fd = sd;
1740 		pfd.events = POLLIN;
1741 		pfd.revents = 0;
1742 
1743 		n = poll(&pfd, 1, MI_RD_CMD_TO);
1744 #else /* SM_CONF_POLL */
1745 		struct timeval timeout;
1746 
1747 		FD_ZERO(&rd_set);
1748 		FD_ZERO(&exc_set);
1749 		FD_SET(sd, &rd_set);
1750 		FD_SET(sd, &exc_set);
1751 
1752 		timeout.tv_sec = MI_RD_CMD_TO / 1000;
1753 		timeout.tv_usec = 0;
1754 		n = select(sd + 1, &rd_set, NULL, &exc_set, &timeout);
1755 #endif /* SM_CONF_POLL */
1756 
1757 		if (n < 0)
1758 		{
1759 			if (errno == EINTR)
1760 			{
1761 				nerr++;
1762 				continue;
1763 			}
1764 			return true;
1765 		}
1766 
1767 		if (n == 0)
1768 			return false;
1769 		break;
1770 	} while (nerr < MI_RD_MAX_ERR);
1771 	if (nerr >= MI_RD_MAX_ERR)
1772 		return false;
1773 
1774 #if SM_CONF_POLL
1775 	return (pfd.revents != 0);
1776 #else /* SM_CONF_POLL */
1777 	return FD_ISSET(sd, &rd_set) || FD_ISSET(sd, &exc_set);
1778 #endif /* SM_CONF_POLL */
1779 }
1780 #endif /* _FFR_WORKERS_POOL */
1781