2 * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3 * Copyright (c) 2014 Yandex LLC
4 * Copyright (c) 2014 Alexander V. Chernikov
6 * Supported by: Valeria Paoli
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
34 * Control socket and rule management routines for ipfw.
35 * Control is currently implemented via IP_FW3 setsockopt() code.
41 #error IPFIREWALL requires INET.
43 #include "opt_inet6.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h> /* struct m_tag used by nested headers */
49 #include <sys/kernel.h>
53 #include <sys/rwlock.h>
54 #include <sys/rmlock.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/syslog.h>
59 #include <sys/fnv_hash.h>
61 #include <net/route.h>
64 #include <vm/vm_extern.h>
66 #include <netinet/in.h>
67 #include <netinet/ip_var.h> /* hooks */
68 #include <netinet/ip_fw.h>
70 #include <netpfil/ipfw/ip_fw_private.h>
71 #include <netpfil/ipfw/ip_fw_table.h>
74 #include <security/mac/mac_framework.h>
77 static int ipfw_ctl(struct sockopt *sopt);
78 static int check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len,
79 struct rule_check_info *ci);
80 static int check_ipfw_rule1(struct ip_fw_rule *rule, int size,
81 struct rule_check_info *ci);
82 static int check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
83 struct rule_check_info *ci);
85 #define NAMEDOBJ_HASH_SIZE 32
87 struct namedobj_instance {
88 struct namedobjects_head *names;
89 struct namedobjects_head *values;
90 uint32_t nn_size; /* names hash size */
91 uint32_t nv_size; /* number hash size */
92 u_long *idx_mask; /* used items bitmask */
93 uint32_t max_blocks; /* number of "long" blocks in bitmask */
94 uint32_t count; /* number of items */
95 uint16_t free_off[IPFW_MAX_SETS]; /* first possible free offset */
96 objhash_hash_f *hash_f;
99 #define BLOCK_ITEMS (8 * sizeof(u_long)) /* Number of items for ffsl() */
101 static uint32_t objhash_hash_name(struct namedobj_instance *ni, void *key,
103 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
104 static int objhash_cmp_name(struct named_object *no, void *name, uint32_t set);
106 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
108 static int dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
109 struct sockopt_data *sd);
110 static int add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
111 struct sockopt_data *sd);
112 static int del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
113 struct sockopt_data *sd);
114 static int clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
115 struct sockopt_data *sd);
116 static int move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
117 struct sockopt_data *sd);
118 static int manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
119 struct sockopt_data *sd);
120 static int dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
121 struct sockopt_data *sd);
123 /* ctl3 handler data */
124 struct mtx ctl3_lock;
125 #define CTL3_LOCK_INIT() mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
126 #define CTL3_LOCK_DESTROY() mtx_destroy(&ctl3_lock)
127 #define CTL3_LOCK() mtx_lock(&ctl3_lock)
128 #define CTL3_UNLOCK() mtx_unlock(&ctl3_lock)
130 static struct ipfw_sopt_handler *ctl3_handlers;
131 static size_t ctl3_hsize;
132 static uint64_t ctl3_refct, ctl3_gencnt;
133 #define CTL3_SMALLBUF 4096 /* small page-size write buffer */
134 #define CTL3_LARGEBUF 16 * 1024 * 1024 /* handle large rulesets */
136 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
138 static struct ipfw_sopt_handler scodes[] = {
139 { IP_FW_XGET, 0, HDIR_GET, dump_config },
140 { IP_FW_XADD, 0, HDIR_BOTH, add_rules },
141 { IP_FW_XDEL, 0, HDIR_BOTH, del_rules },
142 { IP_FW_XZERO, 0, HDIR_SET, clear_rules },
143 { IP_FW_XRESETLOG, 0, HDIR_SET, clear_rules },
144 { IP_FW_XMOVE, 0, HDIR_SET, move_rules },
145 { IP_FW_SET_SWAP, 0, HDIR_SET, manage_sets },
146 { IP_FW_SET_MOVE, 0, HDIR_SET, manage_sets },
147 { IP_FW_SET_ENABLE, 0, HDIR_SET, manage_sets },
148 { IP_FW_DUMP_SOPTCODES, 0, HDIR_GET, dump_soptcodes },
152 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule);
153 struct opcode_obj_rewrite *ipfw_find_op_rw(uint16_t opcode);
154 static int mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
156 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
157 static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
158 struct sockopt_data *sd);
161 * Opcode object rewriter variables
163 struct opcode_obj_rewrite *ctl3_rewriters;
164 static size_t ctl3_rsize;
167 * static variables followed by global ones
170 static VNET_DEFINE(uma_zone_t, ipfw_cntr_zone);
171 #define V_ipfw_cntr_zone VNET(ipfw_cntr_zone)
177 V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
178 IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
179 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
183 ipfw_destroy_counters()
186 uma_zdestroy(V_ipfw_cntr_zone);
190 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
194 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
195 rule->cntr = uma_zalloc(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
201 free_rule(struct ip_fw *rule)
204 uma_zfree(V_ipfw_cntr_zone, rule->cntr);
210 * Find the smallest rule >= key, id.
211 * We could use bsearch but it is so simple that we code it directly
214 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
219 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
222 if (r->rulenum < key)
223 lo = i + 1; /* continue from the next one */
224 else if (r->rulenum > key)
225 hi = i; /* this might be good */
227 lo = i + 1; /* continue from the next one */
228 else /* r->id >= id */
229 hi = i; /* this might be good */
235 * Builds skipto cache on rule set @map.
238 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
243 IPFW_UH_WLOCK_ASSERT(chain);
246 rulenum = map[mi]->rulenum;
247 smap = chain->idxmap_back;
252 for (i = 0; i < 65536; i++) {
254 /* Use the same rule index until i < rulenum */
255 if (i != rulenum || i == 65535)
257 /* Find next rule with num > i */
258 rulenum = map[++mi]->rulenum;
260 rulenum = map[++mi]->rulenum;
265 * Swaps prepared (backup) index with current one.
268 swap_skipto_cache(struct ip_fw_chain *chain)
272 IPFW_UH_WLOCK_ASSERT(chain);
273 IPFW_WLOCK_ASSERT(chain);
276 chain->idxmap = chain->idxmap_back;
277 chain->idxmap_back = map;
281 * Allocate and initialize skipto cache.
284 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
286 int *idxmap, *idxmap_back;
288 idxmap = malloc(65536 * sizeof(uint32_t *), M_IPFW,
290 idxmap_back = malloc(65536 * sizeof(uint32_t *), M_IPFW,
294 * Note we may be called at any time after initialization,
295 * for example, on first skipto rule, so we need to
296 * provide valid chain->idxmap on return
299 IPFW_UH_WLOCK(chain);
300 if (chain->idxmap != NULL) {
301 IPFW_UH_WUNLOCK(chain);
302 free(idxmap, M_IPFW);
303 free(idxmap_back, M_IPFW);
307 /* Set backup pointer first to permit building cache */
308 chain->idxmap_back = idxmap_back;
309 update_skipto_cache(chain, chain->map);
311 /* It is now safe to set chain->idxmap ptr */
312 chain->idxmap = idxmap;
313 swap_skipto_cache(chain);
315 IPFW_UH_WUNLOCK(chain);
319 * Destroys skipto cache.
322 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
325 if (chain->idxmap != NULL)
326 free(chain->idxmap, M_IPFW);
327 if (chain->idxmap != NULL)
328 free(chain->idxmap_back, M_IPFW);
333 * allocate a new map, returns the chain locked. extra is the number
334 * of entries to add or delete.
336 static struct ip_fw **
337 get_map(struct ip_fw_chain *chain, int extra, int locked)
344 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
346 i = chain->n_rules + extra;
347 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
349 printf("%s: cannot allocate map\n", __FUNCTION__);
353 IPFW_UH_WLOCK(chain);
354 if (i >= chain->n_rules + extra) /* good */
356 /* otherwise we lost the race, free and retry */
358 IPFW_UH_WUNLOCK(chain);
364 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
366 static struct ip_fw **
367 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
369 struct ip_fw **old_map;
373 chain->n_rules = new_len;
374 old_map = chain->map;
375 chain->map = new_map;
376 swap_skipto_cache(chain);
383 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
386 cntr->size = sizeof(*cntr);
388 if (krule->cntr != NULL) {
389 cntr->pcnt = counter_u64_fetch(krule->cntr);
390 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
391 cntr->timestamp = krule->timestamp;
393 if (cntr->timestamp > 0)
394 cntr->timestamp += boottime.tv_sec;
398 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
401 if (krule->cntr != NULL) {
402 cntr->pcnt = counter_u64_fetch(krule->cntr);
403 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
404 cntr->timestamp = krule->timestamp;
406 if (cntr->timestamp > 0)
407 cntr->timestamp += boottime.tv_sec;
411 * Copies rule @urule from v1 userland format (current).
413 * Assume @krule is zeroed.
416 import_rule1(struct rule_check_info *ci)
418 struct ip_fw_rule *urule;
421 urule = (struct ip_fw_rule *)ci->urule;
422 krule = (struct ip_fw *)ci->krule;
425 krule->act_ofs = urule->act_ofs;
426 krule->cmd_len = urule->cmd_len;
427 krule->rulenum = urule->rulenum;
428 krule->set = urule->set;
429 krule->flags = urule->flags;
431 /* Save rulenum offset */
432 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
435 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
439 * Export rule into v1 format (Current).
441 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
443 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
445 * Assume @data is zeroed.
448 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
450 struct ip_fw_bcounter *cntr;
451 struct ip_fw_rule *urule;
454 /* Fill in TLV header */
455 tlv = (ipfw_obj_tlv *)data;
456 tlv->type = IPFW_TLV_RULE_ENT;
461 cntr = (struct ip_fw_bcounter *)(tlv + 1);
462 urule = (struct ip_fw_rule *)(cntr + 1);
463 export_cntr1_base(krule, cntr);
465 urule = (struct ip_fw_rule *)(tlv + 1);
468 urule->act_ofs = krule->act_ofs;
469 urule->cmd_len = krule->cmd_len;
470 urule->rulenum = krule->rulenum;
471 urule->set = krule->set;
472 urule->flags = krule->flags;
473 urule->id = krule->id;
476 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
481 * Copies rule @urule from FreeBSD8 userland format (v0)
483 * Assume @krule is zeroed.
486 import_rule0(struct rule_check_info *ci)
488 struct ip_fw_rule0 *urule;
492 ipfw_insn_limit *lcmd;
495 urule = (struct ip_fw_rule0 *)ci->urule;
496 krule = (struct ip_fw *)ci->krule;
499 krule->act_ofs = urule->act_ofs;
500 krule->cmd_len = urule->cmd_len;
501 krule->rulenum = urule->rulenum;
502 krule->set = urule->set;
503 if ((urule->_pad & 1) != 0)
504 krule->flags |= IPFW_RULE_NOOPT;
506 /* Save rulenum offset */
507 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
510 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
514 * 1) convert tablearg value from 65335 to 0
515 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room for targ).
516 * 3) convert table number in iface opcodes to u16
522 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
525 switch (cmd->opcode) {
526 /* Opcodes supporting tablearg */
538 if (cmd->arg1 == 65535)
539 cmd->arg1 = IP_FW_TARG;
543 if (cmd->arg1 == 65535)
544 cmd->arg1 = IP_FW_TARG;
549 lcmd = (ipfw_insn_limit *)cmd;
550 if (lcmd->conn_limit == 65535)
551 lcmd->conn_limit = IP_FW_TARG;
553 /* Interface tables */
557 /* Interface table, possibly */
558 cmdif = (ipfw_insn_if *)cmd;
559 if (cmdif->name[0] != '\1')
562 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
569 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
572 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
576 ipfw_insn_limit *lcmd;
580 memset(urule, 0, len);
581 urule->act_ofs = krule->act_ofs;
582 urule->cmd_len = krule->cmd_len;
583 urule->rulenum = krule->rulenum;
584 urule->set = krule->set;
585 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
589 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
591 /* Export counters */
592 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
596 * 1) convert tablearg value from 0 to 65335
597 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
598 * 3) convert table number in iface opcodes to int
604 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
607 switch (cmd->opcode) {
608 /* Opcodes supporting tablearg */
620 if (cmd->arg1 == IP_FW_TARG)
625 if (cmd->arg1 == IP_FW_TARG)
628 cmd->arg1 &= ~0x8000;
631 lcmd = (ipfw_insn_limit *)cmd;
632 if (lcmd->conn_limit == IP_FW_TARG)
633 lcmd->conn_limit = 65535;
635 /* Interface tables */
639 /* Interface table, possibly */
640 cmdif = (ipfw_insn_if *)cmd;
641 if (cmdif->name[0] != '\1')
644 cmdif->p.glob = cmdif->p.kidx;
651 * Add new rule(s) to the list possibly creating rule number for each.
652 * Update the rule_number in the input struct so the caller knows it as well.
653 * Must be called without IPFW_UH held
656 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
658 int error, i, insert_before, tcount;
659 uint16_t rulenum, *pnum;
660 struct rule_check_info *ci;
662 struct ip_fw **map; /* the new array of pointers */
664 /* Check if we need to do table/obj index remap */
666 for (ci = rci, i = 0; i < count; ci++, i++) {
667 if (ci->object_opcodes == 0)
671 * Rule has some object opcodes.
672 * We need to find (and create non-existing)
673 * kernel objects, and reference existing ones.
675 error = ipfw_rewrite_rule_uidx(chain, ci);
679 * rewrite failed, state for current rule
680 * has been reverted. Check if we need to
686 * We have some more table rules
687 * we need to rollback.
690 IPFW_UH_WLOCK(chain);
693 if (ci->object_opcodes == 0)
695 unref_rule_objects(chain,ci->krule);
698 IPFW_UH_WUNLOCK(chain);
708 /* get_map returns with IPFW_UH_WLOCK if successful */
709 map = get_map(chain, count, 0 /* not locked */);
713 IPFW_UH_WLOCK(chain);
714 for (ci = rci, i = 0; i < count; ci++, i++) {
715 if (ci->object_opcodes == 0)
718 unref_rule_objects(chain, ci->krule);
720 IPFW_UH_WUNLOCK(chain);
726 if (V_autoinc_step < 1)
728 else if (V_autoinc_step > 1000)
729 V_autoinc_step = 1000;
731 /* FIXME: Handle count > 1 */
734 rulenum = krule->rulenum;
736 /* find the insertion point, we will insert before */
737 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
738 i = ipfw_find_rule(chain, insert_before, 0);
739 /* duplicate first part */
741 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
743 /* duplicate remaining part, we always have the default rule */
744 bcopy(chain->map + i, map + i + 1,
745 sizeof(struct ip_fw *) *(chain->n_rules - i));
747 /* Compute rule number and write it back */
748 rulenum = i > 0 ? map[i-1]->rulenum : 0;
749 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
750 rulenum += V_autoinc_step;
751 krule->rulenum = rulenum;
752 /* Save number to userland rule */
753 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
757 krule->id = chain->id + 1;
758 update_skipto_cache(chain, map);
759 map = swap_map(chain, map, chain->n_rules + 1);
760 chain->static_len += RULEUSIZE0(krule);
761 IPFW_UH_WUNLOCK(chain);
768 * Adds @rule to the list of rules to reap
771 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
775 IPFW_UH_WLOCK_ASSERT(chain);
777 /* Unlink rule from everywhere */
778 unref_rule_objects(chain, rule);
780 *((struct ip_fw **)rule) = *head;
785 * Reclaim storage associated with a list of rules. This is
786 * typically the list created using remove_rule.
787 * A NULL pointer on input is handled correctly.
790 ipfw_reap_rules(struct ip_fw *head)
794 while ((rule = head) != NULL) {
795 head = *((struct ip_fw **)head);
802 * (default || reserved || !match_set || !match_number)
804 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
805 * // the default rule is always protected
807 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
808 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
810 * match_set ::= (cmd == 0 || rule->set == set)
811 * // set number is ignored for cmd == 0
813 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
814 * // number is ignored for cmd == 1 or n == 0
818 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
821 /* Don't match default rule for modification queries */
822 if (rule->rulenum == IPFW_DEFAULT_RULE &&
823 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
826 /* Don't match rules in reserved set for flush requests */
827 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
830 /* If we're filtering by set, don't match other sets */
831 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
834 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
835 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
842 * Delete rules matching range @rt.
843 * Saves number of deleted rules in @ndel.
845 * Returns 0 on success.
848 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
850 struct ip_fw *reap, *rule, **map;
855 IPFW_UH_WLOCK(chain); /* arbitrate writers */
858 * Stage 1: Determine range to inspect.
859 * Range is half-inclusive, e.g [start, end).
862 end = chain->n_rules - 1;
864 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
865 start = ipfw_find_rule(chain, rt->start_rule, 0);
867 end = ipfw_find_rule(chain, rt->end_rule, 0);
868 if (rt->end_rule != IPFW_DEFAULT_RULE)
869 while (chain->map[end]->rulenum == rt->end_rule)
873 /* Allocate new map of the same size */
874 map = get_map(chain, 0, 1 /* locked */);
876 IPFW_UH_WUNLOCK(chain);
883 /* 1. bcopy the initial part of the map */
885 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
886 /* 2. copy active rules between start and end */
887 for (i = start; i < end; i++) {
888 rule = chain->map[i];
889 if (ipfw_match_range(rule, rt) == 0) {
895 if (ipfw_is_dyn_rule(rule) != 0)
898 /* 3. copy the final part of the map */
899 bcopy(chain->map + end, map + ofs,
900 (chain->n_rules - end) * sizeof(struct ip_fw *));
901 /* 4. recalculate skipto cache */
902 update_skipto_cache(chain, map);
903 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
904 map = swap_map(chain, map, chain->n_rules - n);
905 /* 6. Remove all dynamic states originated by deleted rules */
907 ipfw_expire_dyn_rules(chain, rt);
908 /* 7. now remove the rules deleted from the old map */
909 for (i = start; i < end; i++) {
911 if (ipfw_match_range(rule, rt) == 0)
913 chain->static_len -= RULEUSIZE0(rule);
914 ipfw_reap_add(chain, &reap, rule);
916 IPFW_UH_WUNLOCK(chain);
918 ipfw_reap_rules(reap);
926 * Changes set of given rule rannge @rt
929 * Returns 0 on success.
932 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
937 IPFW_UH_WLOCK(chain);
940 * Move rules with matching paramenerts to a new set.
941 * This one is much more complex. We have to ensure
942 * that all referenced tables (if any) are referenced
943 * by given rule subset only. Otherwise, we can't move
944 * them to new set and have to return error.
946 if (V_fw_tables_sets != 0) {
947 if (ipfw_move_tables_sets(chain, rt, rt->new_set) != 0) {
948 IPFW_UH_WUNLOCK(chain);
953 /* XXX: We have to do swap holding WLOCK */
954 for (i = 0; i < chain->n_rules; i++) {
955 rule = chain->map[i];
956 if (ipfw_match_range(rule, rt) == 0)
958 rule->set = rt->new_set;
961 IPFW_UH_WUNLOCK(chain);
967 * Clear counters for a specific rule.
968 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
969 * so we only care that rules do not disappear.
972 clear_counters(struct ip_fw *rule, int log_only)
974 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
977 IPFW_ZERO_RULE_COUNTER(rule);
978 if (l->o.opcode == O_LOG)
979 l->log_left = l->max_log;
983 * Flushes rules counters and/or log values on matching range.
985 * Returns number of items cleared.
988 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
995 rt->flags |= IPFW_RCFLAG_DEFAULT;
997 IPFW_UH_WLOCK(chain); /* arbitrate writers */
998 for (i = 0; i < chain->n_rules; i++) {
999 rule = chain->map[i];
1000 if (ipfw_match_range(rule, rt) == 0)
1002 clear_counters(rule, log_only);
1005 IPFW_UH_WUNLOCK(chain);
1011 check_range_tlv(ipfw_range_tlv *rt)
1014 if (rt->head.length != sizeof(*rt))
1016 if (rt->start_rule > rt->end_rule)
1018 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1021 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1028 * Delete rules matching specified parameters
1029 * Data layout (v0)(current):
1030 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1031 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1033 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1035 * Returns 0 on success.
1038 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1039 struct sockopt_data *sd)
1041 ipfw_range_header *rh;
1044 if (sd->valsize != sizeof(*rh))
1047 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1049 if (check_range_tlv(&rh->range) != 0)
1053 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1056 /* Save number of rules deleted */
1057 rh->range.new_set = ndel;
1062 * Move rules/sets matching specified parameters
1063 * Data layout (v0)(current):
1064 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1066 * Returns 0 on success.
1069 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1070 struct sockopt_data *sd)
1072 ipfw_range_header *rh;
1074 if (sd->valsize != sizeof(*rh))
1077 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1079 if (check_range_tlv(&rh->range) != 0)
1082 return (move_range(chain, &rh->range));
1086 * Clear rule accounting data matching specified parameters
1087 * Data layout (v0)(current):
1088 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1089 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1091 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1093 * Returns 0 on success.
1096 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1097 struct sockopt_data *sd)
1099 ipfw_range_header *rh;
1103 if (sd->valsize != sizeof(*rh))
1106 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1108 if (check_range_tlv(&rh->range) != 0)
1111 log_only = (op3->opcode == IP_FW_XRESETLOG);
1113 num = clear_range(chain, &rh->range, log_only);
1115 if (rh->range.flags & IPFW_RCFLAG_ALL)
1116 msg = log_only ? "All logging counts reset" :
1117 "Accounting cleared";
1119 msg = log_only ? "logging count reset" : "cleared";
1122 int lev = LOG_SECURITY | LOG_NOTICE;
1123 log(lev, "ipfw: %s.\n", msg);
1126 /* Save number of rules cleared */
1127 rh->range.new_set = num;
1132 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1136 IPFW_UH_WLOCK_ASSERT(chain);
1138 /* Change enabled/disabled sets mask */
1139 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1140 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1142 V_set_disable = v_set;
1143 IPFW_WUNLOCK(chain);
1147 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1152 IPFW_UH_WLOCK_ASSERT(chain);
1154 /* Swap or move two sets */
1155 for (i = 0; i < chain->n_rules - 1; i++) {
1156 rule = chain->map[i];
1157 if (rule->set == rt->set)
1158 rule->set = rt->new_set;
1159 else if (rule->set == rt->new_set && mv == 0)
1160 rule->set = rt->set;
1162 if (V_fw_tables_sets != 0)
1163 ipfw_swap_tables_sets(chain, rt->set, rt->new_set, mv);
1167 * Swaps or moves set
1168 * Data layout (v0)(current):
1169 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1171 * Returns 0 on success.
1174 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1175 struct sockopt_data *sd)
1177 ipfw_range_header *rh;
1179 if (sd->valsize != sizeof(*rh))
1182 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1184 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1187 IPFW_UH_WLOCK(chain);
1188 switch (op3->opcode) {
1189 case IP_FW_SET_SWAP:
1190 case IP_FW_SET_MOVE:
1191 swap_sets(chain, &rh->range, op3->opcode == IP_FW_SET_MOVE);
1193 case IP_FW_SET_ENABLE:
1194 enable_sets(chain, &rh->range);
1197 IPFW_UH_WUNLOCK(chain);
1203 * Remove all rules with given number, or do set manipulation.
1204 * Assumes chain != NULL && *chain != NULL.
1206 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1207 * the next 8 bits are the new set; the top 8 bits indicate the command:
1209 * 0 delete rules numbered "rulenum"
1210 * 1 delete rules in set "rulenum"
1211 * 2 move rules "rulenum" to set "new_set"
1212 * 3 move rules from set "rulenum" to set "new_set"
1213 * 4 swap sets "rulenum" and "new_set"
1214 * 5 delete rules "rulenum" and set "new_set"
1217 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1219 uint32_t num; /* rule number or old_set */
1220 uint8_t cmd, new_set;
1226 cmd = (arg >> 24) & 0xff;
1227 new_set = (arg >> 16) & 0xff;
1229 if (cmd > 5 || new_set > RESVD_SET)
1231 if (cmd == 0 || cmd == 2 || cmd == 5) {
1232 if (num >= IPFW_DEFAULT_RULE)
1235 if (num > RESVD_SET) /* old_set */
1239 /* Convert old requests into new representation */
1240 memset(&rt, 0, sizeof(rt));
1241 rt.start_rule = num;
1244 rt.new_set = new_set;
1248 case 0: /* delete rules numbered "rulenum" */
1250 rt.flags |= IPFW_RCFLAG_ALL;
1252 rt.flags |= IPFW_RCFLAG_RANGE;
1255 case 1: /* delete rules in set "rulenum" */
1256 rt.flags |= IPFW_RCFLAG_SET;
1259 case 5: /* delete rules "rulenum" and set "new_set" */
1260 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1265 case 2: /* move rules "rulenum" to set "new_set" */
1266 rt.flags |= IPFW_RCFLAG_RANGE;
1268 case 3: /* move rules from set "rulenum" to set "new_set" */
1269 IPFW_UH_WLOCK(chain);
1270 swap_sets(chain, &rt, 1);
1271 IPFW_UH_WUNLOCK(chain);
1273 case 4: /* swap sets "rulenum" and "new_set" */
1274 IPFW_UH_WLOCK(chain);
1275 swap_sets(chain, &rt, 0);
1276 IPFW_UH_WUNLOCK(chain);
1283 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1286 if (ndel == 0 && (cmd != 1 && num != 0))
1292 return (move_range(chain, &rt));
1296 * Reset some or all counters on firewall rules.
1297 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1298 * the next 8 bits are the set number, the top 8 bits are the command:
1299 * 0 work with rules from all set's;
1300 * 1 work with rules only from specified set.
1301 * Specified rule number is zero if we want to clear all entries.
1302 * log_only is 1 if we only want to reset logs, zero otherwise.
1305 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1311 uint16_t rulenum = arg & 0xffff;
1312 uint8_t set = (arg >> 16) & 0xff;
1313 uint8_t cmd = (arg >> 24) & 0xff;
1317 if (cmd == 1 && set > RESVD_SET)
1320 IPFW_UH_RLOCK(chain);
1322 V_norule_counter = 0;
1323 for (i = 0; i < chain->n_rules; i++) {
1324 rule = chain->map[i];
1325 /* Skip rules not in our set. */
1326 if (cmd == 1 && rule->set != set)
1328 clear_counters(rule, log_only);
1330 msg = log_only ? "All logging counts reset" :
1331 "Accounting cleared";
1334 for (i = 0; i < chain->n_rules; i++) {
1335 rule = chain->map[i];
1336 if (rule->rulenum == rulenum) {
1337 if (cmd == 0 || rule->set == set)
1338 clear_counters(rule, log_only);
1341 if (rule->rulenum > rulenum)
1344 if (!cleared) { /* we did not find any matching rules */
1345 IPFW_UH_RUNLOCK(chain);
1348 msg = log_only ? "logging count reset" : "cleared";
1350 IPFW_UH_RUNLOCK(chain);
1353 int lev = LOG_SECURITY | LOG_NOTICE;
1356 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1358 log(lev, "ipfw: %s.\n", msg);
1365 * Check rule head in FreeBSD11 format
1369 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1370 struct rule_check_info *ci)
1374 if (size < sizeof(*rule)) {
1375 printf("ipfw: rule too short\n");
1379 /* Check for valid cmd_len */
1380 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1382 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1385 if (rule->act_ofs >= rule->cmd_len) {
1386 printf("ipfw: bogus action offset (%u > %u)\n",
1387 rule->act_ofs, rule->cmd_len - 1);
1391 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1394 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1398 * Check rule head in FreeBSD8 format
1402 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1403 struct rule_check_info *ci)
1407 if (size < sizeof(*rule)) {
1408 printf("ipfw: rule too short\n");
1412 /* Check for valid cmd_len */
1413 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1415 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1418 if (rule->act_ofs >= rule->cmd_len) {
1419 printf("ipfw: bogus action offset (%u > %u)\n",
1420 rule->act_ofs, rule->cmd_len - 1);
1424 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1427 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1431 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1439 * Now go for the individual checks. Very simple ones, basically only
1440 * instruction sizes.
1442 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1443 cmdlen = F_LEN(cmd);
1445 printf("ipfw: opcode %d size truncated\n",
1449 switch (cmd->opcode) {
1461 case O_IPPRECEDENCE:
1479 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1484 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1486 if (cmd->arg1 >= rt_numfibs) {
1487 printf("ipfw: invalid fib number %d\n",
1494 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1496 if ((cmd->arg1 != IP_FW_TARG) &&
1497 ((cmd->arg1 & 0x7FFFF) >= rt_numfibs)) {
1498 printf("ipfw: invalid fib number %d\n",
1499 cmd->arg1 & 0x7FFFF);
1513 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1518 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1523 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1526 ((ipfw_insn_log *)cmd)->log_left =
1527 ((ipfw_insn_log *)cmd)->max_log;
1533 /* only odd command lengths */
1534 if ( !(cmdlen & 1) || cmdlen > 31)
1540 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1541 printf("ipfw: invalid set size %d\n",
1545 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1550 case O_IP_SRC_LOOKUP:
1551 case O_IP_DST_LOOKUP:
1552 if (cmd->arg1 >= V_fw_tables_max) {
1553 printf("ipfw: invalid table number %d\n",
1557 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1558 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1559 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1561 ci->object_opcodes++;
1563 case O_IP_FLOW_LOOKUP:
1564 if (cmd->arg1 >= V_fw_tables_max) {
1565 printf("ipfw: invalid table number %d\n",
1569 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1570 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1572 ci->object_opcodes++;
1575 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1586 if (cmdlen < 1 || cmdlen > 31)
1591 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1597 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1598 if (cmdlen < 2 || cmdlen > 31)
1605 if (((ipfw_insn_if *)cmd)->name[0] == '\1')
1606 ci->object_opcodes++;
1607 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1612 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1618 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1623 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1628 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1635 if (ip_divert_ptr == NULL)
1641 if (ng_ipfw_input_p == NULL)
1646 if (!IPFW_NAT_LOADED)
1648 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1651 case O_FORWARD_MAC: /* XXX not implemented yet */
1665 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1669 printf("ipfw: opcode %d, multiple actions"
1676 printf("ipfw: opcode %d, action must be"
1685 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
1686 F_INSN_SIZE(ipfw_insn))
1691 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1692 ((ipfw_insn_u32 *)cmd)->o.arg1)
1696 case O_IP6_SRC_MASK:
1697 case O_IP6_DST_MASK:
1698 if ( !(cmdlen & 1) || cmdlen > 127)
1702 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
1708 switch (cmd->opcode) {
1718 case O_IP6_SRC_MASK:
1719 case O_IP6_DST_MASK:
1721 printf("ipfw: no IPv6 support in kernel\n");
1722 return (EPROTONOSUPPORT);
1725 printf("ipfw: opcode %d, unknown opcode\n",
1731 if (have_action == 0) {
1732 printf("ipfw: missing action\n");
1738 printf("ipfw: opcode %d size %d wrong\n",
1739 cmd->opcode, cmdlen);
1745 * Translation of requests for compatibility with FreeBSD 7.2/8.
1746 * a static variable tells us if we have an old client from userland,
1747 * and if necessary we translate requests and responses between the
1753 struct ip_fw7 *next; /* linked list of rules */
1754 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
1755 /* 'next_rule' is used to pass up 'set_disable' status */
1757 uint16_t act_ofs; /* offset of action in 32-bit units */
1758 uint16_t cmd_len; /* # of 32-bit words in cmd */
1759 uint16_t rulenum; /* rule number */
1760 uint8_t set; /* rule set (0..31) */
1761 // #define RESVD_SET 31 /* set for default and persistent rules */
1762 uint8_t _pad; /* padding */
1763 // uint32_t id; /* rule id, only in v.8 */
1764 /* These fields are present in all rules. */
1765 uint64_t pcnt; /* Packet counter */
1766 uint64_t bcnt; /* Byte counter */
1767 uint32_t timestamp; /* tv_sec of last match */
1769 ipfw_insn cmd[1]; /* storage for commands */
1772 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
1773 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
1776 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
1777 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
1782 * Copy the static and dynamic rules to the supplied buffer
1783 * and return the amount of space actually used.
1784 * Must be run under IPFW_UH_RLOCK
1787 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
1790 char *ep = bp + space;
1792 struct ip_fw_rule0 *dst;
1793 int error, i, l, warnflag;
1794 time_t boot_seconds;
1798 boot_seconds = boottime.tv_sec;
1799 for (i = 0; i < chain->n_rules; i++) {
1800 rule = chain->map[i];
1803 /* Convert rule to FreeBSd 7.2 format */
1804 l = RULESIZE7(rule);
1805 if (bp + l + sizeof(uint32_t) <= ep) {
1806 bcopy(rule, bp, l + sizeof(uint32_t));
1807 error = set_legacy_obj_kidx(chain,
1808 (struct ip_fw_rule0 *)bp);
1811 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
1813 return 0; /*XXX correct? */
1815 * XXX HACK. Store the disable mask in the "next"
1816 * pointer in a wild attempt to keep the ABI the same.
1817 * Why do we do this on EVERY rule?
1819 bcopy(&V_set_disable,
1820 &(((struct ip_fw7 *)bp)->next_rule),
1821 sizeof(V_set_disable));
1822 if (((struct ip_fw7 *)bp)->timestamp)
1823 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
1826 continue; /* go to next rule */
1829 l = RULEUSIZE0(rule);
1830 if (bp + l > ep) { /* should not happen */
1831 printf("overflow dumping static rules\n");
1834 dst = (struct ip_fw_rule0 *)bp;
1835 export_rule0(rule, dst, l);
1836 error = set_legacy_obj_kidx(chain, dst);
1839 * XXX HACK. Store the disable mask in the "next"
1840 * pointer in a wild attempt to keep the ABI the same.
1841 * Why do we do this on EVERY rule?
1843 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
1844 * so we need to fail _after_ saving at least one mask.
1846 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
1848 dst->timestamp += boot_seconds;
1853 /* Non-fatal table rewrite error. */
1857 printf("Stop on rule %d. Fail to convert table\n",
1863 printf("ipfw: process %s is using legacy interfaces,"
1864 " consider rebuilding\n", "");
1865 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
1866 return (bp - (char *)buf);
1871 uint32_t b; /* start rule */
1872 uint32_t e; /* end rule */
1873 uint32_t rcount; /* number of rules */
1874 uint32_t rsize; /* rules size */
1875 uint32_t tcount; /* number of tables */
1876 int rcounters; /* counters */
1880 * Export named object info in instance @ni, identified by @kidx
1881 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
1883 * Returns 0 on success.
1886 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
1887 struct sockopt_data *sd)
1889 struct named_object *no;
1890 ipfw_obj_ntlv *ntlv;
1892 no = ipfw_objhash_lookup_kidx(ni, kidx);
1893 KASSERT(no != NULL, ("invalid object kernel index passed"));
1895 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
1899 ntlv->head.type = no->etlv;
1900 ntlv->head.length = sizeof(*ntlv);
1901 ntlv->idx = no->kidx;
1902 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
1908 * Dumps static rules with table TLVs in buffer @sd.
1910 * Returns 0 on success.
1913 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
1914 uint32_t *bmask, struct sockopt_data *sd)
1919 ipfw_obj_ctlv *ctlv;
1920 struct ip_fw *krule;
1921 struct namedobj_instance *ni;
1924 /* Dump table names first (if any) */
1925 if (da->tcount > 0) {
1927 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1930 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
1931 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
1933 ctlv->count = da->tcount;
1934 ctlv->objsize = sizeof(ipfw_obj_ntlv);
1938 tcount = da->tcount;
1939 ni = ipfw_get_table_objhash(chain);
1940 while (tcount > 0) {
1941 if ((bmask[i / 32] & (1 << (i % 32))) == 0) {
1946 /* Jump to shared named object bitmask */
1947 if (i >= IPFW_TABLES_MAX) {
1948 ni = CHAIN_TO_SRV(chain);
1949 i -= IPFW_TABLES_MAX;
1950 bmask += IPFW_TABLES_MAX / 32;
1953 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
1961 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1964 ctlv->head.type = IPFW_TLV_RULE_LIST;
1965 ctlv->head.length = da->rsize + sizeof(*ctlv);
1966 ctlv->count = da->rcount;
1968 for (i = da->b; i < da->e; i++) {
1969 krule = chain->map[i];
1971 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
1972 if (da->rcounters != 0)
1973 l += sizeof(struct ip_fw_bcounter);
1974 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
1978 export_rule1(krule, dst, l, da->rcounters);
1985 * Marks every object index used in @rule with bit in @bmask.
1986 * Used to generate bitmask of referenced tables/objects for given ruleset
1989 * Returns number of newly-referenced objects.
1992 mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
1995 int cmdlen, l, count;
1998 struct opcode_obj_rewrite *rw;
2006 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2007 cmdlen = F_LEN(cmd);
2009 rw = ipfw_find_op_rw(cmd->opcode);
2013 if (rw->classifier(cmd, &kidx, &subtype) != 0)
2017 /* Maintain separate bitmasks for table and non-table objects */
2018 if (rw->etlv != IPFW_TLV_TBL_NAME)
2019 bidx += IPFW_TABLES_MAX / 32;
2021 if ((bmask[bidx] & (1 << (kidx % 32))) == 0)
2024 bmask[bidx] |= 1 << (kidx % 32);
2031 * Dumps requested objects data
2032 * Data layout (version 0)(current):
2033 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2034 * size = ipfw_cfg_lheader.size
2035 * Reply: [ ipfw_cfg_lheader
2036 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2037 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2038 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2040 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2042 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2043 * The rest (size, count) are set to zero and needs to be ignored.
2045 * Returns 0 on success.
2048 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2049 struct sockopt_data *sd)
2051 ipfw_cfg_lheader *hdr;
2056 struct dump_args da;
2059 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2065 /* Allocate needed state. Note we allocate 2xspace mask, for table&srv */
2066 if (hdr->flags & IPFW_CFG_GET_STATIC)
2067 bmask = malloc(IPFW_TABLES_MAX / 4, M_TEMP, M_WAITOK | M_ZERO);
2069 IPFW_UH_RLOCK(chain);
2072 * STAGE 1: Determine size/count for objects in range.
2073 * Prepare used tables bitmask.
2075 sz = sizeof(ipfw_cfg_lheader);
2076 memset(&da, 0, sizeof(da));
2079 da.e = chain->n_rules;
2081 if (hdr->end_rule != 0) {
2082 /* Handle custom range */
2083 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2084 rnum = IPFW_DEFAULT_RULE;
2085 da.b = ipfw_find_rule(chain, rnum, 0);
2086 rnum = hdr->end_rule;
2087 rnum = (rnum < IPFW_DEFAULT_RULE) ? rnum+1 : IPFW_DEFAULT_RULE;
2088 da.e = ipfw_find_rule(chain, rnum, 0) + 1;
2091 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2092 for (i = da.b; i < da.e; i++) {
2093 rule = chain->map[i];
2094 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2096 /* Update bitmask of used objects for given range */
2097 da.tcount += mark_object_kidx(chain, rule, bmask);
2099 /* Add counters if requested */
2100 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2101 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2106 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2107 sizeof(ipfw_obj_ctlv);
2108 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2111 if (hdr->flags & IPFW_CFG_GET_STATES)
2112 sz += ipfw_dyn_get_count() * sizeof(ipfw_obj_dyntlv) +
2113 sizeof(ipfw_obj_ctlv);
2117 * Fill header anyway.
2118 * Note we have to save header fields to stable storage
2119 * buffer inside @sd can be flushed after dumping rules
2122 hdr->set_mask = ~V_set_disable;
2123 hdr_flags = hdr->flags;
2126 if (sd->valsize < sz) {
2131 /* STAGE2: Store actual data */
2132 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2133 error = dump_static_rules(chain, &da, bmask, sd);
2138 if (hdr_flags & IPFW_CFG_GET_STATES)
2139 error = ipfw_dump_states(chain, sd);
2142 IPFW_UH_RUNLOCK(chain);
2145 free(bmask, M_TEMP);
2151 check_object_name(ipfw_obj_ntlv *ntlv)
2155 switch (ntlv->head.type) {
2156 case IPFW_TLV_TBL_NAME:
2157 error = ipfw_check_table_name(ntlv->name);
2167 * Creates non-existent objects referenced by rule.
2169 * Return 0 on success.
2172 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2173 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2175 struct opcode_obj_rewrite *rw;
2181 * Compatibility stuff: do actual creation for non-existing,
2182 * but referenced objects.
2184 for (p = oib; p < pidx; p++) {
2192 rw = ipfw_find_op_rw((cmd + p->off)->opcode);
2193 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2194 (cmd + p->off)->opcode));
2196 error = rw->create_object(ch, ti, &kidx);
2203 * Error happened. We have to rollback everything.
2204 * Drop all already acquired references.
2207 unref_oib_objects(ch, cmd, oib, pidx);
2208 IPFW_UH_WUNLOCK(ch);
2217 * Compatibility function for old ipfw(8) binaries.
2218 * Rewrites table/nat kernel indices with userland ones.
2219 * Convert tables matching '/^\d+$/' to their atoi() value.
2220 * Use number 65535 for other tables.
2222 * Returns 0 on success.
2225 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2227 int cmdlen, error, l;
2229 uint16_t kidx, uidx;
2230 struct named_object *no;
2231 struct opcode_obj_rewrite *rw;
2241 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2242 cmdlen = F_LEN(cmd);
2244 rw = ipfw_find_op_rw(cmd->opcode);
2248 /* Check if is index in given opcode */
2249 if (rw->classifier(cmd, &kidx, &subtype) != 0)
2252 /* Try to find referenced kernel object */
2253 no = rw->find_bykidx(ch, kidx);
2257 val = strtol(no->name, &end, 10);
2258 if (*end == '\0' && val < 65535) {
2263 * We are called via legacy opcode.
2264 * Save error and show table as fake number
2265 * not to make ipfw(8) hang.
2271 rw->update(cmd, uidx);
2279 * Unreferences all already-referenced objects in given @cmd rule,
2280 * using information in @oib.
2282 * Used to rollback partially converted rule on error.
2285 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2286 struct obj_idx *end)
2288 struct opcode_obj_rewrite *rw;
2289 struct named_object *no;
2292 IPFW_UH_WLOCK_ASSERT(ch);
2294 for (p = oib; p < end; p++) {
2298 rw = ipfw_find_op_rw((cmd + p->off)->opcode);
2299 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2300 (cmd + p->off)->opcode));
2302 /* Find & unref by existing idx */
2303 no = rw->find_bykidx(ch, p->kidx);
2304 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2310 * Remove references from every object used in @rule.
2311 * Used at rule removal code.
2314 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2318 struct named_object *no;
2320 struct opcode_obj_rewrite *rw;
2323 IPFW_UH_WLOCK_ASSERT(ch);
2328 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2329 cmdlen = F_LEN(cmd);
2331 rw = ipfw_find_op_rw(cmd->opcode);
2334 if (rw->classifier(cmd, &kidx, &subtype) != 0)
2337 no = rw->find_bykidx(ch, kidx);
2339 KASSERT(no != NULL, ("table id %d not found", kidx));
2340 KASSERT(no->subtype == subtype,
2341 ("wrong type %d (%d) for table id %d",
2342 no->subtype, subtype, kidx));
2343 KASSERT(no->refcnt > 0, ("refcount for table %d is %d",
2352 * Find and reference object (if any) stored in instruction @cmd.
2354 * Saves object info in @pidx, sets
2355 * - @found to 1 if object was found and references
2356 * - @unresolved to 1 if object should exists but not found
2358 * Returns non-zero value in case of error.
2361 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2362 struct obj_idx *pidx, int *found, int *unresolved)
2364 struct named_object *no;
2365 struct opcode_obj_rewrite *rw;
2371 /* Check if this opcode is candidate for rewrite */
2372 rw = ipfw_find_op_rw(cmd->opcode);
2376 /* Check if we need to rewrite this opcode */
2377 if (rw->classifier(cmd, &ti->uidx, &ti->type) != 0)
2380 /* Need to rewrite. Save necessary fields */
2381 pidx->uidx = ti->uidx;
2382 pidx->type = ti->type;
2384 /* Try to find referenced kernel object */
2385 error = rw->find_byname(ch, ti, &no);
2393 /* Found. bump refcount */
2396 pidx->kidx = no->kidx;
2402 * Adds one or more rules to ipfw @chain.
2403 * Data layout (version 0)(current):
2407 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2408 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2413 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2414 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2417 * Rules in reply are modified to store their actual ruleset number.
2419 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2420 * accoring to their idx field and there has to be no duplicates.
2421 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2422 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2424 * Returns 0 on success.
2427 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2428 struct sockopt_data *sd)
2430 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2431 ipfw_obj_ntlv *ntlv;
2432 int clen, error, idx;
2433 uint32_t count, read;
2434 struct ip_fw_rule *r;
2435 struct rule_check_info rci, *ci, *cbuf;
2438 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2439 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2441 read = sizeof(ip_fw3_opheader);
2445 memset(&rci, 0, sizeof(struct rule_check_info));
2447 if (read + sizeof(*ctlv) > sd->valsize)
2450 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2451 clen = ctlv->head.length;
2452 /* Check size and alignment */
2453 if (clen > sd->valsize || clen < sizeof(*ctlv))
2455 if ((clen % sizeof(uint64_t)) != 0)
2459 * Some table names or other named objects.
2460 * Check for validness.
2462 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2463 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2468 * Ensure TLVs are sorted ascending and
2469 * there are no duplicates.
2472 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2474 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2477 error = check_object_name(ntlv);
2481 if (ntlv->idx <= idx)
2490 read += ctlv->head.length;
2491 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2494 if (read + sizeof(*ctlv) > sd->valsize)
2497 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2498 clen = ctlv->head.length;
2499 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2501 if ((clen % sizeof(uint64_t)) != 0)
2505 * TODO: Permit adding multiple rules at once
2507 if (ctlv->count != 1)
2510 clen -= sizeof(*ctlv);
2512 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2515 /* Allocate state for each rule or use stack */
2516 if (ctlv->count == 1) {
2517 memset(&rci, 0, sizeof(struct rule_check_info));
2520 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2525 * Check each rule for validness.
2526 * Ensure numbered rules are sorted ascending
2527 * and properly aligned
2530 r = (struct ip_fw_rule *)(ctlv + 1);
2534 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
2535 if (rsize > clen || ctlv->count <= count) {
2541 error = check_ipfw_rule1(r, rsize, ci);
2546 if (r->rulenum != 0 && r->rulenum < idx) {
2547 printf("rulenum %d idx %d\n", r->rulenum, idx);
2553 ci->urule = (caddr_t)r;
2555 rsize = roundup2(rsize, sizeof(uint64_t));
2557 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
2562 if (ctlv->count != count || error != 0) {
2569 read += ctlv->head.length;
2570 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2573 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
2574 if (cbuf != NULL && cbuf != &rci)
2580 * Passed rules seems to be valid.
2581 * Allocate storage and try to add them to chain.
2583 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
2584 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
2585 ci->krule = ipfw_alloc_rule(chain, clen);
2589 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
2590 /* Free allocate krules */
2591 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
2592 free(ci->krule, M_IPFW);
2595 if (cbuf != NULL && cbuf != &rci)
2602 * Lists all sopts currently registered.
2603 * Data layout (v0)(current):
2604 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
2605 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
2607 * Returns 0 on success
2610 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2611 struct sockopt_data *sd)
2613 struct _ipfw_obj_lheader *olh;
2615 struct ipfw_sopt_handler *sh;
2616 uint32_t count, n, size;
2618 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
2621 if (sd->valsize < olh->size)
2626 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
2628 /* Fill in header regadless of buffer size */
2630 olh->objsize = sizeof(ipfw_sopt_info);
2632 if (size > olh->size) {
2639 for (n = 1; n <= count; n++) {
2640 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
2641 KASSERT(i != 0, ("previously checked buffer is not enough"));
2642 sh = &ctl3_handlers[n];
2643 i->opcode = sh->opcode;
2644 i->version = sh->version;
2645 i->refcnt = sh->refcnt;
2653 * Compares two opcodes.
2654 * Used both in qsort() and bsearch().
2656 * Returns 0 if match is found.
2659 compare_opcodes(const void *_a, const void *_b)
2661 const struct opcode_obj_rewrite *a, *b;
2663 a = (const struct opcode_obj_rewrite *)_a;
2664 b = (const struct opcode_obj_rewrite *)_b;
2666 if (a->opcode < b->opcode)
2668 else if (a->opcode > b->opcode)
2675 * Finds opcode object rewriter based on @code.
2677 * Returns pointer to handler or NULL.
2679 struct opcode_obj_rewrite *
2680 ipfw_find_op_rw(uint16_t opcode)
2682 struct opcode_obj_rewrite *rw, h;
2684 memset(&h, 0, sizeof(h));
2687 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
2688 ctl3_rsize, sizeof(h), compare_opcodes);
2694 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
2696 struct opcode_obj_rewrite *rw;
2699 rw = ipfw_find_op_rw(cmd->opcode);
2703 return (rw->classifier(cmd, puidx, &subtype));
2707 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
2709 struct opcode_obj_rewrite *rw;
2711 rw = ipfw_find_op_rw(cmd->opcode);
2712 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
2713 rw->update(cmd, idx);
2717 ipfw_init_obj_rewriter()
2720 ctl3_rewriters = NULL;
2725 ipfw_destroy_obj_rewriter()
2728 if (ctl3_rewriters != NULL)
2729 free(ctl3_rewriters, M_IPFW);
2730 ctl3_rewriters = NULL;
2735 * Adds one or more opcode object rewrite handlers to the global array.
2736 * Function may sleep.
2739 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
2742 struct opcode_obj_rewrite *tmp;
2747 sz = ctl3_rsize + count;
2749 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
2751 if (ctl3_rsize + count <= sz)
2758 /* Merge old & new arrays */
2759 sz = ctl3_rsize + count;
2760 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
2761 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
2762 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
2763 /* Switch new and free old */
2764 if (ctl3_rewriters != NULL)
2765 free(ctl3_rewriters, M_IPFW);
2766 ctl3_rewriters = tmp;
2773 * Removes one or more object rewrite handlers from the global array.
2776 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
2779 struct opcode_obj_rewrite *tmp, *h;
2784 for (i = 0; i < count; i++) {
2786 h = ipfw_find_op_rw(tmp->opcode);
2790 sz = (ctl3_rewriters + ctl3_rsize - (h + 1)) * sizeof(*h);
2791 memmove(h, h + 1, sz);
2795 if (ctl3_rsize == 0) {
2796 if (ctl3_rewriters != NULL)
2797 free(ctl3_rewriters, M_IPFW);
2798 ctl3_rewriters = NULL;
2807 * Compares two sopt handlers (code, version and handler ptr).
2808 * Used both as qsort() and bsearch().
2809 * Does not compare handler for latter case.
2811 * Returns 0 if match is found.
2814 compare_sh(const void *_a, const void *_b)
2816 const struct ipfw_sopt_handler *a, *b;
2818 a = (const struct ipfw_sopt_handler *)_a;
2819 b = (const struct ipfw_sopt_handler *)_b;
2821 if (a->opcode < b->opcode)
2823 else if (a->opcode > b->opcode)
2826 if (a->version < b->version)
2828 else if (a->version > b->version)
2831 /* bsearch helper */
2832 if (a->handler == NULL)
2835 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
2837 else if ((uintptr_t)b->handler > (uintptr_t)b->handler)
2844 * Finds sopt handler based on @code and @version.
2846 * Returns pointer to handler or NULL.
2848 static struct ipfw_sopt_handler *
2849 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
2851 struct ipfw_sopt_handler *sh, h;
2853 memset(&h, 0, sizeof(h));
2855 h.version = version;
2856 h.handler = handler;
2858 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
2859 ctl3_hsize, sizeof(h), compare_sh);
2865 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
2867 struct ipfw_sopt_handler *sh;
2870 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
2872 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
2878 /* Copy handler data to requested buffer */
2886 find_unref_sh(struct ipfw_sopt_handler *psh)
2888 struct ipfw_sopt_handler *sh;
2891 sh = find_sh(psh->opcode, psh->version, NULL);
2892 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
2899 ipfw_init_sopt_handler()
2903 IPFW_ADD_SOPT_HANDLER(1, scodes);
2907 ipfw_destroy_sopt_handler()
2910 IPFW_DEL_SOPT_HANDLER(1, scodes);
2911 CTL3_LOCK_DESTROY();
2915 * Adds one or more sockopt handlers to the global array.
2916 * Function may sleep.
2919 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
2922 struct ipfw_sopt_handler *tmp;
2927 sz = ctl3_hsize + count;
2929 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
2931 if (ctl3_hsize + count <= sz)
2938 /* Merge old & new arrays */
2939 sz = ctl3_hsize + count;
2940 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
2941 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
2942 qsort(tmp, sz, sizeof(*sh), compare_sh);
2943 /* Switch new and free old */
2944 if (ctl3_handlers != NULL)
2945 free(ctl3_handlers, M_IPFW);
2946 ctl3_handlers = tmp;
2954 * Removes one or more sockopt handlers from the global array.
2957 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
2960 struct ipfw_sopt_handler *tmp, *h;
2965 for (i = 0; i < count; i++) {
2967 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
2971 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
2972 memmove(h, h + 1, sz);
2976 if (ctl3_hsize == 0) {
2977 if (ctl3_handlers != NULL)
2978 free(ctl3_handlers, M_IPFW);
2979 ctl3_handlers = NULL;
2990 * Writes data accumulated in @sd to sockopt buffer.
2991 * Zeroes internal @sd buffer.
2994 ipfw_flush_sopt_data(struct sockopt_data *sd)
2996 struct sockopt *sopt;
3006 if (sopt->sopt_dir == SOPT_GET) {
3007 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3012 memset(sd->kbuf, 0, sd->ksize);
3015 if (sd->ktotal + sd->ksize < sd->valsize)
3016 sd->kavail = sd->ksize;
3018 sd->kavail = sd->valsize - sd->ktotal;
3020 /* Update sopt buffer data */
3021 sopt->sopt_valsize = sd->ktotal;
3022 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3028 * Ensures that @sd buffer has contigious @neeeded number of
3031 * Returns pointer to requested space or NULL.
3034 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3039 if (sd->kavail < needed) {
3041 * Flush data and try another time.
3043 error = ipfw_flush_sopt_data(sd);
3045 if (sd->kavail < needed || error != 0)
3049 addr = sd->kbuf + sd->koff;
3051 sd->kavail -= needed;
3056 * Requests @needed contigious bytes from @sd buffer.
3057 * Function is used to notify subsystem that we are
3058 * interesed in first @needed bytes (request header)
3059 * and the rest buffer can be safely zeroed.
3061 * Returns pointer to requested space or NULL.
3064 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3068 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3072 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3078 * New sockopt handler.
3081 ipfw_ctl3(struct sockopt *sopt)
3084 size_t size, valsize;
3085 struct ip_fw_chain *chain;
3087 struct sockopt_data sdata;
3088 struct ipfw_sopt_handler h;
3089 ip_fw3_opheader *op3 = NULL;
3091 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3095 if (sopt->sopt_name != IP_FW3)
3096 return (ipfw_ctl(sopt));
3098 chain = &V_layer3_chain;
3101 /* Save original valsize before it is altered via sooptcopyin() */
3102 valsize = sopt->sopt_valsize;
3103 memset(&sdata, 0, sizeof(sdata));
3104 /* Read op3 header first to determine actual operation */
3105 op3 = (ip_fw3_opheader *)xbuf;
3106 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3109 sopt->sopt_valsize = valsize;
3112 * Find and reference command.
3114 error = find_ref_sh(op3->opcode, op3->version, &h);
3119 * Disallow modifications in really-really secure mode, but still allow
3120 * the logging counters to be reset.
3122 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3123 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3131 * Fill in sockopt_data structure that may be useful for
3132 * IP_FW3 get requests.
3135 if (valsize <= sizeof(xbuf)) {
3136 /* use on-stack buffer */
3138 sdata.ksize = sizeof(xbuf);
3139 sdata.kavail = valsize;
3143 * Determine opcode type/buffer size:
3144 * allocate sliding-window buf for data export or
3145 * contigious buffer for special ops.
3147 if ((h.dir & HDIR_SET) != 0) {
3148 /* Set request. Allocate contigous buffer. */
3149 if (valsize > CTL3_LARGEBUF) {
3156 /* Get request. Allocate sliding window buffer */
3157 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3159 if (size < valsize) {
3160 /* We have to wire user buffer */
3161 error = vslock(sopt->sopt_val, valsize);
3168 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3170 sdata.kavail = size;
3174 sdata.sopt_val = sopt->sopt_val;
3175 sdata.valsize = valsize;
3178 * Copy either all request (if valsize < bsize_max)
3179 * or first bsize_max bytes to guarantee most consumers
3180 * that all necessary data has been copied).
3181 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3183 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3184 sizeof(ip_fw3_opheader))) != 0)
3186 op3 = (ip_fw3_opheader *)sdata.kbuf;
3188 /* Finally, run handler */
3189 error = h.handler(chain, op3, &sdata);
3192 /* Flush state and free buffers */
3194 error = ipfw_flush_sopt_data(&sdata);
3196 ipfw_flush_sopt_data(&sdata);
3199 vsunlock(sdata.sopt_val, valsize);
3201 /* Restore original pointer and set number of bytes written */
3202 sopt->sopt_val = sdata.sopt_val;
3203 sopt->sopt_valsize = sdata.ktotal;
3204 if (sdata.kbuf != xbuf)
3205 free(sdata.kbuf, M_TEMP);
3211 * {set|get}sockopt parser.
3214 ipfw_ctl(struct sockopt *sopt)
3216 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3218 size_t size, valsize;
3220 struct ip_fw_rule0 *rule;
3221 struct ip_fw_chain *chain;
3222 u_int32_t rulenum[2];
3224 struct rule_check_info ci;
3227 chain = &V_layer3_chain;
3230 /* Save original valsize before it is altered via sooptcopyin() */
3231 valsize = sopt->sopt_valsize;
3232 opt = sopt->sopt_name;
3235 * Disallow modifications in really-really secure mode, but still allow
3236 * the logging counters to be reset.
3238 if (opt == IP_FW_ADD ||
3239 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3240 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3248 * pass up a copy of the current rules. Static rules
3249 * come first (the last of which has number IPFW_DEFAULT_RULE),
3250 * followed by a possibly empty list of dynamic rule.
3251 * The last dynamic rule has NULL in the "next" field.
3253 * Note that the calculated size is used to bound the
3254 * amount of data returned to the user. The rule set may
3255 * change between calculating the size and returning the
3256 * data in which case we'll just return what fits.
3261 size = chain->static_len;
3262 size += ipfw_dyn_len();
3263 if (size >= sopt->sopt_valsize)
3265 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3266 IPFW_UH_RLOCK(chain);
3267 /* check again how much space we need */
3268 want = chain->static_len + ipfw_dyn_len();
3270 len = ipfw_getrules(chain, buf, size);
3271 IPFW_UH_RUNLOCK(chain);
3273 error = sooptcopyout(sopt, buf, len);
3281 /* locking is done within del_entry() */
3282 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3286 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3287 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3288 sizeof(struct ip_fw7) );
3290 memset(&ci, 0, sizeof(struct rule_check_info));
3293 * If the size of commands equals RULESIZE7 then we assume
3294 * a FreeBSD7.2 binary is talking to us (set is7=1).
3295 * is7 is persistent so the next 'ipfw list' command
3296 * will use this format.
3297 * NOTE: If wrong version is guessed (this can happen if
3298 * the first ipfw command is 'ipfw [pipe] list')
3299 * the ipfw binary may crash or loop infinitly...
3301 size = sopt->sopt_valsize;
3302 if (size == RULESIZE7(rule)) {
3304 error = convert_rule_to_8(rule);
3309 size = RULESIZE(rule);
3313 error = check_ipfw_rule0(rule, size, &ci);
3315 /* locking is done within add_rule() */
3316 struct ip_fw *krule;
3317 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3318 ci.urule = (caddr_t)rule;
3321 error = commit_rules(chain, &ci, 1);
3322 if (!error && sopt->sopt_dir == SOPT_GET) {
3324 error = convert_rule_to_7(rule);
3325 size = RULESIZE7(rule);
3331 error = sooptcopyout(sopt, rule, size);
3339 * IP_FW_DEL is used for deleting single rules or sets,
3340 * and (ab)used to atomically manipulate sets. Argument size
3341 * is used to distinguish between the two:
3343 * delete single rule or set of rules,
3344 * or reassign rules (or sets) to a different set.
3345 * 2*sizeof(u_int32_t)
3346 * atomic disable/enable sets.
3347 * first u_int32_t contains sets to be disabled,
3348 * second u_int32_t contains sets to be enabled.
3350 error = sooptcopyin(sopt, rulenum,
3351 2*sizeof(u_int32_t), sizeof(u_int32_t));
3354 size = sopt->sopt_valsize;
3355 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3356 /* delete or reassign, locking done in del_entry() */
3357 error = del_entry(chain, rulenum[0]);
3358 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3359 IPFW_UH_WLOCK(chain);
3361 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3362 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3363 IPFW_UH_WUNLOCK(chain);
3369 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3371 if (sopt->sopt_val != 0) {
3372 error = sooptcopyin(sopt, rulenum,
3373 sizeof(u_int32_t), sizeof(u_int32_t));
3377 error = zero_entry(chain, rulenum[0],
3378 sopt->sopt_name == IP_FW_RESETLOG);
3381 /*--- TABLE opcodes ---*/
3382 case IP_FW_TABLE_ADD:
3383 case IP_FW_TABLE_DEL:
3385 ipfw_table_entry ent;
3386 struct tentry_info tei;
3388 struct table_value v;
3390 error = sooptcopyin(sopt, &ent,
3391 sizeof(ent), sizeof(ent));
3395 memset(&tei, 0, sizeof(tei));
3396 tei.paddr = &ent.addr;
3397 tei.subtype = AF_INET;
3398 tei.masklen = ent.masklen;
3399 ipfw_import_table_value_legacy(ent.value, &v);
3401 memset(&ti, 0, sizeof(ti));
3403 ti.type = IPFW_TABLE_CIDR;
3405 error = (opt == IP_FW_TABLE_ADD) ?
3406 add_table_entry(chain, &ti, &tei, 0, 1) :
3407 del_table_entry(chain, &ti, &tei, 0, 1);
3412 case IP_FW_TABLE_FLUSH:
3417 error = sooptcopyin(sopt, &tbl,
3418 sizeof(tbl), sizeof(tbl));
3421 memset(&ti, 0, sizeof(ti));
3423 error = flush_table(chain, &ti);
3427 case IP_FW_TABLE_GETSIZE:
3432 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3435 memset(&ti, 0, sizeof(ti));
3438 error = ipfw_count_table(chain, &ti, &cnt);
3439 IPFW_RUNLOCK(chain);
3442 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
3446 case IP_FW_TABLE_LIST:
3451 if (sopt->sopt_valsize < sizeof(*tbl)) {
3455 size = sopt->sopt_valsize;
3456 tbl = malloc(size, M_TEMP, M_WAITOK);
3457 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
3462 tbl->size = (size - sizeof(*tbl)) /
3463 sizeof(ipfw_table_entry);
3464 memset(&ti, 0, sizeof(ti));
3467 error = ipfw_dump_table_legacy(chain, &ti, tbl);
3468 IPFW_RUNLOCK(chain);
3473 error = sooptcopyout(sopt, tbl, size);
3478 /*--- NAT operations are protected by the IPFW_LOCK ---*/
3480 if (IPFW_NAT_LOADED)
3481 error = ipfw_nat_cfg_ptr(sopt);
3483 printf("IP_FW_NAT_CFG: %s\n",
3484 "ipfw_nat not present, please load it");
3490 if (IPFW_NAT_LOADED)
3491 error = ipfw_nat_del_ptr(sopt);
3493 printf("IP_FW_NAT_DEL: %s\n",
3494 "ipfw_nat not present, please load it");
3499 case IP_FW_NAT_GET_CONFIG:
3500 if (IPFW_NAT_LOADED)
3501 error = ipfw_nat_get_cfg_ptr(sopt);
3503 printf("IP_FW_NAT_GET_CFG: %s\n",
3504 "ipfw_nat not present, please load it");
3509 case IP_FW_NAT_GET_LOG:
3510 if (IPFW_NAT_LOADED)
3511 error = ipfw_nat_get_log_ptr(sopt);
3513 printf("IP_FW_NAT_GET_LOG: %s\n",
3514 "ipfw_nat not present, please load it");
3520 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
3527 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
3529 /* Functions to convert rules 7.2 <==> 8.0 */
3531 convert_rule_to_7(struct ip_fw_rule0 *rule)
3533 /* Used to modify original rule */
3534 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
3535 /* copy of original rule, version 8 */
3536 struct ip_fw_rule0 *tmp;
3538 /* Used to copy commands */
3539 ipfw_insn *ccmd, *dst;
3540 int ll = 0, ccmdlen = 0;
3542 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
3544 return 1; //XXX error
3546 bcopy(rule, tmp, RULE_MAXSIZE);
3549 //rule7->_pad = tmp->_pad;
3550 rule7->set = tmp->set;
3551 rule7->rulenum = tmp->rulenum;
3552 rule7->cmd_len = tmp->cmd_len;
3553 rule7->act_ofs = tmp->act_ofs;
3554 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
3555 rule7->cmd_len = tmp->cmd_len;
3556 rule7->pcnt = tmp->pcnt;
3557 rule7->bcnt = tmp->bcnt;
3558 rule7->timestamp = tmp->timestamp;
3561 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
3562 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
3563 ccmdlen = F_LEN(ccmd);
3565 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
3567 if (dst->opcode > O_NAT)
3568 /* O_REASS doesn't exists in 7.2 version, so
3569 * decrement opcode if it is after O_REASS
3574 printf("ipfw: opcode %d size truncated\n",
3585 convert_rule_to_8(struct ip_fw_rule0 *rule)
3587 /* Used to modify original rule */
3588 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
3590 /* Used to copy commands */
3591 ipfw_insn *ccmd, *dst;
3592 int ll = 0, ccmdlen = 0;
3594 /* Copy of original rule */
3595 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
3597 return 1; //XXX error
3600 bcopy(rule7, tmp, RULE_MAXSIZE);
3602 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
3603 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
3604 ccmdlen = F_LEN(ccmd);
3606 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
3608 if (dst->opcode > O_NAT)
3609 /* O_REASS doesn't exists in 7.2 version, so
3610 * increment opcode if it is after O_REASS
3615 printf("ipfw: opcode %d size truncated\n",
3621 rule->_pad = tmp->_pad;
3622 rule->set = tmp->set;
3623 rule->rulenum = tmp->rulenum;
3624 rule->cmd_len = tmp->cmd_len;
3625 rule->act_ofs = tmp->act_ofs;
3626 rule->next_rule = (struct ip_fw *)tmp->next_rule;
3627 rule->cmd_len = tmp->cmd_len;
3628 rule->id = 0; /* XXX see if is ok = 0 */
3629 rule->pcnt = tmp->pcnt;
3630 rule->bcnt = tmp->bcnt;
3631 rule->timestamp = tmp->timestamp;
3643 ipfw_init_srv(struct ip_fw_chain *ch)
3646 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
3647 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
3648 M_IPFW, M_WAITOK | M_ZERO);
3652 ipfw_destroy_srv(struct ip_fw_chain *ch)
3655 free(ch->srvstate, M_IPFW);
3656 ipfw_objhash_destroy(ch->srvmap);
3660 * Allocate new bitmask which can be used to enlarge/shrink
3661 * named instance index.
3664 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
3670 KASSERT((items % BLOCK_ITEMS) == 0,
3671 ("bitmask size needs to power of 2 and greater or equal to %zu",
3674 max_blocks = items / BLOCK_ITEMS;
3676 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
3677 /* Mark all as free */
3678 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
3679 *idx_mask &= ~(u_long)1; /* Skip index 0 */
3682 *pblocks = max_blocks;
3686 * Copy current bitmask index to new one.
3689 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
3691 int old_blocks, new_blocks;
3692 u_long *old_idx, *new_idx;
3695 old_idx = ni->idx_mask;
3696 old_blocks = ni->max_blocks;
3698 new_blocks = *blocks;
3700 for (i = 0; i < IPFW_MAX_SETS; i++) {
3701 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
3702 old_blocks * sizeof(u_long));
3707 * Swaps current @ni index with new one.
3710 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
3715 old_idx = ni->idx_mask;
3716 old_blocks = ni->max_blocks;
3718 ni->idx_mask = *idx;
3719 ni->max_blocks = *blocks;
3721 /* Save old values */
3723 *blocks = old_blocks;
3727 ipfw_objhash_bitmap_free(void *idx, int blocks)
3734 * Creates named hash instance.
3735 * Must be called without holding any locks.
3736 * Return pointer to new instance.
3738 struct namedobj_instance *
3739 ipfw_objhash_create(uint32_t items)
3741 struct namedobj_instance *ni;
3745 size = sizeof(struct namedobj_instance) +
3746 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
3747 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
3749 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
3750 ni->nn_size = NAMEDOBJ_HASH_SIZE;
3751 ni->nv_size = NAMEDOBJ_HASH_SIZE;
3753 ni->names = (struct namedobjects_head *)(ni +1);
3754 ni->values = &ni->names[ni->nn_size];
3756 for (i = 0; i < ni->nn_size; i++)
3757 TAILQ_INIT(&ni->names[i]);
3759 for (i = 0; i < ni->nv_size; i++)
3760 TAILQ_INIT(&ni->values[i]);
3762 /* Set default hashing/comparison functions */
3763 ni->hash_f = objhash_hash_name;
3764 ni->cmp_f = objhash_cmp_name;
3766 /* Allocate bitmask separately due to possible resize */
3767 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
3773 ipfw_objhash_destroy(struct namedobj_instance *ni)
3776 free(ni->idx_mask, M_IPFW);
3781 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
3782 objhash_cmp_f *cmp_f)
3785 ni->hash_f = hash_f;
3790 objhash_hash_name(struct namedobj_instance *ni, void *name, uint32_t set)
3793 return (fnv_32_str((char *)name, FNV1_32_INIT));
3797 objhash_cmp_name(struct named_object *no, void *name, uint32_t set)
3800 if ((strcmp(no->name, (char *)name) == 0) && (no->set == set))
3807 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
3811 v = val % (ni->nv_size - 1);
3816 struct named_object *
3817 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
3819 struct named_object *no;
3822 hash = ni->hash_f(ni, name, set) % ni->nn_size;
3824 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
3825 if (ni->cmp_f(no, name, set) == 0)
3833 * Find named object by name, considering also its TLV type.
3835 struct named_object *
3836 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
3837 uint32_t type, char *name)
3839 struct named_object *no;
3842 hash = ni->hash_f(ni, name, set) % ni->nn_size;
3844 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
3845 if (ni->cmp_f(no, name, set) == 0 && no->etlv == type)
3852 struct named_object *
3853 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
3855 struct named_object *no;
3858 hash = objhash_hash_idx(ni, kidx);
3860 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
3861 if (no->kidx == kidx)
3869 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
3870 struct named_object *b)
3873 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
3880 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
3884 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
3885 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
3887 hash = objhash_hash_idx(ni, no->kidx);
3888 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
3894 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
3898 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
3899 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
3901 hash = objhash_hash_idx(ni, no->kidx);
3902 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
3908 ipfw_objhash_count(struct namedobj_instance *ni)
3915 * Runs @func for each found named object.
3916 * It is safe to delete objects from callback
3919 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
3921 struct named_object *no, *no_tmp;
3924 for (i = 0; i < ni->nn_size; i++) {
3925 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp)
3931 * Removes index from given set.
3932 * Returns 0 on success.
3935 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
3940 i = idx / BLOCK_ITEMS;
3941 v = idx % BLOCK_ITEMS;
3943 if (i >= ni->max_blocks)
3946 mask = &ni->idx_mask[i];
3948 if ((*mask & ((u_long)1 << v)) != 0)
3952 *mask |= (u_long)1 << v;
3954 /* Update free offset */
3955 if (ni->free_off[0] > i)
3956 ni->free_off[0] = i;
3962 * Allocate new index in given instance and stores in in @pidx.
3963 * Returns 0 on success.
3966 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
3968 struct namedobj_instance *ni;
3972 ni = (struct namedobj_instance *)n;
3974 off = ni->free_off[0];
3975 mask = &ni->idx_mask[off];
3977 for (i = off; i < ni->max_blocks; i++, mask++) {
3978 if ((v = ffsl(*mask)) == 0)
3982 *mask &= ~ ((u_long)1 << (v - 1));
3984 ni->free_off[0] = i;
3986 v = BLOCK_ITEMS * i + v - 1;