npf_test_subr.c revision 1.4 1 /* $NetBSD: npf_test_subr.c,v 1.4 2012/08/15 19:47:38 rmind Exp $ */
2
3 /*
4 * NPF initialisation and handler routines.
5 *
6 * Public Domain.
7 */
8
9 #include <sys/types.h>
10 #include <net/if.h>
11 #include <net/if_types.h>
12
13 #include "npf_impl.h"
14 #include "npf_test.h"
15
16 /* State of the current stream. */
17 static npf_state_t cstream_state;
18 static void * cstream_ptr;
19 static bool cstream_retval;
20
21 static void npf_state_sample(npf_state_t *, bool);
22
23 void
24 npf_test_init(void)
25 {
26 npf_state_setsampler(npf_state_sample);
27 }
28
29 int
30 npf_test_load(const void *xml)
31 {
32 prop_dictionary_t npf_dict = prop_dictionary_internalize(xml);
33 return npfctl_reload(0, npf_dict);
34 }
35
36 unsigned
37 npf_test_addif(const char *ifname, unsigned if_idx, bool verbose)
38 {
39 ifnet_t *ifp = if_alloc(IFT_OTHER);
40
41 /*
42 * This is a "fake" interface with explicitly set index.
43 */
44 strlcpy(ifp->if_xname, ifname, sizeof(ifp->if_xname));
45 if (verbose) {
46 printf("+ Interface %s\n", ifp->if_xname);
47 }
48 ifp->if_dlt = DLT_NULL;
49 if_attach(ifp);
50 ifp->if_index = if_idx;
51 if_alloc_sadl(ifp);
52 return if_idx;
53 }
54
55 unsigned
56 npf_test_getif(const char *ifname)
57 {
58 ifnet_t *ifp = ifunit(ifname);
59 return ifp ? ifp->if_index : 0;
60 }
61
62 /*
63 * State sampler - this routine is called from inside of NPF state engine.
64 */
65 static void
66 npf_state_sample(npf_state_t *nst, bool retval)
67 {
68 /* Pointer will serve as an ID. */
69 cstream_ptr = nst;
70 memcpy(&cstream_state, nst, sizeof(npf_state_t));
71 cstream_retval = retval;
72 }
73
74 int
75 npf_test_handlepkt(const void *data, size_t len, unsigned idx,
76 bool forw, int64_t *result)
77 {
78 ifnet_t ifp = { .if_index = idx };
79 struct mbuf *m;
80 int i = 0, error;
81
82 m = mbuf_getwithdata(data, len);
83 error = npf_packet_handler(NULL, &m, &ifp, forw ? PFIL_OUT : PFIL_IN);
84 if (error) {
85 assert(m == NULL);
86 return error;
87 }
88 assert(m != NULL);
89 m_freem(m);
90
91 const int di = forw ? NPF_FLOW_FORW : NPF_FLOW_BACK;
92 npf_tcpstate_t *fstate = &cstream_state.nst_tcpst[di];
93 npf_tcpstate_t *tstate = &cstream_state.nst_tcpst[!di];
94
95 result[i++] = (intptr_t)cstream_ptr;
96 result[i++] = cstream_retval;
97 result[i++] = cstream_state.nst_state;
98
99 result[i++] = fstate->nst_end;
100 result[i++] = fstate->nst_maxend;
101 result[i++] = fstate->nst_maxwin;
102 result[i++] = fstate->nst_wscale;
103
104 result[i++] = tstate->nst_end;
105 result[i++] = tstate->nst_maxend;
106 result[i++] = tstate->nst_maxwin;
107 result[i++] = tstate->nst_wscale;
108
109 return 0;
110 }
111