xref: /dragonfly/sys/net/ipfw/ip_fw2.c (revision bd611623)
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 *q=NULL;
995 
996 	if (ipfw_dyn_v == NULL)
997 		goto done;	/* not found */
998 
999 	i = hash_packet(pkt);
1000 	for (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 		q = q->next;
1030 	}
1031 	if (q == NULL)
1032 		goto done; /* q = NULL, not found */
1033 
1034 	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1035 		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1036 
1037 #define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
1038 #define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
1039 
1040 		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1041 		switch (q->state) {
1042 		case TH_SYN:				/* opening */
1043 			q->expire = time_second + dyn_syn_lifetime;
1044 			break;
1045 
1046 		case BOTH_SYN:			/* move to established */
1047 		case BOTH_SYN | TH_FIN :	/* one side tries to close */
1048 		case BOTH_SYN | (TH_FIN << 8) :
1049  			if (tcp) {
1050 				uint32_t ack = ntohl(tcp->th_ack);
1051 
1052 #define _SEQ_GE(a, b)	((int)(a) - (int)(b) >= 0)
1053 
1054 				if (dir == MATCH_FORWARD) {
1055 					if (q->ack_fwd == 0 ||
1056 					    _SEQ_GE(ack, q->ack_fwd))
1057 						q->ack_fwd = ack;
1058 					else /* ignore out-of-sequence */
1059 						break;
1060 				} else {
1061 					if (q->ack_rev == 0 ||
1062 					    _SEQ_GE(ack, q->ack_rev))
1063 						q->ack_rev = ack;
1064 					else /* ignore out-of-sequence */
1065 						break;
1066 				}
1067 #undef _SEQ_GE
1068 			}
1069 			q->expire = time_second + dyn_ack_lifetime;
1070 			break;
1071 
1072 		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
1073 			KKASSERT(dyn_fin_lifetime < dyn_keepalive_period);
1074 			q->expire = time_second + dyn_fin_lifetime;
1075 			break;
1076 
1077 		default:
1078 #if 0
1079 			/*
1080 			 * reset or some invalid combination, but can also
1081 			 * occur if we use keep-state the wrong way.
1082 			 */
1083 			if ((q->state & ((TH_RST << 8) | TH_RST)) == 0)
1084 				kprintf("invalid state: 0x%x\n", q->state);
1085 #endif
1086 			KKASSERT(dyn_rst_lifetime < dyn_keepalive_period);
1087 			q->expire = time_second + dyn_rst_lifetime;
1088 			break;
1089 		}
1090 	} else if (pkt->proto == IPPROTO_UDP) {
1091 		q->expire = time_second + dyn_udp_lifetime;
1092 	} else {
1093 		/* other protocols */
1094 		q->expire = time_second + dyn_short_lifetime;
1095 	}
1096 done:
1097 	if (match_direction)
1098 		*match_direction = dir;
1099 	return q;
1100 }
1101 
1102 static struct ip_fw *
1103 lookup_rule(struct ipfw_flow_id *pkt, int *match_direction, struct tcphdr *tcp,
1104 	    uint16_t len, int *deny)
1105 {
1106 	struct ip_fw *rule = NULL;
1107 	ipfw_dyn_rule *q;
1108 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1109 	uint32_t gen;
1110 
1111 	*deny = 0;
1112 	gen = ctx->ipfw_gen;
1113 
1114 	lockmgr(&dyn_lock, LK_SHARED);
1115 
1116 	if (ctx->ipfw_gen != gen) {
1117 		/*
1118 		 * Static rules had been change when we were waiting
1119 		 * for the dynamic hash table lock; deny this packet,
1120 		 * since it is _not_ known whether it is safe to keep
1121 		 * iterating the static rules.
1122 		 */
1123 		*deny = 1;
1124 		goto back;
1125 	}
1126 
1127 	q = lookup_dyn_rule(pkt, match_direction, tcp);
1128 	if (q == NULL) {
1129 		rule = NULL;
1130 	} else {
1131 		rule = q->stub->rule[mycpuid];
1132 		KKASSERT(rule->stub == q->stub && rule->cpuid == mycpuid);
1133 
1134 		/* XXX */
1135 		q->pcnt++;
1136 		q->bcnt += len;
1137 	}
1138 back:
1139 	lockmgr(&dyn_lock, LK_RELEASE);
1140 	return rule;
1141 }
1142 
1143 static void
1144 realloc_dynamic_table(void)
1145 {
1146 	ipfw_dyn_rule **old_dyn_v;
1147 	uint32_t old_curr_dyn_buckets;
1148 
1149 	KASSERT(dyn_buckets <= 65536 && (dyn_buckets & (dyn_buckets - 1)) == 0,
1150 		("invalid dyn_buckets %d", dyn_buckets));
1151 
1152 	/* Save the current buckets array for later error recovery */
1153 	old_dyn_v = ipfw_dyn_v;
1154 	old_curr_dyn_buckets = curr_dyn_buckets;
1155 
1156 	curr_dyn_buckets = dyn_buckets;
1157 	for (;;) {
1158 		ipfw_dyn_v = kmalloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1159 				     M_IPFW, M_NOWAIT | M_ZERO);
1160 		if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1161 			break;
1162 
1163 		curr_dyn_buckets /= 2;
1164 		if (curr_dyn_buckets <= old_curr_dyn_buckets &&
1165 		    old_dyn_v != NULL) {
1166 			/*
1167 			 * Don't try allocating smaller buckets array, reuse
1168 			 * the old one, which alreay contains enough buckets
1169 			 */
1170 			break;
1171 		}
1172 	}
1173 
1174 	if (ipfw_dyn_v != NULL) {
1175 		if (old_dyn_v != NULL)
1176 			kfree(old_dyn_v, M_IPFW);
1177 	} else {
1178 		/* Allocation failed, restore old buckets array */
1179 		ipfw_dyn_v = old_dyn_v;
1180 		curr_dyn_buckets = old_curr_dyn_buckets;
1181 	}
1182 
1183 	if (ipfw_dyn_v != NULL)
1184 		++dyn_buckets_gen;
1185 }
1186 
1187 /**
1188  * Install state of type 'type' for a dynamic session.
1189  * The hash table contains two type of rules:
1190  * - regular rules (O_KEEP_STATE)
1191  * - rules for sessions with limited number of sess per user
1192  *   (O_LIMIT). When they are created, the parent is
1193  *   increased by 1, and decreased on delete. In this case,
1194  *   the third parameter is the parent rule and not the chain.
1195  * - "parent" rules for the above (O_LIMIT_PARENT).
1196  */
1197 static ipfw_dyn_rule *
1198 add_dyn_rule(struct ipfw_flow_id *id, uint8_t dyn_type, struct ip_fw *rule)
1199 {
1200 	ipfw_dyn_rule *r;
1201 	int i;
1202 
1203 	if (ipfw_dyn_v == NULL ||
1204 	    (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1205 		realloc_dynamic_table();
1206 		if (ipfw_dyn_v == NULL)
1207 			return NULL; /* failed ! */
1208 	}
1209 	i = hash_packet(id);
1210 
1211 	r = kmalloc(sizeof(*r), M_IPFW, M_NOWAIT | M_ZERO);
1212 	if (r == NULL)
1213 		return NULL;
1214 
1215 	/* increase refcount on parent, and set pointer */
1216 	if (dyn_type == O_LIMIT) {
1217 		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1218 
1219 		if (parent->dyn_type != O_LIMIT_PARENT)
1220 			panic("invalid parent");
1221 		parent->count++;
1222 		r->parent = parent;
1223 		rule = parent->stub->rule[mycpuid];
1224 		KKASSERT(rule->stub == parent->stub);
1225 	}
1226 	KKASSERT(rule->cpuid == mycpuid && rule->stub != NULL);
1227 
1228 	r->id = *id;
1229 	r->expire = time_second + dyn_syn_lifetime;
1230 	r->stub = rule->stub;
1231 	r->dyn_type = dyn_type;
1232 	r->pcnt = r->bcnt = 0;
1233 	r->count = 0;
1234 
1235 	r->bucket = i;
1236 	r->next = ipfw_dyn_v[i];
1237 	ipfw_dyn_v[i] = r;
1238 	dyn_count++;
1239 	dyn_buckets_gen++;
1240 	DPRINTF("-- add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1241 		dyn_type,
1242 		r->id.src_ip, r->id.src_port,
1243 		r->id.dst_ip, r->id.dst_port, dyn_count);
1244 	return r;
1245 }
1246 
1247 /**
1248  * lookup dynamic parent rule using pkt and rule as search keys.
1249  * If the lookup fails, then install one.
1250  */
1251 static ipfw_dyn_rule *
1252 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1253 {
1254 	ipfw_dyn_rule *q;
1255 	int i;
1256 
1257 	if (ipfw_dyn_v) {
1258 		i = hash_packet(pkt);
1259 		for (q = ipfw_dyn_v[i]; q != NULL; q = q->next) {
1260 			if (q->dyn_type == O_LIMIT_PARENT &&
1261 			    rule->stub == q->stub &&
1262 			    pkt->proto == q->id.proto &&
1263 			    pkt->src_ip == q->id.src_ip &&
1264 			    pkt->dst_ip == q->id.dst_ip &&
1265 			    pkt->src_port == q->id.src_port &&
1266 			    pkt->dst_port == q->id.dst_port) {
1267 				q->expire = time_second + dyn_short_lifetime;
1268 				DPRINTF("lookup_dyn_parent found 0x%p\n", q);
1269 				return q;
1270 			}
1271 		}
1272 	}
1273 	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1274 }
1275 
1276 /**
1277  * Install dynamic state for rule type cmd->o.opcode
1278  *
1279  * Returns 1 (failure) if state is not installed because of errors or because
1280  * session limitations are enforced.
1281  */
1282 static int
1283 install_state_locked(struct ip_fw *rule, ipfw_insn_limit *cmd,
1284 		     struct ip_fw_args *args)
1285 {
1286 	static int last_log; /* XXX */
1287 
1288 	ipfw_dyn_rule *q;
1289 
1290 	DPRINTF("-- install state type %d 0x%08x %u -> 0x%08x %u\n",
1291 		cmd->o.opcode,
1292 		args->f_id.src_ip, args->f_id.src_port,
1293 		args->f_id.dst_ip, args->f_id.dst_port);
1294 
1295 	q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1296 	if (q != NULL) { /* should never occur */
1297 		if (last_log != time_second) {
1298 			last_log = time_second;
1299 			kprintf(" install_state: entry already present, done\n");
1300 		}
1301 		return 0;
1302 	}
1303 
1304 	if (dyn_count >= dyn_max) {
1305 		/*
1306 		 * Run out of slots, try to remove any expired rule.
1307 		 */
1308 		remove_dyn_rule_locked(NULL, (ipfw_dyn_rule *)1);
1309 		if (dyn_count >= dyn_max) {
1310 			if (last_log != time_second) {
1311 				last_log = time_second;
1312 				kprintf("install_state: "
1313 					"Too many dynamic rules\n");
1314 			}
1315 			return 1; /* cannot install, notify caller */
1316 		}
1317 	}
1318 
1319 	switch (cmd->o.opcode) {
1320 	case O_KEEP_STATE: /* bidir rule */
1321 		if (add_dyn_rule(&args->f_id, O_KEEP_STATE, rule) == NULL)
1322 			return 1;
1323 		break;
1324 
1325 	case O_LIMIT: /* limit number of sessions */
1326 		{
1327 			uint16_t limit_mask = cmd->limit_mask;
1328 			struct ipfw_flow_id id;
1329 			ipfw_dyn_rule *parent;
1330 
1331 			DPRINTF("installing dyn-limit rule %d\n",
1332 				cmd->conn_limit);
1333 
1334 			id.dst_ip = id.src_ip = 0;
1335 			id.dst_port = id.src_port = 0;
1336 			id.proto = args->f_id.proto;
1337 
1338 			if (limit_mask & DYN_SRC_ADDR)
1339 				id.src_ip = args->f_id.src_ip;
1340 			if (limit_mask & DYN_DST_ADDR)
1341 				id.dst_ip = args->f_id.dst_ip;
1342 			if (limit_mask & DYN_SRC_PORT)
1343 				id.src_port = args->f_id.src_port;
1344 			if (limit_mask & DYN_DST_PORT)
1345 				id.dst_port = args->f_id.dst_port;
1346 
1347 			parent = lookup_dyn_parent(&id, rule);
1348 			if (parent == NULL) {
1349 				kprintf("add parent failed\n");
1350 				return 1;
1351 			}
1352 
1353 			if (parent->count >= cmd->conn_limit) {
1354 				/*
1355 				 * See if we can remove some expired rule.
1356 				 */
1357 				remove_dyn_rule_locked(rule, parent);
1358 				if (parent->count >= cmd->conn_limit) {
1359 					if (fw_verbose &&
1360 					    last_log != time_second) {
1361 						last_log = time_second;
1362 						log(LOG_SECURITY | LOG_DEBUG,
1363 						    "drop session, "
1364 						    "too many entries\n");
1365 					}
1366 					return 1;
1367 				}
1368 			}
1369 			if (add_dyn_rule(&args->f_id, O_LIMIT,
1370 					 (struct ip_fw *)parent) == NULL)
1371 				return 1;
1372 		}
1373 		break;
1374 	default:
1375 		kprintf("unknown dynamic rule type %u\n", cmd->o.opcode);
1376 		return 1;
1377 	}
1378 	lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1379 	return 0;
1380 }
1381 
1382 static int
1383 install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1384 	      struct ip_fw_args *args, int *deny)
1385 {
1386 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1387 	uint32_t gen;
1388 	int ret = 0;
1389 
1390 	*deny = 0;
1391 	gen = ctx->ipfw_gen;
1392 
1393 	lockmgr(&dyn_lock, LK_EXCLUSIVE);
1394 	if (ctx->ipfw_gen != gen) {
1395 		/* See the comment in lookup_rule() */
1396 		*deny = 1;
1397 	} else {
1398 		ret = install_state_locked(rule, cmd, args);
1399 	}
1400 	lockmgr(&dyn_lock, LK_RELEASE);
1401 
1402 	return ret;
1403 }
1404 
1405 /*
1406  * Transmit a TCP packet, containing either a RST or a keepalive.
1407  * When flags & TH_RST, we are sending a RST packet, because of a
1408  * "reset" action matched the packet.
1409  * Otherwise we are sending a keepalive, and flags & TH_
1410  */
1411 static void
1412 send_pkt(struct ipfw_flow_id *id, uint32_t seq, uint32_t ack, int flags)
1413 {
1414 	struct mbuf *m;
1415 	struct ip *ip;
1416 	struct tcphdr *tcp;
1417 	struct route sro;	/* fake route */
1418 
1419 	MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1420 	if (m == NULL)
1421 		return;
1422 	m->m_pkthdr.rcvif = NULL;
1423 	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1424 	m->m_data += max_linkhdr;
1425 
1426 	ip = mtod(m, struct ip *);
1427 	bzero(ip, m->m_len);
1428 	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1429 	ip->ip_p = IPPROTO_TCP;
1430 	tcp->th_off = 5;
1431 
1432 	/*
1433 	 * Assume we are sending a RST (or a keepalive in the reverse
1434 	 * direction), swap src and destination addresses and ports.
1435 	 */
1436 	ip->ip_src.s_addr = htonl(id->dst_ip);
1437 	ip->ip_dst.s_addr = htonl(id->src_ip);
1438 	tcp->th_sport = htons(id->dst_port);
1439 	tcp->th_dport = htons(id->src_port);
1440 	if (flags & TH_RST) {	/* we are sending a RST */
1441 		if (flags & TH_ACK) {
1442 			tcp->th_seq = htonl(ack);
1443 			tcp->th_ack = htonl(0);
1444 			tcp->th_flags = TH_RST;
1445 		} else {
1446 			if (flags & TH_SYN)
1447 				seq++;
1448 			tcp->th_seq = htonl(0);
1449 			tcp->th_ack = htonl(seq);
1450 			tcp->th_flags = TH_RST | TH_ACK;
1451 		}
1452 	} else {
1453 		/*
1454 		 * We are sending a keepalive. flags & TH_SYN determines
1455 		 * the direction, forward if set, reverse if clear.
1456 		 * NOTE: seq and ack are always assumed to be correct
1457 		 * as set by the caller. This may be confusing...
1458 		 */
1459 		if (flags & TH_SYN) {
1460 			/*
1461 			 * we have to rewrite the correct addresses!
1462 			 */
1463 			ip->ip_dst.s_addr = htonl(id->dst_ip);
1464 			ip->ip_src.s_addr = htonl(id->src_ip);
1465 			tcp->th_dport = htons(id->dst_port);
1466 			tcp->th_sport = htons(id->src_port);
1467 		}
1468 		tcp->th_seq = htonl(seq);
1469 		tcp->th_ack = htonl(ack);
1470 		tcp->th_flags = TH_ACK;
1471 	}
1472 
1473 	/*
1474 	 * set ip_len to the payload size so we can compute
1475 	 * the tcp checksum on the pseudoheader
1476 	 * XXX check this, could save a couple of words ?
1477 	 */
1478 	ip->ip_len = htons(sizeof(struct tcphdr));
1479 	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1480 
1481 	/*
1482 	 * now fill fields left out earlier
1483 	 */
1484 	ip->ip_ttl = ip_defttl;
1485 	ip->ip_len = m->m_pkthdr.len;
1486 
1487 	bzero(&sro, sizeof(sro));
1488 	ip_rtaddr(ip->ip_dst, &sro);
1489 
1490 	m->m_pkthdr.fw_flags |= IPFW_MBUF_GENERATED;
1491 	ip_output(m, NULL, &sro, 0, NULL, NULL);
1492 	if (sro.ro_rt)
1493 		RTFREE(sro.ro_rt);
1494 }
1495 
1496 /*
1497  * sends a reject message, consuming the mbuf passed as an argument.
1498  */
1499 static void
1500 send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1501 {
1502 	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1503 		/* We need the IP header in host order for icmp_error(). */
1504 		if (args->eh != NULL) {
1505 			struct ip *ip = mtod(args->m, struct ip *);
1506 
1507 			ip->ip_len = ntohs(ip->ip_len);
1508 			ip->ip_off = ntohs(ip->ip_off);
1509 		}
1510 		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1511 	} else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1512 		struct tcphdr *const tcp =
1513 		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1514 
1515 		if ((tcp->th_flags & TH_RST) == 0) {
1516 			send_pkt(&args->f_id, ntohl(tcp->th_seq),
1517 				 ntohl(tcp->th_ack), tcp->th_flags | TH_RST);
1518 		}
1519 		m_freem(args->m);
1520 	} else {
1521 		m_freem(args->m);
1522 	}
1523 	args->m = NULL;
1524 }
1525 
1526 /**
1527  *
1528  * Given an ip_fw *, lookup_next_rule will return a pointer
1529  * to the next rule, which can be either the jump
1530  * target (for skipto instructions) or the next one in the list (in
1531  * all other cases including a missing jump target).
1532  * The result is also written in the "next_rule" field of the rule.
1533  * Backward jumps are not allowed, so start looking from the next
1534  * rule...
1535  *
1536  * This never returns NULL -- in case we do not have an exact match,
1537  * the next rule is returned. When the ruleset is changed,
1538  * pointers are flushed so we are always correct.
1539  */
1540 
1541 static struct ip_fw *
1542 lookup_next_rule(struct ip_fw *me)
1543 {
1544 	struct ip_fw *rule = NULL;
1545 	ipfw_insn *cmd;
1546 
1547 	/* look for action, in case it is a skipto */
1548 	cmd = ACTION_PTR(me);
1549 	if (cmd->opcode == O_LOG)
1550 		cmd += F_LEN(cmd);
1551 	if (cmd->opcode == O_SKIPTO) {
1552 		for (rule = me->next; rule; rule = rule->next) {
1553 			if (rule->rulenum >= cmd->arg1)
1554 				break;
1555 		}
1556 	}
1557 	if (rule == NULL)			/* failure or not a skipto */
1558 		rule = me->next;
1559 	me->next_rule = rule;
1560 	return rule;
1561 }
1562 
1563 static int
1564 _ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1565 		enum ipfw_opcodes opcode, uid_t uid)
1566 {
1567 	struct in_addr src_ip, dst_ip;
1568 	struct inpcbinfo *pi;
1569 	int wildcard;
1570 	struct inpcb *pcb;
1571 
1572 	if (fid->proto == IPPROTO_TCP) {
1573 		wildcard = 0;
1574 		pi = &tcbinfo[mycpuid];
1575 	} else if (fid->proto == IPPROTO_UDP) {
1576 		wildcard = 1;
1577 		pi = &udbinfo;
1578 	} else {
1579 		return 0;
1580 	}
1581 
1582 	/*
1583 	 * Values in 'fid' are in host byte order
1584 	 */
1585 	dst_ip.s_addr = htonl(fid->dst_ip);
1586 	src_ip.s_addr = htonl(fid->src_ip);
1587 	if (oif) {
1588 		pcb = in_pcblookup_hash(pi,
1589 			dst_ip, htons(fid->dst_port),
1590 			src_ip, htons(fid->src_port),
1591 			wildcard, oif);
1592 	} else {
1593 		pcb = in_pcblookup_hash(pi,
1594 			src_ip, htons(fid->src_port),
1595 			dst_ip, htons(fid->dst_port),
1596 			wildcard, NULL);
1597 	}
1598 	if (pcb == NULL || pcb->inp_socket == NULL)
1599 		return 0;
1600 
1601 	if (opcode == O_UID) {
1602 #define socheckuid(a,b)	((a)->so_cred->cr_uid != (b))
1603 		return !socheckuid(pcb->inp_socket, uid);
1604 #undef socheckuid
1605 	} else  {
1606 		return groupmember(uid, pcb->inp_socket->so_cred);
1607 	}
1608 }
1609 
1610 static int
1611 ipfw_match_uid(const struct ipfw_flow_id *fid, struct ifnet *oif,
1612 	       enum ipfw_opcodes opcode, uid_t uid, int *deny)
1613 {
1614 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1615 	uint32_t gen;
1616 	int match = 0;
1617 
1618 	*deny = 0;
1619 	gen = ctx->ipfw_gen;
1620 
1621 	get_mplock();
1622 	if (gen != ctx->ipfw_gen) {
1623 		/* See the comment in lookup_rule() */
1624 		*deny = 1;
1625 	} else {
1626 		match = _ipfw_match_uid(fid, oif, opcode, uid);
1627 	}
1628 	rel_mplock();
1629 	return match;
1630 }
1631 
1632 /*
1633  * The main check routine for the firewall.
1634  *
1635  * All arguments are in args so we can modify them and return them
1636  * back to the caller.
1637  *
1638  * Parameters:
1639  *
1640  *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
1641  *		Starts with the IP header.
1642  *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
1643  *	args->oif	Outgoing interface, or NULL if packet is incoming.
1644  *		The incoming interface is in the mbuf. (in)
1645  *
1646  *	args->rule	Pointer to the last matching rule (in/out)
1647  *	args->f_id	Addresses grabbed from the packet (out)
1648  *
1649  * Return value:
1650  *
1651  *	If the packet was denied/rejected and has been dropped, *m is equal
1652  *	to NULL upon return.
1653  *
1654  *	IP_FW_DENY	the packet must be dropped.
1655  *	IP_FW_PASS	The packet is to be accepted and routed normally.
1656  *	IP_FW_DIVERT	Divert the packet to port (args->cookie)
1657  *	IP_FW_TEE	Tee the packet to port (args->cookie)
1658  *	IP_FW_DUMMYNET	Send the packet to pipe/queue (args->cookie)
1659  */
1660 
1661 static int
1662 ipfw_chk(struct ip_fw_args *args)
1663 {
1664 	/*
1665 	 * Local variables hold state during the processing of a packet.
1666 	 *
1667 	 * IMPORTANT NOTE: to speed up the processing of rules, there
1668 	 * are some assumption on the values of the variables, which
1669 	 * are documented here. Should you change them, please check
1670 	 * the implementation of the various instructions to make sure
1671 	 * that they still work.
1672 	 *
1673 	 * args->eh	The MAC header. It is non-null for a layer2
1674 	 *	packet, it is NULL for a layer-3 packet.
1675 	 *
1676 	 * m | args->m	Pointer to the mbuf, as received from the caller.
1677 	 *	It may change if ipfw_chk() does an m_pullup, or if it
1678 	 *	consumes the packet because it calls send_reject().
1679 	 *	XXX This has to change, so that ipfw_chk() never modifies
1680 	 *	or consumes the buffer.
1681 	 * ip	is simply an alias of the value of m, and it is kept
1682 	 *	in sync with it (the packet is	supposed to start with
1683 	 *	the ip header).
1684 	 */
1685 	struct mbuf *m = args->m;
1686 	struct ip *ip = mtod(m, struct ip *);
1687 
1688 	/*
1689 	 * oif | args->oif	If NULL, ipfw_chk has been called on the
1690 	 *	inbound path (ether_input, ip_input).
1691 	 *	If non-NULL, ipfw_chk has been called on the outbound path
1692 	 *	(ether_output, ip_output).
1693 	 */
1694 	struct ifnet *oif = args->oif;
1695 
1696 	struct ip_fw *f = NULL;		/* matching rule */
1697 	int retval = IP_FW_PASS;
1698 	struct m_tag *mtag;
1699 	struct divert_info *divinfo;
1700 
1701 	/*
1702 	 * hlen	The length of the IPv4 header.
1703 	 *	hlen >0 means we have an IPv4 packet.
1704 	 */
1705 	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1706 
1707 	/*
1708 	 * offset	The offset of a fragment. offset != 0 means that
1709 	 *	we have a fragment at this offset of an IPv4 packet.
1710 	 *	offset == 0 means that (if this is an IPv4 packet)
1711 	 *	this is the first or only fragment.
1712 	 */
1713 	u_short offset = 0;
1714 
1715 	/*
1716 	 * Local copies of addresses. They are only valid if we have
1717 	 * an IP packet.
1718 	 *
1719 	 * proto	The protocol. Set to 0 for non-ip packets,
1720 	 *	or to the protocol read from the packet otherwise.
1721 	 *	proto != 0 means that we have an IPv4 packet.
1722 	 *
1723 	 * src_port, dst_port	port numbers, in HOST format. Only
1724 	 *	valid for TCP and UDP packets.
1725 	 *
1726 	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1727 	 *	Only valid for IPv4 packets.
1728 	 */
1729 	uint8_t proto;
1730 	uint16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
1731 	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1732 	uint16_t ip_len = 0;
1733 
1734 	/*
1735 	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1736 	 * 	MATCH_NONE when checked and not matched (dyn_f = NULL),
1737 	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (dyn_f != NULL)
1738 	 */
1739 	int dyn_dir = MATCH_UNKNOWN;
1740 	struct ip_fw *dyn_f = NULL;
1741 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
1742 
1743 	if (m->m_pkthdr.fw_flags & IPFW_MBUF_GENERATED)
1744 		return IP_FW_PASS;	/* accept */
1745 
1746 	if (args->eh == NULL ||		/* layer 3 packet */
1747 	    (m->m_pkthdr.len >= sizeof(struct ip) &&
1748 	     ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1749 		hlen = ip->ip_hl << 2;
1750 
1751 	/*
1752 	 * Collect parameters into local variables for faster matching.
1753 	 */
1754 	if (hlen == 0) {	/* do not grab addresses for non-ip pkts */
1755 		proto = args->f_id.proto = 0;	/* mark f_id invalid */
1756 		goto after_ip_checks;
1757 	}
1758 
1759 	proto = args->f_id.proto = ip->ip_p;
1760 	src_ip = ip->ip_src;
1761 	dst_ip = ip->ip_dst;
1762 	if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1763 		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1764 		ip_len = ntohs(ip->ip_len);
1765 	} else {
1766 		offset = ip->ip_off & IP_OFFMASK;
1767 		ip_len = ip->ip_len;
1768 	}
1769 
1770 #define PULLUP_TO(len)				\
1771 do {						\
1772 	if (m->m_len < (len)) {			\
1773 		args->m = m = m_pullup(m, (len));\
1774 		if (m == NULL)			\
1775 			goto pullup_failed;	\
1776 		ip = mtod(m, struct ip *);	\
1777 	}					\
1778 } while (0)
1779 
1780 	if (offset == 0) {
1781 		switch (proto) {
1782 		case IPPROTO_TCP:
1783 			{
1784 				struct tcphdr *tcp;
1785 
1786 				PULLUP_TO(hlen + sizeof(struct tcphdr));
1787 				tcp = L3HDR(struct tcphdr, ip);
1788 				dst_port = tcp->th_dport;
1789 				src_port = tcp->th_sport;
1790 				args->f_id.flags = tcp->th_flags;
1791 			}
1792 			break;
1793 
1794 		case IPPROTO_UDP:
1795 			{
1796 				struct udphdr *udp;
1797 
1798 				PULLUP_TO(hlen + sizeof(struct udphdr));
1799 				udp = L3HDR(struct udphdr, ip);
1800 				dst_port = udp->uh_dport;
1801 				src_port = udp->uh_sport;
1802 			}
1803 			break;
1804 
1805 		case IPPROTO_ICMP:
1806 			PULLUP_TO(hlen + 4);	/* type, code and checksum. */
1807 			args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1808 			break;
1809 
1810 		default:
1811 			break;
1812 		}
1813 	}
1814 
1815 #undef PULLUP_TO
1816 
1817 	args->f_id.src_ip = ntohl(src_ip.s_addr);
1818 	args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1819 	args->f_id.src_port = src_port = ntohs(src_port);
1820 	args->f_id.dst_port = dst_port = ntohs(dst_port);
1821 
1822 after_ip_checks:
1823 	if (args->rule) {
1824 		/*
1825 		 * Packet has already been tagged. Look for the next rule
1826 		 * to restart processing.
1827 		 *
1828 		 * If fw_one_pass != 0 then just accept it.
1829 		 * XXX should not happen here, but optimized out in
1830 		 * the caller.
1831 		 */
1832 		if (fw_one_pass)
1833 			return IP_FW_PASS;
1834 
1835 		/* This rule is being/has been flushed */
1836 		if (ipfw_flushing)
1837 			return IP_FW_DENY;
1838 
1839 		KASSERT(args->rule->cpuid == mycpuid,
1840 			("rule used on cpu%d", mycpuid));
1841 
1842 		/* This rule was deleted */
1843 		if (args->rule->rule_flags & IPFW_RULE_F_INVALID)
1844 			return IP_FW_DENY;
1845 
1846 		f = args->rule->next_rule;
1847 		if (f == NULL)
1848 			f = lookup_next_rule(args->rule);
1849 	} else {
1850 		/*
1851 		 * Find the starting rule. It can be either the first
1852 		 * one, or the one after divert_rule if asked so.
1853 		 */
1854 		int skipto;
1855 
1856 		mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1857 		if (mtag != NULL) {
1858 			divinfo = m_tag_data(mtag);
1859 			skipto = divinfo->skipto;
1860 		} else {
1861 			skipto = 0;
1862 		}
1863 
1864 		f = ctx->ipfw_layer3_chain;
1865 		if (args->eh == NULL && skipto != 0) {
1866 			/* No skipto during rule flushing */
1867 			if (ipfw_flushing)
1868 				return IP_FW_DENY;
1869 
1870 			if (skipto >= IPFW_DEFAULT_RULE)
1871 				return IP_FW_DENY; /* invalid */
1872 
1873 			while (f && f->rulenum <= skipto)
1874 				f = f->next;
1875 			if (f == NULL)	/* drop packet */
1876 				return IP_FW_DENY;
1877 		} else if (ipfw_flushing) {
1878 			/* Rules are being flushed; skip to default rule */
1879 			f = ctx->ipfw_default_rule;
1880 		}
1881 	}
1882 	if ((mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL)) != NULL)
1883 		m_tag_delete(m, mtag);
1884 
1885 	/*
1886 	 * Now scan the rules, and parse microinstructions for each rule.
1887 	 */
1888 	for (; f; f = f->next) {
1889 		int l, cmdlen;
1890 		ipfw_insn *cmd;
1891 		int skip_or; /* skip rest of OR block */
1892 
1893 again:
1894 		if (ctx->ipfw_set_disable & (1 << f->set))
1895 			continue;
1896 
1897 		skip_or = 0;
1898 		for (l = f->cmd_len, cmd = f->cmd; l > 0;
1899 		     l -= cmdlen, cmd += cmdlen) {
1900 			int match, deny;
1901 
1902 			/*
1903 			 * check_body is a jump target used when we find a
1904 			 * CHECK_STATE, and need to jump to the body of
1905 			 * the target rule.
1906 			 */
1907 
1908 check_body:
1909 			cmdlen = F_LEN(cmd);
1910 			/*
1911 			 * An OR block (insn_1 || .. || insn_n) has the
1912 			 * F_OR bit set in all but the last instruction.
1913 			 * The first match will set "skip_or", and cause
1914 			 * the following instructions to be skipped until
1915 			 * past the one with the F_OR bit clear.
1916 			 */
1917 			if (skip_or) {		/* skip this instruction */
1918 				if ((cmd->len & F_OR) == 0)
1919 					skip_or = 0;	/* next one is good */
1920 				continue;
1921 			}
1922 			match = 0; /* set to 1 if we succeed */
1923 
1924 			switch (cmd->opcode) {
1925 			/*
1926 			 * The first set of opcodes compares the packet's
1927 			 * fields with some pattern, setting 'match' if a
1928 			 * match is found. At the end of the loop there is
1929 			 * logic to deal with F_NOT and F_OR flags associated
1930 			 * with the opcode.
1931 			 */
1932 			case O_NOP:
1933 				match = 1;
1934 				break;
1935 
1936 			case O_FORWARD_MAC:
1937 				kprintf("ipfw: opcode %d unimplemented\n",
1938 					cmd->opcode);
1939 				break;
1940 
1941 			case O_GID:
1942 			case O_UID:
1943 				/*
1944 				 * We only check offset == 0 && proto != 0,
1945 				 * as this ensures that we have an IPv4
1946 				 * packet with the ports info.
1947 				 */
1948 				if (offset!=0)
1949 					break;
1950 
1951 				match = ipfw_match_uid(&args->f_id, oif,
1952 					cmd->opcode,
1953 					(uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1954 					&deny);
1955 				if (deny)
1956 					return IP_FW_DENY;
1957 				break;
1958 
1959 			case O_RECV:
1960 				match = iface_match(m->m_pkthdr.rcvif,
1961 				    (ipfw_insn_if *)cmd);
1962 				break;
1963 
1964 			case O_XMIT:
1965 				match = iface_match(oif, (ipfw_insn_if *)cmd);
1966 				break;
1967 
1968 			case O_VIA:
1969 				match = iface_match(oif ? oif :
1970 				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1971 				break;
1972 
1973 			case O_MACADDR2:
1974 				if (args->eh != NULL) {	/* have MAC header */
1975 					uint32_t *want = (uint32_t *)
1976 						((ipfw_insn_mac *)cmd)->addr;
1977 					uint32_t *mask = (uint32_t *)
1978 						((ipfw_insn_mac *)cmd)->mask;
1979 					uint32_t *hdr = (uint32_t *)args->eh;
1980 
1981 					match =
1982 					(want[0] == (hdr[0] & mask[0]) &&
1983 					 want[1] == (hdr[1] & mask[1]) &&
1984 					 want[2] == (hdr[2] & mask[2]));
1985 				}
1986 				break;
1987 
1988 			case O_MAC_TYPE:
1989 				if (args->eh != NULL) {
1990 					uint16_t t =
1991 					    ntohs(args->eh->ether_type);
1992 					uint16_t *p =
1993 					    ((ipfw_insn_u16 *)cmd)->ports;
1994 					int i;
1995 
1996 					/* Special vlan handling */
1997 					if (m->m_flags & M_VLANTAG)
1998 						t = ETHERTYPE_VLAN;
1999 
2000 					for (i = cmdlen - 1; !match && i > 0;
2001 					     i--, p += 2) {
2002 						match =
2003 						(t >= p[0] && t <= p[1]);
2004 					}
2005 				}
2006 				break;
2007 
2008 			case O_FRAG:
2009 				match = (hlen > 0 && offset != 0);
2010 				break;
2011 
2012 			case O_IN:	/* "out" is "not in" */
2013 				match = (oif == NULL);
2014 				break;
2015 
2016 			case O_LAYER2:
2017 				match = (args->eh != NULL);
2018 				break;
2019 
2020 			case O_PROTO:
2021 				/*
2022 				 * We do not allow an arg of 0 so the
2023 				 * check of "proto" only suffices.
2024 				 */
2025 				match = (proto == cmd->arg1);
2026 				break;
2027 
2028 			case O_IP_SRC:
2029 				match = (hlen > 0 &&
2030 				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2031 				    src_ip.s_addr);
2032 				break;
2033 
2034 			case O_IP_SRC_MASK:
2035 				match = (hlen > 0 &&
2036 				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2037 				     (src_ip.s_addr &
2038 				     ((ipfw_insn_ip *)cmd)->mask.s_addr));
2039 				break;
2040 
2041 			case O_IP_SRC_ME:
2042 				if (hlen > 0) {
2043 					struct ifnet *tif;
2044 
2045 					tif = INADDR_TO_IFP(&src_ip);
2046 					match = (tif != NULL);
2047 				}
2048 				break;
2049 
2050 			case O_IP_DST_SET:
2051 			case O_IP_SRC_SET:
2052 				if (hlen > 0) {
2053 					uint32_t *d = (uint32_t *)(cmd + 1);
2054 					uint32_t addr =
2055 					    cmd->opcode == O_IP_DST_SET ?
2056 						args->f_id.dst_ip :
2057 						args->f_id.src_ip;
2058 
2059 					if (addr < d[0])
2060 						break;
2061 					addr -= d[0]; /* subtract base */
2062 					match =
2063 					(addr < cmd->arg1) &&
2064 					 (d[1 + (addr >> 5)] &
2065 					  (1 << (addr & 0x1f)));
2066 				}
2067 				break;
2068 
2069 			case O_IP_DST:
2070 				match = (hlen > 0 &&
2071 				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2072 				    dst_ip.s_addr);
2073 				break;
2074 
2075 			case O_IP_DST_MASK:
2076 				match = (hlen > 0) &&
2077 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2078 				     (dst_ip.s_addr &
2079 				     ((ipfw_insn_ip *)cmd)->mask.s_addr));
2080 				break;
2081 
2082 			case O_IP_DST_ME:
2083 				if (hlen > 0) {
2084 					struct ifnet *tif;
2085 
2086 					tif = INADDR_TO_IFP(&dst_ip);
2087 					match = (tif != NULL);
2088 				}
2089 				break;
2090 
2091 			case O_IP_SRCPORT:
2092 			case O_IP_DSTPORT:
2093 				/*
2094 				 * offset == 0 && proto != 0 is enough
2095 				 * to guarantee that we have an IPv4
2096 				 * packet with port info.
2097 				 */
2098 				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2099 				    && offset == 0) {
2100 					uint16_t x =
2101 					    (cmd->opcode == O_IP_SRCPORT) ?
2102 						src_port : dst_port ;
2103 					uint16_t *p =
2104 					    ((ipfw_insn_u16 *)cmd)->ports;
2105 					int i;
2106 
2107 					for (i = cmdlen - 1; !match && i > 0;
2108 					     i--, p += 2) {
2109 						match =
2110 						(x >= p[0] && x <= p[1]);
2111 					}
2112 				}
2113 				break;
2114 
2115 			case O_ICMPTYPE:
2116 				match = (offset == 0 && proto==IPPROTO_ICMP &&
2117 				    icmptype_match(ip, (ipfw_insn_u32 *)cmd));
2118 				break;
2119 
2120 			case O_IPOPT:
2121 				match = (hlen > 0 && ipopts_match(ip, cmd));
2122 				break;
2123 
2124 			case O_IPVER:
2125 				match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2126 				break;
2127 
2128 			case O_IPTTL:
2129 				match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
2130 				break;
2131 
2132 			case O_IPID:
2133 				match = (hlen > 0 &&
2134 				    cmd->arg1 == ntohs(ip->ip_id));
2135 				break;
2136 
2137 			case O_IPLEN:
2138 				match = (hlen > 0 && cmd->arg1 == ip_len);
2139 				break;
2140 
2141 			case O_IPPRECEDENCE:
2142 				match = (hlen > 0 &&
2143 				    (cmd->arg1 == (ip->ip_tos & 0xe0)));
2144 				break;
2145 
2146 			case O_IPTOS:
2147 				match = (hlen > 0 &&
2148 				    flags_match(cmd, ip->ip_tos));
2149 				break;
2150 
2151 			case O_TCPFLAGS:
2152 				match = (proto == IPPROTO_TCP && offset == 0 &&
2153 				    flags_match(cmd,
2154 					L3HDR(struct tcphdr,ip)->th_flags));
2155 				break;
2156 
2157 			case O_TCPOPTS:
2158 				match = (proto == IPPROTO_TCP && offset == 0 &&
2159 				    tcpopts_match(ip, cmd));
2160 				break;
2161 
2162 			case O_TCPSEQ:
2163 				match = (proto == IPPROTO_TCP && offset == 0 &&
2164 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2165 					L3HDR(struct tcphdr,ip)->th_seq);
2166 				break;
2167 
2168 			case O_TCPACK:
2169 				match = (proto == IPPROTO_TCP && offset == 0 &&
2170 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2171 					L3HDR(struct tcphdr,ip)->th_ack);
2172 				break;
2173 
2174 			case O_TCPWIN:
2175 				match = (proto == IPPROTO_TCP && offset == 0 &&
2176 				    cmd->arg1 ==
2177 					L3HDR(struct tcphdr,ip)->th_win);
2178 				break;
2179 
2180 			case O_ESTAB:
2181 				/* reject packets which have SYN only */
2182 				/* XXX should i also check for TH_ACK ? */
2183 				match = (proto == IPPROTO_TCP && offset == 0 &&
2184 				    (L3HDR(struct tcphdr,ip)->th_flags &
2185 				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2186 				break;
2187 
2188 			case O_LOG:
2189 				if (fw_verbose)
2190 					ipfw_log(f, hlen, args->eh, m, oif);
2191 				match = 1;
2192 				break;
2193 
2194 			case O_PROB:
2195 				match = (krandom() <
2196 					((ipfw_insn_u32 *)cmd)->d[0]);
2197 				break;
2198 
2199 			/*
2200 			 * The second set of opcodes represents 'actions',
2201 			 * i.e. the terminal part of a rule once the packet
2202 			 * matches all previous patterns.
2203 			 * Typically there is only one action for each rule,
2204 			 * and the opcode is stored at the end of the rule
2205 			 * (but there are exceptions -- see below).
2206 			 *
2207 			 * In general, here we set retval and terminate the
2208 			 * outer loop (would be a 'break 3' in some language,
2209 			 * but we need to do a 'goto done').
2210 			 *
2211 			 * Exceptions:
2212 			 * O_COUNT and O_SKIPTO actions:
2213 			 *   instead of terminating, we jump to the next rule
2214 			 *   ('goto next_rule', equivalent to a 'break 2'),
2215 			 *   or to the SKIPTO target ('goto again' after
2216 			 *   having set f, cmd and l), respectively.
2217 			 *
2218 			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2219 			 *   not real 'actions', and are stored right
2220 			 *   before the 'action' part of the rule.
2221 			 *   These opcodes try to install an entry in the
2222 			 *   state tables; if successful, we continue with
2223 			 *   the next opcode (match=1; break;), otherwise
2224 			 *   the packet must be dropped ('goto done' after
2225 			 *   setting retval).  If static rules are changed
2226 			 *   during the state installation, the packet will
2227 			 *   be dropped and rule's stats will not beupdated
2228 			 *   ('return IP_FW_DENY').
2229 			 *
2230 			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2231 			 *   cause a lookup of the state table, and a jump
2232 			 *   to the 'action' part of the parent rule
2233 			 *   ('goto check_body') if an entry is found, or
2234 			 *   (CHECK_STATE only) a jump to the next rule if
2235 			 *   the entry is not found ('goto next_rule').
2236 			 *   The result of the lookup is cached to make
2237 			 *   further instances of these opcodes are
2238 			 *   effectively NOPs.  If static rules are changed
2239 			 *   during the state looking up, the packet will
2240 			 *   be dropped and rule's stats will not be updated
2241 			 *   ('return IP_FW_DENY').
2242 			 */
2243 			case O_LIMIT:
2244 			case O_KEEP_STATE:
2245 				if (!(f->rule_flags & IPFW_RULE_F_STATE)) {
2246 					kprintf("%s rule (%d) is not ready "
2247 						"on cpu%d\n",
2248 						cmd->opcode == O_LIMIT ?
2249 						"limit" : "keep state",
2250 						f->rulenum, f->cpuid);
2251 					goto next_rule;
2252 				}
2253 				if (install_state(f,
2254 				    (ipfw_insn_limit *)cmd, args, &deny)) {
2255 					if (deny)
2256 						return IP_FW_DENY;
2257 
2258 					retval = IP_FW_DENY;
2259 					goto done; /* error/limit violation */
2260 				}
2261 				if (deny)
2262 					return IP_FW_DENY;
2263 				match = 1;
2264 				break;
2265 
2266 			case O_PROBE_STATE:
2267 			case O_CHECK_STATE:
2268 				/*
2269 				 * dynamic rules are checked at the first
2270 				 * keep-state or check-state occurrence,
2271 				 * with the result being stored in dyn_dir.
2272 				 * The compiler introduces a PROBE_STATE
2273 				 * instruction for us when we have a
2274 				 * KEEP_STATE (because PROBE_STATE needs
2275 				 * to be run first).
2276 				 */
2277 				if (dyn_dir == MATCH_UNKNOWN) {
2278 					dyn_f = lookup_rule(&args->f_id,
2279 						&dyn_dir,
2280 						proto == IPPROTO_TCP ?
2281 						L3HDR(struct tcphdr, ip) : NULL,
2282 						ip_len, &deny);
2283 					if (deny)
2284 						return IP_FW_DENY;
2285 					if (dyn_f != NULL) {
2286 						/*
2287 						 * Found a rule from a dynamic
2288 						 * entry; jump to the 'action'
2289 						 * part of the rule.
2290 						 */
2291 						f = dyn_f;
2292 						cmd = ACTION_PTR(f);
2293 						l = f->cmd_len - f->act_ofs;
2294 						goto check_body;
2295 					}
2296 				}
2297 				/*
2298 				 * Dynamic entry not found. If CHECK_STATE,
2299 				 * skip to next rule, if PROBE_STATE just
2300 				 * ignore and continue with next opcode.
2301 				 */
2302 				if (cmd->opcode == O_CHECK_STATE)
2303 					goto next_rule;
2304 				else if (!(f->rule_flags & IPFW_RULE_F_STATE))
2305 					goto next_rule; /* not ready yet */
2306 				match = 1;
2307 				break;
2308 
2309 			case O_ACCEPT:
2310 				retval = IP_FW_PASS;	/* accept */
2311 				goto done;
2312 
2313 			case O_PIPE:
2314 			case O_QUEUE:
2315 				args->rule = f; /* report matching rule */
2316 				args->cookie = cmd->arg1;
2317 				retval = IP_FW_DUMMYNET;
2318 				goto done;
2319 
2320 			case O_DIVERT:
2321 			case O_TEE:
2322 				if (args->eh) /* not on layer 2 */
2323 					break;
2324 
2325 				mtag = m_tag_get(PACKET_TAG_IPFW_DIVERT,
2326 						 sizeof(*divinfo), MB_DONTWAIT);
2327 				if (mtag == NULL) {
2328 					retval = IP_FW_DENY;
2329 					goto done;
2330 				}
2331 				divinfo = m_tag_data(mtag);
2332 
2333 				divinfo->skipto = f->rulenum;
2334 				divinfo->port = cmd->arg1;
2335 				divinfo->tee = (cmd->opcode == O_TEE);
2336 				m_tag_prepend(m, mtag);
2337 
2338 				args->cookie = cmd->arg1;
2339 				retval = (cmd->opcode == O_DIVERT) ?
2340 					 IP_FW_DIVERT : IP_FW_TEE;
2341 				goto done;
2342 
2343 			case O_COUNT:
2344 			case O_SKIPTO:
2345 				f->pcnt++;	/* update stats */
2346 				f->bcnt += ip_len;
2347 				f->timestamp = time_second;
2348 				if (cmd->opcode == O_COUNT)
2349 					goto next_rule;
2350 				/* handle skipto */
2351 				if (f->next_rule == NULL)
2352 					lookup_next_rule(f);
2353 				f = f->next_rule;
2354 				goto again;
2355 
2356 			case O_REJECT:
2357 				/*
2358 				 * Drop the packet and send a reject notice
2359 				 * if the packet is not ICMP (or is an ICMP
2360 				 * query), and it is not multicast/broadcast.
2361 				 */
2362 				if (hlen > 0 &&
2363 				    (proto != IPPROTO_ICMP ||
2364 				     is_icmp_query(ip)) &&
2365 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2366 				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2367 					/*
2368 					 * Update statistics before the possible
2369 					 * blocking 'send_reject'
2370 					 */
2371 					f->pcnt++;
2372 					f->bcnt += ip_len;
2373 					f->timestamp = time_second;
2374 
2375 					send_reject(args, cmd->arg1,
2376 					    offset,ip_len);
2377 					m = args->m;
2378 
2379 					/*
2380 					 * Return directly here, rule stats
2381 					 * have been updated above.
2382 					 */
2383 					return IP_FW_DENY;
2384 				}
2385 				/* FALLTHROUGH */
2386 			case O_DENY:
2387 				retval = IP_FW_DENY;
2388 				goto done;
2389 
2390 			case O_FORWARD_IP:
2391 				if (args->eh)	/* not valid on layer2 pkts */
2392 					break;
2393 				if (!dyn_f || dyn_dir == MATCH_FORWARD) {
2394 					struct sockaddr_in *sin;
2395 
2396 					mtag = m_tag_get(PACKET_TAG_IPFORWARD,
2397 					       sizeof(*sin), MB_DONTWAIT);
2398 					if (mtag == NULL) {
2399 						retval = IP_FW_DENY;
2400 						goto done;
2401 					}
2402 					sin = m_tag_data(mtag);
2403 
2404 					/* Structure copy */
2405 					*sin = ((ipfw_insn_sa *)cmd)->sa;
2406 
2407 					m_tag_prepend(m, mtag);
2408 					m->m_pkthdr.fw_flags |=
2409 						IPFORWARD_MBUF_TAGGED;
2410 					m->m_pkthdr.fw_flags &=
2411 						~BRIDGE_MBUF_TAGGED;
2412 				}
2413 				retval = IP_FW_PASS;
2414 				goto done;
2415 
2416 			default:
2417 				panic("-- unknown opcode %d", cmd->opcode);
2418 			} /* end of switch() on opcodes */
2419 
2420 			if (cmd->len & F_NOT)
2421 				match = !match;
2422 
2423 			if (match) {
2424 				if (cmd->len & F_OR)
2425 					skip_or = 1;
2426 			} else {
2427 				if (!(cmd->len & F_OR)) /* not an OR block, */
2428 					break;		/* try next rule    */
2429 			}
2430 
2431 		}	/* end of inner for, scan opcodes */
2432 
2433 next_rule:;		/* try next rule		*/
2434 
2435 	}		/* end of outer for, scan rules */
2436 	kprintf("+++ ipfw: ouch!, skip past end of rules, denying packet\n");
2437 	return IP_FW_DENY;
2438 
2439 done:
2440 	/* Update statistics */
2441 	f->pcnt++;
2442 	f->bcnt += ip_len;
2443 	f->timestamp = time_second;
2444 	return retval;
2445 
2446 pullup_failed:
2447 	if (fw_verbose)
2448 		kprintf("pullup failed\n");
2449 	return IP_FW_DENY;
2450 }
2451 
2452 static void
2453 ipfw_dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
2454 {
2455 	struct m_tag *mtag;
2456 	struct dn_pkt *pkt;
2457 	ipfw_insn *cmd;
2458 	const struct ipfw_flow_id *id;
2459 	struct dn_flow_id *fid;
2460 
2461 	M_ASSERTPKTHDR(m);
2462 
2463 	mtag = m_tag_get(PACKET_TAG_DUMMYNET, sizeof(*pkt), MB_DONTWAIT);
2464 	if (mtag == NULL) {
2465 		m_freem(m);
2466 		return;
2467 	}
2468 	m_tag_prepend(m, mtag);
2469 
2470 	pkt = m_tag_data(mtag);
2471 	bzero(pkt, sizeof(*pkt));
2472 
2473 	cmd = fwa->rule->cmd + fwa->rule->act_ofs;
2474 	if (cmd->opcode == O_LOG)
2475 		cmd += F_LEN(cmd);
2476 	KASSERT(cmd->opcode == O_PIPE || cmd->opcode == O_QUEUE,
2477 		("Rule is not PIPE or QUEUE, opcode %d", cmd->opcode));
2478 
2479 	pkt->dn_m = m;
2480 	pkt->dn_flags = (dir & DN_FLAGS_DIR_MASK);
2481 	pkt->ifp = fwa->oif;
2482 	pkt->pipe_nr = pipe_nr;
2483 
2484 	pkt->cpuid = mycpuid;
2485 	pkt->msgport = cur_netport();
2486 
2487 	id = &fwa->f_id;
2488 	fid = &pkt->id;
2489 	fid->fid_dst_ip = id->dst_ip;
2490 	fid->fid_src_ip = id->src_ip;
2491 	fid->fid_dst_port = id->dst_port;
2492 	fid->fid_src_port = id->src_port;
2493 	fid->fid_proto = id->proto;
2494 	fid->fid_flags = id->flags;
2495 
2496 	ipfw_ref_rule(fwa->rule);
2497 	pkt->dn_priv = fwa->rule;
2498 	pkt->dn_unref_priv = ipfw_unref_rule;
2499 
2500 	if (cmd->opcode == O_PIPE)
2501 		pkt->dn_flags |= DN_FLAGS_IS_PIPE;
2502 
2503 	m->m_pkthdr.fw_flags |= DUMMYNET_MBUF_TAGGED;
2504 }
2505 
2506 /*
2507  * When a rule is added/deleted, clear the next_rule pointers in all rules.
2508  * These will be reconstructed on the fly as packets are matched.
2509  * Must be called at splimp().
2510  */
2511 static void
2512 ipfw_flush_rule_ptrs(struct ipfw_context *ctx)
2513 {
2514 	struct ip_fw *rule;
2515 
2516 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
2517 		rule->next_rule = NULL;
2518 }
2519 
2520 static __inline void
2521 ipfw_inc_static_count(struct ip_fw *rule)
2522 {
2523 	/* Static rule's counts are updated only on CPU0 */
2524 	KKASSERT(mycpuid == 0);
2525 
2526 	static_count++;
2527 	static_ioc_len += IOC_RULESIZE(rule);
2528 }
2529 
2530 static __inline void
2531 ipfw_dec_static_count(struct ip_fw *rule)
2532 {
2533 	int l = IOC_RULESIZE(rule);
2534 
2535 	/* Static rule's counts are updated only on CPU0 */
2536 	KKASSERT(mycpuid == 0);
2537 
2538 	KASSERT(static_count > 0, ("invalid static count %u", static_count));
2539 	static_count--;
2540 
2541 	KASSERT(static_ioc_len >= l,
2542 		("invalid static len %u", static_ioc_len));
2543 	static_ioc_len -= l;
2544 }
2545 
2546 static void
2547 ipfw_link_sibling(struct netmsg_ipfw *fwmsg, struct ip_fw *rule)
2548 {
2549 	if (fwmsg->sibling != NULL) {
2550 		KKASSERT(mycpuid > 0 && fwmsg->sibling->cpuid == mycpuid - 1);
2551 		fwmsg->sibling->sibling = rule;
2552 	}
2553 	fwmsg->sibling = rule;
2554 }
2555 
2556 static struct ip_fw *
2557 ipfw_create_rule(const struct ipfw_ioc_rule *ioc_rule, struct ip_fw_stub *stub)
2558 {
2559 	struct ip_fw *rule;
2560 
2561 	rule = kmalloc(RULESIZE(ioc_rule), M_IPFW, M_WAITOK | M_ZERO);
2562 
2563 	rule->act_ofs = ioc_rule->act_ofs;
2564 	rule->cmd_len = ioc_rule->cmd_len;
2565 	rule->rulenum = ioc_rule->rulenum;
2566 	rule->set = ioc_rule->set;
2567 	rule->usr_flags = ioc_rule->usr_flags;
2568 
2569 	bcopy(ioc_rule->cmd, rule->cmd, rule->cmd_len * 4 /* XXX */);
2570 
2571 	rule->refcnt = 1;
2572 	rule->cpuid = mycpuid;
2573 
2574 	rule->stub = stub;
2575 	if (stub != NULL)
2576 		stub->rule[mycpuid] = rule;
2577 
2578 	return rule;
2579 }
2580 
2581 static void
2582 ipfw_add_rule_dispatch(netmsg_t nmsg)
2583 {
2584 	struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
2585 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2586 	struct ip_fw *rule;
2587 
2588 	rule = ipfw_create_rule(fwmsg->ioc_rule, fwmsg->stub);
2589 
2590 	/*
2591 	 * Bump generation after ipfw_create_rule(),
2592 	 * since this function is blocking
2593 	 */
2594 	ctx->ipfw_gen++;
2595 
2596 	/*
2597 	 * Insert rule into the pre-determined position
2598 	 */
2599 	if (fwmsg->prev_rule != NULL) {
2600 		struct ip_fw *prev, *next;
2601 
2602 		prev = fwmsg->prev_rule;
2603 		KKASSERT(prev->cpuid == mycpuid);
2604 
2605 		next = fwmsg->next_rule;
2606 		KKASSERT(next->cpuid == mycpuid);
2607 
2608 		rule->next = next;
2609 		prev->next = rule;
2610 
2611 		/*
2612 		 * Move to the position on the next CPU
2613 		 * before the msg is forwarded.
2614 		 */
2615 		fwmsg->prev_rule = prev->sibling;
2616 		fwmsg->next_rule = next->sibling;
2617 	} else {
2618 		KKASSERT(fwmsg->next_rule == NULL);
2619 		rule->next = ctx->ipfw_layer3_chain;
2620 		ctx->ipfw_layer3_chain = rule;
2621 	}
2622 
2623 	/* Link rule CPU sibling */
2624 	ipfw_link_sibling(fwmsg, rule);
2625 
2626 	ipfw_flush_rule_ptrs(ctx);
2627 
2628 	if (mycpuid == 0) {
2629 		/* Statistics only need to be updated once */
2630 		ipfw_inc_static_count(rule);
2631 
2632 		/* Return the rule on CPU0 */
2633 		nmsg->lmsg.u.ms_resultp = rule;
2634 	}
2635 
2636 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2637 }
2638 
2639 static void
2640 ipfw_enable_state_dispatch(netmsg_t nmsg)
2641 {
2642 	struct lwkt_msg *lmsg = &nmsg->lmsg;
2643 	struct ip_fw *rule = lmsg->u.ms_resultp;
2644 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2645 
2646 	ctx->ipfw_gen++;
2647 
2648 	KKASSERT(rule->cpuid == mycpuid);
2649 	KKASSERT(rule->stub != NULL && rule->stub->rule[mycpuid] == rule);
2650 	KKASSERT(!(rule->rule_flags & IPFW_RULE_F_STATE));
2651 	rule->rule_flags |= IPFW_RULE_F_STATE;
2652 	lmsg->u.ms_resultp = rule->sibling;
2653 
2654 	ifnet_forwardmsg(lmsg, mycpuid + 1);
2655 }
2656 
2657 /*
2658  * Add a new rule to the list.  Copy the rule into a malloc'ed area,
2659  * then possibly create a rule number and add the rule to the list.
2660  * Update the rule_number in the input struct so the caller knows
2661  * it as well.
2662  */
2663 static void
2664 ipfw_add_rule(struct ipfw_ioc_rule *ioc_rule, uint32_t rule_flags)
2665 {
2666 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2667 	struct netmsg_ipfw fwmsg;
2668 	struct netmsg_base *nmsg;
2669 	struct ip_fw *f, *prev, *rule;
2670 	struct ip_fw_stub *stub;
2671 
2672 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2673 
2674 	/*
2675 	 * If rulenum is 0, find highest numbered rule before the
2676 	 * default rule, and add rule number incremental step.
2677 	 */
2678 	if (ioc_rule->rulenum == 0) {
2679 		int step = autoinc_step;
2680 
2681 		KKASSERT(step >= IPFW_AUTOINC_STEP_MIN &&
2682 			 step <= IPFW_AUTOINC_STEP_MAX);
2683 
2684 		/*
2685 		 * Locate the highest numbered rule before default
2686 		 */
2687 		for (f = ctx->ipfw_layer3_chain; f; f = f->next) {
2688 			if (f->rulenum == IPFW_DEFAULT_RULE)
2689 				break;
2690 			ioc_rule->rulenum = f->rulenum;
2691 		}
2692 		if (ioc_rule->rulenum < IPFW_DEFAULT_RULE - step)
2693 			ioc_rule->rulenum += step;
2694 	}
2695 	KASSERT(ioc_rule->rulenum != IPFW_DEFAULT_RULE &&
2696 		ioc_rule->rulenum != 0,
2697 		("invalid rule num %d", ioc_rule->rulenum));
2698 
2699 	/*
2700 	 * Now find the right place for the new rule in the sorted list.
2701 	 */
2702 	for (prev = NULL, f = ctx->ipfw_layer3_chain; f;
2703 	     prev = f, f = f->next) {
2704 		if (f->rulenum > ioc_rule->rulenum) {
2705 			/* Found the location */
2706 			break;
2707 		}
2708 	}
2709 	KASSERT(f != NULL, ("no default rule?!"));
2710 
2711 	if (rule_flags & IPFW_RULE_F_STATE) {
2712 		int size;
2713 
2714 		/*
2715 		 * If the new rule will create states, then allocate
2716 		 * a rule stub, which will be referenced by states
2717 		 * (dyn rules)
2718 		 */
2719 		size = sizeof(*stub) + ((ncpus - 1) * sizeof(struct ip_fw *));
2720 		stub = kmalloc(size, M_IPFW, M_WAITOK | M_ZERO);
2721 	} else {
2722 		stub = NULL;
2723 	}
2724 
2725 	/*
2726 	 * Duplicate the rule onto each CPU.
2727 	 * The rule duplicated on CPU0 will be returned.
2728 	 */
2729 	bzero(&fwmsg, sizeof(fwmsg));
2730 	nmsg = &fwmsg.base;
2731 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
2732 		    0, ipfw_add_rule_dispatch);
2733 	fwmsg.ioc_rule = ioc_rule;
2734 	fwmsg.prev_rule = prev;
2735 	fwmsg.next_rule = prev == NULL ? NULL : f;
2736 	fwmsg.stub = stub;
2737 
2738 	ifnet_domsg(&nmsg->lmsg, 0);
2739 	KKASSERT(fwmsg.prev_rule == NULL && fwmsg.next_rule == NULL);
2740 
2741 	rule = nmsg->lmsg.u.ms_resultp;
2742 	KKASSERT(rule != NULL && rule->cpuid == mycpuid);
2743 
2744 	if (rule_flags & IPFW_RULE_F_STATE) {
2745 		/*
2746 		 * Turn on state flag, _after_ everything on all
2747 		 * CPUs have been setup.
2748 		 */
2749 		bzero(nmsg, sizeof(*nmsg));
2750 		netmsg_init(nmsg, NULL, &curthread->td_msgport,
2751 			    0, ipfw_enable_state_dispatch);
2752 		nmsg->lmsg.u.ms_resultp = rule;
2753 
2754 		ifnet_domsg(&nmsg->lmsg, 0);
2755 		KKASSERT(nmsg->lmsg.u.ms_resultp == NULL);
2756 	}
2757 
2758 	DPRINTF("++ installed rule %d, static count now %d\n",
2759 		rule->rulenum, static_count);
2760 }
2761 
2762 /**
2763  * Free storage associated with a static rule (including derived
2764  * dynamic rules).
2765  * The caller is in charge of clearing rule pointers to avoid
2766  * dangling pointers.
2767  * @return a pointer to the next entry.
2768  * Arguments are not checked, so they better be correct.
2769  * Must be called at splimp().
2770  */
2771 static struct ip_fw *
2772 ipfw_delete_rule(struct ipfw_context *ctx,
2773 		 struct ip_fw *prev, struct ip_fw *rule)
2774 {
2775 	struct ip_fw *n;
2776 	struct ip_fw_stub *stub;
2777 
2778 	ctx->ipfw_gen++;
2779 
2780 	/* STATE flag should have been cleared before we reach here */
2781 	KKASSERT((rule->rule_flags & IPFW_RULE_F_STATE) == 0);
2782 
2783 	stub = rule->stub;
2784 	n = rule->next;
2785 	if (prev == NULL)
2786 		ctx->ipfw_layer3_chain = n;
2787 	else
2788 		prev->next = n;
2789 
2790 	/* Mark the rule as invalid */
2791 	rule->rule_flags |= IPFW_RULE_F_INVALID;
2792 	rule->next_rule = NULL;
2793 	rule->sibling = NULL;
2794 	rule->stub = NULL;
2795 #ifdef foo
2796 	/* Don't reset cpuid here; keep various assertion working */
2797 	rule->cpuid = -1;
2798 #endif
2799 
2800 	/* Statistics only need to be updated once */
2801 	if (mycpuid == 0)
2802 		ipfw_dec_static_count(rule);
2803 
2804 	/* Free 'stub' on the last CPU */
2805 	if (stub != NULL && mycpuid == ncpus - 1)
2806 		kfree(stub, M_IPFW);
2807 
2808 	/* Try to free this rule */
2809 	ipfw_free_rule(rule);
2810 
2811 	/* Return the next rule */
2812 	return n;
2813 }
2814 
2815 static void
2816 ipfw_flush_dispatch(netmsg_t nmsg)
2817 {
2818 	struct lwkt_msg *lmsg = &nmsg->lmsg;
2819 	int kill_default = lmsg->u.ms_result;
2820 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2821 	struct ip_fw *rule;
2822 
2823 	ipfw_flush_rule_ptrs(ctx); /* more efficient to do outside the loop */
2824 
2825 	while ((rule = ctx->ipfw_layer3_chain) != NULL &&
2826 	       (kill_default || rule->rulenum != IPFW_DEFAULT_RULE))
2827 		ipfw_delete_rule(ctx, NULL, rule);
2828 
2829 	ifnet_forwardmsg(lmsg, mycpuid + 1);
2830 }
2831 
2832 static void
2833 ipfw_disable_rule_state_dispatch(netmsg_t nmsg)
2834 {
2835 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2836 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2837 	struct ip_fw *rule;
2838 
2839 	ctx->ipfw_gen++;
2840 
2841 	rule = dmsg->start_rule;
2842 	if (rule != NULL) {
2843 		KKASSERT(rule->cpuid == mycpuid);
2844 
2845 		/*
2846 		 * Move to the position on the next CPU
2847 		 * before the msg is forwarded.
2848 		 */
2849 		dmsg->start_rule = rule->sibling;
2850 	} else {
2851 		KKASSERT(dmsg->rulenum == 0);
2852 		rule = ctx->ipfw_layer3_chain;
2853 	}
2854 
2855 	while (rule != NULL) {
2856 		if (dmsg->rulenum && rule->rulenum != dmsg->rulenum)
2857 			break;
2858 		rule->rule_flags &= ~IPFW_RULE_F_STATE;
2859 		rule = rule->next;
2860 	}
2861 
2862 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2863 }
2864 
2865 /*
2866  * Deletes all rules from a chain (including the default rule
2867  * if the second argument is set).
2868  * Must be called at splimp().
2869  */
2870 static void
2871 ipfw_flush(int kill_default)
2872 {
2873 	struct netmsg_del dmsg;
2874 	struct netmsg_base nmsg;
2875 	struct lwkt_msg *lmsg;
2876 	struct ip_fw *rule;
2877 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2878 
2879 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
2880 
2881 	/*
2882 	 * If 'kill_default' then caller has done the necessary
2883 	 * msgport syncing; unnecessary to do it again.
2884 	 */
2885 	if (!kill_default) {
2886 		/*
2887 		 * Let ipfw_chk() know the rules are going to
2888 		 * be flushed, so it could jump directly to
2889 		 * the default rule.
2890 		 */
2891 		ipfw_flushing = 1;
2892 		netmsg_service_sync();
2893 	}
2894 
2895 	/*
2896 	 * Clear STATE flag on rules, so no more states (dyn rules)
2897 	 * will be created.
2898 	 */
2899 	bzero(&dmsg, sizeof(dmsg));
2900 	netmsg_init(&dmsg.base, NULL, &curthread->td_msgport,
2901 		    0, ipfw_disable_rule_state_dispatch);
2902 	ifnet_domsg(&dmsg.base.lmsg, 0);
2903 
2904 	/*
2905 	 * This actually nukes all states (dyn rules)
2906 	 */
2907 	lockmgr(&dyn_lock, LK_EXCLUSIVE);
2908 	for (rule = ctx->ipfw_layer3_chain; rule != NULL; rule = rule->next) {
2909 		/*
2910 		 * Can't check IPFW_RULE_F_STATE here,
2911 		 * since it has been cleared previously.
2912 		 * Check 'stub' instead.
2913 		 */
2914 		if (rule->stub != NULL) {
2915 			/* Force removal */
2916 			remove_dyn_rule_locked(rule, NULL);
2917 		}
2918 	}
2919 	lockmgr(&dyn_lock, LK_RELEASE);
2920 
2921 	/*
2922 	 * Press the 'flush' button
2923 	 */
2924 	bzero(&nmsg, sizeof(nmsg));
2925 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
2926 		    0, ipfw_flush_dispatch);
2927 	lmsg = &nmsg.lmsg;
2928 	lmsg->u.ms_result = kill_default;
2929 	ifnet_domsg(lmsg, 0);
2930 
2931 	KASSERT(dyn_count == 0, ("%u dyn rule remains", dyn_count));
2932 
2933 	if (kill_default) {
2934 		if (ipfw_dyn_v != NULL) {
2935 			/*
2936 			 * Free dynamic rules(state) hash table
2937 			 */
2938 			kfree(ipfw_dyn_v, M_IPFW);
2939 			ipfw_dyn_v = NULL;
2940 		}
2941 
2942 		KASSERT(static_count == 0,
2943 			("%u static rules remain", static_count));
2944 		KASSERT(static_ioc_len == 0,
2945 			("%u bytes of static rules remain", static_ioc_len));
2946 	} else {
2947 		KASSERT(static_count == 1,
2948 			("%u static rules remain", static_count));
2949 		KASSERT(static_ioc_len == IOC_RULESIZE(ctx->ipfw_default_rule),
2950 			("%u bytes of static rules remain, should be %lu",
2951 			 static_ioc_len,
2952 			 (u_long)IOC_RULESIZE(ctx->ipfw_default_rule)));
2953 	}
2954 
2955 	/* Flush is done */
2956 	ipfw_flushing = 0;
2957 }
2958 
2959 static void
2960 ipfw_alt_delete_rule_dispatch(netmsg_t nmsg)
2961 {
2962 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
2963 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2964 	struct ip_fw *rule, *prev;
2965 
2966 	rule = dmsg->start_rule;
2967 	KKASSERT(rule->cpuid == mycpuid);
2968 	dmsg->start_rule = rule->sibling;
2969 
2970 	prev = dmsg->prev_rule;
2971 	if (prev != NULL) {
2972 		KKASSERT(prev->cpuid == mycpuid);
2973 
2974 		/*
2975 		 * Move to the position on the next CPU
2976 		 * before the msg is forwarded.
2977 		 */
2978 		dmsg->prev_rule = prev->sibling;
2979 	}
2980 
2981 	/*
2982 	 * flush pointers outside the loop, then delete all matching
2983 	 * rules.  'prev' remains the same throughout the cycle.
2984 	 */
2985 	ipfw_flush_rule_ptrs(ctx);
2986 	while (rule && rule->rulenum == dmsg->rulenum)
2987 		rule = ipfw_delete_rule(ctx, prev, rule);
2988 
2989 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
2990 }
2991 
2992 static int
2993 ipfw_alt_delete_rule(uint16_t rulenum)
2994 {
2995 	struct ip_fw *prev, *rule, *f;
2996 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
2997 	struct netmsg_del dmsg;
2998 	struct netmsg_base *nmsg;
2999 	int state;
3000 
3001 	/*
3002 	 * Locate first rule to delete
3003 	 */
3004 	for (prev = NULL, rule = ctx->ipfw_layer3_chain;
3005 	     rule && rule->rulenum < rulenum;
3006 	     prev = rule, rule = rule->next)
3007 		; /* EMPTY */
3008 	if (rule->rulenum != rulenum)
3009 		return EINVAL;
3010 
3011 	/*
3012 	 * Check whether any rules with the given number will
3013 	 * create states.
3014 	 */
3015 	state = 0;
3016 	for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3017 		if (f->rule_flags & IPFW_RULE_F_STATE) {
3018 			state = 1;
3019 			break;
3020 		}
3021 	}
3022 
3023 	if (state) {
3024 		/*
3025 		 * Clear the STATE flag, so no more states will be
3026 		 * created based the rules numbered 'rulenum'.
3027 		 */
3028 		bzero(&dmsg, sizeof(dmsg));
3029 		nmsg = &dmsg.base;
3030 		netmsg_init(nmsg, NULL, &curthread->td_msgport,
3031 			    0, ipfw_disable_rule_state_dispatch);
3032 		dmsg.start_rule = rule;
3033 		dmsg.rulenum = rulenum;
3034 
3035 		ifnet_domsg(&nmsg->lmsg, 0);
3036 		KKASSERT(dmsg.start_rule == NULL);
3037 
3038 		/*
3039 		 * Nuke all related states
3040 		 */
3041 		lockmgr(&dyn_lock, LK_EXCLUSIVE);
3042 		for (f = rule; f && f->rulenum == rulenum; f = f->next) {
3043 			/*
3044 			 * Can't check IPFW_RULE_F_STATE here,
3045 			 * since it has been cleared previously.
3046 			 * Check 'stub' instead.
3047 			 */
3048 			if (f->stub != NULL) {
3049 				/* Force removal */
3050 				remove_dyn_rule_locked(f, NULL);
3051 			}
3052 		}
3053 		lockmgr(&dyn_lock, LK_RELEASE);
3054 	}
3055 
3056 	/*
3057 	 * Get rid of the rule duplications on all CPUs
3058 	 */
3059 	bzero(&dmsg, sizeof(dmsg));
3060 	nmsg = &dmsg.base;
3061 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3062 		    0, ipfw_alt_delete_rule_dispatch);
3063 	dmsg.prev_rule = prev;
3064 	dmsg.start_rule = rule;
3065 	dmsg.rulenum = rulenum;
3066 
3067 	ifnet_domsg(&nmsg->lmsg, 0);
3068 	KKASSERT(dmsg.prev_rule == NULL && dmsg.start_rule == NULL);
3069 	return 0;
3070 }
3071 
3072 static void
3073 ipfw_alt_delete_ruleset_dispatch(netmsg_t nmsg)
3074 {
3075 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3076 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3077 	struct ip_fw *prev, *rule;
3078 #ifdef INVARIANTS
3079 	int del = 0;
3080 #endif
3081 
3082 	ipfw_flush_rule_ptrs(ctx);
3083 
3084 	prev = NULL;
3085 	rule = ctx->ipfw_layer3_chain;
3086 	while (rule != NULL) {
3087 		if (rule->set == dmsg->from_set) {
3088 			rule = ipfw_delete_rule(ctx, prev, rule);
3089 #ifdef INVARIANTS
3090 			del = 1;
3091 #endif
3092 		} else {
3093 			prev = rule;
3094 			rule = rule->next;
3095 		}
3096 	}
3097 	KASSERT(del, ("no match set?!"));
3098 
3099 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3100 }
3101 
3102 static void
3103 ipfw_disable_ruleset_state_dispatch(netmsg_t nmsg)
3104 {
3105 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3106 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3107 	struct ip_fw *rule;
3108 #ifdef INVARIANTS
3109 	int cleared = 0;
3110 #endif
3111 
3112 	ctx->ipfw_gen++;
3113 
3114 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3115 		if (rule->set == dmsg->from_set) {
3116 #ifdef INVARIANTS
3117 			cleared = 1;
3118 #endif
3119 			rule->rule_flags &= ~IPFW_RULE_F_STATE;
3120 		}
3121 	}
3122 	KASSERT(cleared, ("no match set?!"));
3123 
3124 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3125 }
3126 
3127 static int
3128 ipfw_alt_delete_ruleset(uint8_t set)
3129 {
3130 	struct netmsg_del dmsg;
3131 	struct netmsg_base *nmsg;
3132 	int state, del;
3133 	struct ip_fw *rule;
3134 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3135 
3136 	/*
3137 	 * Check whether the 'set' exists.  If it exists,
3138 	 * then check whether any rules within the set will
3139 	 * try to create states.
3140 	 */
3141 	state = 0;
3142 	del = 0;
3143 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3144 		if (rule->set == set) {
3145 			del = 1;
3146 			if (rule->rule_flags & IPFW_RULE_F_STATE) {
3147 				state = 1;
3148 				break;
3149 			}
3150 		}
3151 	}
3152 	if (!del)
3153 		return 0; /* XXX EINVAL? */
3154 
3155 	if (state) {
3156 		/*
3157 		 * Clear the STATE flag, so no more states will be
3158 		 * created based the rules in this set.
3159 		 */
3160 		bzero(&dmsg, sizeof(dmsg));
3161 		nmsg = &dmsg.base;
3162 		netmsg_init(nmsg, NULL, &curthread->td_msgport,
3163 			    0, ipfw_disable_ruleset_state_dispatch);
3164 		dmsg.from_set = set;
3165 
3166 		ifnet_domsg(&nmsg->lmsg, 0);
3167 
3168 		/*
3169 		 * Nuke all related states
3170 		 */
3171 		lockmgr(&dyn_lock, LK_EXCLUSIVE);
3172 		for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3173 			if (rule->set != set)
3174 				continue;
3175 
3176 			/*
3177 			 * Can't check IPFW_RULE_F_STATE here,
3178 			 * since it has been cleared previously.
3179 			 * Check 'stub' instead.
3180 			 */
3181 			if (rule->stub != NULL) {
3182 				/* Force removal */
3183 				remove_dyn_rule_locked(rule, NULL);
3184 			}
3185 		}
3186 		lockmgr(&dyn_lock, LK_RELEASE);
3187 	}
3188 
3189 	/*
3190 	 * Delete this set
3191 	 */
3192 	bzero(&dmsg, sizeof(dmsg));
3193 	nmsg = &dmsg.base;
3194 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3195 		    0, ipfw_alt_delete_ruleset_dispatch);
3196 	dmsg.from_set = set;
3197 
3198 	ifnet_domsg(&nmsg->lmsg, 0);
3199 	return 0;
3200 }
3201 
3202 static void
3203 ipfw_alt_move_rule_dispatch(netmsg_t nmsg)
3204 {
3205 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3206 	struct ip_fw *rule;
3207 
3208 	rule = dmsg->start_rule;
3209 	KKASSERT(rule->cpuid == mycpuid);
3210 
3211 	/*
3212 	 * Move to the position on the next CPU
3213 	 * before the msg is forwarded.
3214 	 */
3215 	dmsg->start_rule = rule->sibling;
3216 
3217 	while (rule && rule->rulenum <= dmsg->rulenum) {
3218 		if (rule->rulenum == dmsg->rulenum)
3219 			rule->set = dmsg->to_set;
3220 		rule = rule->next;
3221 	}
3222 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3223 }
3224 
3225 static int
3226 ipfw_alt_move_rule(uint16_t rulenum, uint8_t set)
3227 {
3228 	struct netmsg_del dmsg;
3229 	struct netmsg_base *nmsg;
3230 	struct ip_fw *rule;
3231 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3232 
3233 	/*
3234 	 * Locate first rule to move
3235 	 */
3236 	for (rule = ctx->ipfw_layer3_chain; rule && rule->rulenum <= rulenum;
3237 	     rule = rule->next) {
3238 		if (rule->rulenum == rulenum && rule->set != set)
3239 			break;
3240 	}
3241 	if (rule == NULL || rule->rulenum > rulenum)
3242 		return 0; /* XXX error? */
3243 
3244 	bzero(&dmsg, sizeof(dmsg));
3245 	nmsg = &dmsg.base;
3246 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3247 		    0, ipfw_alt_move_rule_dispatch);
3248 	dmsg.start_rule = rule;
3249 	dmsg.rulenum = rulenum;
3250 	dmsg.to_set = set;
3251 
3252 	ifnet_domsg(&nmsg->lmsg, 0);
3253 	KKASSERT(dmsg.start_rule == NULL);
3254 	return 0;
3255 }
3256 
3257 static void
3258 ipfw_alt_move_ruleset_dispatch(netmsg_t nmsg)
3259 {
3260 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3261 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3262 	struct ip_fw *rule;
3263 
3264 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3265 		if (rule->set == dmsg->from_set)
3266 			rule->set = dmsg->to_set;
3267 	}
3268 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3269 }
3270 
3271 static int
3272 ipfw_alt_move_ruleset(uint8_t from_set, uint8_t to_set)
3273 {
3274 	struct netmsg_del dmsg;
3275 	struct netmsg_base *nmsg;
3276 
3277 	bzero(&dmsg, sizeof(dmsg));
3278 	nmsg = &dmsg.base;
3279 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3280 		    0, ipfw_alt_move_ruleset_dispatch);
3281 	dmsg.from_set = from_set;
3282 	dmsg.to_set = to_set;
3283 
3284 	ifnet_domsg(&nmsg->lmsg, 0);
3285 	return 0;
3286 }
3287 
3288 static void
3289 ipfw_alt_swap_ruleset_dispatch(netmsg_t nmsg)
3290 {
3291 	struct netmsg_del *dmsg = (struct netmsg_del *)nmsg;
3292 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3293 	struct ip_fw *rule;
3294 
3295 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3296 		if (rule->set == dmsg->from_set)
3297 			rule->set = dmsg->to_set;
3298 		else if (rule->set == dmsg->to_set)
3299 			rule->set = dmsg->from_set;
3300 	}
3301 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3302 }
3303 
3304 static int
3305 ipfw_alt_swap_ruleset(uint8_t set1, uint8_t set2)
3306 {
3307 	struct netmsg_del dmsg;
3308 	struct netmsg_base *nmsg;
3309 
3310 	bzero(&dmsg, sizeof(dmsg));
3311 	nmsg = &dmsg.base;
3312 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3313 		    0, ipfw_alt_swap_ruleset_dispatch);
3314 	dmsg.from_set = set1;
3315 	dmsg.to_set = set2;
3316 
3317 	ifnet_domsg(&nmsg->lmsg, 0);
3318 	return 0;
3319 }
3320 
3321 /**
3322  * Remove all rules with given number, and also do set manipulation.
3323  *
3324  * The argument is an uint32_t. The low 16 bit are the rule or set number,
3325  * the next 8 bits are the new set, the top 8 bits are the command:
3326  *
3327  *	0	delete rules with given number
3328  *	1	delete rules with given set number
3329  *	2	move rules with given number to new set
3330  *	3	move rules with given set number to new set
3331  *	4	swap sets with given numbers
3332  */
3333 static int
3334 ipfw_ctl_alter(uint32_t arg)
3335 {
3336 	uint16_t rulenum;
3337 	uint8_t cmd, new_set;
3338 	int error = 0;
3339 
3340 	rulenum = arg & 0xffff;
3341 	cmd = (arg >> 24) & 0xff;
3342 	new_set = (arg >> 16) & 0xff;
3343 
3344 	if (cmd > 4)
3345 		return EINVAL;
3346 	if (new_set >= IPFW_DEFAULT_SET)
3347 		return EINVAL;
3348 	if (cmd == 0 || cmd == 2) {
3349 		if (rulenum == IPFW_DEFAULT_RULE)
3350 			return EINVAL;
3351 	} else {
3352 		if (rulenum >= IPFW_DEFAULT_SET)
3353 			return EINVAL;
3354 	}
3355 
3356 	switch (cmd) {
3357 	case 0:	/* delete rules with given number */
3358 		error = ipfw_alt_delete_rule(rulenum);
3359 		break;
3360 
3361 	case 1:	/* delete all rules with given set number */
3362 		error = ipfw_alt_delete_ruleset(rulenum);
3363 		break;
3364 
3365 	case 2:	/* move rules with given number to new set */
3366 		error = ipfw_alt_move_rule(rulenum, new_set);
3367 		break;
3368 
3369 	case 3: /* move rules with given set number to new set */
3370 		error = ipfw_alt_move_ruleset(rulenum, new_set);
3371 		break;
3372 
3373 	case 4: /* swap two sets */
3374 		error = ipfw_alt_swap_ruleset(rulenum, new_set);
3375 		break;
3376 	}
3377 	return error;
3378 }
3379 
3380 /*
3381  * Clear counters for a specific rule.
3382  */
3383 static void
3384 clear_counters(struct ip_fw *rule, int log_only)
3385 {
3386 	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3387 
3388 	if (log_only == 0) {
3389 		rule->bcnt = rule->pcnt = 0;
3390 		rule->timestamp = 0;
3391 	}
3392 	if (l->o.opcode == O_LOG)
3393 		l->log_left = l->max_log;
3394 }
3395 
3396 static void
3397 ipfw_zero_entry_dispatch(netmsg_t nmsg)
3398 {
3399 	struct netmsg_zent *zmsg = (struct netmsg_zent *)nmsg;
3400 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3401 	struct ip_fw *rule;
3402 
3403 	if (zmsg->rulenum == 0) {
3404 		KKASSERT(zmsg->start_rule == NULL);
3405 
3406 		ctx->ipfw_norule_counter = 0;
3407 		for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3408 			clear_counters(rule, zmsg->log_only);
3409 	} else {
3410 		struct ip_fw *start = zmsg->start_rule;
3411 
3412 		KKASSERT(start->cpuid == mycpuid);
3413 		KKASSERT(start->rulenum == zmsg->rulenum);
3414 
3415 		/*
3416 		 * We can have multiple rules with the same number, so we
3417 		 * need to clear them all.
3418 		 */
3419 		for (rule = start; rule && rule->rulenum == zmsg->rulenum;
3420 		     rule = rule->next)
3421 			clear_counters(rule, zmsg->log_only);
3422 
3423 		/*
3424 		 * Move to the position on the next CPU
3425 		 * before the msg is forwarded.
3426 		 */
3427 		zmsg->start_rule = start->sibling;
3428 	}
3429 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
3430 }
3431 
3432 /**
3433  * Reset some or all counters on firewall rules.
3434  * @arg frwl is null to clear all entries, or contains a specific
3435  * rule number.
3436  * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3437  */
3438 static int
3439 ipfw_ctl_zero_entry(int rulenum, int log_only)
3440 {
3441 	struct netmsg_zent zmsg;
3442 	struct netmsg_base *nmsg;
3443 	const char *msg;
3444 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3445 
3446 	bzero(&zmsg, sizeof(zmsg));
3447 	nmsg = &zmsg.base;
3448 	netmsg_init(nmsg, NULL, &curthread->td_msgport,
3449 		    0, ipfw_zero_entry_dispatch);
3450 	zmsg.log_only = log_only;
3451 
3452 	if (rulenum == 0) {
3453 		msg = log_only ? "ipfw: All logging counts reset.\n"
3454 			       : "ipfw: Accounting cleared.\n";
3455 	} else {
3456 		struct ip_fw *rule;
3457 
3458 		/*
3459 		 * Locate the first rule with 'rulenum'
3460 		 */
3461 		for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next) {
3462 			if (rule->rulenum == rulenum)
3463 				break;
3464 		}
3465 		if (rule == NULL) /* we did not find any matching rules */
3466 			return (EINVAL);
3467 		zmsg.start_rule = rule;
3468 		zmsg.rulenum = rulenum;
3469 
3470 		msg = log_only ? "ipfw: Entry %d logging count reset.\n"
3471 			       : "ipfw: Entry %d cleared.\n";
3472 	}
3473 	ifnet_domsg(&nmsg->lmsg, 0);
3474 	KKASSERT(zmsg.start_rule == NULL);
3475 
3476 	if (fw_verbose)
3477 		log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3478 	return (0);
3479 }
3480 
3481 /*
3482  * Check validity of the structure before insert.
3483  * Fortunately rules are simple, so this mostly need to check rule sizes.
3484  */
3485 static int
3486 ipfw_check_ioc_rule(struct ipfw_ioc_rule *rule, int size, uint32_t *rule_flags)
3487 {
3488 	int l, cmdlen = 0;
3489 	int have_action = 0;
3490 	ipfw_insn *cmd;
3491 
3492 	*rule_flags = 0;
3493 
3494 	/* Check for valid size */
3495 	if (size < sizeof(*rule)) {
3496 		kprintf("ipfw: rule too short\n");
3497 		return EINVAL;
3498 	}
3499 	l = IOC_RULESIZE(rule);
3500 	if (l != size) {
3501 		kprintf("ipfw: size mismatch (have %d want %d)\n", size, l);
3502 		return EINVAL;
3503 	}
3504 
3505 	/* Check rule number */
3506 	if (rule->rulenum == IPFW_DEFAULT_RULE) {
3507 		kprintf("ipfw: invalid rule number\n");
3508 		return EINVAL;
3509 	}
3510 
3511 	/*
3512 	 * Now go for the individual checks. Very simple ones, basically only
3513 	 * instruction sizes.
3514 	 */
3515 	for (l = rule->cmd_len, cmd = rule->cmd; l > 0;
3516 	     l -= cmdlen, cmd += cmdlen) {
3517 		cmdlen = F_LEN(cmd);
3518 		if (cmdlen > l) {
3519 			kprintf("ipfw: opcode %d size truncated\n",
3520 				cmd->opcode);
3521 			return EINVAL;
3522 		}
3523 
3524 		DPRINTF("ipfw: opcode %d\n", cmd->opcode);
3525 
3526 		if (cmd->opcode == O_KEEP_STATE || cmd->opcode == O_LIMIT) {
3527 			/* This rule will create states */
3528 			*rule_flags |= IPFW_RULE_F_STATE;
3529 		}
3530 
3531 		switch (cmd->opcode) {
3532 		case O_NOP:
3533 		case O_PROBE_STATE:
3534 		case O_KEEP_STATE:
3535 		case O_PROTO:
3536 		case O_IP_SRC_ME:
3537 		case O_IP_DST_ME:
3538 		case O_LAYER2:
3539 		case O_IN:
3540 		case O_FRAG:
3541 		case O_IPOPT:
3542 		case O_IPLEN:
3543 		case O_IPID:
3544 		case O_IPTOS:
3545 		case O_IPPRECEDENCE:
3546 		case O_IPTTL:
3547 		case O_IPVER:
3548 		case O_TCPWIN:
3549 		case O_TCPFLAGS:
3550 		case O_TCPOPTS:
3551 		case O_ESTAB:
3552 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3553 				goto bad_size;
3554 			break;
3555 
3556 		case O_UID:
3557 		case O_GID:
3558 		case O_IP_SRC:
3559 		case O_IP_DST:
3560 		case O_TCPSEQ:
3561 		case O_TCPACK:
3562 		case O_PROB:
3563 		case O_ICMPTYPE:
3564 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3565 				goto bad_size;
3566 			break;
3567 
3568 		case O_LIMIT:
3569 			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3570 				goto bad_size;
3571 			break;
3572 
3573 		case O_LOG:
3574 			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3575 				goto bad_size;
3576 
3577 			((ipfw_insn_log *)cmd)->log_left =
3578 			    ((ipfw_insn_log *)cmd)->max_log;
3579 
3580 			break;
3581 
3582 		case O_IP_SRC_MASK:
3583 		case O_IP_DST_MASK:
3584 			if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
3585 				goto bad_size;
3586 			if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
3587 				kprintf("ipfw: opcode %d, useless rule\n",
3588 					cmd->opcode);
3589 				return EINVAL;
3590 			}
3591 			break;
3592 
3593 		case O_IP_SRC_SET:
3594 		case O_IP_DST_SET:
3595 			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3596 				kprintf("ipfw: invalid set size %d\n",
3597 					cmd->arg1);
3598 				return EINVAL;
3599 			}
3600 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3601 			    (cmd->arg1+31)/32 )
3602 				goto bad_size;
3603 			break;
3604 
3605 		case O_MACADDR2:
3606 			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3607 				goto bad_size;
3608 			break;
3609 
3610 		case O_MAC_TYPE:
3611 		case O_IP_SRCPORT:
3612 		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3613 			if (cmdlen < 2 || cmdlen > 31)
3614 				goto bad_size;
3615 			break;
3616 
3617 		case O_RECV:
3618 		case O_XMIT:
3619 		case O_VIA:
3620 			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3621 				goto bad_size;
3622 			break;
3623 
3624 		case O_PIPE:
3625 		case O_QUEUE:
3626 			if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3627 				goto bad_size;
3628 			goto check_action;
3629 
3630 		case O_FORWARD_IP:
3631 			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa)) {
3632 				goto bad_size;
3633 			} else {
3634 				in_addr_t fwd_addr;
3635 
3636 				fwd_addr = ((ipfw_insn_sa *)cmd)->
3637 					   sa.sin_addr.s_addr;
3638 				if (IN_MULTICAST(ntohl(fwd_addr))) {
3639 					kprintf("ipfw: try forwarding to "
3640 						"multicast address\n");
3641 					return EINVAL;
3642 				}
3643 			}
3644 			goto check_action;
3645 
3646 		case O_FORWARD_MAC: /* XXX not implemented yet */
3647 		case O_CHECK_STATE:
3648 		case O_COUNT:
3649 		case O_ACCEPT:
3650 		case O_DENY:
3651 		case O_REJECT:
3652 		case O_SKIPTO:
3653 		case O_DIVERT:
3654 		case O_TEE:
3655 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3656 				goto bad_size;
3657 check_action:
3658 			if (have_action) {
3659 				kprintf("ipfw: opcode %d, multiple actions"
3660 					" not allowed\n",
3661 					cmd->opcode);
3662 				return EINVAL;
3663 			}
3664 			have_action = 1;
3665 			if (l != cmdlen) {
3666 				kprintf("ipfw: opcode %d, action must be"
3667 					" last opcode\n",
3668 					cmd->opcode);
3669 				return EINVAL;
3670 			}
3671 			break;
3672 		default:
3673 			kprintf("ipfw: opcode %d, unknown opcode\n",
3674 				cmd->opcode);
3675 			return EINVAL;
3676 		}
3677 	}
3678 	if (have_action == 0) {
3679 		kprintf("ipfw: missing action\n");
3680 		return EINVAL;
3681 	}
3682 	return 0;
3683 
3684 bad_size:
3685 	kprintf("ipfw: opcode %d size %d wrong\n",
3686 		cmd->opcode, cmdlen);
3687 	return EINVAL;
3688 }
3689 
3690 static int
3691 ipfw_ctl_add_rule(struct sockopt *sopt)
3692 {
3693 	struct ipfw_ioc_rule *ioc_rule;
3694 	size_t size;
3695 	uint32_t rule_flags;
3696 	int error;
3697 
3698 	size = sopt->sopt_valsize;
3699 	if (size > (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX) ||
3700 	    size < sizeof(*ioc_rule)) {
3701 		return EINVAL;
3702 	}
3703 	if (size != (sizeof(uint32_t) * IPFW_RULE_SIZE_MAX)) {
3704 		sopt->sopt_val = krealloc(sopt->sopt_val, sizeof(uint32_t) *
3705 					  IPFW_RULE_SIZE_MAX, M_TEMP, M_WAITOK);
3706 	}
3707 	ioc_rule = sopt->sopt_val;
3708 
3709 	error = ipfw_check_ioc_rule(ioc_rule, size, &rule_flags);
3710 	if (error)
3711 		return error;
3712 
3713 	ipfw_add_rule(ioc_rule, rule_flags);
3714 
3715 	if (sopt->sopt_dir == SOPT_GET)
3716 		sopt->sopt_valsize = IOC_RULESIZE(ioc_rule);
3717 	return 0;
3718 }
3719 
3720 static void *
3721 ipfw_copy_rule(const struct ip_fw *rule, struct ipfw_ioc_rule *ioc_rule)
3722 {
3723 	const struct ip_fw *sibling;
3724 #ifdef INVARIANTS
3725 	int i;
3726 #endif
3727 
3728 	KKASSERT(rule->cpuid == IPFW_CFGCPUID);
3729 
3730 	ioc_rule->act_ofs = rule->act_ofs;
3731 	ioc_rule->cmd_len = rule->cmd_len;
3732 	ioc_rule->rulenum = rule->rulenum;
3733 	ioc_rule->set = rule->set;
3734 	ioc_rule->usr_flags = rule->usr_flags;
3735 
3736 	ioc_rule->set_disable = ipfw_ctx[mycpuid]->ipfw_set_disable;
3737 	ioc_rule->static_count = static_count;
3738 	ioc_rule->static_len = static_ioc_len;
3739 
3740 	/*
3741 	 * Visit (read-only) all of the rule's duplications to get
3742 	 * the necessary statistics
3743 	 */
3744 #ifdef INVARIANTS
3745 	i = 0;
3746 #endif
3747 	ioc_rule->pcnt = 0;
3748 	ioc_rule->bcnt = 0;
3749 	ioc_rule->timestamp = 0;
3750 	for (sibling = rule; sibling != NULL; sibling = sibling->sibling) {
3751 		ioc_rule->pcnt += sibling->pcnt;
3752 		ioc_rule->bcnt += sibling->bcnt;
3753 		if (sibling->timestamp > ioc_rule->timestamp)
3754 			ioc_rule->timestamp = sibling->timestamp;
3755 #ifdef INVARIANTS
3756 		++i;
3757 #endif
3758 	}
3759 	KASSERT(i == ncpus, ("static rule is not duplicated on every cpu"));
3760 
3761 	bcopy(rule->cmd, ioc_rule->cmd, ioc_rule->cmd_len * 4 /* XXX */);
3762 
3763 	return ((uint8_t *)ioc_rule + IOC_RULESIZE(ioc_rule));
3764 }
3765 
3766 static void
3767 ipfw_copy_state(const ipfw_dyn_rule *dyn_rule,
3768 		struct ipfw_ioc_state *ioc_state)
3769 {
3770 	const struct ipfw_flow_id *id;
3771 	struct ipfw_ioc_flowid *ioc_id;
3772 
3773 	ioc_state->expire = TIME_LEQ(dyn_rule->expire, time_second) ?
3774 			    0 : dyn_rule->expire - time_second;
3775 	ioc_state->pcnt = dyn_rule->pcnt;
3776 	ioc_state->bcnt = dyn_rule->bcnt;
3777 
3778 	ioc_state->dyn_type = dyn_rule->dyn_type;
3779 	ioc_state->count = dyn_rule->count;
3780 
3781 	ioc_state->rulenum = dyn_rule->stub->rule[mycpuid]->rulenum;
3782 
3783 	id = &dyn_rule->id;
3784 	ioc_id = &ioc_state->id;
3785 
3786 	ioc_id->type = ETHERTYPE_IP;
3787 	ioc_id->u.ip.dst_ip = id->dst_ip;
3788 	ioc_id->u.ip.src_ip = id->src_ip;
3789 	ioc_id->u.ip.dst_port = id->dst_port;
3790 	ioc_id->u.ip.src_port = id->src_port;
3791 	ioc_id->u.ip.proto = id->proto;
3792 }
3793 
3794 static int
3795 ipfw_ctl_get_rules(struct sockopt *sopt)
3796 {
3797 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3798 	struct ip_fw *rule;
3799 	void *bp;
3800 	size_t size;
3801 	uint32_t dcount = 0;
3802 
3803 	/*
3804 	 * pass up a copy of the current rules. Static rules
3805 	 * come first (the last of which has number IPFW_DEFAULT_RULE),
3806 	 * followed by a possibly empty list of dynamic rule.
3807 	 */
3808 
3809 	size = static_ioc_len;	/* size of static rules */
3810 	if (ipfw_dyn_v) {	/* add size of dyn.rules */
3811 		dcount = dyn_count;
3812 		size += dcount * sizeof(struct ipfw_ioc_state);
3813 	}
3814 
3815 	if (sopt->sopt_valsize < size) {
3816 		/* short length, no need to return incomplete rules */
3817 		/* XXX: if superuser, no need to zero buffer */
3818 		bzero(sopt->sopt_val, sopt->sopt_valsize);
3819 		return 0;
3820 	}
3821 	bp = sopt->sopt_val;
3822 
3823 	for (rule = ctx->ipfw_layer3_chain; rule; rule = rule->next)
3824 		bp = ipfw_copy_rule(rule, bp);
3825 
3826 	if (ipfw_dyn_v && dcount != 0) {
3827 		struct ipfw_ioc_state *ioc_state = bp;
3828 		uint32_t dcount2 = 0;
3829 #ifdef INVARIANTS
3830 		size_t old_size = size;
3831 #endif
3832 		int i;
3833 
3834 		lockmgr(&dyn_lock, LK_SHARED);
3835 
3836 		/* Check 'ipfw_dyn_v' again with lock held */
3837 		if (ipfw_dyn_v == NULL)
3838 			goto skip;
3839 
3840 		for (i = 0; i < curr_dyn_buckets; i++) {
3841 			ipfw_dyn_rule *p;
3842 
3843 			/*
3844 			 * The # of dynamic rules may have grown after the
3845 			 * snapshot of 'dyn_count' was taken, so we will have
3846 			 * to check 'dcount' (snapshot of dyn_count) here to
3847 			 * make sure that we don't overflow the pre-allocated
3848 			 * buffer.
3849 			 */
3850 			for (p = ipfw_dyn_v[i]; p != NULL && dcount != 0;
3851 			     p = p->next, ioc_state++, dcount--, dcount2++)
3852 				ipfw_copy_state(p, ioc_state);
3853 		}
3854 skip:
3855 		lockmgr(&dyn_lock, LK_RELEASE);
3856 
3857 		/*
3858 		 * The # of dynamic rules may be shrinked after the
3859 		 * snapshot of 'dyn_count' was taken.  To give user a
3860 		 * correct dynamic rule count, we use the 'dcount2'
3861 		 * calculated above (with shared lockmgr lock held).
3862 		 */
3863 		size = static_ioc_len +
3864 		       (dcount2 * sizeof(struct ipfw_ioc_state));
3865 		KKASSERT(size <= old_size);
3866 	}
3867 
3868 	sopt->sopt_valsize = size;
3869 	return 0;
3870 }
3871 
3872 static void
3873 ipfw_set_disable_dispatch(netmsg_t nmsg)
3874 {
3875 	struct lwkt_msg *lmsg = &nmsg->lmsg;
3876 	struct ipfw_context *ctx = ipfw_ctx[mycpuid];
3877 
3878 	ctx->ipfw_gen++;
3879 	ctx->ipfw_set_disable = lmsg->u.ms_result32;
3880 
3881 	ifnet_forwardmsg(lmsg, mycpuid + 1);
3882 }
3883 
3884 static void
3885 ipfw_ctl_set_disable(uint32_t disable, uint32_t enable)
3886 {
3887 	struct netmsg_base nmsg;
3888 	struct lwkt_msg *lmsg;
3889 	uint32_t set_disable;
3890 
3891 	/* IPFW_DEFAULT_SET is always enabled */
3892 	enable |= (1 << IPFW_DEFAULT_SET);
3893 	set_disable = (ipfw_ctx[mycpuid]->ipfw_set_disable | disable) & ~enable;
3894 
3895 	bzero(&nmsg, sizeof(nmsg));
3896 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
3897 		    0, ipfw_set_disable_dispatch);
3898 	lmsg = &nmsg.lmsg;
3899 	lmsg->u.ms_result32 = set_disable;
3900 
3901 	ifnet_domsg(lmsg, 0);
3902 }
3903 
3904 /**
3905  * {set|get}sockopt parser.
3906  */
3907 static int
3908 ipfw_ctl(struct sockopt *sopt)
3909 {
3910 	int error, rulenum;
3911 	uint32_t *masks;
3912 	size_t size;
3913 
3914 	error = 0;
3915 
3916 	switch (sopt->sopt_name) {
3917 	case IP_FW_GET:
3918 		error = ipfw_ctl_get_rules(sopt);
3919 		break;
3920 
3921 	case IP_FW_FLUSH:
3922 		ipfw_flush(0 /* keep default rule */);
3923 		break;
3924 
3925 	case IP_FW_ADD:
3926 		error = ipfw_ctl_add_rule(sopt);
3927 		break;
3928 
3929 	case IP_FW_DEL:
3930 		/*
3931 		 * IP_FW_DEL is used for deleting single rules or sets,
3932 		 * and (ab)used to atomically manipulate sets.
3933 		 * Argument size is used to distinguish between the two:
3934 		 *    sizeof(uint32_t)
3935 		 *	delete single rule or set of rules,
3936 		 *	or reassign rules (or sets) to a different set.
3937 		 *    2 * sizeof(uint32_t)
3938 		 *	atomic disable/enable sets.
3939 		 *	first uint32_t contains sets to be disabled,
3940 		 *	second uint32_t contains sets to be enabled.
3941 		 */
3942 		masks = sopt->sopt_val;
3943 		size = sopt->sopt_valsize;
3944 		if (size == sizeof(*masks)) {
3945 			/*
3946 			 * Delete or reassign static rule
3947 			 */
3948 			error = ipfw_ctl_alter(masks[0]);
3949 		} else if (size == (2 * sizeof(*masks))) {
3950 			/*
3951 			 * Set enable/disable
3952 			 */
3953 			ipfw_ctl_set_disable(masks[0], masks[1]);
3954 		} else {
3955 			error = EINVAL;
3956 		}
3957 		break;
3958 
3959 	case IP_FW_ZERO:
3960 	case IP_FW_RESETLOG: /* argument is an int, the rule number */
3961 		rulenum = 0;
3962 
3963 		if (sopt->sopt_val != 0) {
3964 		    error = soopt_to_kbuf(sopt, &rulenum,
3965 			    sizeof(int), sizeof(int));
3966 		    if (error)
3967 			break;
3968 		}
3969 		error = ipfw_ctl_zero_entry(rulenum,
3970 			sopt->sopt_name == IP_FW_RESETLOG);
3971 		break;
3972 
3973 	default:
3974 		kprintf("ipfw_ctl invalid option %d\n", sopt->sopt_name);
3975 		error = EINVAL;
3976 	}
3977 	return error;
3978 }
3979 
3980 /*
3981  * This procedure is only used to handle keepalives. It is invoked
3982  * every dyn_keepalive_period
3983  */
3984 static void
3985 ipfw_tick_dispatch(netmsg_t nmsg)
3986 {
3987 	time_t keep_alive;
3988 	uint32_t gen;
3989 	int i;
3990 
3991 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
3992 	KKASSERT(IPFW_LOADED);
3993 
3994 	/* Reply ASAP */
3995 	crit_enter();
3996 	lwkt_replymsg(&nmsg->lmsg, 0);
3997 	crit_exit();
3998 
3999 	if (ipfw_dyn_v == NULL || dyn_count == 0)
4000 		goto done;
4001 
4002 	keep_alive = time_second;
4003 
4004 	lockmgr(&dyn_lock, LK_EXCLUSIVE);
4005 again:
4006 	if (ipfw_dyn_v == NULL || dyn_count == 0) {
4007 		lockmgr(&dyn_lock, LK_RELEASE);
4008 		goto done;
4009 	}
4010 	gen = dyn_buckets_gen;
4011 
4012 	for (i = 0; i < curr_dyn_buckets; i++) {
4013 		ipfw_dyn_rule *q, *prev;
4014 
4015 		for (prev = NULL, q = ipfw_dyn_v[i]; q != NULL;) {
4016 			uint32_t ack_rev, ack_fwd;
4017 			struct ipfw_flow_id id;
4018 
4019 			if (q->dyn_type == O_LIMIT_PARENT)
4020 				goto next;
4021 
4022 			if (TIME_LEQ(q->expire, time_second)) {
4023 				/* State expired */
4024 				UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
4025 				continue;
4026 			}
4027 
4028 			/*
4029 			 * Keep alive processing
4030 			 */
4031 
4032 			if (!dyn_keepalive)
4033 				goto next;
4034 			if (q->id.proto != IPPROTO_TCP)
4035 				goto next;
4036 			if ((q->state & BOTH_SYN) != BOTH_SYN)
4037 				goto next;
4038 			if (TIME_LEQ(time_second + dyn_keepalive_interval,
4039 			    q->expire))
4040 				goto next;	/* too early */
4041 			if (q->keep_alive == keep_alive)
4042 				goto next;	/* alreay done */
4043 
4044 			/*
4045 			 * Save necessary information, so that they could
4046 			 * survive after possible blocking in send_pkt()
4047 			 */
4048 			id = q->id;
4049 			ack_rev = q->ack_rev;
4050 			ack_fwd = q->ack_fwd;
4051 
4052 			/* Sending has been started */
4053 			q->keep_alive = keep_alive;
4054 
4055 			/* Release lock to avoid possible dead lock */
4056 			lockmgr(&dyn_lock, LK_RELEASE);
4057 			send_pkt(&id, ack_rev - 1, ack_fwd, TH_SYN);
4058 			send_pkt(&id, ack_fwd - 1, ack_rev, 0);
4059 			lockmgr(&dyn_lock, LK_EXCLUSIVE);
4060 
4061 			if (gen != dyn_buckets_gen) {
4062 				/*
4063 				 * Dyn bucket array has been changed during
4064 				 * the above two sending; reiterate.
4065 				 */
4066 				goto again;
4067 			}
4068 next:
4069 			prev = q;
4070 			q = q->next;
4071 		}
4072 	}
4073 	lockmgr(&dyn_lock, LK_RELEASE);
4074 done:
4075 	callout_reset(&ipfw_timeout_h, dyn_keepalive_period * hz,
4076 		      ipfw_tick, NULL);
4077 }
4078 
4079 /*
4080  * This procedure is only used to handle keepalives. It is invoked
4081  * every dyn_keepalive_period
4082  */
4083 static void
4084 ipfw_tick(void *dummy __unused)
4085 {
4086 	struct lwkt_msg *lmsg = &ipfw_timeout_netmsg.lmsg;
4087 
4088 	KKASSERT(mycpuid == IPFW_CFGCPUID);
4089 
4090 	crit_enter();
4091 
4092 	KKASSERT(lmsg->ms_flags & MSGF_DONE);
4093 	if (IPFW_LOADED) {
4094 		lwkt_sendmsg(IPFW_CFGPORT, lmsg);
4095 		/* ipfw_timeout_netmsg's handler reset this callout */
4096 	}
4097 
4098 	crit_exit();
4099 }
4100 
4101 static int
4102 ipfw_check_in(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4103 {
4104 	struct ip_fw_args args;
4105 	struct mbuf *m = *m0;
4106 	struct m_tag *mtag;
4107 	int tee = 0, error = 0, ret;
4108 
4109 	if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4110 		/* Extract info from dummynet tag */
4111 		mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4112 		KKASSERT(mtag != NULL);
4113 		args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4114 		KKASSERT(args.rule != NULL);
4115 
4116 		m_tag_delete(m, mtag);
4117 		m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4118 	} else {
4119 		args.rule = NULL;
4120 	}
4121 
4122 	args.eh = NULL;
4123 	args.oif = NULL;
4124 	args.m = m;
4125 	ret = ipfw_chk(&args);
4126 	m = args.m;
4127 
4128 	if (m == NULL) {
4129 		error = EACCES;
4130 		goto back;
4131 	}
4132 
4133 	switch (ret) {
4134 	case IP_FW_PASS:
4135 		break;
4136 
4137 	case IP_FW_DENY:
4138 		m_freem(m);
4139 		m = NULL;
4140 		error = EACCES;
4141 		break;
4142 
4143 	case IP_FW_DUMMYNET:
4144 		/* Send packet to the appropriate pipe */
4145 		ipfw_dummynet_io(m, args.cookie, DN_TO_IP_IN, &args);
4146 		break;
4147 
4148 	case IP_FW_TEE:
4149 		tee = 1;
4150 		/* FALL THROUGH */
4151 
4152 	case IP_FW_DIVERT:
4153 		/*
4154 		 * Must clear bridge tag when changing
4155 		 */
4156 		m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4157 		if (ip_divert_p != NULL) {
4158 			m = ip_divert_p(m, tee, 1);
4159 		} else {
4160 			m_freem(m);
4161 			m = NULL;
4162 			/* not sure this is the right error msg */
4163 			error = EACCES;
4164 		}
4165 		break;
4166 
4167 	default:
4168 		panic("unknown ipfw return value: %d", ret);
4169 	}
4170 back:
4171 	*m0 = m;
4172 	return error;
4173 }
4174 
4175 static int
4176 ipfw_check_out(void *arg, struct mbuf **m0, struct ifnet *ifp, int dir)
4177 {
4178 	struct ip_fw_args args;
4179 	struct mbuf *m = *m0;
4180 	struct m_tag *mtag;
4181 	int tee = 0, error = 0, ret;
4182 
4183 	if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
4184 		/* Extract info from dummynet tag */
4185 		mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
4186 		KKASSERT(mtag != NULL);
4187 		args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
4188 		KKASSERT(args.rule != NULL);
4189 
4190 		m_tag_delete(m, mtag);
4191 		m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
4192 	} else {
4193 		args.rule = NULL;
4194 	}
4195 
4196 	args.eh = NULL;
4197 	args.m = m;
4198 	args.oif = ifp;
4199 	ret = ipfw_chk(&args);
4200 	m = args.m;
4201 
4202 	if (m == NULL) {
4203 		error = EACCES;
4204 		goto back;
4205 	}
4206 
4207 	switch (ret) {
4208 	case IP_FW_PASS:
4209 		break;
4210 
4211 	case IP_FW_DENY:
4212 		m_freem(m);
4213 		m = NULL;
4214 		error = EACCES;
4215 		break;
4216 
4217 	case IP_FW_DUMMYNET:
4218 		ipfw_dummynet_io(m, args.cookie, DN_TO_IP_OUT, &args);
4219 		break;
4220 
4221 	case IP_FW_TEE:
4222 		tee = 1;
4223 		/* FALL THROUGH */
4224 
4225 	case IP_FW_DIVERT:
4226 		if (ip_divert_p != NULL) {
4227 			m = ip_divert_p(m, tee, 0);
4228 		} else {
4229 			m_freem(m);
4230 			m = NULL;
4231 			/* not sure this is the right error msg */
4232 			error = EACCES;
4233 		}
4234 		break;
4235 
4236 	default:
4237 		panic("unknown ipfw return value: %d", ret);
4238 	}
4239 back:
4240 	*m0 = m;
4241 	return error;
4242 }
4243 
4244 static void
4245 ipfw_hook(void)
4246 {
4247 	struct pfil_head *pfh;
4248 
4249 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4250 
4251 	pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4252 	if (pfh == NULL)
4253 		return;
4254 
4255 	pfil_add_hook(ipfw_check_in, NULL, PFIL_IN | PFIL_MPSAFE, pfh);
4256 	pfil_add_hook(ipfw_check_out, NULL, PFIL_OUT | PFIL_MPSAFE, pfh);
4257 }
4258 
4259 static void
4260 ipfw_dehook(void)
4261 {
4262 	struct pfil_head *pfh;
4263 
4264 	IPFW_ASSERT_CFGPORT(&curthread->td_msgport);
4265 
4266 	pfh = pfil_head_get(PFIL_TYPE_AF, AF_INET);
4267 	if (pfh == NULL)
4268 		return;
4269 
4270 	pfil_remove_hook(ipfw_check_in, NULL, PFIL_IN, pfh);
4271 	pfil_remove_hook(ipfw_check_out, NULL, PFIL_OUT, pfh);
4272 }
4273 
4274 static void
4275 ipfw_sysctl_enable_dispatch(netmsg_t nmsg)
4276 {
4277 	struct lwkt_msg *lmsg = &nmsg->lmsg;
4278 	int enable = lmsg->u.ms_result;
4279 
4280 	if (fw_enable == enable)
4281 		goto reply;
4282 
4283 	fw_enable = enable;
4284 	if (fw_enable)
4285 		ipfw_hook();
4286 	else
4287 		ipfw_dehook();
4288 reply:
4289 	lwkt_replymsg(lmsg, 0);
4290 }
4291 
4292 static int
4293 ipfw_sysctl_enable(SYSCTL_HANDLER_ARGS)
4294 {
4295 	struct netmsg_base nmsg;
4296 	struct lwkt_msg *lmsg;
4297 	int enable, error;
4298 
4299 	enable = fw_enable;
4300 	error = sysctl_handle_int(oidp, &enable, 0, req);
4301 	if (error || req->newptr == NULL)
4302 		return error;
4303 
4304 	netmsg_init(&nmsg, NULL, &curthread->td_msgport,
4305 		    0, ipfw_sysctl_enable_dispatch);
4306 	lmsg = &nmsg.lmsg;
4307 	lmsg->u.ms_result = enable;
4308 
4309 	return lwkt_domsg(IPFW_CFGPORT, lmsg, 0);
4310 }
4311 
4312 static int
4313 ipfw_sysctl_autoinc_step(SYSCTL_HANDLER_ARGS)
4314 {
4315 	return sysctl_int_range(oidp, arg1, arg2, req,
4316 	       IPFW_AUTOINC_STEP_MIN, IPFW_AUTOINC_STEP_MAX);
4317 }
4318 
4319 static int
4320 ipfw_sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
4321 {
4322 	int error, value;
4323 
4324 	lockmgr(&dyn_lock, LK_EXCLUSIVE);
4325 
4326 	value = dyn_buckets;
4327 	error = sysctl_handle_int(oidp, &value, 0, req);
4328 	if (error || !req->newptr)
4329 		goto back;
4330 
4331 	/*
4332 	 * Make sure we have a power of 2 and
4333 	 * do not allow more than 64k entries.
4334 	 */
4335 	error = EINVAL;
4336 	if (value <= 1 || value > 65536)
4337 		goto back;
4338 	if ((value & (value - 1)) != 0)
4339 		goto back;
4340 
4341 	error = 0;
4342 	dyn_buckets = value;
4343 back:
4344 	lockmgr(&dyn_lock, LK_RELEASE);
4345 	return error;
4346 }
4347 
4348 static int
4349 ipfw_sysctl_dyn_fin(SYSCTL_HANDLER_ARGS)
4350 {
4351 	return sysctl_int_range(oidp, arg1, arg2, req,
4352 				1, dyn_keepalive_period - 1);
4353 }
4354 
4355 static int
4356 ipfw_sysctl_dyn_rst(SYSCTL_HANDLER_ARGS)
4357 {
4358 	return sysctl_int_range(oidp, arg1, arg2, req,
4359 				1, dyn_keepalive_period - 1);
4360 }
4361 
4362 static void
4363 ipfw_ctx_init_dispatch(netmsg_t nmsg)
4364 {
4365 	struct netmsg_ipfw *fwmsg = (struct netmsg_ipfw *)nmsg;
4366 	struct ipfw_context *ctx;
4367 	struct ip_fw *def_rule;
4368 
4369 	ctx = kmalloc(sizeof(*ctx), M_IPFW, M_WAITOK | M_ZERO);
4370 	ipfw_ctx[mycpuid] = ctx;
4371 
4372 	def_rule = kmalloc(sizeof(*def_rule), M_IPFW, M_WAITOK | M_ZERO);
4373 
4374 	def_rule->act_ofs = 0;
4375 	def_rule->rulenum = IPFW_DEFAULT_RULE;
4376 	def_rule->cmd_len = 1;
4377 	def_rule->set = IPFW_DEFAULT_SET;
4378 
4379 	def_rule->cmd[0].len = 1;
4380 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4381 	def_rule->cmd[0].opcode = O_ACCEPT;
4382 #else
4383 	def_rule->cmd[0].opcode = O_DENY;
4384 #endif
4385 
4386 	def_rule->refcnt = 1;
4387 	def_rule->cpuid = mycpuid;
4388 
4389 	/* Install the default rule */
4390 	ctx->ipfw_default_rule = def_rule;
4391 	ctx->ipfw_layer3_chain = def_rule;
4392 
4393 	/* Link rule CPU sibling */
4394 	ipfw_link_sibling(fwmsg, def_rule);
4395 
4396 	/* Statistics only need to be updated once */
4397 	if (mycpuid == 0)
4398 		ipfw_inc_static_count(def_rule);
4399 
4400 	ifnet_forwardmsg(&nmsg->lmsg, mycpuid + 1);
4401 }
4402 
4403 static void
4404 ipfw_init_dispatch(netmsg_t nmsg)
4405 {
4406 	struct netmsg_ipfw fwmsg;
4407 	int error = 0;
4408 
4409 	if (IPFW_LOADED) {
4410 		kprintf("IP firewall already loaded\n");
4411 		error = EEXIST;
4412 		goto reply;
4413 	}
4414 
4415 	bzero(&fwmsg, sizeof(fwmsg));
4416 	netmsg_init(&fwmsg.base, NULL, &curthread->td_msgport,
4417 		    0, ipfw_ctx_init_dispatch);
4418 	ifnet_domsg(&fwmsg.base.lmsg, 0);
4419 
4420 	ip_fw_chk_ptr = ipfw_chk;
4421 	ip_fw_ctl_ptr = ipfw_ctl;
4422 	ip_fw_dn_io_ptr = ipfw_dummynet_io;
4423 
4424 	kprintf("ipfw2 initialized, default to %s, logging ",
4425 		ipfw_ctx[mycpuid]->ipfw_default_rule->cmd[0].opcode ==
4426 		O_ACCEPT ? "accept" : "deny");
4427 
4428 #ifdef IPFIREWALL_VERBOSE
4429 	fw_verbose = 1;
4430 #endif
4431 #ifdef IPFIREWALL_VERBOSE_LIMIT
4432 	verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4433 #endif
4434 	if (fw_verbose == 0) {
4435 		kprintf("disabled\n");
4436 	} else if (verbose_limit == 0) {
4437 		kprintf("unlimited\n");
4438 	} else {
4439 		kprintf("limited to %d packets/entry by default\n",
4440 			verbose_limit);
4441 	}
4442 
4443 	callout_init_mp(&ipfw_timeout_h);
4444 	netmsg_init(&ipfw_timeout_netmsg, NULL, &netisr_adone_rport,
4445 		    MSGF_DROPABLE | MSGF_PRIORITY,
4446 		    ipfw_tick_dispatch);
4447 	lockinit(&dyn_lock, "ipfw_dyn", 0, 0);
4448 
4449 	ip_fw_loaded = 1;
4450 	callout_reset(&ipfw_timeout_h, hz, ipfw_tick, NULL);
4451 
4452 	if (fw_enable)
4453 		ipfw_hook();
4454 reply:
4455 	lwkt_replymsg(&nmsg->lmsg, error);
4456 }
4457 
4458 static int
4459 ipfw_init(void)
4460 {
4461 	struct netmsg_base smsg;
4462 
4463 	netmsg_init(&smsg, NULL, &curthread->td_msgport,
4464 		    0, ipfw_init_dispatch);
4465 	return lwkt_domsg(IPFW_CFGPORT, &smsg.lmsg, 0);
4466 }
4467 
4468 #ifdef KLD_MODULE
4469 
4470 static void
4471 ipfw_fini_dispatch(netmsg_t nmsg)
4472 {
4473 	int error = 0, cpu;
4474 
4475 	if (ipfw_refcnt != 0) {
4476 		error = EBUSY;
4477 		goto reply;
4478 	}
4479 
4480 	ip_fw_loaded = 0;
4481 
4482 	ipfw_dehook();
4483 	callout_stop(&ipfw_timeout_h);
4484 
4485 	netmsg_service_sync();
4486 
4487 	crit_enter();
4488 	if ((ipfw_timeout_netmsg.lmsg.ms_flags & MSGF_DONE) == 0) {
4489 		/*
4490 		 * Callout message is pending; drop it
4491 		 */
4492 		lwkt_dropmsg(&ipfw_timeout_netmsg.lmsg);
4493 	}
4494 	crit_exit();
4495 
4496 	ip_fw_chk_ptr = NULL;
4497 	ip_fw_ctl_ptr = NULL;
4498 	ip_fw_dn_io_ptr = NULL;
4499 	ipfw_flush(1 /* kill default rule */);
4500 
4501 	/* Free pre-cpu context */
4502 	for (cpu = 0; cpu < ncpus; ++cpu)
4503 		kfree(ipfw_ctx[cpu], M_IPFW);
4504 
4505 	kprintf("IP firewall unloaded\n");
4506 reply:
4507 	lwkt_replymsg(&nmsg->lmsg, error);
4508 }
4509 
4510 static int
4511 ipfw_fini(void)
4512 {
4513 	struct netmsg_base smsg;
4514 
4515 	netmsg_init(&smsg, NULL, &curthread->td_msgport,
4516 		    0, ipfw_fini_dispatch);
4517 	return lwkt_domsg(IPFW_CFGPORT, &smsg.lmsg, 0);
4518 }
4519 
4520 #endif	/* KLD_MODULE */
4521 
4522 static int
4523 ipfw_modevent(module_t mod, int type, void *unused)
4524 {
4525 	int err = 0;
4526 
4527 	switch (type) {
4528 	case MOD_LOAD:
4529 		err = ipfw_init();
4530 		break;
4531 
4532 	case MOD_UNLOAD:
4533 #ifndef KLD_MODULE
4534 		kprintf("ipfw statically compiled, cannot unload\n");
4535 		err = EBUSY;
4536 #else
4537 		err = ipfw_fini();
4538 #endif
4539 		break;
4540 	default:
4541 		break;
4542 	}
4543 	return err;
4544 }
4545 
4546 static moduledata_t ipfwmod = {
4547 	"ipfw",
4548 	ipfw_modevent,
4549 	0
4550 };
4551 DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PROTO_END, SI_ORDER_ANY);
4552 MODULE_VERSION(ipfw, 1);
4553