xref: /titanic_52/usr/src/cmd/sendmail/libmilter/engine.c (revision a83cadce5d3331b64803bfc641036cec23602c74)
1 /*
2  *  Copyright (c) 1999-2004, 2006, 2007 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.159 2007/04/23 22:22:50 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 
1007 	if (ctx->ctx_dbg > 3)
1008 		sm_dprintf("[%ld] milter_negotiate:"
1009 			" mta_actions=0x%lx, mta_flags=0x%lx"
1010 			" actions=0x%lx, flags=0x%lx\n"
1011 			, (long) ctx->ctx_id
1012 			, ctx->ctx_mta_aflags, ctx->ctx_mta_pflags
1013 			, ctx->ctx_aflags, ctx->ctx_pflags);
1014 
1015 	return _SMFIS_OPTIONS;
1016 }
1017 
1018 /*
1019 **  ST_CONNECTINFO -- receive connection information
1020 **
1021 **	Parameters:
1022 **		g -- generic argument structure
1023 **
1024 **	Returns:
1025 **		continue or filter-specified value
1026 */
1027 
1028 static int
1029 st_connectinfo(g)
1030 	genarg *g;
1031 {
1032 	size_t l;
1033 	size_t i;
1034 	char *s, family;
1035 	unsigned short port = 0;
1036 	_SOCK_ADDR sockaddr;
1037 	sfsistat (*fi_connect) __P((SMFICTX *, char *, _SOCK_ADDR *));
1038 
1039 	if (g == NULL)
1040 		return _SMFIS_ABORT;
1041 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
1042 	if (g->a_ctx->ctx_smfi == NULL ||
1043 	    (fi_connect = g->a_ctx->ctx_smfi->xxfi_connect) == NULL)
1044 		return SMFIS_CONTINUE;
1045 
1046 	s = g->a_buf;
1047 	i = 0;
1048 	l = g->a_len;
1049 	while (s[i] != '\0' && i <= l)
1050 		++i;
1051 	if (i + 1 >= l)
1052 		return _SMFIS_ABORT;
1053 
1054 	/* Move past trailing \0 in host string */
1055 	i++;
1056 	family = s[i++];
1057 	(void) memset(&sockaddr, '\0', sizeof sockaddr);
1058 	if (family != SMFIA_UNKNOWN)
1059 	{
1060 		if (i + sizeof port >= l)
1061 		{
1062 			smi_log(SMI_LOG_ERR,
1063 				"%s: connect[%ld]: wrong len %d >= %d",
1064 				g->a_ctx->ctx_smfi->xxfi_name,
1065 				(long) g->a_ctx->ctx_id, (int) i, (int) l);
1066 			return _SMFIS_ABORT;
1067 		}
1068 		(void) memcpy((void *) &port, (void *) (s + i),
1069 			      sizeof port);
1070 		i += sizeof port;
1071 
1072 		/* make sure string is terminated */
1073 		if (s[l - 1] != '\0')
1074 			return _SMFIS_ABORT;
1075 # if NETINET
1076 		if (family == SMFIA_INET)
1077 		{
1078 			if (inet_aton(s + i, (struct in_addr *) &sockaddr.sin.sin_addr)
1079 			    != 1)
1080 			{
1081 				smi_log(SMI_LOG_ERR,
1082 					"%s: connect[%ld]: inet_aton failed",
1083 					g->a_ctx->ctx_smfi->xxfi_name,
1084 					(long) g->a_ctx->ctx_id);
1085 				return _SMFIS_ABORT;
1086 			}
1087 			sockaddr.sa.sa_family = AF_INET;
1088 			if (port > 0)
1089 				sockaddr.sin.sin_port = port;
1090 		}
1091 		else
1092 # endif /* NETINET */
1093 # if NETINET6
1094 		if (family == SMFIA_INET6)
1095 		{
1096 			if (mi_inet_pton(AF_INET6, s + i,
1097 					 &sockaddr.sin6.sin6_addr) != 1)
1098 			{
1099 				smi_log(SMI_LOG_ERR,
1100 					"%s: connect[%ld]: mi_inet_pton failed",
1101 					g->a_ctx->ctx_smfi->xxfi_name,
1102 					(long) g->a_ctx->ctx_id);
1103 				return _SMFIS_ABORT;
1104 			}
1105 			sockaddr.sa.sa_family = AF_INET6;
1106 			if (port > 0)
1107 				sockaddr.sin6.sin6_port = port;
1108 		}
1109 		else
1110 # endif /* NETINET6 */
1111 # if NETUNIX
1112 		if (family == SMFIA_UNIX)
1113 		{
1114 			if (sm_strlcpy(sockaddr.sunix.sun_path, s + i,
1115 			    sizeof sockaddr.sunix.sun_path) >=
1116 			    sizeof sockaddr.sunix.sun_path)
1117 			{
1118 				smi_log(SMI_LOG_ERR,
1119 					"%s: connect[%ld]: path too long",
1120 					g->a_ctx->ctx_smfi->xxfi_name,
1121 					(long) g->a_ctx->ctx_id);
1122 				return _SMFIS_ABORT;
1123 			}
1124 			sockaddr.sunix.sun_family = AF_UNIX;
1125 		}
1126 		else
1127 # endif /* NETUNIX */
1128 		{
1129 			smi_log(SMI_LOG_ERR,
1130 				"%s: connect[%ld]: unknown family %d",
1131 				g->a_ctx->ctx_smfi->xxfi_name,
1132 				(long) g->a_ctx->ctx_id, family);
1133 			return _SMFIS_ABORT;
1134 		}
1135 	}
1136 	return (*fi_connect)(g->a_ctx, g->a_buf,
1137 			     family != SMFIA_UNKNOWN ? &sockaddr : NULL);
1138 }
1139 
1140 /*
1141 **  ST_EOH -- end of headers
1142 **
1143 **	Parameters:
1144 **		g -- generic argument structure
1145 **
1146 **	Returns:
1147 **		continue or filter-specified value
1148 */
1149 
1150 static int
1151 st_eoh(g)
1152 	genarg *g;
1153 {
1154 	sfsistat (*fi_eoh) __P((SMFICTX *));
1155 
1156 	if (g == NULL)
1157 		return _SMFIS_ABORT;
1158 	if (g->a_ctx->ctx_smfi != NULL &&
1159 	    (fi_eoh = g->a_ctx->ctx_smfi->xxfi_eoh) != NULL)
1160 		return (*fi_eoh)(g->a_ctx);
1161 	return SMFIS_CONTINUE;
1162 }
1163 
1164 /*
1165 **  ST_DATA -- DATA command
1166 **
1167 **	Parameters:
1168 **		g -- generic argument structure
1169 **
1170 **	Returns:
1171 **		continue or filter-specified value
1172 */
1173 
1174 static int
1175 st_data(g)
1176 	genarg *g;
1177 {
1178 	sfsistat (*fi_data) __P((SMFICTX *));
1179 
1180 	if (g == NULL)
1181 		return _SMFIS_ABORT;
1182 	if (g->a_ctx->ctx_smfi != NULL &&
1183 	    g->a_ctx->ctx_smfi->xxfi_version > 3 &&
1184 	    (fi_data = g->a_ctx->ctx_smfi->xxfi_data) != NULL)
1185 		return (*fi_data)(g->a_ctx);
1186 	return SMFIS_CONTINUE;
1187 }
1188 
1189 /*
1190 **  ST_HELO -- helo/ehlo command
1191 **
1192 **	Parameters:
1193 **		g -- generic argument structure
1194 **
1195 **	Returns:
1196 **		continue or filter-specified value
1197 */
1198 
1199 static int
1200 st_helo(g)
1201 	genarg *g;
1202 {
1203 	sfsistat (*fi_helo) __P((SMFICTX *, char *));
1204 
1205 	if (g == NULL)
1206 		return _SMFIS_ABORT;
1207 	mi_clr_macros(g->a_ctx, g->a_idx + 1);
1208 	if (g->a_ctx->ctx_smfi != NULL &&
1209 	    (fi_helo = g->a_ctx->ctx_smfi->xxfi_helo) != NULL)
1210 	{
1211 		/* paranoia: check for terminating '\0' */
1212 		if (g->a_len == 0 || g->a_buf[g->a_len - 1] != '\0')
1213 			return MI_FAILURE;
1214 		return (*fi_helo)(g->a_ctx, g->a_buf);
1215 	}
1216 	return SMFIS_CONTINUE;
1217 }
1218 
1219 /*
1220 **  ST_HEADER -- header line
1221 **
1222 **	Parameters:
1223 **		g -- generic argument structure
1224 **
1225 **	Returns:
1226 **		continue or filter-specified value
1227 */
1228 
1229 static int
1230 st_header(g)
1231 	genarg *g;
1232 {
1233 	char *hf, *hv;
1234 	sfsistat (*fi_header) __P((SMFICTX *, char *, char *));
1235 
1236 	if (g == NULL)
1237 		return _SMFIS_ABORT;
1238 	if (g->a_ctx->ctx_smfi == NULL ||
1239 	    (fi_header = g->a_ctx->ctx_smfi->xxfi_header) == NULL)
1240 		return SMFIS_CONTINUE;
1241 	if (dec_arg2(g->a_buf, g->a_len, &hf, &hv) == MI_SUCCESS)
1242 		return (*fi_header)(g->a_ctx, hf, hv);
1243 	else
1244 		return _SMFIS_ABORT;
1245 }
1246 
1247 #define ARGV_FCT(lf, rf, idx)					\
1248 	char **argv;						\
1249 	sfsistat (*lf) __P((SMFICTX *, char **));		\
1250 	int r;							\
1251 								\
1252 	if (g == NULL)						\
1253 		return _SMFIS_ABORT;				\
1254 	mi_clr_macros(g->a_ctx, g->a_idx + 1);			\
1255 	if (g->a_ctx->ctx_smfi == NULL ||			\
1256 	    (lf = g->a_ctx->ctx_smfi->rf) == NULL)		\
1257 		return SMFIS_CONTINUE;				\
1258 	if ((argv = dec_argv(g->a_buf, g->a_len)) == NULL)	\
1259 		return _SMFIS_ABORT;				\
1260 	r = (*lf)(g->a_ctx, argv);				\
1261 	free(argv);						\
1262 	return r;
1263 
1264 /*
1265 **  ST_SENDER -- MAIL FROM command
1266 **
1267 **	Parameters:
1268 **		g -- generic argument structure
1269 **
1270 **	Returns:
1271 **		continue or filter-specified value
1272 */
1273 
1274 static int
1275 st_sender(g)
1276 	genarg *g;
1277 {
1278 	ARGV_FCT(fi_envfrom, xxfi_envfrom, CI_MAIL)
1279 }
1280 
1281 /*
1282 **  ST_RCPT -- RCPT TO command
1283 **
1284 **	Parameters:
1285 **		g -- generic argument structure
1286 **
1287 **	Returns:
1288 **		continue or filter-specified value
1289 */
1290 
1291 static int
1292 st_rcpt(g)
1293 	genarg *g;
1294 {
1295 	ARGV_FCT(fi_envrcpt, xxfi_envrcpt, CI_RCPT)
1296 }
1297 
1298 /*
1299 **  ST_UNKNOWN -- unrecognized or unimplemented command
1300 **
1301 **	Parameters:
1302 **		g -- generic argument structure
1303 **
1304 **	Returns:
1305 **		continue or filter-specified value
1306 */
1307 
1308 static int
1309 st_unknown(g)
1310 	genarg *g;
1311 {
1312 	sfsistat (*fi_unknown) __P((SMFICTX *, const char *));
1313 
1314 	if (g == NULL)
1315 		return _SMFIS_ABORT;
1316 	if (g->a_ctx->ctx_smfi != NULL &&
1317 	    g->a_ctx->ctx_smfi->xxfi_version > 2 &&
1318 	    (fi_unknown = g->a_ctx->ctx_smfi->xxfi_unknown) != NULL)
1319 		return (*fi_unknown)(g->a_ctx, (const char *) g->a_buf);
1320 	return SMFIS_CONTINUE;
1321 }
1322 
1323 /*
1324 **  ST_MACROS -- deal with macros received from the MTA
1325 **
1326 **	Parameters:
1327 **		g -- generic argument structure
1328 **
1329 **	Returns:
1330 **		continue/keep
1331 **
1332 **	Side effects:
1333 **		set pointer in macro array to current values.
1334 */
1335 
1336 static int
1337 st_macros(g)
1338 	genarg *g;
1339 {
1340 	int i;
1341 	char **argv;
1342 
1343 	if (g == NULL || g->a_len < 1)
1344 		return _SMFIS_FAIL;
1345 	if ((argv = dec_argv(g->a_buf + 1, g->a_len - 1)) == NULL)
1346 		return _SMFIS_FAIL;
1347 	switch (g->a_buf[0])
1348 	{
1349 	  case SMFIC_CONNECT:
1350 		i = CI_CONN;
1351 		break;
1352 	  case SMFIC_HELO:
1353 		i = CI_HELO;
1354 		break;
1355 	  case SMFIC_MAIL:
1356 		i = CI_MAIL;
1357 		break;
1358 	  case SMFIC_RCPT:
1359 		i = CI_RCPT;
1360 		break;
1361 	  case SMFIC_DATA:
1362 		i = CI_DATA;
1363 		break;
1364 	  case SMFIC_BODYEOB:
1365 		i = CI_EOM;
1366 		break;
1367 	  case SMFIC_EOH:
1368 		i = CI_EOH;
1369 		break;
1370 	  default:
1371 		free(argv);
1372 		return _SMFIS_FAIL;
1373 	}
1374 	if (g->a_ctx->ctx_mac_ptr[i] != NULL)
1375 		free(g->a_ctx->ctx_mac_ptr[i]);
1376 	if (g->a_ctx->ctx_mac_buf[i] != NULL)
1377 		free(g->a_ctx->ctx_mac_buf[i]);
1378 	g->a_ctx->ctx_mac_ptr[i] = argv;
1379 	g->a_ctx->ctx_mac_buf[i] = g->a_buf;
1380 	return _SMFIS_KEEP;
1381 }
1382 
1383 /*
1384 **  ST_QUIT -- quit command
1385 **
1386 **	Parameters:
1387 **		g -- generic argument structure
1388 **
1389 **	Returns:
1390 **		noreply
1391 */
1392 
1393 /* ARGSUSED */
1394 static int
1395 st_quit(g)
1396 	genarg *g;
1397 {
1398 	sfsistat (*fi_close) __P((SMFICTX *));
1399 
1400 	if (g == NULL)
1401 		return _SMFIS_ABORT;
1402 	if (g->a_ctx->ctx_smfi != NULL &&
1403 	    (fi_close = g->a_ctx->ctx_smfi->xxfi_close) != NULL)
1404 		(void) (*fi_close)(g->a_ctx);
1405 	mi_clr_macros(g->a_ctx, 0);
1406 	return _SMFIS_NOREPLY;
1407 }
1408 
1409 /*
1410 **  ST_BODYCHUNK -- deal with a piece of the mail body
1411 **
1412 **	Parameters:
1413 **		g -- generic argument structure
1414 **
1415 **	Returns:
1416 **		continue or filter-specified value
1417 */
1418 
1419 static int
1420 st_bodychunk(g)
1421 	genarg *g;
1422 {
1423 	sfsistat (*fi_body) __P((SMFICTX *, unsigned char *, size_t));
1424 
1425 	if (g == NULL)
1426 		return _SMFIS_ABORT;
1427 	if (g->a_ctx->ctx_smfi != NULL &&
1428 	    (fi_body = g->a_ctx->ctx_smfi->xxfi_body) != NULL)
1429 		return (*fi_body)(g->a_ctx, (unsigned char *)g->a_buf,
1430 				  g->a_len);
1431 	return SMFIS_CONTINUE;
1432 }
1433 
1434 /*
1435 **  ST_BODYEND -- deal with the last piece of the mail body
1436 **
1437 **	Parameters:
1438 **		g -- generic argument structure
1439 **
1440 **	Returns:
1441 **		continue or filter-specified value
1442 **
1443 **	Side effects:
1444 **		sends a reply for the body part (if non-empty).
1445 */
1446 
1447 static int
1448 st_bodyend(g)
1449 	genarg *g;
1450 {
1451 	sfsistat r;
1452 	sfsistat (*fi_body) __P((SMFICTX *, unsigned char *, size_t));
1453 	sfsistat (*fi_eom) __P((SMFICTX *));
1454 
1455 	if (g == NULL)
1456 		return _SMFIS_ABORT;
1457 	r = SMFIS_CONTINUE;
1458 	if (g->a_ctx->ctx_smfi != NULL)
1459 	{
1460 		if ((fi_body = g->a_ctx->ctx_smfi->xxfi_body) != NULL &&
1461 		    g->a_len > 0)
1462 		{
1463 			socket_t sd;
1464 			struct timeval timeout;
1465 
1466 			timeout.tv_sec = g->a_ctx->ctx_timeout;
1467 			timeout.tv_usec = 0;
1468 			sd = g->a_ctx->ctx_sd;
1469 			r = (*fi_body)(g->a_ctx, (unsigned char *)g->a_buf,
1470 				       g->a_len);
1471 			if (r != SMFIS_CONTINUE &&
1472 			    sendreply(r, sd, &timeout, g->a_ctx) != MI_SUCCESS)
1473 				return _SMFIS_ABORT;
1474 		}
1475 	}
1476 	if (r == SMFIS_CONTINUE &&
1477 	    (fi_eom = g->a_ctx->ctx_smfi->xxfi_eom) != NULL)
1478 		return (*fi_eom)(g->a_ctx);
1479 	return r;
1480 }
1481 
1482 /*
1483 **  ST_ABORTFCT -- deal with aborts
1484 **
1485 **	Parameters:
1486 **		g -- generic argument structure
1487 **
1488 **	Returns:
1489 **		abort or filter-specified value
1490 */
1491 
1492 static int
1493 st_abortfct(g)
1494 	genarg *g;
1495 {
1496 	sfsistat (*fi_abort) __P((SMFICTX *));
1497 
1498 	if (g == NULL)
1499 		return _SMFIS_ABORT;
1500 	if (g != NULL && g->a_ctx->ctx_smfi != NULL &&
1501 	    (fi_abort = g->a_ctx->ctx_smfi->xxfi_abort) != NULL)
1502 		(void) (*fi_abort)(g->a_ctx);
1503 	return _SMFIS_NOREPLY;
1504 }
1505 
1506 /*
1507 **  TRANS_OK -- is the state transition ok?
1508 **
1509 **	Parameters:
1510 **		old -- old state
1511 **		new -- new state
1512 **
1513 **	Returns:
1514 **		state transition ok
1515 */
1516 
1517 static bool
1518 trans_ok(old, new)
1519 	int old, new;
1520 {
1521 	int s, n;
1522 
1523 	s = old;
1524 	if (s >= SIZE_NEXT_STATES)
1525 		return false;
1526 	do
1527 	{
1528 		/* is this state transition allowed? */
1529 		if ((MI_MASK(new) & next_states[s]) != 0)
1530 			return true;
1531 
1532 		/*
1533 		**  no: try next state;
1534 		**  this works since the relevant states are ordered
1535 		**  strict sequentially
1536 		*/
1537 
1538 		n = s + 1;
1539 		if (n >= SIZE_NEXT_STATES)
1540 			return false;
1541 
1542 		/*
1543 		**  can we actually "skip" this state?
1544 		**  see fix_stm() which sets this bit for those
1545 		**  states which the filter program is not interested in
1546 		*/
1547 
1548 		if (bitset(NX_SKIP, next_states[n]))
1549 			s = n;
1550 		else
1551 			return false;
1552 	} while (s < SIZE_NEXT_STATES);
1553 	return false;
1554 }
1555 
1556 /*
1557 **  FIX_STM -- add "skip" bits to the state transition table
1558 **
1559 **	Parameters:
1560 **		ctx -- context structure
1561 **
1562 **	Returns:
1563 **		None.
1564 **
1565 **	Side effects:
1566 **		may change state transition table.
1567 */
1568 
1569 static void
1570 fix_stm(ctx)
1571 	SMFICTX_PTR ctx;
1572 {
1573 	unsigned long fl;
1574 
1575 	if (ctx == NULL || ctx->ctx_smfi == NULL)
1576 		return;
1577 	fl = ctx->ctx_pflags;
1578 	if (bitset(SMFIP_NOCONNECT, fl))
1579 		next_states[ST_CONN] |= NX_SKIP;
1580 	if (bitset(SMFIP_NOHELO, fl))
1581 		next_states[ST_HELO] |= NX_SKIP;
1582 	if (bitset(SMFIP_NOMAIL, fl))
1583 		next_states[ST_MAIL] |= NX_SKIP;
1584 	if (bitset(SMFIP_NORCPT, fl))
1585 		next_states[ST_RCPT] |= NX_SKIP;
1586 	if (bitset(SMFIP_NOHDRS, fl))
1587 		next_states[ST_HDRS] |= NX_SKIP;
1588 	if (bitset(SMFIP_NOEOH, fl))
1589 		next_states[ST_EOHS] |= NX_SKIP;
1590 	if (bitset(SMFIP_NOBODY, fl))
1591 		next_states[ST_BODY] |= NX_SKIP;
1592 	if (bitset(SMFIP_NODATA, fl))
1593 		next_states[ST_DATA] |= NX_SKIP;
1594 	if (bitset(SMFIP_NOUNKNOWN, fl))
1595 		next_states[ST_UNKN] |= NX_SKIP;
1596 }
1597 
1598 /*
1599 **  DEC_ARGV -- split a buffer into a list of strings, NULL terminated
1600 **
1601 **	Parameters:
1602 **		buf -- buffer with several strings
1603 **		len -- length of buffer
1604 **
1605 **	Returns:
1606 **		array of pointers to the individual strings
1607 */
1608 
1609 static char **
1610 dec_argv(buf, len)
1611 	char *buf;
1612 	size_t len;
1613 {
1614 	char **s;
1615 	size_t i;
1616 	int elem, nelem;
1617 
1618 	nelem = 0;
1619 	for (i = 0; i < len; i++)
1620 	{
1621 		if (buf[i] == '\0')
1622 			++nelem;
1623 	}
1624 	if (nelem == 0)
1625 		return NULL;
1626 
1627 	/* last entry is only for the name */
1628 	s = (char **)malloc((nelem + 1) * (sizeof *s));
1629 	if (s == NULL)
1630 		return NULL;
1631 	s[0] = buf;
1632 	for (i = 0, elem = 0; i < len && elem < nelem; i++)
1633 	{
1634 		if (buf[i] == '\0')
1635 		{
1636 			++elem;
1637 			if (i + 1 >= len)
1638 				s[elem] = NULL;
1639 			else
1640 				s[elem] = &(buf[i + 1]);
1641 		}
1642 	}
1643 
1644 	/* overwrite last entry (already done above, just paranoia) */
1645 	s[elem] = NULL;
1646 	return s;
1647 }
1648 
1649 /*
1650 **  DEC_ARG2 -- split a buffer into two strings
1651 **
1652 **	Parameters:
1653 **		buf -- buffer with two strings
1654 **		len -- length of buffer
1655 **		s1,s2 -- pointer to result strings
1656 **
1657 **	Returns:
1658 **		MI_FAILURE/MI_SUCCESS
1659 */
1660 
1661 static int
1662 dec_arg2(buf, len, s1, s2)
1663 	char *buf;
1664 	size_t len;
1665 	char **s1;
1666 	char **s2;
1667 {
1668 	size_t i;
1669 
1670 	/* paranoia: check for terminating '\0' */
1671 	if (len == 0 || buf[len - 1] != '\0')
1672 		return MI_FAILURE;
1673 	*s1 = buf;
1674 	for (i = 1; i < len && buf[i] != '\0'; i++)
1675 		continue;
1676 	if (i >= len - 1)
1677 		return MI_FAILURE;
1678 	*s2 = buf + i + 1;
1679 	return MI_SUCCESS;
1680 }
1681 
1682 /*
1683 **  SENDOK -- is it ok for the filter to send stuff to the MTA?
1684 **
1685 **	Parameters:
1686 **		ctx -- context structure
1687 **		flag -- flag to check
1688 **
1689 **	Returns:
1690 **		sending allowed (in current state)
1691 */
1692 
1693 bool
1694 mi_sendok(ctx, flag)
1695 	SMFICTX_PTR ctx;
1696 	int flag;
1697 {
1698 	if (ctx == NULL || ctx->ctx_smfi == NULL)
1699 		return false;
1700 
1701 	/* did the milter request this operation? */
1702 	if (flag != 0 && !bitset(flag, ctx->ctx_aflags))
1703 		return false;
1704 
1705 	/* are we in the correct state? It must be "End of Message". */
1706 	return ctx->ctx_state == ST_ENDM;
1707 }
1708 
1709 #if _FFR_WORKERS_POOL
1710 /*
1711 **  MI_RD_SOCKET_READY - checks if the socket is ready for read(2)
1712 **
1713 **	Parameters:
1714 **		sd -- socket_t
1715 **
1716 **	Returns:
1717 **		true iff socket is ready for read(2)
1718 */
1719 
1720 #define MI_RD_CMD_TO  1
1721 #define MI_RD_MAX_ERR 16
1722 
1723 static bool
1724 mi_rd_socket_ready (sd)
1725 	socket_t sd;
1726 {
1727 	int n;
1728 	int nerr = 0;
1729 #if SM_CONF_POLL
1730 		struct pollfd pfd;
1731 #else /* SM_CONF_POLL */
1732 		fd_set	rd_set, exc_set;
1733 #endif /* SM_CONF_POLL */
1734 
1735 	do
1736 	{
1737 #if SM_CONF_POLL
1738 		pfd.fd = sd;
1739 		pfd.events = POLLIN;
1740 		pfd.revents = 0;
1741 
1742 		n = poll(&pfd, 1, MI_RD_CMD_TO);
1743 #else /* SM_CONF_POLL */
1744 		struct timeval timeout;
1745 
1746 		FD_ZERO(&rd_set);
1747 		FD_ZERO(&exc_set);
1748 		FD_SET(sd, &rd_set);
1749 		FD_SET(sd, &exc_set);
1750 
1751 		timeout.tv_sec = MI_RD_CMD_TO / 1000;
1752 		timeout.tv_usec = 0;
1753 		n = select(sd + 1, &rd_set, NULL, &exc_set, &timeout);
1754 #endif /* SM_CONF_POLL */
1755 
1756 		if (n < 0)
1757 		{
1758 			if (errno == EINTR)
1759 			{
1760 				nerr++;
1761 				continue;
1762 			}
1763 			return true;
1764 		}
1765 
1766 		if (n == 0)
1767 			return false;
1768 		break;
1769 	} while (nerr < MI_RD_MAX_ERR);
1770 	if (nerr >= MI_RD_MAX_ERR)
1771 		return false;
1772 
1773 #if SM_CONF_POLL
1774 	return (pfd.revents != 0);
1775 #else /* SM_CONF_POLL */
1776 	return FD_ISSET(sd, &rd_set) || FD_ISSET(sd, &exc_set);
1777 #endif /* SM_CONF_POLL */
1778 }
1779 #endif /* _FFR_WORKERS_POOL */
1780