xref: /dragonfly/sys/net/ipfw/ip_fw2.c (revision 51871435)
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  * $FreeBSD: src/sys/netinet/ip_fw2.c,v 1.6.2.12 2003/04/08 10:42:32 maxim Exp $
26  */
27 
28 /*
29  * Implement IP packet firewall (new version)
30  */
31 
32 #include "opt_ipfw.h"
33 #include "opt_inet.h"
34 #ifndef INET
35 #error IPFIREWALL requires INET.
36 #endif /* INET */
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/kernel.h>
43 #include <sys/proc.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/sysctl.h>
47 #include <sys/syslog.h>
48 #include <sys/ucred.h>
49 #include <sys/in_cksum.h>
50 #include <sys/lock.h>
51 
52 #include <net/if.h>
53 #include <net/route.h>
54 #include <net/pfil.h>
55 #include <net/dummynet/ip_dummynet.h>
56 
57 #include <sys/thread2.h>
58 #include <sys/mplock2.h>
59 #include <net/netmsg2.h>
60 
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/in_var.h>
64 #include <netinet/in_pcb.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip_var.h>
67 #include <netinet/ip_icmp.h>
68 #include <netinet/tcp.h>
69 #include <netinet/tcp_timer.h>
70 #include <netinet/tcp_var.h>
71 #include <netinet/tcpip.h>
72 #include <netinet/udp.h>
73 #include <netinet/udp_var.h>
74 #include <netinet/ip_divert.h>
75 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
76 
77 #include <net/ipfw/ip_fw2.h>
78 
79 #ifdef IPFIREWALL_DEBUG
80 #define DPRINTF(fmt, ...) \
81 do { \
82 	if (fw_debug > 0) \
83 		kprintf(fmt, __VA_ARGS__); \
84 } while (0)
85 #else
86 #define DPRINTF(fmt, ...)	((void)0)
87 #endif
88 
89 /*
90  * Description about per-CPU rule duplication:
91  *
92  * Module loading/unloading and all ioctl operations are serialized
93  * by netisr0, so we don't have any ordering or locking problems.
94  *
95  * Following graph shows how operation on per-CPU rule list is
96  * performed [2 CPU case]:
97  *
98  *   CPU0                 CPU1
99  *
100  * netisr0 <------------------------------------+
101  *  domsg                                       |
102  *    |                                         |
103  *    | netmsg                                  |
104  *    |                                         |
105  *    V                                         |
106  *  ifnet0                                      |
107  *    :                                         | netmsg
108  *    :(delete/add...)                          |
109  *    :                                         |
110  *    :         netmsg                          |
111  *  forwardmsg---------->ifnet1                 |
112  *                          :                   |
113  *                          :(delete/add...)    |
114  *                          :                   |
115  *                          :                   |
116  *                        replymsg--------------+
117  *
118  *
119  *
120  *
121  * Rules which will not create states (dyn rules) [2 CPU case]
122  *
123  *    CPU0               CPU1
124  * layer3_chain       layer3_chain
125  *     |                  |
126  *     V                  V
127  * +-------+ sibling  +-------+ sibling
128  * | rule1 |--------->| rule1 |--------->NULL
129  * +-------+          +-------+
130  *     |                  |
131  *     |next              |next
132  *     V                  V
133  * +-------+ sibling  +-------+ sibling
134  * | rule2 |--------->| rule2 |--------->NULL
135  * +-------+          +-------+
136  *
137  * ip_fw.sibling:
138  * 1) Ease statistics calculation during IP_FW_GET.  We only need to
139  *    iterate layer3_chain on CPU0; the current rule's duplication on
140  *    the other CPUs could safely be read-only accessed by using
141  *    ip_fw.sibling
142  * 2) Accelerate rule insertion and deletion, e.g. rule insertion:
143  *    a) In netisr0 (on CPU0) rule3 is determined to be inserted between
144  *       rule1 and rule2.  To make this decision we need to iterate the
145  *       layer3_chain on CPU0.  The netmsg, which is used to insert the
146  *       rule, will contain rule1 on CPU0 as prev_rule and rule2 on CPU0
147  *       as next_rule
148  *    b) After the insertion on CPU0 is done, we will move on to CPU1.
149  *       But instead of relocating the rule3's position on CPU1 by
150  *       iterating the layer3_chain on CPU1, we set the netmsg's prev_rule
151  *       to rule1->sibling and next_rule to rule2->sibling before the
152  *       netmsg is forwarded to CPU1 from CPU0
153  *
154  *
155  *
156  * Rules which will create states (dyn rules) [2 CPU case]
157  * (unnecessary parts are omitted; they are same as in the previous figure)
158  *
159  *   CPU0                       CPU1
160  *
161  * +-------+                  +-------+
162  * | rule1 |                  | rule1 |
163  * +-------+                  +-------+
164  *   ^   |                      |   ^
165  *   |   |stub              stub|   |
166  *   |   |                      |   |
167  *   |   +----+            +----+   |
168  *   |        |            |        |
169  *   |        V            V        |
170  *   |    +--------------------+    |
171  *   |    |     rule_stub      |    |
172  *   |    | (read-only shared) |    |
173  *   |    |                    |    |
174  *   |    | back pointer array |    |
175  *   |    | (indexed by cpuid) |    |
176  *   |    |                    |    |
177  *   +----|---------[0]        |    |
178  *        |         [1]--------|----+
179  *        |                    |
180  *        +--------------------+
181  *          ^            ^
182  *          |            |
183  *  ........|............|............
184  *  :       |            |           :
185  *  :       |stub        |stub       :
186  *  :       |            |           :
187  *  :  +---------+  +---------+      :
188  *  :  | state1a |  | state1b | .... :
189  *  :  +---------+  +---------+      :
190  *  :                                :
191  *  :           states table         :
192  *  :            (shared)            :
193  *  :      (protected by dyn_lock)   :
194  *  ..................................
195  *
196  * [state1a and state1b are states created by rule1]
197  *
198  * ip_fw_stub:
199  * This structure is introduced so that shared (locked) state table could
200  * work with per-CPU (duplicated) static rules.  It mainly bridges states
201  * and static rules and serves as static rule's place holder (a read-only
202  * shared part of duplicated rules) from states point of view.
203  *
204  * IPFW_RULE_F_STATE (only for rules which create states):
205  * o  During rule installation, this flag is turned on after rule's
206  *    duplications reach all CPUs, to avoid at least following race:
207  *    1) rule1 is duplicated on CPU0 and is not duplicated on CPU1 yet
208  *    2) rule1 creates state1
209  *    3) state1 is located on CPU1 by check-state
210  *    But rule1 is not duplicated on CPU1 yet
211  * o  During rule deletion, this flag is turned off before deleting states
212  *    created by the rule and before deleting the rule itself, so no
213  *    more states will be created by the to-be-deleted rule even when its
214  *    duplication on certain CPUs are not eliminated yet.
215  */
216 
217 #define IPFW_AUTOINC_STEP_MIN	1
218 #define IPFW_AUTOINC_STEP_MAX	1000
219 #define IPFW_AUTOINC_STEP_DEF	100
220 
221 #define	IPFW_DEFAULT_RULE	65535	/* rulenum for the default rule */
222 #define IPFW_DEFAULT_SET	31	/* set number for the default rule */
223 
224 struct netmsg_ipfw {
225 	struct netmsg_base base;
226 	const struct ipfw_ioc_rule *ioc_rule;
227 	struct ip_fw	*next_rule;
228 	struct ip_fw	*prev_rule;
229 	struct ip_fw	*sibling;
230 	struct ip_fw_stub *stub;
231 };
232 
233 struct netmsg_del {
234 	struct netmsg_base base;
235 	struct ip_fw	*start_rule;
236 	struct ip_fw	*prev_rule;
237 	uint16_t	rulenum;
238 	uint8_t		from_set;
239 	uint8_t		to_set;
240 };
241 
242 struct netmsg_zent {
243 	struct netmsg_base base;
244 	struct ip_fw	*start_rule;
245 	uint16_t	rulenum;
246 	uint16_t	log_only;
247 };
248 
249 struct ipfw_context {
250 	struct ip_fw	*ipfw_layer3_chain;	/* list of rules for layer3 */
251 	struct ip_fw	*ipfw_default_rule;	/* default rule */
252 	uint64_t	ipfw_norule_counter;	/* counter for ipfw_log(NULL) */
253 
254 	/*
255 	 * ipfw_set_disable contains one bit per set value (0..31).
256 	 * If the bit is set, all rules with the corresponding set
257 	 * are disabled.  Set IPDW_DEFAULT_SET is reserved for the
258 	 * default rule and CANNOT be disabled.
259 	 */
260 	uint32_t	ipfw_set_disable;
261 	uint32_t	ipfw_gen;		/* generation of rule list */
262 };
263 
264 static struct ipfw_context	*ipfw_ctx[MAXCPU];
265 
266 #ifdef KLD_MODULE
267 /*
268  * Module can not be unloaded, if there are references to
269  * certains rules of ipfw(4), e.g. dummynet(4)
270  */
271 static int ipfw_refcnt;
272 #endif
273 
274 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
275 
276 /*
277  * Following two global variables are accessed and
278  * updated only on CPU0
279  */
280 static uint32_t static_count;	/* # of static rules */
281 static uint32_t static_ioc_len;	/* bytes of static rules */
282 
283 /*
284  * If 1, then ipfw static rules are being flushed,
285  * ipfw_chk() will skip to the default rule.
286  */
287 static int ipfw_flushing;
288 
289 static int fw_verbose;
290 static int verbose_limit;
291 
292 static int fw_debug;
293 static int autoinc_step = IPFW_AUTOINC_STEP_DEF;
294 
295 static int	ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS);
296 static int	ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS);
297 static int	ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS);
298 static int	ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS);
299 static int	ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS);
300 
301 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
302 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW,
303     &fw_enable, 0, ipfw_sysctl_enable, "I", "Enable ipfw");
304 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLTYPE_INT | CTLFLAG_RW,
305     &autoinc_step, 0, ipfw_sysctl_autoinc_step, "I",
306     "Rule number autincrement step");
307 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO,one_pass,CTLFLAG_RW,
308     &fw_one_pass, 0,
309     "Only do a single pass through ipfw when using dummynet(4)");
310 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
311     &fw_debug, 0, "Enable printing of debug ip_fw statements");
312 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose, CTLFLAG_RW,
313     &fw_verbose, 0, "Log matches to ipfw rules");
314 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
315     &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
316 
317 /*
318  * Description of dynamic rules.
319  *
320  * Dynamic rules are stored in lists accessed through a hash table
321  * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
322  * be modified through the sysctl variable dyn_buckets which is
323  * updated when the table becomes empty.
324  *
325  * XXX currently there is only one list, ipfw_dyn.
326  *
327  * When a packet is received, its address fields are first masked
328  * with the mask defined for the rule, then hashed, then matched
329  * against the entries in the corresponding list.
330  * Dynamic rules can be used for different purposes:
331  *  + stateful rules;
332  *  + enforcing limits on the number of sessions;
333  *  + in-kernel NAT (not implemented yet)
334  *
335  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
336  * measured in seconds and depending on the flags.
337  *
338  * The total number of dynamic rules is stored in dyn_count.
339  * The max number of dynamic rules is dyn_max. When we reach
340  * the maximum number of rules we do not create anymore. This is
341  * done to avoid consuming too much memory, but also too much
342  * time when searching on each packet (ideally, we should try instead
343  * to put a limit on the length of the list on each bucket...).
344  *
345  * Each dynamic rule holds a pointer to the parent ipfw rule so
346  * we know what action to perform. Dynamic rules are removed when
347  * the parent rule is deleted. XXX we should make them survive.
348  *
349  * There are some limitations with dynamic rules -- we do not
350  * obey the 'randomized match', and we do not do multiple
351  * passes through the firewall. XXX check the latter!!!
352  *
353  * NOTE about the SHARED LOCKMGR LOCK during dynamic rule looking up:
354  * Only TCP state transition will change dynamic rule's state and ack
355  * sequences, while all packets of one TCP connection only goes through
356  * one TCP thread, so it is safe to use shared lockmgr lock during dynamic
357  * rule looking up.  The keep alive callout uses exclusive lockmgr lock
358  * when it tries to find suitable dynamic rules to send keep alive, so
359  * it will not see half updated state and ack sequences.  Though the expire
360  * field updating looks racy for other protocols, the resolution (second)
361  * of expire field makes this kind of race harmless.
362  * XXX statistics' updating is _not_ MPsafe!!!
363  * XXX once UDP output path is fixed, we could use lockless dynamic rule
364  *     hash table
365  */
366 static ipfw_dyn_rule **ipfw_dyn_v = NULL;
367 static uint32_t dyn_buckets = 256; /* must be power of 2 */
368 static uint32_t curr_dyn_buckets = 256; /* must be power of 2 */
369 static uint32_t dyn_buckets_gen; /* generation of dyn buckets array */
370 static struct lock dyn_lock; /* dynamic rules' hash table lock */
371 
372 static struct netmsg_base ipfw_timeout_netmsg; /* schedule ipfw timeout */
373 static struct callout ipfw_timeout_h;
374 
375 /*
376  * Timeouts for various events in handing dynamic rules.
377  */
378 static uint32_t dyn_ack_lifetime = 300;
379 static uint32_t dyn_syn_lifetime = 20;
380 static uint32_t dyn_fin_lifetime = 1;
381 static uint32_t dyn_rst_lifetime = 1;
382 static uint32_t dyn_udp_lifetime = 10;
383 static uint32_t dyn_short_lifetime = 5;
384 
385 /*
386  * Keepalives are sent if dyn_keepalive is set. They are sent every
387  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
388  * seconds of lifetime of a rule.
389  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
390  * than dyn_keepalive_period.
391  */
392 
393 static uint32_t dyn_keepalive_interval = 20;
394 static uint32_t dyn_keepalive_period = 5;
395 static uint32_t dyn_keepalive = 1;	/* do send keepalives */
396 
397 static uint32_t dyn_count;		/* # of dynamic rules */
398 static uint32_t dyn_max = 4096;		/* max # of dynamic rules */
399 
400 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLTYPE_INT | CTLFLAG_RW,
401     &dyn_buckets, 0, ipfw_sysctl_dyn_buckets, "I", "Number of dyn. buckets");
402 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
403     &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
404 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
405     &dyn_count, 0, "Number of dyn. rules");
406 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
407     &dyn_max, 0, "Max number of dyn. rules");
408 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
409     &static_count, 0, "Number of static rules");
410 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
411     &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
412 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
413     &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
414 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
415     CTLTYPE_INT | CTLFLAG_RW, &dyn_fin_lifetime, 0, ipfw_sysctl_dyn_fin, "I",
416     "Lifetime of dyn. rules for fin");
417 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
418     CTLTYPE_INT | CTLFLAG_RW, &dyn_rst_lifetime, 0, ipfw_sysctl_dyn_rst, "I",
419     "Lifetime of dyn. rules for rst");
420 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
421     &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
422 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
423     &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
424 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
425     &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
426 
427 static ip_fw_chk_t	ipfw_chk;
428 static void		ipfw_tick(void *);
429 
430 static __inline int
431 ipfw_free_rule(struct ip_fw *rule)
432 {
433 	KASSERT(rule->cpuid == mycpuid, ("rule freed on cpu%d", mycpuid));
434 	KASSERT(rule->refcnt > 0, ("invalid refcnt %u", rule->refcnt));
435 	rule->refcnt--;
436 	if (rule->refcnt == 0) {
437 		kfree(rule, M_IPFW);
438 		return 1;
439 	}
440 	return 0;
441 }
442 
443 static void
444 ipfw_unref_rule(void *priv)
445 {
446 	ipfw_free_rule(priv);
447 #ifdef KLD_MODULE
448 	atomic_subtract_int(&ipfw_refcnt, 1);
449 #endif
450 }
451 
452 static __inline void
453 ipfw_ref_rule(struct ip_fw *rule)
454 {
455 	KASSERT(rule->cpuid == mycpuid, ("rule used on cpu%d", mycpuid));
456 #ifdef KLD_MODULE
457 	atomic_add_int(&ipfw_refcnt, 1);
458 #endif
459 	rule->refcnt++;
460 }
461 
462 /*
463  * This macro maps an ip pointer into a layer3 header pointer of type T
464  */
465 #define	L3HDR(T, ip) ((T *)((uint32_t *)(ip) + (ip)->ip_hl))
466 
467 static __inline int
468 icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
469 {
470 	int type = L3HDR(struct icmp,ip)->icmp_type;
471 
472 	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1 << type)));
473 }
474 
475 #define TT	((1 << ICMP_ECHO) | \
476 		 (1 << ICMP_ROUTERSOLICIT) | \
477 		 (1 << ICMP_TSTAMP) | \
478 		 (1 << ICMP_IREQ) | \
479 		 (1 << ICMP_MASKREQ))
480 
481 static int
482 is_icmp_query(struct ip *ip)
483 {
484 	int type = L3HDR(struct icmp, ip)->icmp_type;
485 
486 	return (type <= ICMP_MAXTYPE && (TT & (1 << type)));
487 }
488 
489 #undef TT
490 
491 /*
492  * The following checks use two arrays of 8 or 16 bits to store the
493  * bits that we want set or clear, respectively. They are in the
494  * low and high half of cmd->arg1 or cmd->d[0].
495  *
496  * We scan options and store the bits we find set. We succeed if
497  *
498  *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
499  *
500  * The code is sometimes optimized not to store additional variables.
501  */
502 
503 static int
504 flags_match(ipfw_insn *cmd, uint8_t bits)
505 {
506 	u_char want_clear;
507 	bits = ~bits;
508 
509 	if (((cmd->arg1 & 0xff) & bits) != 0)
510 		return 0; /* some bits we want set were clear */
511 
512 	want_clear = (cmd->arg1 >> 8) & 0xff;
513 	if ((want_clear & bits) != want_clear)
514 		return 0; /* some bits we want clear were set */
515 	return 1;
516 }
517 
518 static int
519 ipopts_match(struct ip *ip, ipfw_insn *cmd)
520 {
521 	int optlen, bits = 0;
522 	u_char *cp = (u_char *)(ip + 1);
523 	int x = (ip->ip_hl << 2) - sizeof(struct ip);
524 
525 	for (; x > 0; x -= optlen, cp += optlen) {
526 		int opt = cp[IPOPT_OPTVAL];
527 
528 		if (opt == IPOPT_EOL)
529 			break;
530 
531 		if (opt == IPOPT_NOP) {
532 			optlen = 1;
533 		} else {
534 			optlen = cp[IPOPT_OLEN];
535 			if (optlen <= 0 || optlen > x)
536 				return 0; /* invalid or truncated */
537 		}
538 
539 		switch (opt) {
540 		case IPOPT_LSRR:
541 			bits |= IP_FW_IPOPT_LSRR;
542 			break;
543 
544 		case IPOPT_SSRR:
545 			bits |= IP_FW_IPOPT_SSRR;
546 			break;
547 
548 		case IPOPT_RR:
549 			bits |= IP_FW_IPOPT_RR;
550 			break;
551 
552 		case IPOPT_TS:
553 			bits |= IP_FW_IPOPT_TS;
554 			break;
555 
556 		default:
557 			break;
558 		}
559 	}
560 	return (flags_match(cmd, bits));
561 }
562 
563 static int
564 tcpopts_match(struct ip *ip, ipfw_insn *cmd)
565 {
566 	int optlen, bits = 0;
567 	struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
568 	u_char *cp = (u_char *)(tcp + 1);
569 	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
570 
571 	for (; x > 0; x -= optlen, cp += optlen) {
572 		int opt = cp[0];
573 
574 		if (opt == TCPOPT_EOL)
575 			break;
576 
577 		if (opt == TCPOPT_NOP) {
578 			optlen = 1;
579 		} else {
580 			optlen = cp[1];
581 			if (optlen <= 0)
582 				break;
583 		}
584 
585 		switch (opt) {
586 		case TCPOPT_MAXSEG:
587 			bits |= IP_FW_TCPOPT_MSS;
588 			break;
589 
590 		case TCPOPT_WINDOW:
591 			bits |= IP_FW_TCPOPT_WINDOW;
592 			break;
593 
594 		case TCPOPT_SACK_PERMITTED:
595 		case TCPOPT_SACK:
596 			bits |= IP_FW_TCPOPT_SACK;
597 			break;
598 
599 		case TCPOPT_TIMESTAMP:
600 			bits |= IP_FW_TCPOPT_TS;
601 			break;
602 
603 		case TCPOPT_CC:
604 		case TCPOPT_CCNEW:
605 		case TCPOPT_CCECHO:
606 			bits |= IP_FW_TCPOPT_CC;
607 			break;
608 
609 		default:
610 			break;
611 		}
612 	}
613 	return (flags_match(cmd, bits));
614 }
615 
616 static int
617 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
618 {
619 	if (ifp == NULL)	/* no iface with this packet, match fails */
620 		return 0;
621 
622 	/* Check by name or by IP address */
623 	if (cmd->name[0] != '\0') { /* match by name */
624 		/* Check name */
625 		if (cmd->p.glob) {
626 			if (kfnmatch(cmd->name, ifp->if_xname, 0) == 0)
627 				return(1);
628 		} else {
629 			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
630 				return(1);
631 		}
632 	} else {
633 		struct ifaddr_container *ifac;
634 
635 		TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
636 			struct ifaddr *ia = ifac->ifa;
637 
638 			if (ia->ifa_addr == NULL)
639 				continue;
640 			if (ia->ifa_addr->sa_family != AF_INET)
641 				continue;
642 			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
643 			    (ia->ifa_addr))->sin_addr.s_addr)
644 				return(1);	/* match */
645 		}
646 	}
647 	return(0);	/* no match, fail ... */
648 }
649 
650 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
651 
652 /*
653  * We enter here when we have a rule with O_LOG.
654  * XXX this function alone takes about 2Kbytes of code!
655  */
656 static void
657 ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
658 	 struct mbuf *m, struct ifnet *oif)
659 {
660 	char *action;
661 	int limit_reached = 0;
662 	char action2[40], proto[48], fragment[28];
663 
664 	fragment[0] = '\0';
665 	proto[0] = '\0';
666 
667 	if (f == NULL) {	/* bogus pkt */
668 		struct ipfw_context *ctx = ipfw_ctx[mycpuid];
669 
670 		if (verbose_limit != 0 &&
671 		    ctx->ipfw_norule_counter >= verbose_limit)
672 			return;
673 		ctx->ipfw_norule_counter++;
674 		if (ctx->ipfw_norule_counter == verbose_limit)
675 			limit_reached = verbose_limit;
676 		action = "Refuse";
677 	} else {	/* O_LOG is the first action, find the real one */
678 		ipfw_insn *cmd = ACTION_PTR(f);
679 		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
680 
681 		if (l->max_log != 0 && l->log_left == 0)
682 			return;
683 		l->log_left--;
684 		if (l->log_left == 0)
685 			limit_reached = l->max_log;
686 		cmd += F_LEN(cmd);	/* point to first action */
687 		if (cmd->opcode == O_PROB)
688 			cmd += F_LEN(cmd);
689 
690 		action = action2;
691 		switch (cmd->opcode) {
692 		case O_DENY:
693 			action = "Deny";
694 			break;
695 
696 		case O_REJECT:
697 			if (cmd->arg1==ICMP_REJECT_RST) {
698 				action = "Reset";
699 			} else if (cmd->arg1==ICMP_UNREACH_HOST) {
700 				action = "Reject";
701 			} else {
702 				ksnprintf(SNPARGS(action2, 0), "Unreach %d",
703 					  cmd->arg1);
704 			}
705 			break;
706 
707 		case O_ACCEPT:
708 			action = "Accept";
709 			break;
710 
711 		case O_COUNT:
712 			action = "Count";
713 			break;
714 
715 		case O_DIVERT:
716 			ksnprintf(SNPARGS(action2, 0), "Divert %d", cmd->arg1);
717 			break;
718 
719 		case O_TEE:
720 			ksnprintf(SNPARGS(action2, 0), "Tee %d", cmd->arg1);
721 			break;
722 
723 		case O_SKIPTO:
724 			ksnprintf(SNPARGS(action2, 0), "SkipTo %d", cmd->arg1);
725 			break;
726 
727 		case O_PIPE:
728 			ksnprintf(SNPARGS(action2, 0), "Pipe %d", cmd->arg1);
729 			break;
730 
731 		case O_QUEUE:
732 			ksnprintf(SNPARGS(action2, 0), "Queue %d", cmd->arg1);
733 			break;
734 
735 		case O_FORWARD_IP:
736 			{
737 				ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
738 				int len;
739 
740 				len = ksnprintf(SNPARGS(action2, 0),
741 						"Forward to %s",
742 						inet_ntoa(sa->sa.sin_addr));
743 				if (sa->sa.sin_port) {
744 					ksnprintf(SNPARGS(action2, len), ":%d",
745 						  sa->sa.sin_port);
746 				}
747 			}
748 			break;
749 
750 		default:
751 			action = "UNKNOWN";
752 			break;
753 		}
754 	}
755 
756 	if (hlen == 0) {	/* non-ip */
757 		ksnprintf(SNPARGS(proto, 0), "MAC");
758 	} else {
759 		struct ip *ip = mtod(m, struct ip *);
760 		/* these three are all aliases to the same thing */
761 		struct icmp *const icmp = L3HDR(struct icmp, ip);
762 		struct tcphdr *const tcp = (struct tcphdr *)icmp;
763 		struct udphdr *const udp = (struct udphdr *)icmp;
764 
765 		int ip_off, offset, ip_len;
766 		int len;
767 
768 		if (eh != NULL) { /* layer 2 packets are as on the wire */
769 			ip_off = ntohs(ip->ip_off);
770 			ip_len = ntohs(ip->ip_len);
771 		} else {
772 			ip_off = ip->ip_off;
773 			ip_len = ip->ip_len;
774 		}
775 		offset = ip_off & IP_OFFMASK;
776 		switch (ip->ip_p) {
777 		case IPPROTO_TCP:
778 			len = ksnprintf(SNPARGS(proto, 0), "TCP %s",
779 					inet_ntoa(ip->ip_src));
780 			if (offset == 0) {
781 				ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
782 					  ntohs(tcp->th_sport),
783 					  inet_ntoa(ip->ip_dst),
784 					  ntohs(tcp->th_dport));
785 			} else {
786 				ksnprintf(SNPARGS(proto, len), " %s",
787 					  inet_ntoa(ip->ip_dst));
788 			}
789 			break;
790 
791 		case IPPROTO_UDP:
792 			len = ksnprintf(SNPARGS(proto, 0), "UDP %s",
793 					inet_ntoa(ip->ip_src));
794 			if (offset == 0) {
795 				ksnprintf(SNPARGS(proto, len), ":%d %s:%d",
796 					  ntohs(udp->uh_sport),
797 					  inet_ntoa(ip->ip_dst),
798 					  ntohs(udp->uh_dport));
799 			} else {
800 				ksnprintf(SNPARGS(proto, len), " %s",
801 					  inet_ntoa(ip->ip_dst));
802 			}
803 			break;
804 
805 		case IPPROTO_ICMP:
806 			if (offset == 0) {
807 				len = ksnprintf(SNPARGS(proto, 0),
808 						"ICMP:%u.%u ",
809 						icmp->icmp_type,
810 						icmp->icmp_code);
811 			} else {
812 				len = ksnprintf(SNPARGS(proto, 0), "ICMP ");
813 			}
814 			len += ksnprintf(SNPARGS(proto, len), "%s",
815 					 inet_ntoa(ip->ip_src));
816 			ksnprintf(SNPARGS(proto, len), " %s",
817 				  inet_ntoa(ip->ip_dst));
818 			break;
819 
820 		default:
821 			len = ksnprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
822 					inet_ntoa(ip->ip_src));
823 			ksnprintf(SNPARGS(proto, len), " %s",
824 				  inet_ntoa(ip->ip_dst));
825 			break;
826 		}
827 
828 		if (ip_off & (IP_MF | IP_OFFMASK)) {
829 			ksnprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
830 				  ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
831 				  offset << 3, (ip_off & IP_MF) ? "+" : "");
832 		}
833 	}
834 
835 	if (oif || m->m_pkthdr.rcvif) {
836 		log(LOG_SECURITY | LOG_INFO,
837 		    "ipfw: %d %s %s %s via %s%s\n",
838 		    f ? f->rulenum : -1,
839 		    action, proto, oif ? "out" : "in",
840 		    oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
841 		    fragment);
842 	} else {
843 		log(LOG_SECURITY | LOG_INFO,
844 		    "ipfw: %d %s %s [no if info]%s\n",
845 		    f ? f->rulenum : -1,
846 		    action, proto, fragment);
847 	}
848 
849 	if (limit_reached) {
850 		log(LOG_SECURITY | LOG_NOTICE,
851 		    "ipfw: limit %d reached on entry %d\n",
852 		    limit_reached, f ? f->rulenum : -1);
853 	}
854 }
855 
856 #undef SNPARGS
857 
858 /*
859  * IMPORTANT: the hash function for dynamic rules must be commutative
860  * in source and destination (ip,port), because rules are bidirectional
861  * and we want to find both in the same bucket.
862  */
863 static __inline int
864 hash_packet(struct ipfw_flow_id *id)
865 {
866 	uint32_t i;
867 
868 	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
869 	i &= (curr_dyn_buckets - 1);
870 	return i;
871 }
872 
873 /**
874  * unlink a dynamic rule from a chain. prev is a pointer to
875  * the previous one, q is a pointer to the rule to delete,
876  * head is a pointer to the head of the queue.
877  * Modifies q and potentially also head.
878  */
879 #define UNLINK_DYN_RULE(prev, head, q)					\
880 do {									\
881 	ipfw_dyn_rule *old_q = q;					\
882 									\
883 	/* remove a refcount to the parent */				\
884 	if (q->dyn_type == O_LIMIT)					\
885 		q->parent->count--;					\
886 	DPRINTF("-- unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",	\
887 		q->id.src_ip, q->id.src_port,				\
888 		q->id.dst_ip, q->id.dst_port, dyn_count - 1);		\
889 	if (prev != NULL)						\
890 		prev->next = q = q->next;				\
891 	else								\
892 		head = q = q->next;					\
893 	KASSERT(dyn_count > 0, ("invalid dyn count %u", dyn_count));	\
894 	dyn_count--;							\
895 	kfree(old_q, M_IPFW);						\
896 } while (0)
897 
898 #define TIME_LEQ(a, b)	((int)((a) - (b)) <= 0)
899 
900 /**
901  * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
902  *
903  * If keep_me == NULL, rules are deleted even if not expired,
904  * otherwise only expired rules are removed.
905  *
906  * The value of the second parameter is also used to point to identify
907  * a rule we absolutely do not want to remove (e.g. because we are
908  * holding a reference to it -- this is the case with O_LIMIT_PARENT
909  * rules). The pointer is only used for comparison, so any non-null
910  * value will do.
911  */
912 static void
913 remove_dyn_rule_locked(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
914 {
915 	static uint32_t last_remove = 0; /* XXX */
916 
917 #define FORCE	(keep_me == NULL)
918 
919 	ipfw_dyn_rule *prev, *q;
920 	int i, pass = 0, max_pass = 0, unlinked = 0;
921 
922 	if (ipfw_dyn_v == NULL || dyn_count == 0)
923 		return;
924 	/* do not expire more than once per second, it is useless */
925 	if (!FORCE && last_remove == time_second)
926 		return;
927 	last_remove = time_second;
928 
929 	/*
930 	 * because O_LIMIT refer to parent rules, during the first pass only
931 	 * remove child and mark any pending LIMIT_PARENT, and remove
932 	 * them in a second pass.
933 	 */
934 next_pass:
935 	for (i = 0; i < curr_dyn_buckets; i++) {
936 		for (prev = NULL, q = ipfw_dyn_v[i]; q;) {
937 			/*
938 			 * Logic can become complex here, so we split tests.
939 			 */
940 			if (q == keep_me)
941 				goto next;
942 			if (rule != NULL && rule->stub != q->stub)
943 				goto next; /* not the one we are looking for */
944 			if (q->dyn_type == O_LIMIT_PARENT) {
945 				/*
946 				 * handle parent in the second pass,
947 				 * record we need one.
948 				 */
949 				max_pass = 1;
950 				if (pass == 0)
951 					goto next;
952 				if (FORCE && q->count != 0) {
953 					/* XXX should not happen! */
954 					kprintf("OUCH! cannot remove rule, "
955 						"count %d\n", q->count);
956 				}
957 			} else {
958 				if (!FORCE && !TIME_LEQ(q->expire, time_second))
959 					goto next;
960 			}
961 			unlinked = 1;
962 			UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
963 			continue;
964 next:
965 			prev = q;
966 			q = q->next;
967 		}
968 	}
969 	if (pass++ < max_pass)
970 		goto next_pass;
971 
972 	if (unlinked)
973 		++dyn_buckets_gen;
974 
975 #undef FORCE
976 }
977 
978 /**
979  * lookup a dynamic rule.
980  */
981 static ipfw_dyn_rule *
982 lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
983 		struct tcphdr *tcp)
984 {
985 	/*
986 	 * stateful ipfw extensions.
987 	 * Lookup into dynamic session queue
988 	 */
989 #define MATCH_REVERSE	0
990 #define MATCH_FORWARD	1
991 #define MATCH_NONE	2
992 #define MATCH_UNKNOWN	3
993 	int i, dir = MATCH_NONE;
994 	ipfw_dyn_rule *prev, *q=NULL;
995 
996 	if (ipfw_dyn_v == NULL)
997 		goto done;	/* not found */
998 
999 	i = hash_packet(pkt);
1000 	for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
1001 		if (q->dyn_type == O_LIMIT_PARENT)
1002 			goto next;
1003 
1004 		if (TIME_LEQ(q->expire, time_second)) {
1005 			/*
1006 			 * Entry expired; skip.
1007 			 * Let ipfw_tick() take care of it
1008 			 */
1009 			goto next;
1010 		}
1011 
1012 		if (pkt->proto == q->id.proto) {
1013 			if (pkt->src_ip == q->id.src_ip &&
1014 			    pkt->dst_ip == q->id.dst_ip &&
1015 			    pkt->src_port == q->id.src_port &&
1016 			    pkt->dst_port == q->id.dst_port) {
1017 				dir = MATCH_FORWARD;
1018 				break;
1019 			}
1020 			if (pkt->src_ip == q->id.dst_ip &&
1021 			    pkt->dst_ip == q->id.src_ip &&
1022 			    pkt->src_port == q->id.dst_port &&
1023 			    pkt->dst_port == q->id.src_port) {
1024 				dir = MATCH_REVERSE;
1025 				break;
1026 			}
1027 		}
1028 next:
1029 		prev = q;
1030 		q = q->next;
1031 	}
1032 	if (q == NULL)
1033 		goto done; /* q = NULL, not found */
1034 
1035 	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1036 		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1037 
1038 #define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
1039 #define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
1040 
1041 		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1042 		switch (q->state) {
1043 		case TH_SYN:				/* opening */
1044 			q->expire = time_second + dyn_syn_lifetime;
1045 			break;
1046 
1047 		case BOTH_SYN:			/* move to established */
1048 		case BOTH_SYN | TH_FIN :	/* one side tries to close */
1049 		case BOTH_SYN | (TH_FIN << 8) :
1050  			if (tcp) {
1051 				uint32_t ack = ntohl(tcp->th_ack);
1052 
1053 #define _SEQ_GE(a, b)	((int)(a) - (int)(b) >= 0)
1054 
1055 				if (dir == MATCH_FORWARD) {
1056 					if (q->ack_fwd == 0 ||
1057 					    _SEQ_GE(ack, q->ack_fwd))
1058 						q->ack_fwd = ack;
1059 					else /* ignore out-of-sequence */
1060 						break;
1061 				} else {
1062 					if (q->ack_rev == 0 ||
1063 					    _SEQ_GE(ack, q->ack_rev))
1064 						q->ack_rev = ack;
1065 					else /* ignore out-of-sequence */
1066 						break;
1067 				}
1068 #undef _SEQ_GE
1069 			}
1070 			q->expire = time_second + dyn_ack_lifetime;
1071 			break;
1072 
1073 		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
1074 			KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
1075 			q->expire = time_second + dyn_fin_lifetime;
1076 			break;
1077 
1078 		default:
1079 #if 0
1080 			/*
1081 			 * reset or some invalid combination, but can also
1082 			 * occur if we use keep-state the wrong way.
1083 			 */
1084 			if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
1085 				kprintf("invalid state: 0x%x\n", q->state);
1086 #endif
1087 			KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
1088 			q->expire = time_second + dyn_rst_lifetime;
1089 			break;
1090 		}
1091 	} else if (pkt->proto == IPPROTO_UDP) {
1092 		q->expire = time_second + dyn_udp_lifetime;
1093 	} else {
1094 		/* other protocols */
1095 		q->expire = time_second + dyn_short_lifetime;
1096 	}
1097 done:
1098 	if (match_direction)
1099 		*match_direction = dir;
1100 	return q;
1101 }
1102 
1103 static struct ip_fw *
1104 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
1105 	    uint16_t len, int *deny)
1106 {
1107 	struct ip_fw *rule = NULL;
1108 	ipfw_dyn_rule *q;
1109 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1110 	uint32_t gen;
1111 
1112 	*deny = 0;
1113 	gen = ctx->ipfw_gen;
1114 
1115 	lockmgr(&dyn_lock, LK_SHARED);
1116 
1117 	if (ctx->ipfw_gen != gen) {
1118 		/*
1119 		 * Static rules had been change when we were waiting
1120 		 * for the dynamic hash table lock; deny this packet,
1121 		 * since it is _not_ known whether it is safe to keep
1122 		 * iterating the static rules.
1123 		 */
1124 		*deny = 1;
1125 		goto back;
1126 	}
1127 
1128 	q = lookup_dyn_rule(pkt, match_direction, tcp);
1129 	if (q == NULL) {
1130 		rule = NULL;
1131 	} else {
1132 		rule = q->stub->rule[mycpuid];
1133 		KKASSERT(rule->stub == q->stub && rule->cpuid == mycpuid);
1134 
1135 		/* XXX */
1136 		q->pcnt++;
1137 		q->bcnt += len;
1138 	}
1139 back:
1140 	lockmgr(&dyn_lock, LK_RELEASE);
1141 	return rule;
1142 }
1143 
1144 static void
1145 realloc_dynamic_table(void)
1146 {
1147 	ipfw_dyn_rule **old_dyn_v;
1148 	uint32_t old_curr_dyn_buckets;
1149 
1150 	KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
1151 		("invalid dyn_buckets %d", dyn_buckets));
1152 
1153 	/* Save the current buckets array for later error recovery */
1154 	old_dyn_v = ipfw_dyn_v;
1155 	old_curr_dyn_buckets = curr_dyn_buckets;
1156 
1157 	curr_dyn_buckets = dyn_buckets;
1158 	for (;;) {
1159 		ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1160 				     M_IPFW, M_NOWAIT | M_ZERO);
1161 		if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1162 			break;
1163 
1164 		curr_dyn_buckets /= 2;
1165 		if (curr_dyn_buckets <= old_curr_dyn_buckets &&
1166 		    old_dyn_v != NULL) {
1167 			/*
1168 			 * Don't try allocating smaller buckets array, reuse
1169 			 * the old one, which alreay contains enough buckets
1170 			 */
1171 			break;
1172 		}
1173 	}
1174 
1175 	if (ipfw_dyn_v != NULL) {
1176 		if (old_dyn_v != NULL)
1177 			kfree(old_dyn_v, M_IPFW);
1178 	} else {
1179 		/* Allocation failed, restore old buckets array */
1180 		ipfw_dyn_v = old_dyn_v;
1181 		curr_dyn_buckets = old_curr_dyn_buckets;
1182 	}
1183 
1184 	if (ipfw_dyn_v != NULL)
1185 		++dyn_buckets_gen;
1186 }
1187 
1188 /**
1189  * Install state of type 'type' for a dynamic session.
1190  * The hash table contains two type of rules:
1191  * - regular rules (O_KEEP_STATE)
1192  * - rules for sessions with limited number of sess per user
1193  *   (O_LIMIT). When they are created, the parent is
1194  *   increased by 1, and decreased on delete. In this case,
1195  *   the third parameter is the parent rule and not the chain.
1196  * - "parent" rules for the above (O_LIMIT_PARENT).
1197  */
1198 static ipfw_dyn_rule *
1199 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1200 {
1201 	ipfw_dyn_rule *r;
1202 	int i;
1203 
1204 	if (ipfw_dyn_v == NULL ||
1205 	    (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1206 		realloc_dynamic_table();
1207 		if (ipfw_dyn_v == NULL)
1208 			return NULL; /* failed ! */
1209 	}
1210 	i = hash_packet(id);
1211 
1212 	r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1213 	if (r == NULL)
1214 		return NULL;
1215 
1216 	/* increase refcount on parent, and set pointer */
1217 	if (dyn_type == O_LIMIT) {
1218 		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1219 
1220 		if (parent->dyn_type != O_LIMIT_PARENT)
1221 			panic("invalid parent");
1222 		parent->count++;
1223 		r->parent = parent;
1224 		rule = parent->stub->rule[mycpuid];
1225 		KKASSERT(rule->stub == parent->stub);
1226 	}
1227 	KKASSERT(rule->cpuid == mycpuid && rule->stub != NULL);
1228 
1229 	r->id = *id;
1230 	r->expire = time_second + dyn_syn_lifetime;
1231 	r->stub = rule->stub;
1232 	r->dyn_type = dyn_type;
1233 	r->pcnt = r->bcnt = 0;
1234 	r->count = 0;
1235 
1236 	r->bucket = i;
1237 	r->next = ipfw_dyn_v[i];
1238 	ipfw_dyn_v[i] = r;
1239 	dyn_count++;
1240 	dyn_buckets_gen++;
1241 	DPRINTF("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1242 		dyn_type,
1243 		r->id.src_ip, r->id.src_port,
1244 		r->id.dst_ip, r->id.dst_port, dyn_count);
1245 	return r;
1246 }
1247 
1248 /**
1249  * lookup dynamic parent rule using pkt and rule as search keys.
1250  * If the lookup fails, then install one.
1251  */
1252 static ipfw_dyn_rule *
1253 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1254 {
1255 	ipfw_dyn_rule *q;
1256 	int i;
1257 
1258 	if (ipfw_dyn_v) {
1259 		i = hash_packet(pkt);
1260 		for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1261 			if (q->dyn_type == O_LIMIT_PARENT &&
1262 			    rule->stub == q->stub &&
1263 			    pkt->proto == q->id.proto &&
1264 			    pkt->src_ip == q->id.src_ip &&
1265 			    pkt->dst_ip == q->id.dst_ip &&
1266 			    pkt->src_port == q->id.src_port &&
1267 			    pkt->dst_port == q->id.dst_port) {
1268 				q->expire = time_second + dyn_short_lifetime;
1269 				DPRINTF("lookup_dyn_parent found 0x%p\n", q);
1270 				return q;
1271 			}
1272 		}
1273 	}
1274 	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1275 }
1276 
1277 /**
1278  * Install dynamic state for rule type cmd->o.opcode
1279  *
1280  * Returns 1 (failure) if state is not installed because of errors or because
1281  * session limitations are enforced.
1282  */
1283 static int
1284 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1285 		     struct ip_fw_args *args)
1286 {
1287 	static int last_log; /* XXX */
1288 
1289 	ipfw_dyn_rule *q;
1290 
1291 	DPRINTF("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1292 		cmd->o.opcode,
1293 		args->f_id.src_ip, args->f_id.src_port,
1294 		args->f_id.dst_ip, args->f_id.dst_port);
1295 
1296 	q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1297 	if (q != NULL) { /* should never occur */
1298 		if (last_log != time_second) {
1299 			last_log = time_second;
1300 			kprintf(" install_state: entry already present, done\n");
1301 		}
1302 		return 0;
1303 	}
1304 
1305 	if (dyn_count >= dyn_max) {
1306 		/*
1307 		 * Run out of slots, try to remove any expired rule.
1308 		 */
1309 		remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1310 		if (dyn_count >= dyn_max) {
1311 			if (last_log != time_second) {
1312 				last_log = time_second;
1313 				kprintf("install_state: "
1314 					"Too many dynamic rules\n");
1315 			}
1316 			return 1; /* cannot install, notify caller */
1317 		}
1318 	}
1319 
1320 	switch (cmd->o.opcode) {
1321 	case O_KEEP_STATE: /* bidir rule */
1322 		if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1323 			return 1;
1324 		break;
1325 
1326 	case O_LIMIT: /* limit number of sessions */
1327 		{
1328 			uint16_t limit_mask = cmd->limit_mask;
1329 			struct ipfw_flow_id id;
1330 			ipfw_dyn_rule *parent;
1331 
1332 			DPRINTF("installing dyn-limit rule %d\n",
1333 				cmd->conn_limit);
1334 
1335 			id.dst_ip = id.src_ip = 0;
1336 			id.dst_port = id.src_port = 0;
1337 			id.proto = args->f_id.proto;
1338 
1339 			if (limit_mask & DYN_SRC_ADDR)
1340 				id.src_ip = args->f_id.src_ip;
1341 			if (limit_mask & DYN_DST_ADDR)
1342 				id.dst_ip = args->f_id.dst_ip;
1343 			if (limit_mask & DYN_SRC_PORT)
1344 				id.src_port = args->f_id.src_port;
1345 			if (limit_mask & DYN_DST_PORT)
1346 				id.dst_port = args->f_id.dst_port;
1347 
1348 			parent = lookup_dyn_parent(&id, rule);
1349 			if (parent == NULL) {
1350 				kprintf("add parent failed\n");
1351 				return 1;
1352 			}
1353 
1354 			if (parent->count >= cmd->conn_limit) {
1355 				/*
1356 				 * See if we can remove some expired rule.
1357 				 */
1358 				remove_dyn_rule_locked(rule, parent);
1359 				if (parent->count >= cmd->conn_limit) {
1360 					if (fw_verbose &&
1361 					    last_log != time_second) {
1362 						last_log = time_second;
1363 						log(LOG_SECURITY | LOG_DEBUG,
1364 						    "drop session, "
1365 						    "too many entries\n");
1366 					}
1367 					return 1;
1368 				}
1369 			}
1370 			if (add_dyn_rule(&args->f_id, O_LIMIT,
1371 					 (struct ip_fw *)parent) == NULL)
1372 				return 1;
1373 		}
1374 		break;
1375 	default:
1376 		kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1377 		return 1;
1378 	}
1379 	lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1380 	return 0;
1381 }
1382 
1383 static int
1384 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1385 	      struct ip_fw_args *args, int *deny)
1386 {
1387 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1388 	uint32_t gen;
1389 	int ret = 0;
1390 
1391 	*deny = 0;
1392 	gen = ctx->ipfw_gen;
1393 
1394 	lockmgr(&dyn_lock, LK_EXCLUSIVE);
1395 	if (ctx->ipfw_gen != gen) {
1396 		/* See the comment in lookup_rule() */
1397 		*deny = 1;
1398 	} else {
1399 		ret = install_state_locked(rule, cmd, args);
1400 	}
1401 	lockmgr(&dyn_lock, LK_RELEASE);
1402 
1403 	return ret;
1404 }
1405 
1406 /*
1407  * Transmit a TCP packet, containing either a RST or a keepalive.
1408  * When flags & TH_RST, we are sending a RST packet, because of a
1409  * "reset" action matched the packet.
1410  * Otherwise we are sending a keepalive, and flags & TH_
1411  */
1412 static void
1413 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1414 {
1415 	struct mbuf *m;
1416 	struct ip *ip;
1417 	struct tcphdr *tcp;
1418 	struct route sro;	/* fake route */
1419 
1420 	MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1421 	if (m == NULL)
1422 		return;
1423 	m->m_pkthdr.rcvif = NULL;
1424 	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1425 	m->m_data += max_linkhdr;
1426 
1427 	ip = mtod(m, struct ip *);
1428 	bzero(ip, m->m_len);
1429 	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1430 	ip->ip_p = IPPROTO_TCP;
1431 	tcp->th_off = 5;
1432 
1433 	/*
1434 	 * Assume we are sending a RST (or a keepalive in the reverse
1435 	 * direction), swap src and destination addresses and ports.
1436 	 */
1437 	ip->ip_src.s_addr = htonl(id->dst_ip);
1438 	ip->ip_dst.s_addr = htonl(id->src_ip);
1439 	tcp->th_sport = htons(id->dst_port);
1440 	tcp->th_dport = htons(id->src_port);
1441 	if (flags & TH_RST) {	/* we are sending a RST */
1442 		if (flags & TH_ACK) {
1443 			tcp->th_seq = htonl(ack);
1444 			tcp->th_ack = htonl(0);
1445 			tcp->th_flags = TH_RST;
1446 		} else {
1447 			if (flags & TH_SYN)
1448 				seq++;
1449 			tcp->th_seq = htonl(0);
1450 			tcp->th_ack = htonl(seq);
1451 			tcp->th_flags = TH_RST | TH_ACK;
1452 		}
1453 	} else {
1454 		/*
1455 		 * We are sending a keepalive. flags & TH_SYN determines
1456 		 * the direction, forward if set, reverse if clear.
1457 		 * NOTE: seq and ack are always assumed to be correct
1458 		 * as set by the caller. This may be confusing...
1459 		 */
1460 		if (flags & TH_SYN) {
1461 			/*
1462 			 * we have to rewrite the correct addresses!
1463 			 */
1464 			ip->ip_dst.s_addr = htonl(id->dst_ip);
1465 			ip->ip_src.s_addr = htonl(id->src_ip);
1466 			tcp->th_dport = htons(id->dst_port);
1467 			tcp->th_sport = htons(id->src_port);
1468 		}
1469 		tcp->th_seq = htonl(seq);
1470 		tcp->th_ack = htonl(ack);
1471 		tcp->th_flags = TH_ACK;
1472 	}
1473 
1474 	/*
1475 	 * set ip_len to the payload size so we can compute
1476 	 * the tcp checksum on the pseudoheader
1477 	 * XXX check this, could save a couple of words ?
1478 	 */
1479 	ip->ip_len = htons(sizeof(struct tcphdr));
1480 	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1481 
1482 	/*
1483 	 * now fill fields left out earlier
1484 	 */
1485 	ip->ip_ttl = ip_defttl;
1486 	ip->ip_len = m->m_pkthdr.len;
1487 
1488 	bzero(&sro, sizeof(sro));
1489 	ip_rtaddr(ip->ip_dst, &sro);
1490 
1491 	m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1492 	ip_output(m, NULL, &sro, 0, NULL, NULL);
1493 	if (sro.ro_rt)
1494 		RTFREE(sro.ro_rt);
1495 }
1496 
1497 /*
1498  * sends a reject message, consuming the mbuf passed as an argument.
1499  */
1500 static void
1501 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1502 {
1503 	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1504 		/* We need the IP header in host order for icmp_error(). */
1505 		if (args->eh != NULL) {
1506 			struct ip *ip = mtod(args->m, struct ip *);
1507 
1508 			ip->ip_len = ntohs(ip->ip_len);
1509 			ip->ip_off = ntohs(ip->ip_off);
1510 		}
1511 		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1512 	} else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1513 		struct tcphdr *const tcp =
1514 		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1515 
1516 		if ((tcp->th_flags & TH_RST) == 0) {
1517 			send_pkt(&args->f_id, ntohl(tcp->th_seq),
1518 				 ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1519 		}
1520 		m_freem(args->m);
1521 	} else {
1522 		m_freem(args->m);
1523 	}
1524 	args->m = NULL;
1525 }
1526 
1527 /**
1528  *
1529  * Given an ip_fw *, lookup_next_rule will return a pointer
1530  * to the next rule, which can be either the jump
1531  * target (for skipto instructions) or the next one in the list (in
1532  * all other cases including a missing jump target).
1533  * The result is also written in the "next_rule" field of the rule.
1534  * Backward jumps are not allowed, so start looking from the next
1535  * rule...
1536  *
1537  * This never returns NULL -- in case we do not have an exact match,
1538  * the next rule is returned. When the ruleset is changed,
1539  * pointers are flushed so we are always correct.
1540  */
1541 
1542 static struct ip_fw *
1543 lookup_next_rule(struct ip_fw *me)
1544 {
1545 	struct ip_fw *rule = NULL;
1546 	ipfw_insn *cmd;
1547 
1548 	/* look for action, in case it is a skipto */
1549 	cmd = ACTION_PTR(me);
1550 	if (cmd->opcode == O_LOG)
1551 		cmd += F_LEN(cmd);
1552 	if (cmd->opcode == O_SKIPTO) {
1553 		for (rule = me->next; rule; rule = rule->next) {
1554 			if (rule->rulenum >= cmd->arg1)
1555 				break;
1556 		}
1557 	}
1558 	if (rule == NULL)			/* failure or not a skipto */
1559 		rule = me->next;
1560 	me->next_rule = rule;
1561 	return rule;
1562 }
1563 
1564 static int
1565 _ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1566 		enum ipfw_opcodes opcode, uid_t uid)
1567 {
1568 	struct in_addr src_ip, dst_ip;
1569 	struct inpcbinfo *pi;
1570 	int wildcard;
1571 	struct inpcb *pcb;
1572 
1573 	if (fid->proto == IPPROTO_TCP) {
1574 		wildcard = 0;
1575 		pi = &tcbinfo[mycpuid];
1576 	} else if (fid->proto == IPPROTO_UDP) {
1577 		wildcard = 1;
1578 		pi = &udbinfo;
1579 	} else {
1580 		return 0;
1581 	}
1582 
1583 	/*
1584 	 * Values in 'fid' are in host byte order
1585 	 */
1586 	dst_ip.s_addr = htonl(fid->dst_ip);
1587 	src_ip.s_addr = htonl(fid->src_ip);
1588 	if (oif) {
1589 		pcb = in_pcblookup_hash(pi,
1590 			dst_ip, htons(fid->dst_port),
1591 			src_ip, htons(fid->src_port),
1592 			wildcard, oif);
1593 	} else {
1594 		pcb = in_pcblookup_hash(pi,
1595 			src_ip, htons(fid->src_port),
1596 			dst_ip, htons(fid->dst_port),
1597 			wildcard, NULL);
1598 	}
1599 	if (pcb == NULL || pcb->inp_socket == NULL)
1600 		return 0;
1601 
1602 	if (opcode == O_UID) {
1603 #define socheckuid(a,b)	((a)->so_cred->cr_uid != (b))
1604 		return !socheckuid(pcb->inp_socket, uid);
1605 #undef socheckuid
1606 	} else  {
1607 		return groupmember(uid, pcb->inp_socket->so_cred);
1608 	}
1609 }
1610 
1611 static int
1612 ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1613 	       enum ipfw_opcodes opcode, uid_t uid, int *deny)
1614 {
1615 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1616 	uint32_t gen;
1617 	int match = 0;
1618 
1619 	*deny = 0;
1620 	gen = ctx->ipfw_gen;
1621 
1622 	get_mplock();
1623 	if (gen != ctx->ipfw_gen) {
1624 		/* See the comment in lookup_rule() */
1625 		*deny = 1;
1626 	} else {
1627 		match = _ipfw_match_uid(fid, oif, opcode, uid);
1628 	}
1629 	rel_mplock();
1630 	return match;
1631 }
1632 
1633 /*
1634  * The main check routine for the firewall.
1635  *
1636  * All arguments are in args so we can modify them and return them
1637  * back to the caller.
1638  *
1639  * Parameters:
1640  *
1641  *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
1642  *		Starts with the IP header.
1643  *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
1644  *	args->oif	Outgoing interface, or NULL if packet is incoming.
1645  *		The incoming interface is in the mbuf. (in)
1646  *
1647  *	args->rule	Pointer to the last matching rule (in/out)
1648  *	args->f_id	Addresses grabbed from the packet (out)
1649  *
1650  * Return value:
1651  *
1652  *	If the packet was denied/rejected and has been dropped, *m is equal
1653  *	to NULL upon return.
1654  *
1655  *	IP_FW_DENY	the packet must be dropped.
1656  *	IP_FW_PASS	The packet is to be accepted and routed normally.
1657  *	IP_FW_DIVERT	Divert the packet to port (args->cookie)
1658  *	IP_FW_TEE	Tee the packet to port (args->cookie)
1659  *	IP_FW_DUMMYNET	Send the packet to pipe/queue (args->cookie)
1660  */
1661 
1662 static int
1663 ipfw_chk(struct ip_fw_args *args)
1664 {
1665 	/*
1666 	 * Local variables hold state during the processing of a packet.
1667 	 *
1668 	 * IMPORTANT NOTE: to speed up the processing of rules, there
1669 	 * are some assumption on the values of the variables, which
1670 	 * are documented here. Should you change them, please check
1671 	 * the implementation of the various instructions to make sure
1672 	 * that they still work.
1673 	 *
1674 	 * args->eh	The MAC header. It is non-null for a layer2
1675 	 *	packet, it is NULL for a layer-3 packet.
1676 	 *
1677 	 * m | args->m	Pointer to the mbuf, as received from the caller.
1678 	 *	It may change if ipfw_chk() does an m_pullup, or if it
1679 	 *	consumes the packet because it calls send_reject().
1680 	 *	XXX This has to change, so that ipfw_chk() never modifies
1681 	 *	or consumes the buffer.
1682 	 * ip	is simply an alias of the value of m, and it is kept
1683 	 *	in sync with it (the packet is	supposed to start with
1684 	 *	the ip header).
1685 	 */
1686 	struct mbuf *m = args->m;
1687 	struct ip *ip = mtod(m, struct ip *);
1688 
1689 	/*
1690 	 * oif | args->oif	If NULL, ipfw_chk has been called on the
1691 	 *	inbound path (ether_input, ip_input).
1692 	 *	If non-NULL, ipfw_chk has been called on the outbound path
1693 	 *	(ether_output, ip_output).
1694 	 */
1695 	struct ifnet *oif = args->oif;
1696 
1697 	struct ip_fw *f = NULL;		/* matching rule */
1698 	int retval = IP_FW_PASS;
1699 	struct m_tag *mtag;
1700 	struct divert_info *divinfo;
1701 
1702 	/*
1703 	 * hlen	The length of the IPv4 header.
1704 	 *	hlen >0 means we have an IPv4 packet.
1705 	 */
1706 	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1707 
1708 	/*
1709 	 * offset	The offset of a fragment. offset != 0 means that
1710 	 *	we have a fragment at this offset of an IPv4 packet.
1711 	 *	offset == 0 means that (if this is an IPv4 packet)
1712 	 *	this is the first or only fragment.
1713 	 */
1714 	u_short offset = 0;
1715 
1716 	/*
1717 	 * Local copies of addresses. They are only valid if we have
1718 	 * an IP packet.
1719 	 *
1720 	 * proto	The protocol. Set to 0 for non-ip packets,
1721 	 *	or to the protocol read from the packet otherwise.
1722 	 *	proto != 0 means that we have an IPv4 packet.
1723 	 *
1724 	 * src_port, dst_port	port numbers, in HOST format. Only
1725 	 *	valid for TCP and UDP packets.
1726 	 *
1727 	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1728 	 *	Only valid for IPv4 packets.
1729 	 */
1730 	uint8_t proto;
1731 	uint16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
1732 	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1733 	uint16_t ip_len = 0;
1734 
1735 	/*
1736 	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1737 	 * 	MATCH_NONE when checked and not matched (dyn_f = NULL),
1738 	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (dyn_f != NULL)
1739 	 */
1740 	int dyn_dir = MATCH_UNKNOWN;
1741 	struct ip_fw *dyn_f = NULL;
1742 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1743 
1744 	if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1745 		return IP_FW_PASS;	/* accept */
1746 
1747 	if (args->eh == NULL ||		/* layer 3 packet */
1748 	    (m->m_pkthdr.len >= sizeof(struct ip) &&
1749 	     ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1750 		hlen = ip->ip_hl << 2;
1751 
1752 	/*
1753 	 * Collect parameters into local variables for faster matching.
1754 	 */
1755 	if (hlen == 0) {	/* do not grab addresses for non-ip pkts */
1756 		proto = args->f_id.proto = 0;	/* mark f_id invalid */
1757 		goto after_ip_checks;
1758 	}
1759 
1760 	proto = args->f_id.proto = ip->ip_p;
1761 	src_ip = ip->ip_src;
1762 	dst_ip = ip->ip_dst;
1763 	if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1764 		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1765 		ip_len = ntohs(ip->ip_len);
1766 	} else {
1767 		offset = ip->ip_off & IP_OFFMASK;
1768 		ip_len = ip->ip_len;
1769 	}
1770 
1771 #define PULLUP_TO(len)				\
1772 do {						\
1773 	if (m->m_len < (len)) {			\
1774 		args->m = m = m_pullup(m, (len));\
1775 		if (m == NULL)			\
1776 			goto pullup_failed;	\
1777 		ip = mtod(m, struct ip *);	\
1778 	}					\
1779 } while (0)
1780 
1781 	if (offset == 0) {
1782 		switch (proto) {
1783 		case IPPROTO_TCP:
1784 			{
1785 				struct tcphdr *tcp;
1786 
1787 				PULLUP_TO(hlen + sizeof(struct tcphdr));
1788 				tcp = L3HDR(struct tcphdr, ip);
1789 				dst_port = tcp->th_dport;
1790 				src_port = tcp->th_sport;
1791 				args->f_id.flags = tcp->th_flags;
1792 			}
1793 			break;
1794 
1795 		case IPPROTO_UDP:
1796 			{
1797 				struct udphdr *udp;
1798 
1799 				PULLUP_TO(hlen + sizeof(struct udphdr));
1800 				udp = L3HDR(struct udphdr, ip);
1801 				dst_port = udp->uh_dport;
1802 				src_port = udp->uh_sport;
1803 			}
1804 			break;
1805 
1806 		case IPPROTO_ICMP:
1807 			PULLUP_TO(hlen + 4);	/* type, code and checksum. */
1808 			args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1809 			break;
1810 
1811 		default:
1812 			break;
1813 		}
1814 	}
1815 
1816 #undef PULLUP_TO
1817 
1818 	args->f_id.src_ip = ntohl(src_ip.s_addr);
1819 	args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1820 	args->f_id.src_port = src_port = ntohs(src_port);
1821 	args->f_id.dst_port = dst_port = ntohs(dst_port);
1822 
1823 after_ip_checks:
1824 	if (args->rule) {
1825 		/*
1826 		 * Packet has already been tagged. Look for the next rule
1827 		 * to restart processing.
1828 		 *
1829 		 * If fw_one_pass != 0 then just accept it.
1830 		 * XXX should not happen here, but optimized out in
1831 		 * the caller.
1832 		 */
1833 		if (fw_one_pass)
1834 			return IP_FW_PASS;
1835 
1836 		/* This rule is being/has been flushed */
1837 		if (ipfw_flushing)
1838 			return IP_FW_DENY;
1839 
1840 		KASSERT(args->rule->cpuid == mycpuid,
1841 			("rule used on cpu%d", mycpuid));
1842 
1843 		/* This rule was deleted */
1844 		if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1845 			return IP_FW_DENY;
1846 
1847 		f = args->rule->next_rule;
1848 		if (f == NULL)
1849 			f = lookup_next_rule(args->rule);
1850 	} else {
1851 		/*
1852 		 * Find the starting rule. It can be either the first
1853 		 * one, or the one after divert_rule if asked so.
1854 		 */
1855 		int skipto;
1856 
1857 		mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1858 		if (mtag != NULL) {
1859 			divinfo = m_tag_data(mtag);
1860 			skipto = divinfo->skipto;
1861 		} else {
1862 			skipto = 0;
1863 		}
1864 
1865 		f = ctx->ipfw_layer3_chain;
1866 		if (args->eh == NULL && skipto != 0) {
1867 			/* No skipto during rule flushing */
1868 			if (ipfw_flushing)
1869 				return IP_FW_DENY;
1870 
1871 			if (skipto >= IPFW_DEFAULT_RULE)
1872 				return IP_FW_DENY; /* invalid */
1873 
1874 			while (f && f->rulenum <= skipto)
1875 				f = f->next;
1876 			if (f == NULL)	/* drop packet */
1877 				return IP_FW_DENY;
1878 		} else if (ipfw_flushing) {
1879 			/* Rules are being flushed; skip to default rule */
1880 			f = ctx->ipfw_default_rule;
1881 		}
1882 	}
1883 	if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1884 		m_tag_delete(m, mtag);
1885 
1886 	/*
1887 	 * Now scan the rules, and parse microinstructions for each rule.
1888 	 */
1889 	for (; f; f = f->next) {
1890 		int l, cmdlen;
1891 		ipfw_insn *cmd;
1892 		int skip_or; /* skip rest of OR block */
1893 
1894 again:
1895 		if (ctx->ipfw_set_disable & (1 << f->set))
1896 			continue;
1897 
1898 		skip_or = 0;
1899 		for (l = f->cmd_len, cmd = f->cmd; l > 0;
1900 		     l -= cmdlen, cmd += cmdlen) {
1901 			int match, deny;
1902 
1903 			/*
1904 			 * check_body is a jump target used when we find a
1905 			 * CHECK_STATE, and need to jump to the body of
1906 			 * the target rule.
1907 			 */
1908 
1909 check_body:
1910 			cmdlen = F_LEN(cmd);
1911 			/*
1912 			 * An OR block (insn_1 || .. || insn_n) has the
1913 			 * F_OR bit set in all but the last instruction.
1914 			 * The first match will set "skip_or", and cause
1915 			 * the following instructions to be skipped until
1916 			 * past the one with the F_OR bit clear.
1917 			 */
1918 			if (skip_or) {		/* skip this instruction */
1919 				if ((cmd->len & F_OR) == 0)
1920 					skip_or = 0;	/* next one is good */
1921 				continue;
1922 			}
1923 			match = 0; /* set to 1 if we succeed */
1924 
1925 			switch (cmd->opcode) {
1926 			/*
1927 			 * The first set of opcodes compares the packet's
1928 			 * fields with some pattern, setting 'match' if a
1929 			 * match is found. At the end of the loop there is
1930 			 * logic to deal with F_NOT and F_OR flags associated
1931 			 * with the opcode.
1932 			 */
1933 			case O_NOP:
1934 				match = 1;
1935 				break;
1936 
1937 			case O_FORWARD_MAC:
1938 				kprintf("ipfw: opcode %d unimplemented\n",
1939 					cmd->opcode);
1940 				break;
1941 
1942 			case O_GID:
1943 			case O_UID:
1944 				/*
1945 				 * We only check offset == 0 && proto != 0,
1946 				 * as this ensures that we have an IPv4
1947 				 * packet with the ports info.
1948 				 */
1949 				if (offset!=0)
1950 					break;
1951 
1952 				match = ipfw_match_uid(&args->f_id, oif,
1953 					cmd->opcode,
1954 					(uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1955 					&deny);
1956 				if (deny)
1957 					return IP_FW_DENY;
1958 				break;
1959 
1960 			case O_RECV:
1961 				match = iface_match(m->m_pkthdr.rcvif,
1962 				    (ipfw_insn_if *)cmd);
1963 				break;
1964 
1965 			case O_XMIT:
1966 				match = iface_match(oif, (ipfw_insn_if *)cmd);
1967 				break;
1968 
1969 			case O_VIA:
1970 				match = iface_match(oif ? oif :
1971 				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1972 				break;
1973 
1974 			case O_MACADDR2:
1975 				if (args->eh != NULL) {	/* have MAC header */
1976 					uint32_t *want = (uint32_t *)
1977 						((ipfw_insn_mac *)cmd)->addr;
1978 					uint32_t *mask = (uint32_t *)
1979 						((ipfw_insn_mac *)cmd)->mask;
1980 					uint32_t *hdr = (uint32_t *)args->eh;
1981 
1982 					match =
1983 					(want[0] == (hdr[0] & mask[0]) &&
1984 					 want[1] == (hdr[1] & mask[1]) &&
1985 					 want[2] == (hdr[2] & mask[2]));
1986 				}
1987 				break;
1988 
1989 			case O_MAC_TYPE:
1990 				if (args->eh != NULL) {
1991 					uint16_t t =
1992 					    ntohs(args->eh->ether_type);
1993 					uint16_t *p =
1994 					    ((ipfw_insn_u16 *)cmd)->ports;
1995 					int i;
1996 
1997 					/* Special vlan handling */
1998 					if (m->m_flags & M_VLANTAG)
1999 						t = ETHERTYPE_VLAN;
2000 
2001 					for (i = cmdlen - 1; !match && i > 0;
2002 					     i--, p += 2) {
2003 						match =
2004 						(t >= p[0] && t <= p[1]);
2005 					}
2006 				}
2007 				break;
2008 
2009 			case O_FRAG:
2010 				match = (hlen > 0 && offset != 0);
2011 				break;
2012 
2013 			case O_IN:	/* "out" is "not in" */
2014 				match = (oif == NULL);
2015 				break;
2016 
2017 			case O_LAYER2:
2018 				match = (args->eh != NULL);
2019 				break;
2020 
2021 			case O_PROTO:
2022 				/*
2023 				 * We do not allow an arg of 0 so the
2024 				 * check of "proto" only suffices.
2025 				 */
2026 				match = (proto == cmd->arg1);
2027 				break;
2028 
2029 			case O_IP_SRC:
2030 				match = (hlen > 0 &&
2031 				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2032 				    src_ip.s_addr);
2033 				break;
2034 
2035 			case O_IP_SRC_MASK:
2036 				match = (hlen > 0 &&
2037 				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2038 				     (src_ip.s_addr &
2039 				     ((ipfw_insn_ip *)cmd)->mask.s_addr));
2040 				break;
2041 
2042 			case O_IP_SRC_ME:
2043 				if (hlen > 0) {
2044 					struct ifnet *tif;
2045 
2046 					tif = INADDR_TO_IFP(&src_ip);
2047 					match = (tif != NULL);
2048 				}
2049 				break;
2050 
2051 			case O_IP_DST_SET:
2052 			case O_IP_SRC_SET:
2053 				if (hlen > 0) {
2054 					uint32_t *d = (uint32_t *)(cmd + 1);
2055 					uint32_t addr =
2056 					    cmd->opcode == O_IP_DST_SET ?
2057 						args->f_id.dst_ip :
2058 						args->f_id.src_ip;
2059 
2060 					if (addr < d[0])
2061 						break;
2062 					addr -= d[0]; /* subtract base */
2063 					match =
2064 					(addr < cmd->arg1) &&
2065 					 (d[1 + (addr >> 5)] &
2066 					  (1 << (addr & 0x1f)));
2067 				}
2068 				break;
2069 
2070 			case O_IP_DST:
2071 				match = (hlen > 0 &&
2072 				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2073 				    dst_ip.s_addr);
2074 				break;
2075 
2076 			case O_IP_DST_MASK:
2077 				match = (hlen > 0) &&
2078 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2079 				     (dst_ip.s_addr &
2080 				     ((ipfw_insn_ip *)cmd)->mask.s_addr));
2081 				break;
2082 
2083 			case O_IP_DST_ME:
2084 				if (hlen > 0) {
2085 					struct ifnet *tif;
2086 
2087 					tif = INADDR_TO_IFP(&dst_ip);
2088 					match = (tif != NULL);
2089 				}
2090 				break;
2091 
2092 			case O_IP_SRCPORT:
2093 			case O_IP_DSTPORT:
2094 				/*
2095 				 * offset == 0 && proto != 0 is enough
2096 				 * to guarantee that we have an IPv4
2097 				 * packet with port info.
2098 				 */
2099 				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2100 				    && offset == 0) {
2101 					uint16_t x =
2102 					    (cmd->opcode == O_IP_SRCPORT) ?
2103 						src_port : dst_port ;
2104 					uint16_t *p =
2105 					    ((ipfw_insn_u16 *)cmd)->ports;
2106 					int i;
2107 
2108 					for (i = cmdlen - 1; !match && i > 0;
2109 					     i--, p += 2) {
2110 						match =
2111 						(x >= p[0] && x <= p[1]);
2112 					}
2113 				}
2114 				break;
2115 
2116 			case O_ICMPTYPE:
2117 				match = (offset == 0 && proto==IPPROTO_ICMP &&
2118 				    icmptype_match(ip, (ipfw_insn_u32 *)cmd));
2119 				break;
2120 
2121 			case O_IPOPT:
2122 				match = (hlen > 0 && ipopts_match(ip, cmd));
2123 				break;
2124 
2125 			case O_IPVER:
2126 				match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2127 				break;
2128 
2129 			case O_IPTTL:
2130 				match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
2131 				break;
2132 
2133 			case O_IPID:
2134 				match = (hlen > 0 &&
2135 				    cmd->arg1 == ntohs(ip->ip_id));
2136 				break;
2137 
2138 			case O_IPLEN:
2139 				match = (hlen > 0 && cmd->arg1 == ip_len);
2140 				break;
2141 
2142 			case O_IPPRECEDENCE:
2143 				match = (hlen > 0 &&
2144 				    (cmd->arg1 == (ip->ip_tos & 0xe0)));
2145 				break;
2146 
2147 			case O_IPTOS:
2148 				match = (hlen > 0 &&
2149 				    flags_match(cmd, ip->ip_tos));
2150 				break;
2151 
2152 			case O_TCPFLAGS:
2153 				match = (proto == IPPROTO_TCP && offset == 0 &&
2154 				    flags_match(cmd,
2155 					L3HDR(struct tcphdr,ip)->th_flags));
2156 				break;
2157 
2158 			case O_TCPOPTS:
2159 				match = (proto == IPPROTO_TCP && offset == 0 &&
2160 				    tcpopts_match(ip, cmd));
2161 				break;
2162 
2163 			case O_TCPSEQ:
2164 				match = (proto == IPPROTO_TCP && offset == 0 &&
2165 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2166 					L3HDR(struct tcphdr,ip)->th_seq);
2167 				break;
2168 
2169 			case O_TCPACK:
2170 				match = (proto == IPPROTO_TCP && offset == 0 &&
2171 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2172 					L3HDR(struct tcphdr,ip)->th_ack);
2173 				break;
2174 
2175 			case O_TCPWIN:
2176 				match = (proto == IPPROTO_TCP && offset == 0 &&
2177 				    cmd->arg1 ==
2178 					L3HDR(struct tcphdr,ip)->th_win);
2179 				break;
2180 
2181 			case O_ESTAB:
2182 				/* reject packets which have SYN only */
2183 				/* XXX should i also check for TH_ACK ? */
2184 				match = (proto == IPPROTO_TCP && offset == 0 &&
2185 				    (L3HDR(struct tcphdr,ip)->th_flags &
2186 				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2187 				break;
2188 
2189 			case O_LOG:
2190 				if (fw_verbose)
2191 					ipfw_log(f, hlen, args->eh, m, oif);
2192 				match = 1;
2193 				break;
2194 
2195 			case O_PROB:
2196 				match = (krandom() <
2197 					((ipfw_insn_u32 *)cmd)->d[0]);
2198 				break;
2199 
2200 			/*
2201 			 * The second set of opcodes represents 'actions',
2202 			 * i.e. the terminal part of a rule once the packet
2203 			 * matches all previous patterns.
2204 			 * Typically there is only one action for each rule,
2205 			 * and the opcode is stored at the end of the rule
2206 			 * (but there are exceptions -- see below).
2207 			 *
2208 			 * In general, here we set retval and terminate the
2209 			 * outer loop (would be a 'break 3' in some language,
2210 			 * but we need to do a 'goto done').
2211 			 *
2212 			 * Exceptions:
2213 			 * O_COUNT and O_SKIPTO actions:
2214 			 *   instead of terminating, we jump to the next rule
2215 			 *   ('goto next_rule', equivalent to a 'break 2'),
2216 			 *   or to the SKIPTO target ('goto again' after
2217 			 *   having set f, cmd and l), respectively.
2218 			 *
2219 			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2220 			 *   not real 'actions', and are stored right
2221 			 *   before the 'action' part of the rule.
2222 			 *   These opcodes try to install an entry in the
2223 			 *   state tables; if successful, we continue with
2224 			 *   the next opcode (match=1; break;), otherwise
2225 			 *   the packet must be dropped ('goto done' after
2226 			 *   setting retval).  If static rules are changed
2227 			 *   during the state installation, the packet will
2228 			 *   be dropped and rule's stats will not beupdated
2229 			 *   ('return IP_FW_DENY').
2230 			 *
2231 			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2232 			 *   cause a lookup of the state table, and a jump
2233 			 *   to the 'action' part of the parent rule
2234 			 *   ('goto check_body') if an entry is found, or
2235 			 *   (CHECK_STATE only) a jump to the next rule if
2236 			 *   the entry is not found ('goto next_rule').
2237 			 *   The result of the lookup is cached to make
2238 			 *   further instances of these opcodes are
2239 			 *   effectively NOPs.  If static rules are changed
2240 			 *   during the state looking up, the packet will
2241 			 *   be dropped and rule's stats will not be updated
2242 			 *   ('return IP_FW_DENY').
2243 			 */
2244 			case O_LIMIT:
2245 			case O_KEEP_STATE:
2246 				if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2247 					kprintf("%s rule (%d) is not ready "
2248 						"on cpu%d\n",
2249 						cmd->opcode == O_LIMIT ?
2250 						"limit" : "keep state",
2251 						f->rulenum, f->cpuid);
2252 					goto next_rule;
2253 				}
2254 				if (install_state(f,
2255 				    (ipfw_insn_limit *)cmd, args, &deny)) {
2256 					if (deny)
2257 						return IP_FW_DENY;
2258 
2259 					retval = IP_FW_DENY;
2260 					goto done; /* error/limit violation */
2261 				}
2262 				if (deny)
2263 					return IP_FW_DENY;
2264 				match = 1;
2265 				break;
2266 
2267 			case O_PROBE_STATE:
2268 			case O_CHECK_STATE:
2269 				/*
2270 				 * dynamic rules are checked at the first
2271 				 * keep-state or check-state occurrence,
2272 				 * with the result being stored in dyn_dir.
2273 				 * The compiler introduces a PROBE_STATE
2274 				 * instruction for us when we have a
2275 				 * KEEP_STATE (because PROBE_STATE needs
2276 				 * to be run first).
2277 				 */
2278 				if (dyn_dir == MATCH_UNKNOWN) {
2279 					dyn_f = lookup_rule(&args->f_id,
2280 						&dyn_dir,
2281 						proto == IPPROTO_TCP ?
2282 						L3HDR(struct tcphdr, ip) : NULL,
2283 						ip_len, &deny);
2284 					if (deny)
2285 						return IP_FW_DENY;
2286 					if (dyn_f != NULL) {
2287 						/*
2288 						 * Found a rule from a dynamic
2289 						 * entry; jump to the 'action'
2290 						 * part of the rule.
2291 						 */
2292 						f = dyn_f;
2293 						cmd = ACTION_PTR(f);
2294 						l = f->cmd_len - f->act_ofs;
2295 						goto check_body;
2296 					}
2297 				}
2298 				/*
2299 				 * Dynamic entry not found. If CHECK_STATE,
2300 				 * skip to next rule, if PROBE_STATE just
2301 				 * ignore and continue with next opcode.
2302 				 */
2303 				if (cmd->opcode == O_CHECK_STATE)
2304 					goto next_rule;
2305 				else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2306 					goto next_rule; /* not ready yet */
2307 				match = 1;
2308 				break;
2309 
2310 			case O_ACCEPT:
2311 				retval = IP_FW_PASS;	/* accept */
2312 				goto done;
2313 
2314 			case O_PIPE:
2315 			case O_QUEUE:
2316 				args->rule = f; /* report matching rule */
2317 				args->cookie = cmd->arg1;
2318 				retval = IP_FW_DUMMYNET;
2319 				goto done;
2320 
2321 			case O_DIVERT:
2322 			case O_TEE:
2323 				if (args->eh) /* not on layer 2 */
2324 					break;
2325 
2326 				mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2327 						 sizeof(*divinfo), MB_DONTWAIT);
2328 				if (mtag == NULL) {
2329 					retval = IP_FW_DENY;
2330 					goto done;
2331 				}
2332 				divinfo = m_tag_data(mtag);
2333 
2334 				divinfo->skipto = f->rulenum;
2335 				divinfo->port = cmd->arg1;
2336 				divinfo->tee = (cmd->opcode == O_TEE);
2337 				m_tag_prepend(m, mtag);
2338 
2339 				args->cookie = cmd->arg1;
2340 				retval = (cmd->opcode == O_DIVERT) ?
2341 					 IP_FW_DIVERT : IP_FW_TEE;
2342 				goto done;
2343 
2344 			case O_COUNT:
2345 			case O_SKIPTO:
2346 				f->pcnt++;	/* update stats */
2347 				f->bcnt += ip_len;
2348 				f->timestamp = time_second;
2349 				if (cmd->opcode == O_COUNT)
2350 					goto next_rule;
2351 				/* handle skipto */
2352 				if (f->next_rule == NULL)
2353 					lookup_next_rule(f);
2354 				f = f->next_rule;
2355 				goto again;
2356 
2357 			case O_REJECT:
2358 				/*
2359 				 * Drop the packet and send a reject notice
2360 				 * if the packet is not ICMP (or is an ICMP
2361 				 * query), and it is not multicast/broadcast.
2362 				 */
2363 				if (hlen > 0 &&
2364 				    (proto != IPPROTO_ICMP ||
2365 				     is_icmp_query(ip)) &&
2366 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2367 				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2368 					/*
2369 					 * Update statistics before the possible
2370 					 * blocking 'send_reject'
2371 					 */
2372 					f->pcnt++;
2373 					f->bcnt += ip_len;
2374 					f->timestamp = time_second;
2375 
2376 					send_reject(args, cmd->arg1,
2377 					    offset,ip_len);
2378 					m = args->m;
2379 
2380 					/*
2381 					 * Return directly here, rule stats
2382 					 * have been updated above.
2383 					 */
2384 					return IP_FW_DENY;
2385 				}
2386 				/* FALLTHROUGH */
2387 			case O_DENY:
2388 				retval = IP_FW_DENY;
2389 				goto done;
2390 
2391 			case O_FORWARD_IP:
2392 				if (args->eh)	/* not valid on layer2 pkts */
2393 					break;
2394 				if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2395 					struct sockaddr_in *sin;
2396 
2397 					mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2398 					       sizeof(*sin), MB_DONTWAIT);
2399 					if (mtag == NULL) {
2400 						retval = IP_FW_DENY;
2401 						goto done;
2402 					}
2403 					sin = m_tag_data(mtag);
2404 
2405 					/* Structure copy */
2406 					*sin = ((ipfw_insn_sa *)cmd)->sa;
2407 
2408 					m_tag_prepend(m, mtag);
2409 					m->m_pkthdr.fw_flags |=
2410 						IPFORWARD_MBUF_TAGGED;
2411 					m->m_pkthdr.fw_flags &=
2412 						~BRIDGE_MBUF_TAGGED;
2413 				}
2414 				retval = IP_FW_PASS;
2415 				goto done;
2416 
2417 			default:
2418 				panic("-- unknown opcode %d", cmd->opcode);
2419 			} /* end of switch() on opcodes */
2420 
2421 			if (cmd->len & F_NOT)
2422 				match = !match;
2423 
2424 			if (match) {
2425 				if (cmd->len & F_OR)
2426 					skip_or = 1;
2427 			} else {
2428 				if (!(cmd->len & F_OR)) /* not an OR block, */
2429 					break;		/* try next rule    */
2430 			}
2431 
2432 		}	/* end of inner for, scan opcodes */
2433 
2434 next_rule:;		/* try next rule		*/
2435 
2436 	}		/* end of outer for, scan rules */
2437 	kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2438 	return IP_FW_DENY;
2439 
2440 done:
2441 	/* Update statistics */
2442 	f->pcnt++;
2443 	f->bcnt += ip_len;
2444 	f->timestamp = time_second;
2445 	return retval;
2446 
2447 pullup_failed:
2448 	if (fw_verbose)
2449 		kprintf("pullup failed\n");
2450 	return IP_FW_DENY;
2451 }
2452 
2453 static void
2454 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2455 {
2456 	struct m_tag *mtag;
2457 	struct dn_pkt *pkt;
2458 	ipfw_insn *cmd;
2459 	const struct ipfw_flow_id *id;
2460 	struct dn_flow_id *fid;
2461 
2462 	M_ASSERTPKTHDR(m);
2463 
2464 	mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2465 	if (mtag == NULL) {
2466 		m_freem(m);
2467 		return;
2468 	}
2469 	m_tag_prepend(m, mtag);
2470 
2471 	pkt = m_tag_data(mtag);
2472 	bzero(pkt, sizeof(*pkt));
2473 
2474 	cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2475 	if (cmd->opcode == O_LOG)
2476 		cmd += F_LEN(cmd);
2477 	KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2478 		("Rule is not PIPE or QUEUE, opcode %d", cmd->opcode));
2479 
2480 	pkt->dn_m = m;
2481 	pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2482 	pkt->ifp = fwa->oif;
2483 	pkt->pipe_nr = pipe_nr;
2484 
2485 	pkt->cpuid = mycpuid;
2486 	pkt->msgport = cur_netport();
2487 
2488 	id = &fwa->f_id;
2489 	fid = &pkt->id;
2490 	fid->fid_dst_ip = id->dst_ip;
2491 	fid->fid_src_ip = id->src_ip;
2492 	fid->fid_dst_port = id->dst_port;
2493 	fid->fid_src_port = id->src_port;
2494 	fid->fid_proto = id->proto;
2495 	fid->fid_flags = id->flags;
2496 
2497 	ipfw_ref_rule(fwa->rule);
2498 	pkt->dn_priv = fwa->rule;
2499 	pkt->dn_unref_priv = ipfw_unref_rule;
2500 
2501 	if (cmd->opcode == O_PIPE)
2502 		pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2503 
2504 	m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2505 }
2506 
2507 /*
2508  * When a rule is added/deleted, clear the next_rule pointers in all rules.
2509  * These will be reconstructed on the fly as packets are matched.
2510  * Must be called at splimp().
2511  */
2512 static void
2513 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2514 {
2515 	struct ip_fw *rule;
2516 
2517 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2518 		rule->next_rule = NULL;
2519 }
2520 
2521 static __inline void
2522 ipfw_inc_static_count(struct ip_fw *rule)
2523 {
2524 	/* Static rule's counts are updated only on CPU0 */
2525 	KKASSERT(mycpuid == 0);
2526 
2527 	static_count++;
2528 	static_ioc_len += IOC_RULESIZE(rule);
2529 }
2530 
2531 static __inline void
2532 ipfw_dec_static_count(struct ip_fw *rule)
2533 {
2534 	int l = IOC_RULESIZE(rule);
2535 
2536 	/* Static rule's counts are updated only on CPU0 */
2537 	KKASSERT(mycpuid == 0);
2538 
2539 	KASSERT(static_count > 0, ("invalid static count %u", static_count));
2540 	static_count--;
2541 
2542 	KASSERT(static_ioc_len >= l,
2543 		("invalid static len %u", static_ioc_len));
2544 	static_ioc_len -= l;
2545 }
2546 
2547 static void
2548 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2549 {
2550 	if (fwmsg->sibling != NULL) {
2551 		KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2552 		fwmsg->sibling->sibling = rule;
2553 	}
2554 	fwmsg->sibling = rule;
2555 }
2556 
2557 static struct ip_fw *
2558 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2559 {
2560 	struct ip_fw *rule;
2561 
2562 	rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2563 
2564 	rule->act_ofs = ioc_rule->act_ofs;
2565 	rule->cmd_len = ioc_rule->cmd_len;
2566 	rule->rulenum = ioc_rule->rulenum;
2567 	rule->set = ioc_rule->set;
2568 	rule->usr_flags = ioc_rule->usr_flags;
2569 
2570 	bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2571 
2572 	rule->refcnt = 1;
2573 	rule->cpuid = mycpuid;
2574 
2575 	rule->stub = stub;
2576 	if (stub != NULL)
2577 		stub->rule[mycpuid] = rule;
2578 
2579 	return rule;
2580 }
2581 
2582 static void
2583 ipfw_add_rule_dispatch(netmsg_t nmsg)
2584 {
2585 	struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2586 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2587 	struct ip_fw *rule;
2588 
2589 	rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2590 
2591 	/*
2592 	 * Bump generation after ipfw_create_rule(),
2593 	 * since this function is blocking
2594 	 */
2595 	ctx->ipfw_gen++;
2596 
2597 	/*
2598 	 * Insert rule into the pre-determined position
2599 	 */
2600 	if (fwmsg->prev_rule != NULL) {
2601 		struct ip_fw *prev, *next;
2602 
2603 		prev = fwmsg->prev_rule;
2604 		KKASSERT(prev->cpuid == mycpuid);
2605 
2606 		next = fwmsg->next_rule;
2607 		KKASSERT(next->cpuid == mycpuid);
2608 
2609 		rule->next = next;
2610 		prev->next = rule;
2611 
2612 		/*
2613 		 * Move to the position on the next CPU
2614 		 * before the msg is forwarded.
2615 		 */
2616 		fwmsg->prev_rule = prev->sibling;
2617 		fwmsg->next_rule = next->sibling;
2618 	} else {
2619 		KKASSERT(fwmsg->next_rule == NULL);
2620 		rule->next = ctx->ipfw_layer3_chain;
2621 		ctx->ipfw_layer3_chain = rule;
2622 	}
2623 
2624 	/* Link rule CPU sibling */
2625 	ipfw_link_sibling(fwmsg, rule);
2626 
2627 	ipfw_flush_rule_ptrs(ctx);
2628 
2629 	if (mycpuid == 0) {
2630 		/* Statistics only need to be updated once */
2631 		ipfw_inc_static_count(rule);
2632 
2633 		/* Return the rule on CPU0 */
2634 		nmsg->lmsg.u.ms_resultp = rule;
2635 	}
2636 
2637 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2638 }
2639 
2640 static void
2641 ipfw_enable_state_dispatch(netmsg_t nmsg)
2642 {
2643 	struct lwkt_msg *lmsg = &nmsg->lmsg;
2644 	struct ip_fw *rule = lmsg->u.ms_resultp;
2645 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2646 
2647 	ctx->ipfw_gen++;
2648 
2649 	KKASSERT(rule->cpuid == mycpuid);
2650 	KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2651 	KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2652 	rule->rule_flags |= IPFW_RULE_F_STATE;
2653 	lmsg->u.ms_resultp = rule->sibling;
2654 
2655 	ifnet_forwardmsg(lmsg, mycpuid + 1);
2656 }
2657 
2658 /*
2659  * Add a new rule to the list.  Copy the rule into a malloc'ed area,
2660  * then possibly create a rule number and add the rule to the list.
2661  * Update the rule_number in the input struct so the caller knows
2662  * it as well.
2663  */
2664 static void
2665 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2666 {
2667 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2668 	struct netmsg_ipfw fwmsg;
2669 	struct netmsg_base *nmsg;
2670 	struct ip_fw *f, *prev, *rule;
2671 	struct ip_fw_stub *stub;
2672 
2673 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2674 
2675 	/*
2676 	 * If rulenum is 0, find highest numbered rule before the
2677 	 * default rule, and add rule number incremental step.
2678 	 */
2679 	if (ioc_rule->rulenum == 0) {
2680 		int step = autoinc_step;
2681 
2682 		KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2683 			 step <= IPFW_AUTOINC_STEP_MAX);
2684 
2685 		/*
2686 		 * Locate the highest numbered rule before default
2687 		 */
2688 		for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2689 			if (f->rulenum == IPFW_DEFAULT_RULE)
2690 				break;
2691 			ioc_rule->rulenum = f->rulenum;
2692 		}
2693 		if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2694 			ioc_rule->rulenum += step;
2695 	}
2696 	KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2697 		ioc_rule->rulenum != 0,
2698 		("invalid rule num %d", ioc_rule->rulenum));
2699 
2700 	/*
2701 	 * Now find the right place for the new rule in the sorted list.
2702 	 */
2703 	for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2704 	     prev = f, f = f->next) {
2705 		if (f->rulenum > ioc_rule->rulenum) {
2706 			/* Found the location */
2707 			break;
2708 		}
2709 	}
2710 	KASSERT(f != NULL, ("no default rule?!"));
2711 
2712 	if (rule_flags & IPFW_RULE_F_STATE) {
2713 		int size;
2714 
2715 		/*
2716 		 * If the new rule will create states, then allocate
2717 		 * a rule stub, which will be referenced by states
2718 		 * (dyn rules)
2719 		 */
2720 		size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2721 		stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2722 	} else {
2723 		stub = NULL;
2724 	}
2725 
2726 	/*
2727 	 * Duplicate the rule onto each CPU.
2728 	 * The rule duplicated on CPU0 will be returned.
2729 	 */
2730 	bzero(&fwmsg, sizeof(fwmsg));
2731 	nmsg = &fwmsg.base;
2732 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
2733 		    0, ipfw_add_rule_dispatch);
2734 	fwmsg.ioc_rule = ioc_rule;
2735 	fwmsg.prev_rule = prev;
2736 	fwmsg.next_rule = prev == NULL ? NULL : f;
2737 	fwmsg.stub = stub;
2738 
2739 	ifnet_domsg(&nmsg->lmsg, 0);
2740 	KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2741 
2742 	rule = nmsg->lmsg.u.ms_resultp;
2743 	KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2744 
2745 	if (rule_flags & IPFW_RULE_F_STATE) {
2746 		/*
2747 		 * Turn on state flag, _after_ everything on all
2748 		 * CPUs have been setup.
2749 		 */
2750 		bzero(nmsg, sizeof(*nmsg));
2751 		netmsg_init(nmsg, NULL, &curthread->td_msgport,
2752 			    0, ipfw_enable_state_dispatch);
2753 		nmsg->lmsg.u.ms_resultp = rule;
2754 
2755 		ifnet_domsg(&nmsg->lmsg, 0);
2756 		KKASSERT(nmsg->lmsg.u.ms_resultp == NULL);
2757 	}
2758 
2759 	DPRINTF("++ installed rule %d, static count now %d\n",
2760 		rule->rulenum, static_count);
2761 }
2762 
2763 /**
2764  * Free storage associated with a static rule (including derived
2765  * dynamic rules).
2766  * The caller is in charge of clearing rule pointers to avoid
2767  * dangling pointers.
2768  * @return a pointer to the next entry.
2769  * Arguments are not checked, so they better be correct.
2770  * Must be called at splimp().
2771  */
2772 static struct ip_fw *
2773 ipfw_delete_rule(struct ipfw_context *ctx,
2774 		 struct ip_fw *prev, struct ip_fw *rule)
2775 {
2776 	struct ip_fw *n;
2777 	struct ip_fw_stub *stub;
2778 
2779 	ctx->ipfw_gen++;
2780 
2781 	/* STATE flag should have been cleared before we reach here */
2782 	KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2783 
2784 	stub = rule->stub;
2785 	n = rule->next;
2786 	if (prev == NULL)
2787 		ctx->ipfw_layer3_chain = n;
2788 	else
2789 		prev->next = n;
2790 
2791 	/* Mark the rule as invalid */
2792 	rule->rule_flags |= IPFW_RULE_F_INVALID;
2793 	rule->next_rule = NULL;
2794 	rule->sibling = NULL;
2795 	rule->stub = NULL;
2796 #ifdef foo
2797 	/* Don't reset cpuid here; keep various assertion working */
2798 	rule->cpuid = -1;
2799 #endif
2800 
2801 	/* Statistics only need to be updated once */
2802 	if (mycpuid == 0)
2803 		ipfw_dec_static_count(rule);
2804 
2805 	/* Free 'stub' on the last CPU */
2806 	if (stub != NULL && mycpuid == ncpus - 1)
2807 		kfree(stub, M_IPFW);
2808 
2809 	/* Try to free this rule */
2810 	ipfw_free_rule(rule);
2811 
2812 	/* Return the next rule */
2813 	return n;
2814 }
2815 
2816 static void
2817 ipfw_flush_dispatch(netmsg_t nmsg)
2818 {
2819 	struct lwkt_msg *lmsg = &nmsg->lmsg;
2820 	int kill_default = lmsg->u.ms_result;
2821 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2822 	struct ip_fw *rule;
2823 
2824 	ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2825 
2826 	while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2827 	       (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2828 		ipfw_delete_rule(ctx, NULL, rule);
2829 
2830 	ifnet_forwardmsg(lmsg, mycpuid + 1);
2831 }
2832 
2833 static void
2834 ipfw_disable_rule_state_dispatch(netmsg_t nmsg)
2835 {
2836 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2837 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2838 	struct ip_fw *rule;
2839 
2840 	ctx->ipfw_gen++;
2841 
2842 	rule = dmsg->start_rule;
2843 	if (rule != NULL) {
2844 		KKASSERT(rule->cpuid == mycpuid);
2845 
2846 		/*
2847 		 * Move to the position on the next CPU
2848 		 * before the msg is forwarded.
2849 		 */
2850 		dmsg->start_rule = rule->sibling;
2851 	} else {
2852 		KKASSERT(dmsg->rulenum == 0);
2853 		rule = ctx->ipfw_layer3_chain;
2854 	}
2855 
2856 	while (rule != NULL) {
2857 		if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2858 			break;
2859 		rule->rule_flags &= ~IPFW_RULE_F_STATE;
2860 		rule = rule->next;
2861 	}
2862 
2863 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2864 }
2865 
2866 /*
2867  * Deletes all rules from a chain (including the default rule
2868  * if the second argument is set).
2869  * Must be called at splimp().
2870  */
2871 static void
2872 ipfw_flush(int kill_default)
2873 {
2874 	struct netmsg_del dmsg;
2875 	struct netmsg_base nmsg;
2876 	struct lwkt_msg *lmsg;
2877 	struct ip_fw *rule;
2878 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2879 
2880 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2881 
2882 	/*
2883 	 * If 'kill_default' then caller has done the necessary
2884 	 * msgport syncing; unnecessary to do it again.
2885 	 */
2886 	if (!kill_default) {
2887 		/*
2888 		 * Let ipfw_chk() know the rules are going to
2889 		 * be flushed, so it could jump directly to
2890 		 * the default rule.
2891 		 */
2892 		ipfw_flushing = 1;
2893 		netmsg_service_sync();
2894 	}
2895 
2896 	/*
2897 	 * Clear STATE flag on rules, so no more states (dyn rules)
2898 	 * will be created.
2899 	 */
2900 	bzero(&dmsg, sizeof(dmsg));
2901 	netmsg_init(&dmsg.base, NULL, &curthread->td_msgport,
2902 		    0, ipfw_disable_rule_state_dispatch);
2903 	ifnet_domsg(&dmsg.base.lmsg, 0);
2904 
2905 	/*
2906 	 * This actually nukes all states (dyn rules)
2907 	 */
2908 	lockmgr(&dyn_lock, LK_EXCLUSIVE);
2909 	for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2910 		/*
2911 		 * Can't check IPFW_RULE_F_STATE here,
2912 		 * since it has been cleared previously.
2913 		 * Check 'stub' instead.
2914 		 */
2915 		if (rule->stub != NULL) {
2916 			/* Force removal */
2917 			remove_dyn_rule_locked(rule, NULL);
2918 		}
2919 	}
2920 	lockmgr(&dyn_lock, LK_RELEASE);
2921 
2922 	/*
2923 	 * Press the 'flush' button
2924 	 */
2925 	bzero(&nmsg, sizeof(nmsg));
2926 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
2927 		    0, ipfw_flush_dispatch);
2928 	lmsg = &nmsg.lmsg;
2929 	lmsg->u.ms_result = kill_default;
2930 	ifnet_domsg(lmsg, 0);
2931 
2932 	KASSERT(dyn_count == 0, ("%u dyn rule remains", dyn_count));
2933 
2934 	if (kill_default) {
2935 		if (ipfw_dyn_v != NULL) {
2936 			/*
2937 			 * Free dynamic rules(state) hash table
2938 			 */
2939 			kfree(ipfw_dyn_v, M_IPFW);
2940 			ipfw_dyn_v = NULL;
2941 		}
2942 
2943 		KASSERT(static_count == 0,
2944 			("%u static rules remain", static_count));
2945 		KASSERT(static_ioc_len == 0,
2946 			("%u bytes of static rules remain", static_ioc_len));
2947 	} else {
2948 		KASSERT(static_count == 1,
2949 			("%u static rules remain", static_count));
2950 		KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2951 			("%u bytes of static rules remain, should be %lu",
2952 			 static_ioc_len,
2953 			 (u_long)IOC_RULESIZE(ctx->ipfw_default_rule)));
2954 	}
2955 
2956 	/* Flush is done */
2957 	ipfw_flushing = 0;
2958 }
2959 
2960 static void
2961 ipfw_alt_delete_rule_dispatch(netmsg_t nmsg)
2962 {
2963 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2964 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2965 	struct ip_fw *rule, *prev;
2966 
2967 	rule = dmsg->start_rule;
2968 	KKASSERT(rule->cpuid == mycpuid);
2969 	dmsg->start_rule = rule->sibling;
2970 
2971 	prev = dmsg->prev_rule;
2972 	if (prev != NULL) {
2973 		KKASSERT(prev->cpuid == mycpuid);
2974 
2975 		/*
2976 		 * Move to the position on the next CPU
2977 		 * before the msg is forwarded.
2978 		 */
2979 		dmsg->prev_rule = prev->sibling;
2980 	}
2981 
2982 	/*
2983 	 * flush pointers outside the loop, then delete all matching
2984 	 * rules.  'prev' remains the same throughout the cycle.
2985 	 */
2986 	ipfw_flush_rule_ptrs(ctx);
2987 	while (rule && rule->rulenum == dmsg->rulenum)
2988 		rule = ipfw_delete_rule(ctx, prev, rule);
2989 
2990 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2991 }
2992 
2993 static int
2994 ipfw_alt_delete_rule(uint16_t rulenum)
2995 {
2996 	struct ip_fw *prev, *rule, *f;
2997 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2998 	struct netmsg_del dmsg;
2999 	struct netmsg_base *nmsg;
3000 	int state;
3001 
3002 	/*
3003 	 * Locate first rule to delete
3004 	 */
3005 	for (prev = NULL, rule = ctx->ipfw_layer3_chain;
3006 	     rule && rule->rulenum < rulenum;
3007 	     prev = rule, rule = rule->next)
3008 		; /* EMPTY */
3009 	if (rule->rulenum != rulenum)
3010 		return EINVAL;
3011 
3012 	/*
3013 	 * Check whether any rules with the given number will
3014 	 * create states.
3015 	 */
3016 	state = 0;
3017 	for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3018 		if (f->rule_flags & IPFW_RULE_F_STATE) {
3019 			state = 1;
3020 			break;
3021 		}
3022 	}
3023 
3024 	if (state) {
3025 		/*
3026 		 * Clear the STATE flag, so no more states will be
3027 		 * created based the rules numbered 'rulenum'.
3028 		 */
3029 		bzero(&dmsg, sizeof(dmsg));
3030 		nmsg = &dmsg.base;
3031 		netmsg_init(nmsg, NULL, &curthread->td_msgport,
3032 			    0, ipfw_disable_rule_state_dispatch);
3033 		dmsg.start_rule = rule;
3034 		dmsg.rulenum = rulenum;
3035 
3036 		ifnet_domsg(&nmsg->lmsg, 0);
3037 		KKASSERT(dmsg.start_rule == NULL);
3038 
3039 		/*
3040 		 * Nuke all related states
3041 		 */
3042 		lockmgr(&dyn_lock, LK_EXCLUSIVE);
3043 		for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3044 			/*
3045 			 * Can't check IPFW_RULE_F_STATE here,
3046 			 * since it has been cleared previously.
3047 			 * Check 'stub' instead.
3048 			 */
3049 			if (f->stub != NULL) {
3050 				/* Force removal */
3051 				remove_dyn_rule_locked(f, NULL);
3052 			}
3053 		}
3054 		lockmgr(&dyn_lock, LK_RELEASE);
3055 	}
3056 
3057 	/*
3058 	 * Get rid of the rule duplications on all CPUs
3059 	 */
3060 	bzero(&dmsg, sizeof(dmsg));
3061 	nmsg = &dmsg.base;
3062 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3063 		    0, ipfw_alt_delete_rule_dispatch);
3064 	dmsg.prev_rule = prev;
3065 	dmsg.start_rule = rule;
3066 	dmsg.rulenum = rulenum;
3067 
3068 	ifnet_domsg(&nmsg->lmsg, 0);
3069 	KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3070 	return 0;
3071 }
3072 
3073 static void
3074 ipfw_alt_delete_ruleset_dispatch(netmsg_t nmsg)
3075 {
3076 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3077 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3078 	struct ip_fw *prev, *rule;
3079 #ifdef INVARIANTS
3080 	int del = 0;
3081 #endif
3082 
3083 	ipfw_flush_rule_ptrs(ctx);
3084 
3085 	prev = NULL;
3086 	rule = ctx->ipfw_layer3_chain;
3087 	while (rule != NULL) {
3088 		if (rule->set == dmsg->from_set) {
3089 			rule = ipfw_delete_rule(ctx, prev, rule);
3090 #ifdef INVARIANTS
3091 			del = 1;
3092 #endif
3093 		} else {
3094 			prev = rule;
3095 			rule = rule->next;
3096 		}
3097 	}
3098 	KASSERT(del, ("no match set?!"));
3099 
3100 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3101 }
3102 
3103 static void
3104 ipfw_disable_ruleset_state_dispatch(netmsg_t nmsg)
3105 {
3106 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3107 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3108 	struct ip_fw *rule;
3109 #ifdef INVARIANTS
3110 	int cleared = 0;
3111 #endif
3112 
3113 	ctx->ipfw_gen++;
3114 
3115 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3116 		if (rule->set == dmsg->from_set) {
3117 #ifdef INVARIANTS
3118 			cleared = 1;
3119 #endif
3120 			rule->rule_flags &= ~IPFW_RULE_F_STATE;
3121 		}
3122 	}
3123 	KASSERT(cleared, ("no match set?!"));
3124 
3125 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3126 }
3127 
3128 static int
3129 ipfw_alt_delete_ruleset(uint8_t set)
3130 {
3131 	struct netmsg_del dmsg;
3132 	struct netmsg_base *nmsg;
3133 	int state, del;
3134 	struct ip_fw *rule;
3135 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3136 
3137 	/*
3138 	 * Check whether the 'set' exists.  If it exists,
3139 	 * then check whether any rules within the set will
3140 	 * try to create states.
3141 	 */
3142 	state = 0;
3143 	del = 0;
3144 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3145 		if (rule->set == set) {
3146 			del = 1;
3147 			if (rule->rule_flags & IPFW_RULE_F_STATE) {
3148 				state = 1;
3149 				break;
3150 			}
3151 		}
3152 	}
3153 	if (!del)
3154 		return 0; /* XXX EINVAL? */
3155 
3156 	if (state) {
3157 		/*
3158 		 * Clear the STATE flag, so no more states will be
3159 		 * created based the rules in this set.
3160 		 */
3161 		bzero(&dmsg, sizeof(dmsg));
3162 		nmsg = &dmsg.base;
3163 		netmsg_init(nmsg, NULL, &curthread->td_msgport,
3164 			    0, ipfw_disable_ruleset_state_dispatch);
3165 		dmsg.from_set = set;
3166 
3167 		ifnet_domsg(&nmsg->lmsg, 0);
3168 
3169 		/*
3170 		 * Nuke all related states
3171 		 */
3172 		lockmgr(&dyn_lock, LK_EXCLUSIVE);
3173 		for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3174 			if (rule->set != set)
3175 				continue;
3176 
3177 			/*
3178 			 * Can't check IPFW_RULE_F_STATE here,
3179 			 * since it has been cleared previously.
3180 			 * Check 'stub' instead.
3181 			 */
3182 			if (rule->stub != NULL) {
3183 				/* Force removal */
3184 				remove_dyn_rule_locked(rule, NULL);
3185 			}
3186 		}
3187 		lockmgr(&dyn_lock, LK_RELEASE);
3188 	}
3189 
3190 	/*
3191 	 * Delete this set
3192 	 */
3193 	bzero(&dmsg, sizeof(dmsg));
3194 	nmsg = &dmsg.base;
3195 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3196 		    0, ipfw_alt_delete_ruleset_dispatch);
3197 	dmsg.from_set = set;
3198 
3199 	ifnet_domsg(&nmsg->lmsg, 0);
3200 	return 0;
3201 }
3202 
3203 static void
3204 ipfw_alt_move_rule_dispatch(netmsg_t nmsg)
3205 {
3206 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3207 	struct ip_fw *rule;
3208 
3209 	rule = dmsg->start_rule;
3210 	KKASSERT(rule->cpuid == mycpuid);
3211 
3212 	/*
3213 	 * Move to the position on the next CPU
3214 	 * before the msg is forwarded.
3215 	 */
3216 	dmsg->start_rule = rule->sibling;
3217 
3218 	while (rule && rule->rulenum <= dmsg->rulenum) {
3219 		if (rule->rulenum == dmsg->rulenum)
3220 			rule->set = dmsg->to_set;
3221 		rule = rule->next;
3222 	}
3223 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3224 }
3225 
3226 static int
3227 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3228 {
3229 	struct netmsg_del dmsg;
3230 	struct netmsg_base *nmsg;
3231 	struct ip_fw *rule;
3232 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3233 
3234 	/*
3235 	 * Locate first rule to move
3236 	 */
3237 	for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3238 	     rule = rule->next) {
3239 		if (rule->rulenum == rulenum && rule->set != set)
3240 			break;
3241 	}
3242 	if (rule == NULL || rule->rulenum > rulenum)
3243 		return 0; /* XXX error? */
3244 
3245 	bzero(&dmsg, sizeof(dmsg));
3246 	nmsg = &dmsg.base;
3247 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3248 		    0, ipfw_alt_move_rule_dispatch);
3249 	dmsg.start_rule = rule;
3250 	dmsg.rulenum = rulenum;
3251 	dmsg.to_set = set;
3252 
3253 	ifnet_domsg(&nmsg->lmsg, 0);
3254 	KKASSERT(dmsg.start_rule == NULL);
3255 	return 0;
3256 }
3257 
3258 static void
3259 ipfw_alt_move_ruleset_dispatch(netmsg_t nmsg)
3260 {
3261 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3262 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3263 	struct ip_fw *rule;
3264 
3265 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3266 		if (rule->set == dmsg->from_set)
3267 			rule->set = dmsg->to_set;
3268 	}
3269 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3270 }
3271 
3272 static int
3273 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3274 {
3275 	struct netmsg_del dmsg;
3276 	struct netmsg_base *nmsg;
3277 
3278 	bzero(&dmsg, sizeof(dmsg));
3279 	nmsg = &dmsg.base;
3280 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3281 		    0, ipfw_alt_move_ruleset_dispatch);
3282 	dmsg.from_set = from_set;
3283 	dmsg.to_set = to_set;
3284 
3285 	ifnet_domsg(&nmsg->lmsg, 0);
3286 	return 0;
3287 }
3288 
3289 static void
3290 ipfw_alt_swap_ruleset_dispatch(netmsg_t nmsg)
3291 {
3292 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3293 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3294 	struct ip_fw *rule;
3295 
3296 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3297 		if (rule->set == dmsg->from_set)
3298 			rule->set = dmsg->to_set;
3299 		else if (rule->set == dmsg->to_set)
3300 			rule->set = dmsg->from_set;
3301 	}
3302 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3303 }
3304 
3305 static int
3306 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3307 {
3308 	struct netmsg_del dmsg;
3309 	struct netmsg_base *nmsg;
3310 
3311 	bzero(&dmsg, sizeof(dmsg));
3312 	nmsg = &dmsg.base;
3313 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3314 		    0, ipfw_alt_swap_ruleset_dispatch);
3315 	dmsg.from_set = set1;
3316 	dmsg.to_set = set2;
3317 
3318 	ifnet_domsg(&nmsg->lmsg, 0);
3319 	return 0;
3320 }
3321 
3322 /**
3323  * Remove all rules with given number, and also do set manipulation.
3324  *
3325  * The argument is an uint32_t. The low 16 bit are the rule or set number,
3326  * the next 8 bits are the new set, the top 8 bits are the command:
3327  *
3328  *	0	delete rules with given number
3329  *	1	delete rules with given set number
3330  *	2	move rules with given number to new set
3331  *	3	move rules with given set number to new set
3332  *	4	swap sets with given numbers
3333  */
3334 static int
3335 ipfw_ctl_alter(uint32_t arg)
3336 {
3337 	uint16_t rulenum;
3338 	uint8_t cmd, new_set;
3339 	int error = 0;
3340 
3341 	rulenum = arg & 0xffff;
3342 	cmd = (arg >> 24) & 0xff;
3343 	new_set = (arg >> 16) & 0xff;
3344 
3345 	if (cmd > 4)
3346 		return EINVAL;
3347 	if (new_set >= IPFW_DEFAULT_SET)
3348 		return EINVAL;
3349 	if (cmd == 0 || cmd == 2) {
3350 		if (rulenum == IPFW_DEFAULT_RULE)
3351 			return EINVAL;
3352 	} else {
3353 		if (rulenum >= IPFW_DEFAULT_SET)
3354 			return EINVAL;
3355 	}
3356 
3357 	switch (cmd) {
3358 	case 0:	/* delete rules with given number */
3359 		error = ipfw_alt_delete_rule(rulenum);
3360 		break;
3361 
3362 	case 1:	/* delete all rules with given set number */
3363 		error = ipfw_alt_delete_ruleset(rulenum);
3364 		break;
3365 
3366 	case 2:	/* move rules with given number to new set */
3367 		error = ipfw_alt_move_rule(rulenum, new_set);
3368 		break;
3369 
3370 	case 3: /* move rules with given set number to new set */
3371 		error = ipfw_alt_move_ruleset(rulenum, new_set);
3372 		break;
3373 
3374 	case 4: /* swap two sets */
3375 		error = ipfw_alt_swap_ruleset(rulenum, new_set);
3376 		break;
3377 	}
3378 	return error;
3379 }
3380 
3381 /*
3382  * Clear counters for a specific rule.
3383  */
3384 static void
3385 clear_counters(struct ip_fw *rule, int log_only)
3386 {
3387 	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3388 
3389 	if (log_only == 0) {
3390 		rule->bcnt = rule->pcnt = 0;
3391 		rule->timestamp = 0;
3392 	}
3393 	if (l->o.opcode == O_LOG)
3394 		l->log_left = l->max_log;
3395 }
3396 
3397 static void
3398 ipfw_zero_entry_dispatch(netmsg_t nmsg)
3399 {
3400 	struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3401 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3402 	struct ip_fw *rule;
3403 
3404 	if (zmsg->rulenum == 0) {
3405 		KKASSERT(zmsg->start_rule == NULL);
3406 
3407 		ctx->ipfw_norule_counter = 0;
3408 		for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3409 			clear_counters(rule, zmsg->log_only);
3410 	} else {
3411 		struct ip_fw *start = zmsg->start_rule;
3412 
3413 		KKASSERT(start->cpuid == mycpuid);
3414 		KKASSERT(start->rulenum == zmsg->rulenum);
3415 
3416 		/*
3417 		 * We can have multiple rules with the same number, so we
3418 		 * need to clear them all.
3419 		 */
3420 		for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3421 		     rule = rule->next)
3422 			clear_counters(rule, zmsg->log_only);
3423 
3424 		/*
3425 		 * Move to the position on the next CPU
3426 		 * before the msg is forwarded.
3427 		 */
3428 		zmsg->start_rule = start->sibling;
3429 	}
3430 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3431 }
3432 
3433 /**
3434  * Reset some or all counters on firewall rules.
3435  * @arg frwl is null to clear all entries, or contains a specific
3436  * rule number.
3437  * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3438  */
3439 static int
3440 ipfw_ctl_zero_entry(int rulenum, int log_only)
3441 {
3442 	struct netmsg_zent zmsg;
3443 	struct netmsg_base *nmsg;
3444 	const char *msg;
3445 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3446 
3447 	bzero(&zmsg, sizeof(zmsg));
3448 	nmsg = &zmsg.base;
3449 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3450 		    0, ipfw_zero_entry_dispatch);
3451 	zmsg.log_only = log_only;
3452 
3453 	if (rulenum == 0) {
3454 		msg = log_only ? "ipfw: All logging counts reset.\n"
3455 			       : "ipfw: Accounting cleared.\n";
3456 	} else {
3457 		struct ip_fw *rule;
3458 
3459 		/*
3460 		 * Locate the first rule with 'rulenum'
3461 		 */
3462 		for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3463 			if (rule->rulenum == rulenum)
3464 				break;
3465 		}
3466 		if (rule == NULL) /* we did not find any matching rules */
3467 			return (EINVAL);
3468 		zmsg.start_rule = rule;
3469 		zmsg.rulenum = rulenum;
3470 
3471 		msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3472 			       : "ipfw: Entry %d cleared.\n";
3473 	}
3474 	ifnet_domsg(&nmsg->lmsg, 0);
3475 	KKASSERT(zmsg.start_rule == NULL);
3476 
3477 	if (fw_verbose)
3478 		log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3479 	return (0);
3480 }
3481 
3482 /*
3483  * Check validity of the structure before insert.
3484  * Fortunately rules are simple, so this mostly need to check rule sizes.
3485  */
3486 static int
3487 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3488 {
3489 	int l, cmdlen = 0;
3490 	int have_action = 0;
3491 	ipfw_insn *cmd;
3492 
3493 	*rule_flags = 0;
3494 
3495 	/* Check for valid size */
3496 	if (size < sizeof(*rule)) {
3497 		kprintf("ipfw: rule too short\n");
3498 		return EINVAL;
3499 	}
3500 	l = IOC_RULESIZE(rule);
3501 	if (l != size) {
3502 		kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3503 		return EINVAL;
3504 	}
3505 
3506 	/* Check rule number */
3507 	if (rule->rulenum == IPFW_DEFAULT_RULE) {
3508 		kprintf("ipfw: invalid rule number\n");
3509 		return EINVAL;
3510 	}
3511 
3512 	/*
3513 	 * Now go for the individual checks. Very simple ones, basically only
3514 	 * instruction sizes.
3515 	 */
3516 	for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3517 	     l -= cmdlen, cmd += cmdlen) {
3518 		cmdlen = F_LEN(cmd);
3519 		if (cmdlen > l) {
3520 			kprintf("ipfw: opcode %d size truncated\n",
3521 				cmd->opcode);
3522 			return EINVAL;
3523 		}
3524 
3525 		DPRINTF("ipfw: opcode %d\n", cmd->opcode);
3526 
3527 		if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3528 			/* This rule will create states */
3529 			*rule_flags |= IPFW_RULE_F_STATE;
3530 		}
3531 
3532 		switch (cmd->opcode) {
3533 		case O_NOP:
3534 		case O_PROBE_STATE:
3535 		case O_KEEP_STATE:
3536 		case O_PROTO:
3537 		case O_IP_SRC_ME:
3538 		case O_IP_DST_ME:
3539 		case O_LAYER2:
3540 		case O_IN:
3541 		case O_FRAG:
3542 		case O_IPOPT:
3543 		case O_IPLEN:
3544 		case O_IPID:
3545 		case O_IPTOS:
3546 		case O_IPPRECEDENCE:
3547 		case O_IPTTL:
3548 		case O_IPVER:
3549 		case O_TCPWIN:
3550 		case O_TCPFLAGS:
3551 		case O_TCPOPTS:
3552 		case O_ESTAB:
3553 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3554 				goto bad_size;
3555 			break;
3556 
3557 		case O_UID:
3558 		case O_GID:
3559 		case O_IP_SRC:
3560 		case O_IP_DST:
3561 		case O_TCPSEQ:
3562 		case O_TCPACK:
3563 		case O_PROB:
3564 		case O_ICMPTYPE:
3565 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3566 				goto bad_size;
3567 			break;
3568 
3569 		case O_LIMIT:
3570 			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3571 				goto bad_size;
3572 			break;
3573 
3574 		case O_LOG:
3575 			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3576 				goto bad_size;
3577 
3578 			((ipfw_insn_log *)cmd)->log_left =
3579 			    ((ipfw_insn_log *)cmd)->max_log;
3580 
3581 			break;
3582 
3583 		case O_IP_SRC_MASK:
3584 		case O_IP_DST_MASK:
3585 			if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3586 				goto bad_size;
3587 			if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3588 				kprintf("ipfw: opcode %d, useless rule\n",
3589 					cmd->opcode);
3590 				return EINVAL;
3591 			}
3592 			break;
3593 
3594 		case O_IP_SRC_SET:
3595 		case O_IP_DST_SET:
3596 			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3597 				kprintf("ipfw: invalid set size %d\n",
3598 					cmd->arg1);
3599 				return EINVAL;
3600 			}
3601 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3602 			    (cmd->arg1+31)/32 )
3603 				goto bad_size;
3604 			break;
3605 
3606 		case O_MACADDR2:
3607 			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3608 				goto bad_size;
3609 			break;
3610 
3611 		case O_MAC_TYPE:
3612 		case O_IP_SRCPORT:
3613 		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3614 			if (cmdlen < 2 || cmdlen > 31)
3615 				goto bad_size;
3616 			break;
3617 
3618 		case O_RECV:
3619 		case O_XMIT:
3620 		case O_VIA:
3621 			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3622 				goto bad_size;
3623 			break;
3624 
3625 		case O_PIPE:
3626 		case O_QUEUE:
3627 			if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3628 				goto bad_size;
3629 			goto check_action;
3630 
3631 		case O_FORWARD_IP:
3632 			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3633 				goto bad_size;
3634 			} else {
3635 				in_addr_t fwd_addr;
3636 
3637 				fwd_addr = ((ipfw_insn_sa *)cmd)->
3638 					   sa.sin_addr.s_addr;
3639 				if (IN_MULTICAST(ntohl(fwd_addr))) {
3640 					kprintf("ipfw: try forwarding to "
3641 						"multicast address\n");
3642 					return EINVAL;
3643 				}
3644 			}
3645 			goto check_action;
3646 
3647 		case O_FORWARD_MAC: /* XXX not implemented yet */
3648 		case O_CHECK_STATE:
3649 		case O_COUNT:
3650 		case O_ACCEPT:
3651 		case O_DENY:
3652 		case O_REJECT:
3653 		case O_SKIPTO:
3654 		case O_DIVERT:
3655 		case O_TEE:
3656 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3657 				goto bad_size;
3658 check_action:
3659 			if (have_action) {
3660 				kprintf("ipfw: opcode %d, multiple actions"
3661 					" not allowed\n",
3662 					cmd->opcode);
3663 				return EINVAL;
3664 			}
3665 			have_action = 1;
3666 			if (l != cmdlen) {
3667 				kprintf("ipfw: opcode %d, action must be"
3668 					" last opcode\n",
3669 					cmd->opcode);
3670 				return EINVAL;
3671 			}
3672 			break;
3673 		default:
3674 			kprintf("ipfw: opcode %d, unknown opcode\n",
3675 				cmd->opcode);
3676 			return EINVAL;
3677 		}
3678 	}
3679 	if (have_action == 0) {
3680 		kprintf("ipfw: missing action\n");
3681 		return EINVAL;
3682 	}
3683 	return 0;
3684 
3685 bad_size:
3686 	kprintf("ipfw: opcode %d size %d wrong\n",
3687 		cmd->opcode, cmdlen);
3688 	return EINVAL;
3689 }
3690 
3691 static int
3692 ipfw_ctl_add_rule(struct sockopt *sopt)
3693 {
3694 	struct ipfw_ioc_rule *ioc_rule;
3695 	size_t size;
3696 	uint32_t rule_flags;
3697 	int error;
3698 
3699 	size = sopt->sopt_valsize;
3700 	if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3701 	    size < sizeof(*ioc_rule)) {
3702 		return EINVAL;
3703 	}
3704 	if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3705 		sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3706 					  IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3707 	}
3708 	ioc_rule = sopt->sopt_val;
3709 
3710 	error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3711 	if (error)
3712 		return error;
3713 
3714 	ipfw_add_rule(ioc_rule, rule_flags);
3715 
3716 	if (sopt->sopt_dir == SOPT_GET)
3717 		sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3718 	return 0;
3719 }
3720 
3721 static void *
3722 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3723 {
3724 	const struct ip_fw *sibling;
3725 #ifdef INVARIANTS
3726 	int i;
3727 #endif
3728 
3729 	KKASSERT(rule->cpuid == IPFW_CFGCPUID);
3730 
3731 	ioc_rule->act_ofs = rule->act_ofs;
3732 	ioc_rule->cmd_len = rule->cmd_len;
3733 	ioc_rule->rulenum = rule->rulenum;
3734 	ioc_rule->set = rule->set;
3735 	ioc_rule->usr_flags = rule->usr_flags;
3736 
3737 	ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3738 	ioc_rule->static_count = static_count;
3739 	ioc_rule->static_len = static_ioc_len;
3740 
3741 	/*
3742 	 * Visit (read-only) all of the rule's duplications to get
3743 	 * the necessary statistics
3744 	 */
3745 #ifdef INVARIANTS
3746 	i = 0;
3747 #endif
3748 	ioc_rule->pcnt = 0;
3749 	ioc_rule->bcnt = 0;
3750 	ioc_rule->timestamp = 0;
3751 	for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3752 		ioc_rule->pcnt += sibling->pcnt;
3753 		ioc_rule->bcnt += sibling->bcnt;
3754 		if (sibling->timestamp > ioc_rule->timestamp)
3755 			ioc_rule->timestamp = sibling->timestamp;
3756 #ifdef INVARIANTS
3757 		++i;
3758 #endif
3759 	}
3760 	KASSERT(i == ncpus, ("static rule is not duplicated on every cpu"));
3761 
3762 	bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3763 
3764 	return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3765 }
3766 
3767 static void
3768 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3769 		struct ipfw_ioc_state *ioc_state)
3770 {
3771 	const struct ipfw_flow_id *id;
3772 	struct ipfw_ioc_flowid *ioc_id;
3773 
3774 	ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3775 			    0 : dyn_rule->expire - time_second;
3776 	ioc_state->pcnt = dyn_rule->pcnt;
3777 	ioc_state->bcnt = dyn_rule->bcnt;
3778 
3779 	ioc_state->dyn_type = dyn_rule->dyn_type;
3780 	ioc_state->count = dyn_rule->count;
3781 
3782 	ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3783 
3784 	id = &dyn_rule->id;
3785 	ioc_id = &ioc_state->id;
3786 
3787 	ioc_id->type = ETHERTYPE_IP;
3788 	ioc_id->u.ip.dst_ip = id->dst_ip;
3789 	ioc_id->u.ip.src_ip = id->src_ip;
3790 	ioc_id->u.ip.dst_port = id->dst_port;
3791 	ioc_id->u.ip.src_port = id->src_port;
3792 	ioc_id->u.ip.proto = id->proto;
3793 }
3794 
3795 static int
3796 ipfw_ctl_get_rules(struct sockopt *sopt)
3797 {
3798 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3799 	struct ip_fw *rule;
3800 	void *bp;
3801 	size_t size;
3802 	uint32_t dcount = 0;
3803 
3804 	/*
3805 	 * pass up a copy of the current rules. Static rules
3806 	 * come first (the last of which has number IPFW_DEFAULT_RULE),
3807 	 * followed by a possibly empty list of dynamic rule.
3808 	 */
3809 
3810 	size = static_ioc_len;	/* size of static rules */
3811 	if (ipfw_dyn_v) {	/* add size of dyn.rules */
3812 		dcount = dyn_count;
3813 		size += dcount * sizeof(struct ipfw_ioc_state);
3814 	}
3815 
3816 	if (sopt->sopt_valsize < size) {
3817 		/* short length, no need to return incomplete rules */
3818 		/* XXX: if superuser, no need to zero buffer */
3819 		bzero(sopt->sopt_val, sopt->sopt_valsize);
3820 		return 0;
3821 	}
3822 	bp = sopt->sopt_val;
3823 
3824 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3825 		bp = ipfw_copy_rule(rule, bp);
3826 
3827 	if (ipfw_dyn_v && dcount != 0) {
3828 		struct ipfw_ioc_state *ioc_state = bp;
3829 		uint32_t dcount2 = 0;
3830 #ifdef INVARIANTS
3831 		size_t old_size = size;
3832 #endif
3833 		int i;
3834 
3835 		lockmgr(&dyn_lock, LK_SHARED);
3836 
3837 		/* Check 'ipfw_dyn_v' again with lock held */
3838 		if (ipfw_dyn_v == NULL)
3839 			goto skip;
3840 
3841 		for (i = 0; i < curr_dyn_buckets; i++) {
3842 			ipfw_dyn_rule *p;
3843 
3844 			/*
3845 			 * The # of dynamic rules may have grown after the
3846 			 * snapshot of 'dyn_count' was taken, so we will have
3847 			 * to check 'dcount' (snapshot of dyn_count) here to
3848 			 * make sure that we don't overflow the pre-allocated
3849 			 * buffer.
3850 			 */
3851 			for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3852 			     p = p->next, ioc_state++, dcount--, dcount2++)
3853 				ipfw_copy_state(p, ioc_state);
3854 		}
3855 skip:
3856 		lockmgr(&dyn_lock, LK_RELEASE);
3857 
3858 		/*
3859 		 * The # of dynamic rules may be shrinked after the
3860 		 * snapshot of 'dyn_count' was taken.  To give user a
3861 		 * correct dynamic rule count, we use the 'dcount2'
3862 		 * calculated above (with shared lockmgr lock held).
3863 		 */
3864 		size = static_ioc_len +
3865 		       (dcount2 * sizeof(struct ipfw_ioc_state));
3866 		KKASSERT(size <= old_size);
3867 	}
3868 
3869 	sopt->sopt_valsize = size;
3870 	return 0;
3871 }
3872 
3873 static void
3874 ipfw_set_disable_dispatch(netmsg_t nmsg)
3875 {
3876 	struct lwkt_msg *lmsg = &nmsg->lmsg;
3877 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3878 
3879 	ctx->ipfw_gen++;
3880 	ctx->ipfw_set_disable = lmsg->u.ms_result32;
3881 
3882 	ifnet_forwardmsg(lmsg, mycpuid + 1);
3883 }
3884 
3885 static void
3886 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3887 {
3888 	struct netmsg_base nmsg;
3889 	struct lwkt_msg *lmsg;
3890 	uint32_t set_disable;
3891 
3892 	/* IPFW_DEFAULT_SET is always enabled */
3893 	enable |= (1 << IPFW_DEFAULT_SET);
3894 	set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3895 
3896 	bzero(&nmsg, sizeof(nmsg));
3897 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
3898 		    0, ipfw_set_disable_dispatch);
3899 	lmsg = &nmsg.lmsg;
3900 	lmsg->u.ms_result32 = set_disable;
3901 
3902 	ifnet_domsg(lmsg, 0);
3903 }
3904 
3905 /**
3906  * {set|get}sockopt parser.
3907  */
3908 static int
3909 ipfw_ctl(struct sockopt *sopt)
3910 {
3911 	int error, rulenum;
3912 	uint32_t *masks;
3913 	size_t size;
3914 
3915 	error = 0;
3916 
3917 	switch (sopt->sopt_name) {
3918 	case IP_FW_GET:
3919 		error = ipfw_ctl_get_rules(sopt);
3920 		break;
3921 
3922 	case IP_FW_FLUSH:
3923 		ipfw_flush(0 /* keep default rule */);
3924 		break;
3925 
3926 	case IP_FW_ADD:
3927 		error = ipfw_ctl_add_rule(sopt);
3928 		break;
3929 
3930 	case IP_FW_DEL:
3931 		/*
3932 		 * IP_FW_DEL is used for deleting single rules or sets,
3933 		 * and (ab)used to atomically manipulate sets.
3934 		 * Argument size is used to distinguish between the two:
3935 		 *    sizeof(uint32_t)
3936 		 *	delete single rule or set of rules,
3937 		 *	or reassign rules (or sets) to a different set.
3938 		 *    2 * sizeof(uint32_t)
3939 		 *	atomic disable/enable sets.
3940 		 *	first uint32_t contains sets to be disabled,
3941 		 *	second uint32_t contains sets to be enabled.
3942 		 */
3943 		masks = sopt->sopt_val;
3944 		size = sopt->sopt_valsize;
3945 		if (size == sizeof(*masks)) {
3946 			/*
3947 			 * Delete or reassign static rule
3948 			 */
3949 			error = ipfw_ctl_alter(masks[0]);
3950 		} else if (size == (2 * sizeof(*masks))) {
3951 			/*
3952 			 * Set enable/disable
3953 			 */
3954 			ipfw_ctl_set_disable(masks[0], masks[1]);
3955 		} else {
3956 			error = EINVAL;
3957 		}
3958 		break;
3959 
3960 	case IP_FW_ZERO:
3961 	case IP_FW_RESETLOG: /* argument is an int, the rule number */
3962 		rulenum = 0;
3963 
3964 		if (sopt->sopt_val != 0) {
3965 		    error = soopt_to_kbuf(sopt, &rulenum,
3966 			    sizeof(int), sizeof(int));
3967 		    if (error)
3968 			break;
3969 		}
3970 		error = ipfw_ctl_zero_entry(rulenum,
3971 			sopt->sopt_name == IP_FW_RESETLOG);
3972 		break;
3973 
3974 	default:
3975 		kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3976 		error = EINVAL;
3977 	}
3978 	return error;
3979 }
3980 
3981 /*
3982  * This procedure is only used to handle keepalives. It is invoked
3983  * every dyn_keepalive_period
3984  */
3985 static void
3986 ipfw_tick_dispatch(netmsg_t nmsg)
3987 {
3988 	time_t keep_alive;
3989 	uint32_t gen;
3990 	int i;
3991 
3992 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
3993 	KKASSERT(IPFW_LOADED);
3994 
3995 	/* Reply ASAP */
3996 	crit_enter();
3997 	lwkt_replymsg(&nmsg->lmsg, 0);
3998 	crit_exit();
3999 
4000 	if (ipfw_dyn_v == NULL || dyn_count == 0)
4001 		goto done;
4002 
4003 	keep_alive = time_second;
4004 
4005 	lockmgr(&dyn_lock, LK_EXCLUSIVE);
4006 again:
4007 	if (ipfw_dyn_v == NULL || dyn_count == 0) {
4008 		lockmgr(&dyn_lock, LK_RELEASE);
4009 		goto done;
4010 	}
4011 	gen = dyn_buckets_gen;
4012 
4013 	for (i = 0; i < curr_dyn_buckets; i++) {
4014 		ipfw_dyn_rule *q, *prev;
4015 
4016 		for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
4017 			uint32_t ack_rev, ack_fwd;
4018 			struct ipfw_flow_id id;
4019 
4020 			if (q->dyn_type == O_LIMIT_PARENT)
4021 				goto next;
4022 
4023 			if (TIME_LEQ(q->expire, time_second)) {
4024 				/* State expired */
4025 				UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
4026 				continue;
4027 			}
4028 
4029 			/*
4030 			 * Keep alive processing
4031 			 */
4032 
4033 			if (!dyn_keepalive)
4034 				goto next;
4035 			if (q->id.proto != IPPROTO_TCP)
4036 				goto next;
4037 			if ((q->state & BOTH_SYN) != BOTH_SYN)
4038 				goto next;
4039 			if (TIME_LEQ(time_second + dyn_keepalive_interval,
4040 			    q->expire))
4041 				goto next;	/* too early */
4042 			if (q->keep_alive == keep_alive)
4043 				goto next;	/* alreay done */
4044 
4045 			/*
4046 			 * Save necessary information, so that they could
4047 			 * survive after possible blocking in send_pkt()
4048 			 */
4049 			id = q->id;
4050 			ack_rev = q->ack_rev;
4051 			ack_fwd = q->ack_fwd;
4052 
4053 			/* Sending has been started */
4054 			q->keep_alive = keep_alive;
4055 
4056 			/* Release lock to avoid possible dead lock */
4057 			lockmgr(&dyn_lock, LK_RELEASE);
4058 			send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
4059 			send_pkt(&id, ack_fwd - 1, ack_rev, 0);
4060 			lockmgr(&dyn_lock, LK_EXCLUSIVE);
4061 
4062 			if (gen != dyn_buckets_gen) {
4063 				/*
4064 				 * Dyn bucket array has been changed during
4065 				 * the above two sending; reiterate.
4066 				 */
4067 				goto again;
4068 			}
4069 next:
4070 			prev = q;
4071 			q = q->next;
4072 		}
4073 	}
4074 	lockmgr(&dyn_lock, LK_RELEASE);
4075 done:
4076 	callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
4077 		      ipfw_tick, NULL);
4078 }
4079 
4080 /*
4081  * This procedure is only used to handle keepalives. It is invoked
4082  * every dyn_keepalive_period
4083  */
4084 static void
4085 ipfw_tick(void *dummy __unused)
4086 {
4087 	struct lwkt_msg *lmsg = &ipfw_timeout_netmsg.lmsg;
4088 
4089 	KKASSERT(mycpuid == IPFW_CFGCPUID);
4090 
4091 	crit_enter();
4092 
4093 	KKASSERT(lmsg->ms_flags & MSGF_DONE);
4094 	if (IPFW_LOADED) {
4095 		lwkt_sendmsg(IPFW_CFGPORT, lmsg);
4096 		/* ipfw_timeout_netmsg's handler reset this callout */
4097 	}
4098 
4099 	crit_exit();
4100 }
4101 
4102 static int
4103 ipfw_check_in(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4104 {
4105 	struct ip_fw_args args;
4106 	struct mbuf *m = *m0;
4107 	struct m_tag *mtag;
4108 	int tee = 0, error = 0, ret;
4109 
4110 	if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4111 		/* Extract info from dummynet tag */
4112 		mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4113 		KKASSERT(mtag != NULL);
4114 		args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4115 		KKASSERT(args.rule != NULL);
4116 
4117 		m_tag_delete(m, mtag);
4118 		m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4119 	} else {
4120 		args.rule = NULL;
4121 	}
4122 
4123 	args.eh = NULL;
4124 	args.oif = NULL;
4125 	args.m = m;
4126 	ret = ipfw_chk(&args);
4127 	m = args.m;
4128 
4129 	if (m == NULL) {
4130 		error = EACCES;
4131 		goto back;
4132 	}
4133 
4134 	switch (ret) {
4135 	case IP_FW_PASS:
4136 		break;
4137 
4138 	case IP_FW_DENY:
4139 		m_freem(m);
4140 		m = NULL;
4141 		error = EACCES;
4142 		break;
4143 
4144 	case IP_FW_DUMMYNET:
4145 		/* Send packet to the appropriate pipe */
4146 		ipfw_dummynet_io(m, args.cookie, DN_TO_IP_IN, &args);
4147 		break;
4148 
4149 	case IP_FW_TEE:
4150 		tee = 1;
4151 		/* FALL THROUGH */
4152 
4153 	case IP_FW_DIVERT:
4154 		/*
4155 		 * Must clear bridge tag when changing
4156 		 */
4157 		m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4158 		if (ip_divert_p != NULL) {
4159 			m = ip_divert_p(m, tee, 1);
4160 		} else {
4161 			m_freem(m);
4162 			m = NULL;
4163 			/* not sure this is the right error msg */
4164 			error = EACCES;
4165 		}
4166 		break;
4167 
4168 	default:
4169 		panic("unknown ipfw return value: %d", ret);
4170 	}
4171 back:
4172 	*m0 = m;
4173 	return error;
4174 }
4175 
4176 static int
4177 ipfw_check_out(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4178 {
4179 	struct ip_fw_args args;
4180 	struct mbuf *m = *m0;
4181 	struct m_tag *mtag;
4182 	int tee = 0, error = 0, ret;
4183 
4184 	if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4185 		/* Extract info from dummynet tag */
4186 		mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4187 		KKASSERT(mtag != NULL);
4188 		args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4189 		KKASSERT(args.rule != NULL);
4190 
4191 		m_tag_delete(m, mtag);
4192 		m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4193 	} else {
4194 		args.rule = NULL;
4195 	}
4196 
4197 	args.eh = NULL;
4198 	args.m = m;
4199 	args.oif = ifp;
4200 	ret = ipfw_chk(&args);
4201 	m = args.m;
4202 
4203 	if (m == NULL) {
4204 		error = EACCES;
4205 		goto back;
4206 	}
4207 
4208 	switch (ret) {
4209 	case IP_FW_PASS:
4210 		break;
4211 
4212 	case IP_FW_DENY:
4213 		m_freem(m);
4214 		m = NULL;
4215 		error = EACCES;
4216 		break;
4217 
4218 	case IP_FW_DUMMYNET:
4219 		ipfw_dummynet_io(m, args.cookie, DN_TO_IP_OUT, &args);
4220 		break;
4221 
4222 	case IP_FW_TEE:
4223 		tee = 1;
4224 		/* FALL THROUGH */
4225 
4226 	case IP_FW_DIVERT:
4227 		if (ip_divert_p != NULL) {
4228 			m = ip_divert_p(m, tee, 0);
4229 		} else {
4230 			m_freem(m);
4231 			m = NULL;
4232 			/* not sure this is the right error msg */
4233 			error = EACCES;
4234 		}
4235 		break;
4236 
4237 	default:
4238 		panic("unknown ipfw return value: %d", ret);
4239 	}
4240 back:
4241 	*m0 = m;
4242 	return error;
4243 }
4244 
4245 static void
4246 ipfw_hook(void)
4247 {
4248 	struct pfil_head *pfh;
4249 
4250 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4251 
4252 	pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4253 	if (pfh == NULL)
4254 		return;
4255 
4256 	pfil_add_hook(ipfw_check_in, NULL, PFIL_IN | PFIL_MPSAFE, pfh);
4257 	pfil_add_hook(ipfw_check_out, NULL, PFIL_OUT | PFIL_MPSAFE, pfh);
4258 }
4259 
4260 static void
4261 ipfw_dehook(void)
4262 {
4263 	struct pfil_head *pfh;
4264 
4265 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4266 
4267 	pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4268 	if (pfh == NULL)
4269 		return;
4270 
4271 	pfil_remove_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4272 	pfil_remove_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4273 }
4274 
4275 static void
4276 ipfw_sysctl_enable_dispatch(netmsg_t nmsg)
4277 {
4278 	struct lwkt_msg *lmsg = &nmsg->lmsg;
4279 	int enable = lmsg->u.ms_result;
4280 
4281 	if (fw_enable == enable)
4282 		goto reply;
4283 
4284 	fw_enable = enable;
4285 	if (fw_enable)
4286 		ipfw_hook();
4287 	else
4288 		ipfw_dehook();
4289 reply:
4290 	lwkt_replymsg(lmsg, 0);
4291 }
4292 
4293 static int
4294 ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS)
4295 {
4296 	struct netmsg_base nmsg;
4297 	struct lwkt_msg *lmsg;
4298 	int enable, error;
4299 
4300 	enable = fw_enable;
4301 	error = sysctl_handle_int(oidp, &enable, 0, req);
4302 	if (error || req->newptr == NULL)
4303 		return error;
4304 
4305 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
4306 		    0, ipfw_sysctl_enable_dispatch);
4307 	lmsg = &nmsg.lmsg;
4308 	lmsg->u.ms_result = enable;
4309 
4310 	return lwkt_domsg(IPFW_CFGPORT, lmsg, 0);
4311 }
4312 
4313 static int
4314 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4315 {
4316 	return sysctl_int_range(oidp, arg1, arg2, req,
4317 	       IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4318 }
4319 
4320 static int
4321 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4322 {
4323 	int error, value;
4324 
4325 	lockmgr(&dyn_lock, LK_EXCLUSIVE);
4326 
4327 	value = dyn_buckets;
4328 	error = sysctl_handle_int(oidp, &value, 0, req);
4329 	if (error || !req->newptr)
4330 		goto back;
4331 
4332 	/*
4333 	 * Make sure we have a power of 2 and
4334 	 * do not allow more than 64k entries.
4335 	 */
4336 	error = EINVAL;
4337 	if (value <= 1 || value > 65536)
4338 		goto back;
4339 	if ((value & (value - 1)) != 0)
4340 		goto back;
4341 
4342 	error = 0;
4343 	dyn_buckets = value;
4344 back:
4345 	lockmgr(&dyn_lock, LK_RELEASE);
4346 	return error;
4347 }
4348 
4349 static int
4350 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4351 {
4352 	return sysctl_int_range(oidp, arg1, arg2, req,
4353 				1, dyn_keepalive_period - 1);
4354 }
4355 
4356 static int
4357 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4358 {
4359 	return sysctl_int_range(oidp, arg1, arg2, req,
4360 				1, dyn_keepalive_period - 1);
4361 }
4362 
4363 static void
4364 ipfw_ctx_init_dispatch(netmsg_t nmsg)
4365 {
4366 	struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4367 	struct ipfw_context *ctx;
4368 	struct ip_fw *def_rule;
4369 
4370 	ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4371 	ipfw_ctx[mycpuid] = ctx;
4372 
4373 	def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4374 
4375 	def_rule->act_ofs = 0;
4376 	def_rule->rulenum = IPFW_DEFAULT_RULE;
4377 	def_rule->cmd_len = 1;
4378 	def_rule->set = IPFW_DEFAULT_SET;
4379 
4380 	def_rule->cmd[0].len = 1;
4381 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4382 	def_rule->cmd[0].opcode = O_ACCEPT;
4383 #else
4384 	def_rule->cmd[0].opcode = O_DENY;
4385 #endif
4386 
4387 	def_rule->refcnt = 1;
4388 	def_rule->cpuid = mycpuid;
4389 
4390 	/* Install the default rule */
4391 	ctx->ipfw_default_rule = def_rule;
4392 	ctx->ipfw_layer3_chain = def_rule;
4393 
4394 	/* Link rule CPU sibling */
4395 	ipfw_link_sibling(fwmsg, def_rule);
4396 
4397 	/* Statistics only need to be updated once */
4398 	if (mycpuid == 0)
4399 		ipfw_inc_static_count(def_rule);
4400 
4401 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
4402 }
4403 
4404 static void
4405 ipfw_init_dispatch(netmsg_t nmsg)
4406 {
4407 	struct netmsg_ipfw fwmsg;
4408 	int error = 0;
4409 
4410 	if (IPFW_LOADED) {
4411 		kprintf("IP firewall already loaded\n");
4412 		error = EEXIST;
4413 		goto reply;
4414 	}
4415 
4416 	bzero(&fwmsg, sizeof(fwmsg));
4417 	netmsg_init(&fwmsg.base, NULL, &curthread->td_msgport,
4418 		    0, ipfw_ctx_init_dispatch);
4419 	ifnet_domsg(&fwmsg.base.lmsg, 0);
4420 
4421 	ip_fw_chk_ptr = ipfw_chk;
4422 	ip_fw_ctl_ptr = ipfw_ctl;
4423 	ip_fw_dn_io_ptr = ipfw_dummynet_io;
4424 
4425 	kprintf("ipfw2 initialized, default to %s, logging ",
4426 		ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4427 		O_ACCEPT ? "accept" : "deny");
4428 
4429 #ifdef IPFIREWALL_VERBOSE
4430 	fw_verbose = 1;
4431 #endif
4432 #ifdef IPFIREWALL_VERBOSE_LIMIT
4433 	verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4434 #endif
4435 	if (fw_verbose == 0) {
4436 		kprintf("disabled\n");
4437 	} else if (verbose_limit == 0) {
4438 		kprintf("unlimited\n");
4439 	} else {
4440 		kprintf("limited to %d packets/entry by default\n",
4441 			verbose_limit);
4442 	}
4443 
4444 	callout_init_mp(&ipfw_timeout_h);
4445 	netmsg_init(&ipfw_timeout_netmsg, NULL, &netisr_adone_rport,
4446 		    MSGF_DROPABLE | MSGF_PRIORITY,
4447 		    ipfw_tick_dispatch);
4448 	lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4449 
4450 	ip_fw_loaded = 1;
4451 	callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4452 
4453 	if (fw_enable)
4454 		ipfw_hook();
4455 reply:
4456 	lwkt_replymsg(&nmsg->lmsg, error);
4457 }
4458 
4459 static int
4460 ipfw_init(void)
4461 {
4462 	struct netmsg_base smsg;
4463 
4464 	netmsg_init(&smsg, NULL, &curthread->td_msgport,
4465 		    0, ipfw_init_dispatch);
4466 	return lwkt_domsg(IPFW_CFGPORT, &smsg.lmsg, 0);
4467 }
4468 
4469 #ifdef KLD_MODULE
4470 
4471 static void
4472 ipfw_fini_dispatch(netmsg_t nmsg)
4473 {
4474 	int error = 0, cpu;
4475 
4476 	if (ipfw_refcnt != 0) {
4477 		error = EBUSY;
4478 		goto reply;
4479 	}
4480 
4481 	ip_fw_loaded = 0;
4482 
4483 	ipfw_dehook();
4484 	callout_stop(&ipfw_timeout_h);
4485 
4486 	netmsg_service_sync();
4487 
4488 	crit_enter();
4489 	if ((ipfw_timeout_netmsg.lmsg.ms_flags & MSGF_DONE) == 0) {
4490 		/*
4491 		 * Callout message is pending; drop it
4492 		 */
4493 		lwkt_dropmsg(&ipfw_timeout_netmsg.lmsg);
4494 	}
4495 	crit_exit();
4496 
4497 	ip_fw_chk_ptr = NULL;
4498 	ip_fw_ctl_ptr = NULL;
4499 	ip_fw_dn_io_ptr = NULL;
4500 	ipfw_flush(1 /* kill default rule */);
4501 
4502 	/* Free pre-cpu context */
4503 	for (cpu = 0; cpu < ncpus; ++cpu)
4504 		kfree(ipfw_ctx[cpu], M_IPFW);
4505 
4506 	kprintf("IP firewall unloaded\n");
4507 reply:
4508 	lwkt_replymsg(&nmsg->lmsg, error);
4509 }
4510 
4511 static int
4512 ipfw_fini(void)
4513 {
4514 	struct netmsg_base smsg;
4515 
4516 	netmsg_init(&smsg, NULL, &curthread->td_msgport,
4517 		    0, ipfw_fini_dispatch);
4518 	return lwkt_domsg(IPFW_CFGPORT, &smsg.lmsg, 0);
4519 }
4520 
4521 #endif	/* KLD_MODULE */
4522 
4523 static int
4524 ipfw_modevent(module_t mod, int type, void *unused)
4525 {
4526 	int err = 0;
4527 
4528 	switch (type) {
4529 	case MOD_LOAD:
4530 		err = ipfw_init();
4531 		break;
4532 
4533 	case MOD_UNLOAD:
4534 #ifndef KLD_MODULE
4535 		kprintf("ipfw statically compiled, cannot unload\n");
4536 		err = EBUSY;
4537 #else
4538 		err = ipfw_fini();
4539 #endif
4540 		break;
4541 	default:
4542 		break;
4543 	}
4544 	return err;
4545 }
4546 
4547 static moduledata_t ipfwmod = {
4548 	"ipfw",
4549 	ipfw_modevent,
4550 	0
4551 };
4552 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4553 MODULE_VERSION(ipfw, 1);
4554