]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/netinet/ipfw/ip_fw_dynamic.c
MFC r240849:
[FreeBSD/stable/8.git] / sys / netinet / ipfw / ip_fw_dynamic.c
1 /*-
2  * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28
29 #define        DEB(x)
30 #define        DDB(x) x
31
32 /*
33  * Dynamic rule support for ipfw
34  */
35
36 #include "opt_ipfw.h"
37 #include "opt_inet.h"
38 #ifndef INET
39 #error IPFIREWALL requires INET.
40 #endif /* INET */
41 #include "opt_inet6.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <net/ethernet.h> /* for ETHERTYPE_IP */
53 #include <net/if.h>
54 #include <net/vnet.h>
55
56 #include <netinet/in.h>
57 #include <netinet/ip.h>
58 #include <netinet/ip_var.h>     /* ip_defttl */
59 #include <netinet/ip_fw.h>
60 #include <netinet/ipfw/ip_fw_private.h>
61 #include <netinet/tcp_var.h>
62 #include <netinet/udp.h>
63
64 #include <netinet/ip6.h>        /* IN6_ARE_ADDR_EQUAL */
65 #ifdef INET6
66 #include <netinet6/in6_var.h>
67 #include <netinet6/ip6_var.h>
68 #endif
69
70 #include <machine/in_cksum.h>   /* XXX for in_cksum */
71
72 #ifdef MAC
73 #include <security/mac/mac_framework.h>
74 #endif
75
76 /*
77  * Description of dynamic rules.
78  *
79  * Dynamic rules are stored in lists accessed through a hash table
80  * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
81  * be modified through the sysctl variable dyn_buckets which is
82  * updated when the table becomes empty.
83  *
84  * XXX currently there is only one list, ipfw_dyn.
85  *
86  * When a packet is received, its address fields are first masked
87  * with the mask defined for the rule, then hashed, then matched
88  * against the entries in the corresponding list.
89  * Dynamic rules can be used for different purposes:
90  *  + stateful rules;
91  *  + enforcing limits on the number of sessions;
92  *  + in-kernel NAT (not implemented yet)
93  *
94  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
95  * measured in seconds and depending on the flags.
96  *
97  * The total number of dynamic rules is stored in dyn_count.
98  * The max number of dynamic rules is dyn_max. When we reach
99  * the maximum number of rules we do not create anymore. This is
100  * done to avoid consuming too much memory, but also too much
101  * time when searching on each packet (ideally, we should try instead
102  * to put a limit on the length of the list on each bucket...).
103  *
104  * Each dynamic rule holds a pointer to the parent ipfw rule so
105  * we know what action to perform. Dynamic rules are removed when
106  * the parent rule is deleted. XXX we should make them survive.
107  *
108  * There are some limitations with dynamic rules -- we do not
109  * obey the 'randomized match', and we do not do multiple
110  * passes through the firewall. XXX check the latter!!!
111  */
112
113 /*
114  * Static variables followed by global ones
115  */
116 static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
117 static VNET_DEFINE(u_int32_t, dyn_buckets);
118 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
119 static VNET_DEFINE(struct callout, ipfw_timeout);
120 #define V_ipfw_dyn_v                    VNET(ipfw_dyn_v)
121 #define V_dyn_buckets                   VNET(dyn_buckets)
122 #define V_curr_dyn_buckets              VNET(curr_dyn_buckets)
123 #define V_ipfw_timeout                  VNET(ipfw_timeout)
124
125 static uma_zone_t ipfw_dyn_rule_zone;
126 #ifndef __FreeBSD__
127 DEFINE_SPINLOCK(ipfw_dyn_mtx);
128 #else
129 static struct mtx ipfw_dyn_mtx;         /* mutex guarding dynamic rules */
130 #endif
131
132 #define IPFW_DYN_LOCK_INIT() \
133         mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
134 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
135 #define IPFW_DYN_LOCK()         mtx_lock(&ipfw_dyn_mtx)
136 #define IPFW_DYN_UNLOCK()       mtx_unlock(&ipfw_dyn_mtx)
137 #define IPFW_DYN_LOCK_ASSERT()  mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
138
139 void
140 ipfw_dyn_unlock(void)
141 {
142         IPFW_DYN_UNLOCK();
143 }
144
145 /*
146  * Timeouts for various events in handing dynamic rules.
147  */
148 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
149 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
150 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
151 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
152 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
153 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
154
155 #define V_dyn_ack_lifetime              VNET(dyn_ack_lifetime)
156 #define V_dyn_syn_lifetime              VNET(dyn_syn_lifetime)
157 #define V_dyn_fin_lifetime              VNET(dyn_fin_lifetime)
158 #define V_dyn_rst_lifetime              VNET(dyn_rst_lifetime)
159 #define V_dyn_udp_lifetime              VNET(dyn_udp_lifetime)
160 #define V_dyn_short_lifetime            VNET(dyn_short_lifetime)
161
162 /*
163  * Keepalives are sent if dyn_keepalive is set. They are sent every
164  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
165  * seconds of lifetime of a rule.
166  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
167  * than dyn_keepalive_period.
168  */
169
170 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
171 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
172 static VNET_DEFINE(u_int32_t, dyn_keepalive);
173
174 #define V_dyn_keepalive_interval        VNET(dyn_keepalive_interval)
175 #define V_dyn_keepalive_period          VNET(dyn_keepalive_period)
176 #define V_dyn_keepalive                 VNET(dyn_keepalive)
177
178 static VNET_DEFINE(u_int32_t, dyn_count);       /* # of dynamic rules */
179 static VNET_DEFINE(u_int32_t, dyn_max);         /* max # of dynamic rules */
180
181 #define V_dyn_count                     VNET(dyn_count)
182 #define V_dyn_max                       VNET(dyn_max)
183
184 #ifdef SYSCTL_NODE
185
186 SYSBEGIN(f2)
187
188 SYSCTL_DECL(_net_inet_ip_fw);
189 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
190     CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
191     "Number of dyn. buckets");
192 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
193     CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
194     "Current Number of dyn. buckets");
195 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_count,
196     CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
197     "Number of dyn. rules");
198 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_max,
199     CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
200     "Max number of dyn. rules");
201 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
202     CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
203     "Lifetime of dyn. rules for acks");
204 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
205     CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
206     "Lifetime of dyn. rules for syn");
207 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
208     CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
209     "Lifetime of dyn. rules for fin");
210 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
211     CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
212     "Lifetime of dyn. rules for rst");
213 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
214     CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
215     "Lifetime of dyn. rules for UDP");
216 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
217     CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
218     "Lifetime of dyn. rules for other situations");
219 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
220     CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
221     "Enable keepalives for dyn. rules");
222
223 SYSEND
224
225 #endif /* SYSCTL_NODE */
226
227
228 static __inline int
229 hash_packet6(struct ipfw_flow_id *id)
230 {
231         u_int32_t i;
232         i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
233             (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
234             (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
235             (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
236             (id->dst_port) ^ (id->src_port);
237         return i;
238 }
239
240 /*
241  * IMPORTANT: the hash function for dynamic rules must be commutative
242  * in source and destination (ip,port), because rules are bidirectional
243  * and we want to find both in the same bucket.
244  */
245 static __inline int
246 hash_packet(struct ipfw_flow_id *id)
247 {
248         u_int32_t i;
249
250 #ifdef INET6
251         if (IS_IP6_FLOW_ID(id)) 
252                 i = hash_packet6(id);
253         else
254 #endif /* INET6 */
255         i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
256         i &= (V_curr_dyn_buckets - 1);
257         return i;
258 }
259
260 static __inline void
261 unlink_dyn_rule_print(struct ipfw_flow_id *id)
262 {
263         struct in_addr da;
264 #ifdef INET6
265         char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
266 #else
267         char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
268 #endif
269
270 #ifdef INET6
271         if (IS_IP6_FLOW_ID(id)) {
272                 ip6_sprintf(src, &id->src_ip6);
273                 ip6_sprintf(dst, &id->dst_ip6);
274         } else
275 #endif
276         {
277                 da.s_addr = htonl(id->src_ip);
278                 inet_ntoa_r(da, src);
279                 da.s_addr = htonl(id->dst_ip);
280                 inet_ntoa_r(da, dst);
281         }
282         printf("ipfw: unlink entry %s %d -> %s %d, %d left\n",
283             src, id->src_port, dst, id->dst_port, V_dyn_count - 1);
284 }
285
286 /**
287  * unlink a dynamic rule from a chain. prev is a pointer to
288  * the previous one, q is a pointer to the rule to delete,
289  * head is a pointer to the head of the queue.
290  * Modifies q and potentially also head.
291  */
292 #define UNLINK_DYN_RULE(prev, head, q) {                                \
293         ipfw_dyn_rule *old_q = q;                                       \
294                                                                         \
295         /* remove a refcount to the parent */                           \
296         if (q->dyn_type == O_LIMIT)                                     \
297                 q->parent->count--;                                     \
298         DEB(unlink_dyn_rule_print(&q->id);)                             \
299         if (prev != NULL)                                               \
300                 prev->next = q = q->next;                               \
301         else                                                            \
302                 head = q = q->next;                                     \
303         V_dyn_count--;                                                  \
304         uma_zfree(ipfw_dyn_rule_zone, old_q); }
305
306 #define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
307
308 /**
309  * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
310  *
311  * If keep_me == NULL, rules are deleted even if not expired,
312  * otherwise only expired rules are removed.
313  *
314  * The value of the second parameter is also used to point to identify
315  * a rule we absolutely do not want to remove (e.g. because we are
316  * holding a reference to it -- this is the case with O_LIMIT_PARENT
317  * rules). The pointer is only used for comparison, so any non-null
318  * value will do.
319  */
320 static void
321 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
322 {
323         static u_int32_t last_remove = 0;
324
325 #define FORCE (keep_me == NULL)
326
327         ipfw_dyn_rule *prev, *q;
328         int i, pass = 0, max_pass = 0;
329
330         IPFW_DYN_LOCK_ASSERT();
331
332         if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
333                 return;
334         /* do not expire more than once per second, it is useless */
335         if (!FORCE && last_remove == time_uptime)
336                 return;
337         last_remove = time_uptime;
338
339         /*
340          * because O_LIMIT refer to parent rules, during the first pass only
341          * remove child and mark any pending LIMIT_PARENT, and remove
342          * them in a second pass.
343          */
344 next_pass:
345         for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
346                 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
347                         /*
348                          * Logic can become complex here, so we split tests.
349                          */
350                         if (q == keep_me)
351                                 goto next;
352                         if (rule != NULL && rule != q->rule)
353                                 goto next; /* not the one we are looking for */
354                         if (q->dyn_type == O_LIMIT_PARENT) {
355                                 /*
356                                  * handle parent in the second pass,
357                                  * record we need one.
358                                  */
359                                 max_pass = 1;
360                                 if (pass == 0)
361                                         goto next;
362                                 if (FORCE && q->count != 0 ) {
363                                         /* XXX should not happen! */
364                                         printf("ipfw: OUCH! cannot remove rule,"
365                                              " count %d\n", q->count);
366                                 }
367                         } else {
368                                 if (!FORCE &&
369                                     !TIME_LEQ( q->expire, time_uptime ))
370                                         goto next;
371                         }
372              if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
373                      UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
374                      continue;
375              }
376 next:
377                         prev=q;
378                         q=q->next;
379                 }
380         }
381         if (pass++ < max_pass)
382                 goto next_pass;
383 }
384
385 void
386 ipfw_remove_dyn_children(struct ip_fw *rule)
387 {
388         IPFW_DYN_LOCK();
389         remove_dyn_rule(rule, NULL /* force removal */);
390         IPFW_DYN_UNLOCK();
391 }
392
393 /*
394  * Lookup a dynamic rule, locked version.
395  */
396 static ipfw_dyn_rule *
397 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
398     struct tcphdr *tcp)
399 {
400         /*
401          * Stateful ipfw extensions.
402          * Lookup into dynamic session queue.
403          */
404 #define MATCH_REVERSE   0
405 #define MATCH_FORWARD   1
406 #define MATCH_NONE      2
407 #define MATCH_UNKNOWN   3
408         int i, dir = MATCH_NONE;
409         ipfw_dyn_rule *prev, *q = NULL;
410
411         IPFW_DYN_LOCK_ASSERT();
412
413         if (V_ipfw_dyn_v == NULL)
414                 goto done;                              /* not found */
415         i = hash_packet(pkt);
416         for (prev = NULL, q = V_ipfw_dyn_v[i]; q != NULL;) {
417                 if (q->dyn_type == O_LIMIT_PARENT && q->count)
418                         goto next;
419                 if (TIME_LEQ(q->expire, time_uptime)) { /* expire entry */
420                         UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
421                         continue;
422                 }
423                 if (pkt->proto != q->id.proto || q->dyn_type == O_LIMIT_PARENT)
424                         goto next;
425
426                 if (IS_IP6_FLOW_ID(pkt)) {
427                         if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.src_ip6) &&
428                             IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.dst_ip6) &&
429                             pkt->src_port == q->id.src_port &&
430                             pkt->dst_port == q->id.dst_port) {
431                                 dir = MATCH_FORWARD;
432                                 break;
433                         }
434                         if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.dst_ip6) &&
435                             IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.src_ip6) &&
436                             pkt->src_port == q->id.dst_port &&
437                             pkt->dst_port == q->id.src_port) {
438                                 dir = MATCH_REVERSE;
439                                 break;
440                         }
441                 } else {
442                         if (pkt->src_ip == q->id.src_ip &&
443                             pkt->dst_ip == q->id.dst_ip &&
444                             pkt->src_port == q->id.src_port &&
445                             pkt->dst_port == q->id.dst_port) {
446                                 dir = MATCH_FORWARD;
447                                 break;
448                         }
449                         if (pkt->src_ip == q->id.dst_ip &&
450                             pkt->dst_ip == q->id.src_ip &&
451                             pkt->src_port == q->id.dst_port &&
452                             pkt->dst_port == q->id.src_port) {
453                                 dir = MATCH_REVERSE;
454                                 break;
455                         }
456                 }
457 next:
458                 prev = q;
459                 q = q->next;
460         }
461         if (q == NULL)
462                 goto done;      /* q = NULL, not found */
463
464         if (prev != NULL) {     /* found and not in front */
465                 prev->next = q->next;
466                 q->next = V_ipfw_dyn_v[i];
467                 V_ipfw_dyn_v[i] = q;
468         }
469         if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
470                 uint32_t ack;
471                 u_char flags = pkt->_flags & (TH_FIN | TH_SYN | TH_RST);
472
473 #define BOTH_SYN        (TH_SYN | (TH_SYN << 8))
474 #define BOTH_FIN        (TH_FIN | (TH_FIN << 8))
475 #define TCP_FLAGS       (TH_FLAGS | (TH_FLAGS << 8))
476 #define ACK_FWD         0x10000                 /* fwd ack seen */
477 #define ACK_REV         0x20000                 /* rev ack seen */
478
479                 q->state |= (dir == MATCH_FORWARD) ? flags : (flags << 8);
480                 switch (q->state & TCP_FLAGS) {
481                 case TH_SYN:                    /* opening */
482                         q->expire = time_uptime + V_dyn_syn_lifetime;
483                         break;
484
485                 case BOTH_SYN:                  /* move to established */
486                 case BOTH_SYN | TH_FIN:         /* one side tries to close */
487                 case BOTH_SYN | (TH_FIN << 8):
488 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
489                         if (tcp == NULL)
490                                 break;
491
492                         ack = ntohl(tcp->th_ack);
493                         if (dir == MATCH_FORWARD) {
494                                 if (q->ack_fwd == 0 ||
495                                     _SEQ_GE(ack, q->ack_fwd)) {
496                                         q->ack_fwd = ack;
497                                         q->state |= ACK_FWD;
498                                 }
499                         } else {
500                                 if (q->ack_rev == 0 ||
501                                     _SEQ_GE(ack, q->ack_rev)) {
502                                         q->ack_rev = ack;
503                                         q->state |= ACK_REV;
504                                 }
505                         }
506                         if ((q->state & (ACK_FWD | ACK_REV)) ==
507                             (ACK_FWD | ACK_REV)) {
508                                 q->expire = time_uptime + V_dyn_ack_lifetime;
509                                 q->state &= ~(ACK_FWD | ACK_REV);
510                         }
511                         break;
512
513                 case BOTH_SYN | BOTH_FIN:       /* both sides closed */
514                         if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
515                                 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
516                         q->expire = time_uptime + V_dyn_fin_lifetime;
517                         break;
518
519                 default:
520 #if 0
521                         /*
522                          * reset or some invalid combination, but can also
523                          * occur if we use keep-state the wrong way.
524                          */
525                         if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
526                                 printf("invalid state: 0x%x\n", q->state);
527 #endif
528                         if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
529                                 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
530                         q->expire = time_uptime + V_dyn_rst_lifetime;
531                         break;
532                 }
533         } else if (pkt->proto == IPPROTO_UDP) {
534                 q->expire = time_uptime + V_dyn_udp_lifetime;
535         } else {
536                 /* other protocols */
537                 q->expire = time_uptime + V_dyn_short_lifetime;
538         }
539 done:
540         if (match_direction != NULL)
541                 *match_direction = dir;
542         return (q);
543 }
544
545 ipfw_dyn_rule *
546 ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
547     struct tcphdr *tcp)
548 {
549         ipfw_dyn_rule *q;
550
551         IPFW_DYN_LOCK();
552         q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
553         if (q == NULL)
554                 IPFW_DYN_UNLOCK();
555         /* NB: return table locked when q is not NULL */
556         return q;
557 }
558
559 static void
560 realloc_dynamic_table(void)
561 {
562         IPFW_DYN_LOCK_ASSERT();
563
564         /*
565          * Try reallocation, make sure we have a power of 2 and do
566          * not allow more than 64k entries. In case of overflow,
567          * default to 1024.
568          */
569
570         if (V_dyn_buckets > 65536)
571                 V_dyn_buckets = 1024;
572         if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
573                 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
574                 return;
575         }
576         V_curr_dyn_buckets = V_dyn_buckets;
577         if (V_ipfw_dyn_v != NULL)
578                 free(V_ipfw_dyn_v, M_IPFW);
579         for (;;) {
580                 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
581                        M_IPFW, M_NOWAIT | M_ZERO);
582                 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
583                         break;
584                 V_curr_dyn_buckets /= 2;
585         }
586 }
587
588 /**
589  * Install state of type 'type' for a dynamic session.
590  * The hash table contains two type of rules:
591  * - regular rules (O_KEEP_STATE)
592  * - rules for sessions with limited number of sess per user
593  *   (O_LIMIT). When they are created, the parent is
594  *   increased by 1, and decreased on delete. In this case,
595  *   the third parameter is the parent rule and not the chain.
596  * - "parent" rules for the above (O_LIMIT_PARENT).
597  */
598 static ipfw_dyn_rule *
599 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
600 {
601         ipfw_dyn_rule *r;
602         int i;
603
604         IPFW_DYN_LOCK_ASSERT();
605
606         if (V_ipfw_dyn_v == NULL ||
607             (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
608                 realloc_dynamic_table();
609                 if (V_ipfw_dyn_v == NULL)
610                         return NULL; /* failed ! */
611         }
612         i = hash_packet(id);
613
614         r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
615         if (r == NULL) {
616                 printf ("ipfw: sorry cannot allocate state\n");
617                 return NULL;
618         }
619
620         /* increase refcount on parent, and set pointer */
621         if (dyn_type == O_LIMIT) {
622                 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
623                 if ( parent->dyn_type != O_LIMIT_PARENT)
624                         panic("invalid parent");
625                 parent->count++;
626                 r->parent = parent;
627                 rule = parent->rule;
628         }
629
630         r->id = *id;
631         r->expire = time_uptime + V_dyn_syn_lifetime;
632         r->rule = rule;
633         r->dyn_type = dyn_type;
634         r->pcnt = r->bcnt = 0;
635         r->count = 0;
636
637         r->bucket = i;
638         r->next = V_ipfw_dyn_v[i];
639         V_ipfw_dyn_v[i] = r;
640         V_dyn_count++;
641         DEB({
642                 struct in_addr da;
643 #ifdef INET6
644                 char src[INET6_ADDRSTRLEN];
645                 char dst[INET6_ADDRSTRLEN];
646 #else
647                 char src[INET_ADDRSTRLEN];
648                 char dst[INET_ADDRSTRLEN];
649 #endif
650
651 #ifdef INET6
652                 if (IS_IP6_FLOW_ID(&(r->id))) {
653                         ip6_sprintf(src, &r->id.src_ip6);
654                         ip6_sprintf(dst, &r->id.dst_ip6);
655                 } else
656 #endif
657                 {
658                         da.s_addr = htonl(r->id.src_ip);
659                         inet_ntoa_r(da, src);
660                         da.s_addr = htonl(r->id.dst_ip);
661                         inet_ntoa_r(da, dst);
662                 }
663                 printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n",
664                     dyn_type, src, r->id.src_port, dst, r->id.dst_port,
665                     V_dyn_count);
666         })
667         return r;
668 }
669
670 /**
671  * lookup dynamic parent rule using pkt and rule as search keys.
672  * If the lookup fails, then install one.
673  */
674 static ipfw_dyn_rule *
675 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
676 {
677         ipfw_dyn_rule *q;
678         int i;
679
680         IPFW_DYN_LOCK_ASSERT();
681
682         if (V_ipfw_dyn_v) {
683                 int is_v6 = IS_IP6_FLOW_ID(pkt);
684                 i = hash_packet( pkt );
685                 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
686                         if (q->dyn_type == O_LIMIT_PARENT &&
687                             rule== q->rule &&
688                             pkt->proto == q->id.proto &&
689                             pkt->src_port == q->id.src_port &&
690                             pkt->dst_port == q->id.dst_port &&
691                             (
692                                 (is_v6 &&
693                                  IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
694                                         &(q->id.src_ip6)) &&
695                                  IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
696                                         &(q->id.dst_ip6))) ||
697                                 (!is_v6 &&
698                                  pkt->src_ip == q->id.src_ip &&
699                                  pkt->dst_ip == q->id.dst_ip)
700                             )
701                         ) {
702                                 q->expire = time_uptime + V_dyn_short_lifetime;
703                                 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
704                                 return q;
705                         }
706         }
707         return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
708 }
709
710 /**
711  * Install dynamic state for rule type cmd->o.opcode
712  *
713  * Returns 1 (failure) if state is not installed because of errors or because
714  * session limitations are enforced.
715  */
716 int
717 ipfw_install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
718     struct ip_fw_args *args, uint32_t tablearg)
719 {
720         static int last_log;
721         ipfw_dyn_rule *q;
722         struct in_addr da;
723 #ifdef INET6
724         char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
725 #else
726         char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
727 #endif
728
729         src[0] = '\0';
730         dst[0] = '\0';
731
732         IPFW_DYN_LOCK();
733
734         DEB(
735 #ifdef INET6
736         if (IS_IP6_FLOW_ID(&(args->f_id))) {
737                 ip6_sprintf(src, &args->f_id.src_ip6);
738                 ip6_sprintf(dst, &args->f_id.dst_ip6);
739         } else
740 #endif
741         {
742                 da.s_addr = htonl(args->f_id.src_ip);
743                 inet_ntoa_r(da, src);
744                 da.s_addr = htonl(args->f_id.dst_ip);
745                 inet_ntoa_r(da, dst);
746         }
747         printf("ipfw: %s: type %d %s %u -> %s %u\n",
748             __func__, cmd->o.opcode, src, args->f_id.src_port,
749             dst, args->f_id.dst_port);
750         src[0] = '\0';
751         dst[0] = '\0';
752         )
753
754         q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
755
756         if (q != NULL) {        /* should never occur */
757                 DEB(
758                 if (last_log != time_uptime) {
759                         last_log = time_uptime;
760                         printf("ipfw: %s: entry already present, done\n",
761                             __func__);
762                 })
763                 IPFW_DYN_UNLOCK();
764                 return (0);
765         }
766
767         if (V_dyn_count >= V_dyn_max)
768                 /* Run out of slots, try to remove any expired rule. */
769                 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
770
771         if (V_dyn_count >= V_dyn_max) {
772                 if (last_log != time_uptime) {
773                         last_log = time_uptime;
774                         printf("ipfw: %s: Too many dynamic rules\n", __func__);
775                 }
776                 IPFW_DYN_UNLOCK();
777                 return (1);     /* cannot install, notify caller */
778         }
779
780         switch (cmd->o.opcode) {
781         case O_KEEP_STATE:      /* bidir rule */
782                 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
783                 break;
784
785         case O_LIMIT: {         /* limit number of sessions */
786                 struct ipfw_flow_id id;
787                 ipfw_dyn_rule *parent;
788                 uint32_t conn_limit;
789                 uint16_t limit_mask = cmd->limit_mask;
790
791                 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
792                     tablearg : cmd->conn_limit;
793                   
794                 DEB(
795                 if (cmd->conn_limit == IP_FW_TABLEARG)
796                         printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
797                             "(tablearg)\n", __func__, conn_limit);
798                 else
799                         printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
800                             __func__, conn_limit);
801                 )
802
803                 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
804                 id.proto = args->f_id.proto;
805                 id.addr_type = args->f_id.addr_type;
806                 id.fib = M_GETFIB(args->m);
807
808                 if (IS_IP6_FLOW_ID (&(args->f_id))) {
809                         if (limit_mask & DYN_SRC_ADDR)
810                                 id.src_ip6 = args->f_id.src_ip6;
811                         if (limit_mask & DYN_DST_ADDR)
812                                 id.dst_ip6 = args->f_id.dst_ip6;
813                 } else {
814                         if (limit_mask & DYN_SRC_ADDR)
815                                 id.src_ip = args->f_id.src_ip;
816                         if (limit_mask & DYN_DST_ADDR)
817                                 id.dst_ip = args->f_id.dst_ip;
818                 }
819                 if (limit_mask & DYN_SRC_PORT)
820                         id.src_port = args->f_id.src_port;
821                 if (limit_mask & DYN_DST_PORT)
822                         id.dst_port = args->f_id.dst_port;
823                 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
824                         printf("ipfw: %s: add parent failed\n", __func__);
825                         IPFW_DYN_UNLOCK();
826                         return (1);
827                 }
828
829                 if (parent->count >= conn_limit) {
830                         /* See if we can remove some expired rule. */
831                         remove_dyn_rule(rule, parent);
832                         if (parent->count >= conn_limit) {
833                                 if (V_fw_verbose && last_log != time_uptime) {
834                                         last_log = time_uptime;
835 #ifdef INET6
836                                         /*
837                                          * XXX IPv6 flows are not
838                                          * supported yet.
839                                          */
840                                         if (IS_IP6_FLOW_ID(&(args->f_id))) {
841                                                 char ip6buf[INET6_ADDRSTRLEN];
842                                                 snprintf(src, sizeof(src),
843                                                     "[%s]", ip6_sprintf(ip6buf,
844                                                         &args->f_id.src_ip6));
845                                                 snprintf(dst, sizeof(dst),
846                                                     "[%s]", ip6_sprintf(ip6buf,
847                                                         &args->f_id.dst_ip6));
848                                         } else
849 #endif
850                                         {
851                                                 da.s_addr =
852                                                     htonl(args->f_id.src_ip);
853                                                 inet_ntoa_r(da, src);
854                                                 da.s_addr =
855                                                     htonl(args->f_id.dst_ip);
856                                                 inet_ntoa_r(da, dst);
857                                         }
858                                         log(LOG_SECURITY | LOG_DEBUG,
859                                             "ipfw: %d %s %s:%u -> %s:%u, %s\n",
860                                             parent->rule->rulenum,
861                                             "drop session",
862                                             src, (args->f_id.src_port),
863                                             dst, (args->f_id.dst_port),
864                                             "too many entries");
865                                 }
866                                 IPFW_DYN_UNLOCK();
867                                 return (1);
868                         }
869                 }
870                 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
871                 break;
872         }
873         default:
874                 printf("ipfw: %s: unknown dynamic rule type %u\n",
875                     __func__, cmd->o.opcode);
876                 IPFW_DYN_UNLOCK();
877                 return (1);
878         }
879
880         /* XXX just set lifetime */
881         lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
882
883         IPFW_DYN_UNLOCK();
884         return (0);
885 }
886
887 /*
888  * Generate a TCP packet, containing either a RST or a keepalive.
889  * When flags & TH_RST, we are sending a RST packet, because of a
890  * "reset" action matched the packet.
891  * Otherwise we are sending a keepalive, and flags & TH_
892  * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
893  * so that MAC can label the reply appropriately.
894  */
895 struct mbuf *
896 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
897     u_int32_t ack, int flags)
898 {
899 #ifndef __FreeBSD__
900         return NULL;
901 #else
902         struct mbuf *m;
903         int len, dir;
904         struct ip *h = NULL;            /* stupid compiler */
905 #ifdef INET6
906         struct ip6_hdr *h6 = NULL;
907 #endif
908         struct tcphdr *th = NULL;
909
910         MGETHDR(m, M_DONTWAIT, MT_DATA);
911         if (m == NULL)
912                 return (NULL);
913
914         M_SETFIB(m, id->fib);
915 #ifdef MAC
916         if (replyto != NULL)
917                 mac_netinet_firewall_reply(replyto, m);
918         else
919                 mac_netinet_firewall_send(m);
920 #else
921         (void)replyto;          /* don't warn about unused arg */
922 #endif
923
924         switch (id->addr_type) {
925         case 4:
926                 len = sizeof(struct ip) + sizeof(struct tcphdr);
927                 break;
928 #ifdef INET6
929         case 6:
930                 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
931                 break;
932 #endif
933         default:
934                 /* XXX: log me?!? */
935                 FREE_PKT(m);
936                 return (NULL);
937         }
938         dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
939
940         m->m_data += max_linkhdr;
941         m->m_flags |= M_SKIP_FIREWALL;
942         m->m_pkthdr.len = m->m_len = len;
943         m->m_pkthdr.rcvif = NULL;
944         bzero(m->m_data, len);
945
946         switch (id->addr_type) {
947         case 4:
948                 h = mtod(m, struct ip *);
949
950                 /* prepare for checksum */
951                 h->ip_p = IPPROTO_TCP;
952                 h->ip_len = htons(sizeof(struct tcphdr));
953                 if (dir) {
954                         h->ip_src.s_addr = htonl(id->src_ip);
955                         h->ip_dst.s_addr = htonl(id->dst_ip);
956                 } else {
957                         h->ip_src.s_addr = htonl(id->dst_ip);
958                         h->ip_dst.s_addr = htonl(id->src_ip);
959                 }
960
961                 th = (struct tcphdr *)(h + 1);
962                 break;
963 #ifdef INET6
964         case 6:
965                 h6 = mtod(m, struct ip6_hdr *);
966
967                 /* prepare for checksum */
968                 h6->ip6_nxt = IPPROTO_TCP;
969                 h6->ip6_plen = htons(sizeof(struct tcphdr));
970                 if (dir) {
971                         h6->ip6_src = id->src_ip6;
972                         h6->ip6_dst = id->dst_ip6;
973                 } else {
974                         h6->ip6_src = id->dst_ip6;
975                         h6->ip6_dst = id->src_ip6;
976                 }
977
978                 th = (struct tcphdr *)(h6 + 1);
979                 break;
980 #endif
981         }
982
983         if (dir) {
984                 th->th_sport = htons(id->src_port);
985                 th->th_dport = htons(id->dst_port);
986         } else {
987                 th->th_sport = htons(id->dst_port);
988                 th->th_dport = htons(id->src_port);
989         }
990         th->th_off = sizeof(struct tcphdr) >> 2;
991
992         if (flags & TH_RST) {
993                 if (flags & TH_ACK) {
994                         th->th_seq = htonl(ack);
995                         th->th_flags = TH_RST;
996                 } else {
997                         if (flags & TH_SYN)
998                                 seq++;
999                         th->th_ack = htonl(seq);
1000                         th->th_flags = TH_RST | TH_ACK;
1001                 }
1002         } else {
1003                 /*
1004                  * Keepalive - use caller provided sequence numbers
1005                  */
1006                 th->th_seq = htonl(seq);
1007                 th->th_ack = htonl(ack);
1008                 th->th_flags = TH_ACK;
1009         }
1010
1011         switch (id->addr_type) {
1012         case 4:
1013                 th->th_sum = in_cksum(m, len);
1014
1015                 /* finish the ip header */
1016                 h->ip_v = 4;
1017                 h->ip_hl = sizeof(*h) >> 2;
1018                 h->ip_tos = IPTOS_LOWDELAY;
1019                 h->ip_off = 0;
1020                 /* ip_len must be in host format for ip_output */
1021                 h->ip_len = len;
1022                 h->ip_ttl = V_ip_defttl;
1023                 h->ip_sum = 0;
1024                 break;
1025 #ifdef INET6
1026         case 6:
1027                 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
1028                     sizeof(struct tcphdr));
1029
1030                 /* finish the ip6 header */
1031                 h6->ip6_vfc |= IPV6_VERSION;
1032                 h6->ip6_hlim = IPV6_DEFHLIM;
1033                 break;
1034 #endif
1035         }
1036
1037         return (m);
1038 #endif /* __FreeBSD__ */
1039 }
1040
1041 /*
1042  * This procedure is only used to handle keepalives. It is invoked
1043  * every dyn_keepalive_period
1044  */
1045 static void
1046 ipfw_tick(void * vnetx) 
1047 {
1048         struct mbuf *m0, *m, *mnext, **mtailp;
1049 #ifdef INET6
1050         struct mbuf *m6, **m6_tailp;
1051 #endif
1052         int i;
1053         ipfw_dyn_rule *q;
1054 #ifdef VIMAGE
1055         struct vnet *vp = vnetx;
1056 #endif
1057
1058         CURVNET_SET(vp);
1059         if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1060                 goto done;
1061
1062         /*
1063          * We make a chain of packets to go out here -- not deferring
1064          * until after we drop the IPFW dynamic rule lock would result
1065          * in a lock order reversal with the normal packet input -> ipfw
1066          * call stack.
1067          */
1068         m0 = NULL;
1069         mtailp = &m0;
1070 #ifdef INET6
1071         m6 = NULL;
1072         m6_tailp = &m6;
1073 #endif
1074         IPFW_DYN_LOCK();
1075         for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1076                 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
1077                         if (q->dyn_type == O_LIMIT_PARENT)
1078                                 continue;
1079                         if (q->id.proto != IPPROTO_TCP)
1080                                 continue;
1081                         if ( (q->state & BOTH_SYN) != BOTH_SYN)
1082                                 continue;
1083                         if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
1084                             q->expire))
1085                                 continue;       /* too early */
1086                         if (TIME_LEQ(q->expire, time_uptime))
1087                                 continue;       /* too late, rule expired */
1088
1089                         m = (q->state & ACK_REV) ? NULL :
1090                             ipfw_send_pkt(NULL, &(q->id), q->ack_rev - 1,
1091                             q->ack_fwd, TH_SYN);
1092                         mnext = (q->state & ACK_FWD) ? NULL :
1093                             ipfw_send_pkt(NULL, &(q->id), q->ack_fwd - 1,
1094                             q->ack_rev, 0);
1095
1096                         switch (q->id.addr_type) {
1097                         case 4:
1098                                 if (m != NULL) {
1099                                         *mtailp = m;
1100                                         mtailp = &(*mtailp)->m_nextpkt;
1101                                 }
1102                                 if (mnext != NULL) {
1103                                         *mtailp = mnext;
1104                                         mtailp = &(*mtailp)->m_nextpkt;
1105                                 }
1106                                 break;
1107 #ifdef INET6
1108                         case 6:
1109                                 if (m != NULL) {
1110                                         *m6_tailp = m;
1111                                         m6_tailp = &(*m6_tailp)->m_nextpkt;
1112                                 }
1113                                 if (mnext != NULL) {
1114                                         *m6_tailp = mnext;
1115                                         m6_tailp = &(*m6_tailp)->m_nextpkt;
1116                                 }
1117                                 break;
1118 #endif
1119                         }
1120                 }
1121         }
1122         IPFW_DYN_UNLOCK();
1123         for (m = m0; m != NULL; m = mnext) {
1124                 mnext = m->m_nextpkt;
1125                 m->m_nextpkt = NULL;
1126                 ip_output(m, NULL, NULL, 0, NULL, NULL);
1127         }
1128 #ifdef INET6
1129         for (m = m6; m != NULL; m = mnext) {
1130                 mnext = m->m_nextpkt;
1131                 m->m_nextpkt = NULL;
1132                 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1133         }
1134 #endif
1135 done:
1136         callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
1137                       ipfw_tick, vnetx);
1138         CURVNET_RESTORE();
1139 }
1140
1141 void
1142 ipfw_dyn_attach(void)
1143 {
1144         ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1145             sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1146             UMA_ALIGN_PTR, 0);
1147
1148         IPFW_DYN_LOCK_INIT();
1149 }
1150
1151 void
1152 ipfw_dyn_detach(void)
1153 {
1154         uma_zdestroy(ipfw_dyn_rule_zone);
1155         IPFW_DYN_LOCK_DESTROY();
1156 }
1157
1158 void
1159 ipfw_dyn_init(void)
1160 {
1161         V_ipfw_dyn_v = NULL;
1162         V_dyn_buckets = 256;    /* must be power of 2 */
1163         V_curr_dyn_buckets = 256; /* must be power of 2 */
1164  
1165         V_dyn_ack_lifetime = 300;
1166         V_dyn_syn_lifetime = 20;
1167         V_dyn_fin_lifetime = 1;
1168         V_dyn_rst_lifetime = 1;
1169         V_dyn_udp_lifetime = 10;
1170         V_dyn_short_lifetime = 5;
1171
1172         V_dyn_keepalive_interval = 20;
1173         V_dyn_keepalive_period = 5;
1174         V_dyn_keepalive = 1;    /* do send keepalives */
1175         
1176         V_dyn_max = 4096;       /* max # of dynamic rules */
1177         callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
1178         callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
1179 }
1180
1181 void
1182 ipfw_dyn_uninit(int pass)
1183 {
1184         if (pass == 0)
1185                 callout_drain(&V_ipfw_timeout);
1186         else {
1187                 if (V_ipfw_dyn_v != NULL)
1188                         free(V_ipfw_dyn_v, M_IPFW);
1189         }
1190 }
1191
1192 int
1193 ipfw_dyn_len(void)
1194 {
1195         return (V_ipfw_dyn_v == NULL) ? 0 :
1196                 (V_dyn_count * sizeof(ipfw_dyn_rule));
1197 }
1198
1199 void
1200 ipfw_get_dynamic(char **pbp, const char *ep)
1201 {
1202         ipfw_dyn_rule *p, *last = NULL;
1203         char *bp;
1204         int i;
1205
1206         if (V_ipfw_dyn_v == NULL)
1207                 return;
1208         bp = *pbp;
1209
1210         IPFW_DYN_LOCK();
1211         for (i = 0 ; i < V_curr_dyn_buckets; i++)
1212                 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
1213                         if (bp + sizeof *p <= ep) {
1214                                 ipfw_dyn_rule *dst =
1215                                         (ipfw_dyn_rule *)bp;
1216                                 bcopy(p, dst, sizeof *p);
1217                                 bcopy(&(p->rule->rulenum), &(dst->rule),
1218                                     sizeof(p->rule->rulenum));
1219                                 /*
1220                                  * store set number into high word of
1221                                  * dst->rule pointer.
1222                                  */
1223                                 bcopy(&(p->rule->set),
1224                                     (char *)&dst->rule +
1225                                     sizeof(p->rule->rulenum),
1226                                     sizeof(p->rule->set));
1227                                 /*
1228                                  * store a non-null value in "next".
1229                                  * The userland code will interpret a
1230                                  * NULL here as a marker
1231                                  * for the last dynamic rule.
1232                                  */
1233                                 bcopy(&dst, &dst->next, sizeof(dst));
1234                                 last = dst;
1235                                 dst->expire =
1236                                     TIME_LEQ(dst->expire, time_uptime) ?
1237                                         0 : dst->expire - time_uptime ;
1238                                 bp += sizeof(ipfw_dyn_rule);
1239                         }
1240                 }
1241         IPFW_DYN_UNLOCK();
1242         if (last != NULL) /* mark last dynamic rule */
1243                 bzero(&last->next, sizeof(last));
1244         *pbp = bp;
1245 }
1246 /* end of file */