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