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