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);
122 static int dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
123 struct sockopt_data *sd);
125 /* ctl3 handler data */
126 struct mtx ctl3_lock;
127 #define CTL3_LOCK_INIT() mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
128 #define CTL3_LOCK_DESTROY() mtx_destroy(&ctl3_lock)
129 #define CTL3_LOCK() mtx_lock(&ctl3_lock)
130 #define CTL3_UNLOCK() mtx_unlock(&ctl3_lock)
132 static struct ipfw_sopt_handler *ctl3_handlers;
133 static size_t ctl3_hsize;
134 static uint64_t ctl3_refct, ctl3_gencnt;
135 #define CTL3_SMALLBUF 4096 /* small page-size write buffer */
136 #define CTL3_LARGEBUF 16 * 1024 * 1024 /* handle large rulesets */
138 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
140 static struct ipfw_sopt_handler scodes[] = {
141 { IP_FW_XGET, 0, HDIR_GET, dump_config },
142 { IP_FW_XADD, 0, HDIR_BOTH, add_rules },
143 { IP_FW_XDEL, 0, HDIR_BOTH, del_rules },
144 { IP_FW_XZERO, 0, HDIR_SET, clear_rules },
145 { IP_FW_XRESETLOG, 0, HDIR_SET, clear_rules },
146 { IP_FW_XMOVE, 0, HDIR_SET, move_rules },
147 { IP_FW_SET_SWAP, 0, HDIR_SET, manage_sets },
148 { IP_FW_SET_MOVE, 0, HDIR_SET, manage_sets },
149 { IP_FW_SET_ENABLE, 0, HDIR_SET, manage_sets },
150 { IP_FW_DUMP_SOPTCODES, 0, HDIR_GET, dump_soptcodes },
151 { IP_FW_DUMP_SRVOBJECTS,0, HDIR_GET, dump_srvobjects },
155 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule);
156 struct opcode_obj_rewrite *ipfw_find_op_rw(uint16_t opcode);
157 static int mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
159 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
160 static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
161 struct sockopt_data *sd);
164 * Opcode object rewriter variables
166 struct opcode_obj_rewrite *ctl3_rewriters;
167 static size_t ctl3_rsize;
170 * static variables followed by global ones
173 static VNET_DEFINE(uma_zone_t, ipfw_cntr_zone);
174 #define V_ipfw_cntr_zone VNET(ipfw_cntr_zone)
180 V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
181 IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
182 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
186 ipfw_destroy_counters()
189 uma_zdestroy(V_ipfw_cntr_zone);
193 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
197 rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
198 rule->cntr = uma_zalloc(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
204 free_rule(struct ip_fw *rule)
207 uma_zfree(V_ipfw_cntr_zone, rule->cntr);
213 * Find the smallest rule >= key, id.
214 * We could use bsearch but it is so simple that we code it directly
217 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
222 for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
225 if (r->rulenum < key)
226 lo = i + 1; /* continue from the next one */
227 else if (r->rulenum > key)
228 hi = i; /* this might be good */
230 lo = i + 1; /* continue from the next one */
231 else /* r->id >= id */
232 hi = i; /* this might be good */
238 * Builds skipto cache on rule set @map.
241 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
246 IPFW_UH_WLOCK_ASSERT(chain);
249 rulenum = map[mi]->rulenum;
250 smap = chain->idxmap_back;
255 for (i = 0; i < 65536; i++) {
257 /* Use the same rule index until i < rulenum */
258 if (i != rulenum || i == 65535)
260 /* Find next rule with num > i */
261 rulenum = map[++mi]->rulenum;
263 rulenum = map[++mi]->rulenum;
268 * Swaps prepared (backup) index with current one.
271 swap_skipto_cache(struct ip_fw_chain *chain)
275 IPFW_UH_WLOCK_ASSERT(chain);
276 IPFW_WLOCK_ASSERT(chain);
279 chain->idxmap = chain->idxmap_back;
280 chain->idxmap_back = map;
284 * Allocate and initialize skipto cache.
287 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
289 int *idxmap, *idxmap_back;
291 idxmap = malloc(65536 * sizeof(uint32_t *), M_IPFW,
293 idxmap_back = malloc(65536 * sizeof(uint32_t *), M_IPFW,
297 * Note we may be called at any time after initialization,
298 * for example, on first skipto rule, so we need to
299 * provide valid chain->idxmap on return
302 IPFW_UH_WLOCK(chain);
303 if (chain->idxmap != NULL) {
304 IPFW_UH_WUNLOCK(chain);
305 free(idxmap, M_IPFW);
306 free(idxmap_back, M_IPFW);
310 /* Set backup pointer first to permit building cache */
311 chain->idxmap_back = idxmap_back;
312 update_skipto_cache(chain, chain->map);
314 /* It is now safe to set chain->idxmap ptr */
315 chain->idxmap = idxmap;
316 swap_skipto_cache(chain);
318 IPFW_UH_WUNLOCK(chain);
322 * Destroys skipto cache.
325 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
328 if (chain->idxmap != NULL)
329 free(chain->idxmap, M_IPFW);
330 if (chain->idxmap != NULL)
331 free(chain->idxmap_back, M_IPFW);
336 * allocate a new map, returns the chain locked. extra is the number
337 * of entries to add or delete.
339 static struct ip_fw **
340 get_map(struct ip_fw_chain *chain, int extra, int locked)
347 mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
349 i = chain->n_rules + extra;
350 map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
352 printf("%s: cannot allocate map\n", __FUNCTION__);
356 IPFW_UH_WLOCK(chain);
357 if (i >= chain->n_rules + extra) /* good */
359 /* otherwise we lost the race, free and retry */
361 IPFW_UH_WUNLOCK(chain);
367 * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
369 static struct ip_fw **
370 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
372 struct ip_fw **old_map;
376 chain->n_rules = new_len;
377 old_map = chain->map;
378 chain->map = new_map;
379 swap_skipto_cache(chain);
386 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
389 cntr->size = sizeof(*cntr);
391 if (krule->cntr != NULL) {
392 cntr->pcnt = counter_u64_fetch(krule->cntr);
393 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
394 cntr->timestamp = krule->timestamp;
396 if (cntr->timestamp > 0)
397 cntr->timestamp += boottime.tv_sec;
401 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
404 if (krule->cntr != NULL) {
405 cntr->pcnt = counter_u64_fetch(krule->cntr);
406 cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
407 cntr->timestamp = krule->timestamp;
409 if (cntr->timestamp > 0)
410 cntr->timestamp += boottime.tv_sec;
414 * Copies rule @urule from v1 userland format (current).
416 * Assume @krule is zeroed.
419 import_rule1(struct rule_check_info *ci)
421 struct ip_fw_rule *urule;
424 urule = (struct ip_fw_rule *)ci->urule;
425 krule = (struct ip_fw *)ci->krule;
428 krule->act_ofs = urule->act_ofs;
429 krule->cmd_len = urule->cmd_len;
430 krule->rulenum = urule->rulenum;
431 krule->set = urule->set;
432 krule->flags = urule->flags;
434 /* Save rulenum offset */
435 ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
438 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
442 * Export rule into v1 format (Current).
444 * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
446 * [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
448 * Assume @data is zeroed.
451 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
453 struct ip_fw_bcounter *cntr;
454 struct ip_fw_rule *urule;
457 /* Fill in TLV header */
458 tlv = (ipfw_obj_tlv *)data;
459 tlv->type = IPFW_TLV_RULE_ENT;
464 cntr = (struct ip_fw_bcounter *)(tlv + 1);
465 urule = (struct ip_fw_rule *)(cntr + 1);
466 export_cntr1_base(krule, cntr);
468 urule = (struct ip_fw_rule *)(tlv + 1);
471 urule->act_ofs = krule->act_ofs;
472 urule->cmd_len = krule->cmd_len;
473 urule->rulenum = krule->rulenum;
474 urule->set = krule->set;
475 urule->flags = krule->flags;
476 urule->id = krule->id;
479 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
484 * Copies rule @urule from FreeBSD8 userland format (v0)
486 * Assume @krule is zeroed.
489 import_rule0(struct rule_check_info *ci)
491 struct ip_fw_rule0 *urule;
495 ipfw_insn_limit *lcmd;
498 urule = (struct ip_fw_rule0 *)ci->urule;
499 krule = (struct ip_fw *)ci->krule;
502 krule->act_ofs = urule->act_ofs;
503 krule->cmd_len = urule->cmd_len;
504 krule->rulenum = urule->rulenum;
505 krule->set = urule->set;
506 if ((urule->_pad & 1) != 0)
507 krule->flags |= IPFW_RULE_NOOPT;
509 /* Save rulenum offset */
510 ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
513 memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
517 * 1) convert tablearg value from 65335 to 0
518 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room for targ).
519 * 3) convert table number in iface opcodes to u16
525 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
528 switch (cmd->opcode) {
529 /* Opcodes supporting tablearg */
541 if (cmd->arg1 == 65535)
542 cmd->arg1 = IP_FW_TARG;
546 if (cmd->arg1 == 65535)
547 cmd->arg1 = IP_FW_TARG;
552 lcmd = (ipfw_insn_limit *)cmd;
553 if (lcmd->conn_limit == 65535)
554 lcmd->conn_limit = IP_FW_TARG;
556 /* Interface tables */
560 /* Interface table, possibly */
561 cmdif = (ipfw_insn_if *)cmd;
562 if (cmdif->name[0] != '\1')
565 cmdif->p.kidx = (uint16_t)cmdif->p.glob;
572 * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
575 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
579 ipfw_insn_limit *lcmd;
583 memset(urule, 0, len);
584 urule->act_ofs = krule->act_ofs;
585 urule->cmd_len = krule->cmd_len;
586 urule->rulenum = krule->rulenum;
587 urule->set = krule->set;
588 if ((krule->flags & IPFW_RULE_NOOPT) != 0)
592 memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
594 /* Export counters */
595 export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
599 * 1) convert tablearg value from 0 to 65335
600 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
601 * 3) convert table number in iface opcodes to int
607 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
610 switch (cmd->opcode) {
611 /* Opcodes supporting tablearg */
623 if (cmd->arg1 == IP_FW_TARG)
628 if (cmd->arg1 == IP_FW_TARG)
631 cmd->arg1 &= ~0x8000;
634 lcmd = (ipfw_insn_limit *)cmd;
635 if (lcmd->conn_limit == IP_FW_TARG)
636 lcmd->conn_limit = 65535;
638 /* Interface tables */
642 /* Interface table, possibly */
643 cmdif = (ipfw_insn_if *)cmd;
644 if (cmdif->name[0] != '\1')
647 cmdif->p.glob = cmdif->p.kidx;
654 * Add new rule(s) to the list possibly creating rule number for each.
655 * Update the rule_number in the input struct so the caller knows it as well.
656 * Must be called without IPFW_UH held
659 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
661 int error, i, insert_before, tcount;
662 uint16_t rulenum, *pnum;
663 struct rule_check_info *ci;
665 struct ip_fw **map; /* the new array of pointers */
667 /* Check if we need to do table/obj index remap */
669 for (ci = rci, i = 0; i < count; ci++, i++) {
670 if (ci->object_opcodes == 0)
674 * Rule has some object opcodes.
675 * We need to find (and create non-existing)
676 * kernel objects, and reference existing ones.
678 error = ipfw_rewrite_rule_uidx(chain, ci);
682 * rewrite failed, state for current rule
683 * has been reverted. Check if we need to
689 * We have some more table rules
690 * we need to rollback.
693 IPFW_UH_WLOCK(chain);
696 if (ci->object_opcodes == 0)
698 unref_rule_objects(chain,ci->krule);
701 IPFW_UH_WUNLOCK(chain);
711 /* get_map returns with IPFW_UH_WLOCK if successful */
712 map = get_map(chain, count, 0 /* not locked */);
716 IPFW_UH_WLOCK(chain);
717 for (ci = rci, i = 0; i < count; ci++, i++) {
718 if (ci->object_opcodes == 0)
721 unref_rule_objects(chain, ci->krule);
723 IPFW_UH_WUNLOCK(chain);
729 if (V_autoinc_step < 1)
731 else if (V_autoinc_step > 1000)
732 V_autoinc_step = 1000;
734 /* FIXME: Handle count > 1 */
737 rulenum = krule->rulenum;
739 /* find the insertion point, we will insert before */
740 insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
741 i = ipfw_find_rule(chain, insert_before, 0);
742 /* duplicate first part */
744 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
746 /* duplicate remaining part, we always have the default rule */
747 bcopy(chain->map + i, map + i + 1,
748 sizeof(struct ip_fw *) *(chain->n_rules - i));
750 /* Compute rule number and write it back */
751 rulenum = i > 0 ? map[i-1]->rulenum : 0;
752 if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
753 rulenum += V_autoinc_step;
754 krule->rulenum = rulenum;
755 /* Save number to userland rule */
756 pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
760 krule->id = chain->id + 1;
761 update_skipto_cache(chain, map);
762 map = swap_map(chain, map, chain->n_rules + 1);
763 chain->static_len += RULEUSIZE0(krule);
764 IPFW_UH_WUNLOCK(chain);
771 * Adds @rule to the list of rules to reap
774 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
778 IPFW_UH_WLOCK_ASSERT(chain);
780 /* Unlink rule from everywhere */
781 unref_rule_objects(chain, rule);
783 *((struct ip_fw **)rule) = *head;
788 * Reclaim storage associated with a list of rules. This is
789 * typically the list created using remove_rule.
790 * A NULL pointer on input is handled correctly.
793 ipfw_reap_rules(struct ip_fw *head)
797 while ((rule = head) != NULL) {
798 head = *((struct ip_fw **)head);
805 * (default || reserved || !match_set || !match_number)
807 * default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
808 * // the default rule is always protected
810 * reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
811 * // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
813 * match_set ::= (cmd == 0 || rule->set == set)
814 * // set number is ignored for cmd == 0
816 * match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
817 * // number is ignored for cmd == 1 or n == 0
821 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
824 /* Don't match default rule for modification queries */
825 if (rule->rulenum == IPFW_DEFAULT_RULE &&
826 (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
829 /* Don't match rules in reserved set for flush requests */
830 if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
833 /* If we're filtering by set, don't match other sets */
834 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
837 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
838 (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
845 * Delete rules matching range @rt.
846 * Saves number of deleted rules in @ndel.
848 * Returns 0 on success.
851 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
853 struct ip_fw *reap, *rule, **map;
858 IPFW_UH_WLOCK(chain); /* arbitrate writers */
861 * Stage 1: Determine range to inspect.
862 * Range is half-inclusive, e.g [start, end).
865 end = chain->n_rules - 1;
867 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
868 start = ipfw_find_rule(chain, rt->start_rule, 0);
870 end = ipfw_find_rule(chain, rt->end_rule, 0);
871 if (rt->end_rule != IPFW_DEFAULT_RULE)
872 while (chain->map[end]->rulenum == rt->end_rule)
876 /* Allocate new map of the same size */
877 map = get_map(chain, 0, 1 /* locked */);
879 IPFW_UH_WUNLOCK(chain);
886 /* 1. bcopy the initial part of the map */
888 bcopy(chain->map, map, start * sizeof(struct ip_fw *));
889 /* 2. copy active rules between start and end */
890 for (i = start; i < end; i++) {
891 rule = chain->map[i];
892 if (ipfw_match_range(rule, rt) == 0) {
898 if (ipfw_is_dyn_rule(rule) != 0)
901 /* 3. copy the final part of the map */
902 bcopy(chain->map + end, map + ofs,
903 (chain->n_rules - end) * sizeof(struct ip_fw *));
904 /* 4. recalculate skipto cache */
905 update_skipto_cache(chain, map);
906 /* 5. swap the maps (under UH_WLOCK + WHLOCK) */
907 map = swap_map(chain, map, chain->n_rules - n);
908 /* 6. Remove all dynamic states originated by deleted rules */
910 ipfw_expire_dyn_rules(chain, rt);
911 /* 7. now remove the rules deleted from the old map */
912 for (i = start; i < end; i++) {
914 if (ipfw_match_range(rule, rt) == 0)
916 chain->static_len -= RULEUSIZE0(rule);
917 ipfw_reap_add(chain, &reap, rule);
919 IPFW_UH_WUNLOCK(chain);
921 ipfw_reap_rules(reap);
929 * Changes set of given rule rannge @rt
932 * Returns 0 on success.
935 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
940 IPFW_UH_WLOCK(chain);
943 * Move rules with matching paramenerts to a new set.
944 * This one is much more complex. We have to ensure
945 * that all referenced tables (if any) are referenced
946 * by given rule subset only. Otherwise, we can't move
947 * them to new set and have to return error.
949 if (V_fw_tables_sets != 0) {
950 if (ipfw_move_tables_sets(chain, rt, rt->new_set) != 0) {
951 IPFW_UH_WUNLOCK(chain);
956 /* XXX: We have to do swap holding WLOCK */
957 for (i = 0; i < chain->n_rules; i++) {
958 rule = chain->map[i];
959 if (ipfw_match_range(rule, rt) == 0)
961 rule->set = rt->new_set;
964 IPFW_UH_WUNLOCK(chain);
970 * Clear counters for a specific rule.
971 * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
972 * so we only care that rules do not disappear.
975 clear_counters(struct ip_fw *rule, int log_only)
977 ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
980 IPFW_ZERO_RULE_COUNTER(rule);
981 if (l->o.opcode == O_LOG)
982 l->log_left = l->max_log;
986 * Flushes rules counters and/or log values on matching range.
988 * Returns number of items cleared.
991 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
998 rt->flags |= IPFW_RCFLAG_DEFAULT;
1000 IPFW_UH_WLOCK(chain); /* arbitrate writers */
1001 for (i = 0; i < chain->n_rules; i++) {
1002 rule = chain->map[i];
1003 if (ipfw_match_range(rule, rt) == 0)
1005 clear_counters(rule, log_only);
1008 IPFW_UH_WUNLOCK(chain);
1014 check_range_tlv(ipfw_range_tlv *rt)
1017 if (rt->head.length != sizeof(*rt))
1019 if (rt->start_rule > rt->end_rule)
1021 if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1024 if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1031 * Delete rules matching specified parameters
1032 * Data layout (v0)(current):
1033 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1034 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1036 * Saves number of deleted rules in ipfw_range_tlv->new_set.
1038 * Returns 0 on success.
1041 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1042 struct sockopt_data *sd)
1044 ipfw_range_header *rh;
1047 if (sd->valsize != sizeof(*rh))
1050 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1052 if (check_range_tlv(&rh->range) != 0)
1056 if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1059 /* Save number of rules deleted */
1060 rh->range.new_set = ndel;
1065 * Move rules/sets matching specified parameters
1066 * Data layout (v0)(current):
1067 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1069 * Returns 0 on success.
1072 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1073 struct sockopt_data *sd)
1075 ipfw_range_header *rh;
1077 if (sd->valsize != sizeof(*rh))
1080 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1082 if (check_range_tlv(&rh->range) != 0)
1085 return (move_range(chain, &rh->range));
1089 * Clear rule accounting data matching specified parameters
1090 * Data layout (v0)(current):
1091 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1092 * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1094 * Saves number of cleared rules in ipfw_range_tlv->new_set.
1096 * Returns 0 on success.
1099 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1100 struct sockopt_data *sd)
1102 ipfw_range_header *rh;
1106 if (sd->valsize != sizeof(*rh))
1109 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1111 if (check_range_tlv(&rh->range) != 0)
1114 log_only = (op3->opcode == IP_FW_XRESETLOG);
1116 num = clear_range(chain, &rh->range, log_only);
1118 if (rh->range.flags & IPFW_RCFLAG_ALL)
1119 msg = log_only ? "All logging counts reset" :
1120 "Accounting cleared";
1122 msg = log_only ? "logging count reset" : "cleared";
1125 int lev = LOG_SECURITY | LOG_NOTICE;
1126 log(lev, "ipfw: %s.\n", msg);
1129 /* Save number of rules cleared */
1130 rh->range.new_set = num;
1135 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1139 IPFW_UH_WLOCK_ASSERT(chain);
1141 /* Change enabled/disabled sets mask */
1142 v_set = (V_set_disable | rt->set) & ~rt->new_set;
1143 v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1145 V_set_disable = v_set;
1146 IPFW_WUNLOCK(chain);
1150 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1155 IPFW_UH_WLOCK_ASSERT(chain);
1157 /* Swap or move two sets */
1158 for (i = 0; i < chain->n_rules - 1; i++) {
1159 rule = chain->map[i];
1160 if (rule->set == rt->set)
1161 rule->set = rt->new_set;
1162 else if (rule->set == rt->new_set && mv == 0)
1163 rule->set = rt->set;
1165 if (V_fw_tables_sets != 0)
1166 ipfw_swap_tables_sets(chain, rt->set, rt->new_set, mv);
1170 * Swaps or moves set
1171 * Data layout (v0)(current):
1172 * Request: [ ipfw_obj_header ipfw_range_tlv ]
1174 * Returns 0 on success.
1177 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1178 struct sockopt_data *sd)
1180 ipfw_range_header *rh;
1182 if (sd->valsize != sizeof(*rh))
1185 rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1187 if (rh->range.head.length != sizeof(ipfw_range_tlv))
1190 IPFW_UH_WLOCK(chain);
1191 switch (op3->opcode) {
1192 case IP_FW_SET_SWAP:
1193 case IP_FW_SET_MOVE:
1194 swap_sets(chain, &rh->range, op3->opcode == IP_FW_SET_MOVE);
1196 case IP_FW_SET_ENABLE:
1197 enable_sets(chain, &rh->range);
1200 IPFW_UH_WUNLOCK(chain);
1206 * Remove all rules with given number, or do set manipulation.
1207 * Assumes chain != NULL && *chain != NULL.
1209 * The argument is an uint32_t. The low 16 bit are the rule or set number;
1210 * the next 8 bits are the new set; the top 8 bits indicate the command:
1212 * 0 delete rules numbered "rulenum"
1213 * 1 delete rules in set "rulenum"
1214 * 2 move rules "rulenum" to set "new_set"
1215 * 3 move rules from set "rulenum" to set "new_set"
1216 * 4 swap sets "rulenum" and "new_set"
1217 * 5 delete rules "rulenum" and set "new_set"
1220 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1222 uint32_t num; /* rule number or old_set */
1223 uint8_t cmd, new_set;
1229 cmd = (arg >> 24) & 0xff;
1230 new_set = (arg >> 16) & 0xff;
1232 if (cmd > 5 || new_set > RESVD_SET)
1234 if (cmd == 0 || cmd == 2 || cmd == 5) {
1235 if (num >= IPFW_DEFAULT_RULE)
1238 if (num > RESVD_SET) /* old_set */
1242 /* Convert old requests into new representation */
1243 memset(&rt, 0, sizeof(rt));
1244 rt.start_rule = num;
1247 rt.new_set = new_set;
1251 case 0: /* delete rules numbered "rulenum" */
1253 rt.flags |= IPFW_RCFLAG_ALL;
1255 rt.flags |= IPFW_RCFLAG_RANGE;
1258 case 1: /* delete rules in set "rulenum" */
1259 rt.flags |= IPFW_RCFLAG_SET;
1262 case 5: /* delete rules "rulenum" and set "new_set" */
1263 rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1268 case 2: /* move rules "rulenum" to set "new_set" */
1269 rt.flags |= IPFW_RCFLAG_RANGE;
1271 case 3: /* move rules from set "rulenum" to set "new_set" */
1272 IPFW_UH_WLOCK(chain);
1273 swap_sets(chain, &rt, 1);
1274 IPFW_UH_WUNLOCK(chain);
1276 case 4: /* swap sets "rulenum" and "new_set" */
1277 IPFW_UH_WLOCK(chain);
1278 swap_sets(chain, &rt, 0);
1279 IPFW_UH_WUNLOCK(chain);
1286 if ((error = delete_range(chain, &rt, &ndel)) != 0)
1289 if (ndel == 0 && (cmd != 1 && num != 0))
1295 return (move_range(chain, &rt));
1299 * Reset some or all counters on firewall rules.
1300 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1301 * the next 8 bits are the set number, the top 8 bits are the command:
1302 * 0 work with rules from all set's;
1303 * 1 work with rules only from specified set.
1304 * Specified rule number is zero if we want to clear all entries.
1305 * log_only is 1 if we only want to reset logs, zero otherwise.
1308 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1314 uint16_t rulenum = arg & 0xffff;
1315 uint8_t set = (arg >> 16) & 0xff;
1316 uint8_t cmd = (arg >> 24) & 0xff;
1320 if (cmd == 1 && set > RESVD_SET)
1323 IPFW_UH_RLOCK(chain);
1325 V_norule_counter = 0;
1326 for (i = 0; i < chain->n_rules; i++) {
1327 rule = chain->map[i];
1328 /* Skip rules not in our set. */
1329 if (cmd == 1 && rule->set != set)
1331 clear_counters(rule, log_only);
1333 msg = log_only ? "All logging counts reset" :
1334 "Accounting cleared";
1337 for (i = 0; i < chain->n_rules; i++) {
1338 rule = chain->map[i];
1339 if (rule->rulenum == rulenum) {
1340 if (cmd == 0 || rule->set == set)
1341 clear_counters(rule, log_only);
1344 if (rule->rulenum > rulenum)
1347 if (!cleared) { /* we did not find any matching rules */
1348 IPFW_UH_RUNLOCK(chain);
1351 msg = log_only ? "logging count reset" : "cleared";
1353 IPFW_UH_RUNLOCK(chain);
1356 int lev = LOG_SECURITY | LOG_NOTICE;
1359 log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1361 log(lev, "ipfw: %s.\n", msg);
1368 * Check rule head in FreeBSD11 format
1372 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1373 struct rule_check_info *ci)
1377 if (size < sizeof(*rule)) {
1378 printf("ipfw: rule too short\n");
1382 /* Check for valid cmd_len */
1383 l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1385 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1388 if (rule->act_ofs >= rule->cmd_len) {
1389 printf("ipfw: bogus action offset (%u > %u)\n",
1390 rule->act_ofs, rule->cmd_len - 1);
1394 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1397 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1401 * Check rule head in FreeBSD8 format
1405 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1406 struct rule_check_info *ci)
1410 if (size < sizeof(*rule)) {
1411 printf("ipfw: rule too short\n");
1415 /* Check for valid cmd_len */
1416 l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1418 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1421 if (rule->act_ofs >= rule->cmd_len) {
1422 printf("ipfw: bogus action offset (%u > %u)\n",
1423 rule->act_ofs, rule->cmd_len - 1);
1427 if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1430 return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1434 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1442 * Now go for the individual checks. Very simple ones, basically only
1443 * instruction sizes.
1445 for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1446 cmdlen = F_LEN(cmd);
1448 printf("ipfw: opcode %d size truncated\n",
1452 switch (cmd->opcode) {
1464 case O_IPPRECEDENCE:
1482 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1487 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1489 if (cmd->arg1 >= rt_numfibs) {
1490 printf("ipfw: invalid fib number %d\n",
1497 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1499 if ((cmd->arg1 != IP_FW_TARG) &&
1500 ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1501 printf("ipfw: invalid fib number %d\n",
1502 cmd->arg1 & 0x7FFF);
1516 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1521 if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1526 if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1529 ((ipfw_insn_log *)cmd)->log_left =
1530 ((ipfw_insn_log *)cmd)->max_log;
1536 /* only odd command lengths */
1537 if ((cmdlen & 1) == 0)
1543 if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1544 printf("ipfw: invalid set size %d\n",
1548 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1553 case O_IP_SRC_LOOKUP:
1554 case O_IP_DST_LOOKUP:
1555 if (cmd->arg1 >= V_fw_tables_max) {
1556 printf("ipfw: invalid table number %d\n",
1560 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1561 cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1562 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1564 ci->object_opcodes++;
1566 case O_IP_FLOW_LOOKUP:
1567 if (cmd->arg1 >= V_fw_tables_max) {
1568 printf("ipfw: invalid table number %d\n",
1572 if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1573 cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1575 ci->object_opcodes++;
1578 if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1589 if (cmdlen < 1 || cmdlen > 31)
1594 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1600 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1601 if (cmdlen < 2 || cmdlen > 31)
1608 if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1610 ci->object_opcodes++;
1614 if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1620 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1625 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1630 if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1637 if (ip_divert_ptr == NULL)
1643 if (ng_ipfw_input_p == NULL)
1648 if (!IPFW_NAT_LOADED)
1650 if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1653 case O_FORWARD_MAC: /* XXX not implemented yet */
1667 if (cmdlen != F_INSN_SIZE(ipfw_insn))
1671 printf("ipfw: opcode %d, multiple actions"
1678 printf("ipfw: opcode %d, action must be"
1687 if (cmdlen != F_INSN_SIZE(struct in6_addr) +
1688 F_INSN_SIZE(ipfw_insn))
1693 if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1694 ((ipfw_insn_u32 *)cmd)->o.arg1)
1698 case O_IP6_SRC_MASK:
1699 case O_IP6_DST_MASK:
1700 if ( !(cmdlen & 1) || cmdlen > 127)
1704 if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
1710 switch (cmd->opcode) {
1720 case O_IP6_SRC_MASK:
1721 case O_IP6_DST_MASK:
1723 printf("ipfw: no IPv6 support in kernel\n");
1724 return (EPROTONOSUPPORT);
1727 printf("ipfw: opcode %d, unknown opcode\n",
1733 if (have_action == 0) {
1734 printf("ipfw: missing action\n");
1740 printf("ipfw: opcode %d size %d wrong\n",
1741 cmd->opcode, cmdlen);
1747 * Translation of requests for compatibility with FreeBSD 7.2/8.
1748 * a static variable tells us if we have an old client from userland,
1749 * and if necessary we translate requests and responses between the
1755 struct ip_fw7 *next; /* linked list of rules */
1756 struct ip_fw7 *next_rule; /* ptr to next [skipto] rule */
1757 /* 'next_rule' is used to pass up 'set_disable' status */
1759 uint16_t act_ofs; /* offset of action in 32-bit units */
1760 uint16_t cmd_len; /* # of 32-bit words in cmd */
1761 uint16_t rulenum; /* rule number */
1762 uint8_t set; /* rule set (0..31) */
1763 // #define RESVD_SET 31 /* set for default and persistent rules */
1764 uint8_t _pad; /* padding */
1765 // uint32_t id; /* rule id, only in v.8 */
1766 /* These fields are present in all rules. */
1767 uint64_t pcnt; /* Packet counter */
1768 uint64_t bcnt; /* Byte counter */
1769 uint32_t timestamp; /* tv_sec of last match */
1771 ipfw_insn cmd[1]; /* storage for commands */
1774 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
1775 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
1778 #define RULESIZE7(rule) (sizeof(struct ip_fw7) + \
1779 ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
1784 * Copy the static and dynamic rules to the supplied buffer
1785 * and return the amount of space actually used.
1786 * Must be run under IPFW_UH_RLOCK
1789 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
1792 char *ep = bp + space;
1794 struct ip_fw_rule0 *dst;
1795 int error, i, l, warnflag;
1796 time_t boot_seconds;
1800 boot_seconds = boottime.tv_sec;
1801 for (i = 0; i < chain->n_rules; i++) {
1802 rule = chain->map[i];
1805 /* Convert rule to FreeBSd 7.2 format */
1806 l = RULESIZE7(rule);
1807 if (bp + l + sizeof(uint32_t) <= ep) {
1808 bcopy(rule, bp, l + sizeof(uint32_t));
1809 error = set_legacy_obj_kidx(chain,
1810 (struct ip_fw_rule0 *)bp);
1813 error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
1815 return 0; /*XXX correct? */
1817 * XXX HACK. Store the disable mask in the "next"
1818 * pointer in a wild attempt to keep the ABI the same.
1819 * Why do we do this on EVERY rule?
1821 bcopy(&V_set_disable,
1822 &(((struct ip_fw7 *)bp)->next_rule),
1823 sizeof(V_set_disable));
1824 if (((struct ip_fw7 *)bp)->timestamp)
1825 ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
1828 continue; /* go to next rule */
1831 l = RULEUSIZE0(rule);
1832 if (bp + l > ep) { /* should not happen */
1833 printf("overflow dumping static rules\n");
1836 dst = (struct ip_fw_rule0 *)bp;
1837 export_rule0(rule, dst, l);
1838 error = set_legacy_obj_kidx(chain, dst);
1841 * XXX HACK. Store the disable mask in the "next"
1842 * pointer in a wild attempt to keep the ABI the same.
1843 * Why do we do this on EVERY rule?
1845 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
1846 * so we need to fail _after_ saving at least one mask.
1848 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
1850 dst->timestamp += boot_seconds;
1855 /* Non-fatal table rewrite error. */
1859 printf("Stop on rule %d. Fail to convert table\n",
1865 printf("ipfw: process %s is using legacy interfaces,"
1866 " consider rebuilding\n", "");
1867 ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
1868 return (bp - (char *)buf);
1873 uint32_t b; /* start rule */
1874 uint32_t e; /* end rule */
1875 uint32_t rcount; /* number of rules */
1876 uint32_t rsize; /* rules size */
1877 uint32_t tcount; /* number of tables */
1878 int rcounters; /* counters */
1882 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
1885 ntlv->head.type = no->etlv;
1886 ntlv->head.length = sizeof(*ntlv);
1887 ntlv->idx = no->kidx;
1888 strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
1892 * Export named object info in instance @ni, identified by @kidx
1893 * to ipfw_obj_ntlv. TLV is allocated from @sd space.
1895 * Returns 0 on success.
1898 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
1899 struct sockopt_data *sd)
1901 struct named_object *no;
1902 ipfw_obj_ntlv *ntlv;
1904 no = ipfw_objhash_lookup_kidx(ni, kidx);
1905 KASSERT(no != NULL, ("invalid object kernel index passed"));
1907 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
1911 ipfw_export_obj_ntlv(no, ntlv);
1916 * Dumps static rules with table TLVs in buffer @sd.
1918 * Returns 0 on success.
1921 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
1922 uint32_t *bmask, struct sockopt_data *sd)
1927 ipfw_obj_ctlv *ctlv;
1928 struct ip_fw *krule;
1929 struct namedobj_instance *ni;
1932 /* Dump table names first (if any) */
1933 if (da->tcount > 0) {
1935 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1938 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
1939 ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
1941 ctlv->count = da->tcount;
1942 ctlv->objsize = sizeof(ipfw_obj_ntlv);
1946 tcount = da->tcount;
1947 ni = ipfw_get_table_objhash(chain);
1948 while (tcount > 0) {
1949 if ((bmask[i / 32] & (1 << (i % 32))) == 0) {
1954 /* Jump to shared named object bitmask */
1955 if (i >= IPFW_TABLES_MAX) {
1956 ni = CHAIN_TO_SRV(chain);
1957 i -= IPFW_TABLES_MAX;
1958 bmask += IPFW_TABLES_MAX / 32;
1961 if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
1969 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1972 ctlv->head.type = IPFW_TLV_RULE_LIST;
1973 ctlv->head.length = da->rsize + sizeof(*ctlv);
1974 ctlv->count = da->rcount;
1976 for (i = da->b; i < da->e; i++) {
1977 krule = chain->map[i];
1979 l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
1980 if (da->rcounters != 0)
1981 l += sizeof(struct ip_fw_bcounter);
1982 dst = (caddr_t)ipfw_get_sopt_space(sd, l);
1986 export_rule1(krule, dst, l, da->rcounters);
1993 * Marks every object index used in @rule with bit in @bmask.
1994 * Used to generate bitmask of referenced tables/objects for given ruleset
1997 * Returns number of newly-referenced objects.
2000 mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule,
2003 int cmdlen, l, count;
2006 struct opcode_obj_rewrite *rw;
2014 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2015 cmdlen = F_LEN(cmd);
2017 rw = ipfw_find_op_rw(cmd->opcode);
2021 if (rw->classifier(cmd, &kidx, &subtype) != 0)
2025 /* Maintain separate bitmasks for table and non-table objects */
2026 if (rw->etlv != IPFW_TLV_TBL_NAME)
2027 bidx += IPFW_TABLES_MAX / 32;
2029 if ((bmask[bidx] & (1 << (kidx % 32))) == 0)
2032 bmask[bidx] |= 1 << (kidx % 32);
2039 * Dumps requested objects data
2040 * Data layout (version 0)(current):
2041 * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2042 * size = ipfw_cfg_lheader.size
2043 * Reply: [ ipfw_cfg_lheader
2044 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2045 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2046 * ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2048 * [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2050 * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2051 * The rest (size, count) are set to zero and needs to be ignored.
2053 * Returns 0 on success.
2056 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2057 struct sockopt_data *sd)
2059 ipfw_cfg_lheader *hdr;
2064 struct dump_args da;
2067 hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2073 /* Allocate needed state. Note we allocate 2xspace mask, for table&srv */
2074 if (hdr->flags & IPFW_CFG_GET_STATIC)
2075 bmask = malloc(IPFW_TABLES_MAX / 4, M_TEMP, M_WAITOK | M_ZERO);
2077 IPFW_UH_RLOCK(chain);
2080 * STAGE 1: Determine size/count for objects in range.
2081 * Prepare used tables bitmask.
2083 sz = sizeof(ipfw_cfg_lheader);
2084 memset(&da, 0, sizeof(da));
2087 da.e = chain->n_rules;
2089 if (hdr->end_rule != 0) {
2090 /* Handle custom range */
2091 if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2092 rnum = IPFW_DEFAULT_RULE;
2093 da.b = ipfw_find_rule(chain, rnum, 0);
2094 rnum = hdr->end_rule;
2095 rnum = (rnum < IPFW_DEFAULT_RULE) ? rnum+1 : IPFW_DEFAULT_RULE;
2096 da.e = ipfw_find_rule(chain, rnum, 0) + 1;
2099 if (hdr->flags & IPFW_CFG_GET_STATIC) {
2100 for (i = da.b; i < da.e; i++) {
2101 rule = chain->map[i];
2102 da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2104 /* Update bitmask of used objects for given range */
2105 da.tcount += mark_object_kidx(chain, rule, bmask);
2107 /* Add counters if requested */
2108 if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2109 da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2114 sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2115 sizeof(ipfw_obj_ctlv);
2116 sz += da.rsize + sizeof(ipfw_obj_ctlv);
2119 if (hdr->flags & IPFW_CFG_GET_STATES)
2120 sz += ipfw_dyn_get_count() * sizeof(ipfw_obj_dyntlv) +
2121 sizeof(ipfw_obj_ctlv);
2125 * Fill header anyway.
2126 * Note we have to save header fields to stable storage
2127 * buffer inside @sd can be flushed after dumping rules
2130 hdr->set_mask = ~V_set_disable;
2131 hdr_flags = hdr->flags;
2134 if (sd->valsize < sz) {
2139 /* STAGE2: Store actual data */
2140 if (hdr_flags & IPFW_CFG_GET_STATIC) {
2141 error = dump_static_rules(chain, &da, bmask, sd);
2146 if (hdr_flags & IPFW_CFG_GET_STATES)
2147 error = ipfw_dump_states(chain, sd);
2150 IPFW_UH_RUNLOCK(chain);
2153 free(bmask, M_TEMP);
2159 ipfw_check_object_name_generic(const char *name)
2163 nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2164 if (strnlen(name, nsize) == nsize)
2166 if (name[0] == '\0')
2172 * Creates non-existent objects referenced by rule.
2174 * Return 0 on success.
2177 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2178 struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2180 struct opcode_obj_rewrite *rw;
2186 * Compatibility stuff: do actual creation for non-existing,
2187 * but referenced objects.
2189 for (p = oib; p < pidx; p++) {
2197 rw = ipfw_find_op_rw((cmd + p->off)->opcode);
2198 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2199 (cmd + p->off)->opcode));
2201 error = rw->create_object(ch, ti, &kidx);
2208 * Error happened. We have to rollback everything.
2209 * Drop all already acquired references.
2212 unref_oib_objects(ch, cmd, oib, pidx);
2213 IPFW_UH_WUNLOCK(ch);
2222 * Compatibility function for old ipfw(8) binaries.
2223 * Rewrites table/nat kernel indices with userland ones.
2224 * Convert tables matching '/^\d+$/' to their atoi() value.
2225 * Use number 65535 for other tables.
2227 * Returns 0 on success.
2230 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2232 int cmdlen, error, l;
2234 uint16_t kidx, uidx;
2235 struct named_object *no;
2236 struct opcode_obj_rewrite *rw;
2246 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2247 cmdlen = F_LEN(cmd);
2249 rw = ipfw_find_op_rw(cmd->opcode);
2253 /* Check if is index in given opcode */
2254 if (rw->classifier(cmd, &kidx, &subtype) != 0)
2257 /* Try to find referenced kernel object */
2258 no = rw->find_bykidx(ch, kidx);
2262 val = strtol(no->name, &end, 10);
2263 if (*end == '\0' && val < 65535) {
2268 * We are called via legacy opcode.
2269 * Save error and show table as fake number
2270 * not to make ipfw(8) hang.
2276 rw->update(cmd, uidx);
2284 * Unreferences all already-referenced objects in given @cmd rule,
2285 * using information in @oib.
2287 * Used to rollback partially converted rule on error.
2290 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2291 struct obj_idx *end)
2293 struct opcode_obj_rewrite *rw;
2294 struct named_object *no;
2297 IPFW_UH_WLOCK_ASSERT(ch);
2299 for (p = oib; p < end; p++) {
2303 rw = ipfw_find_op_rw((cmd + p->off)->opcode);
2304 KASSERT(rw != NULL, ("Unable to find handler for op %d",
2305 (cmd + p->off)->opcode));
2307 /* Find & unref by existing idx */
2308 no = rw->find_bykidx(ch, p->kidx);
2309 KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2315 * Remove references from every object used in @rule.
2316 * Used at rule removal code.
2319 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2323 struct named_object *no;
2325 struct opcode_obj_rewrite *rw;
2328 IPFW_UH_WLOCK_ASSERT(ch);
2333 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2334 cmdlen = F_LEN(cmd);
2336 rw = ipfw_find_op_rw(cmd->opcode);
2339 if (rw->classifier(cmd, &kidx, &subtype) != 0)
2342 no = rw->find_bykidx(ch, kidx);
2344 KASSERT(no != NULL, ("table id %d not found", kidx));
2345 KASSERT(no->subtype == subtype,
2346 ("wrong type %d (%d) for table id %d",
2347 no->subtype, subtype, kidx));
2348 KASSERT(no->refcnt > 0, ("refcount for table %d is %d",
2351 if (no->refcnt == 1 && rw->destroy_object != NULL)
2352 rw->destroy_object(ch, no);
2360 * Find and reference object (if any) stored in instruction @cmd.
2362 * Saves object info in @pidx, sets
2363 * - @found to 1 if object was found and references
2364 * - @unresolved to 1 if object should exists but not found
2366 * Returns non-zero value in case of error.
2369 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2370 struct obj_idx *pidx, int *found, int *unresolved)
2372 struct named_object *no;
2373 struct opcode_obj_rewrite *rw;
2379 /* Check if this opcode is candidate for rewrite */
2380 rw = ipfw_find_op_rw(cmd->opcode);
2384 /* Check if we need to rewrite this opcode */
2385 if (rw->classifier(cmd, &ti->uidx, &ti->type) != 0)
2388 /* Need to rewrite. Save necessary fields */
2389 pidx->uidx = ti->uidx;
2390 pidx->type = ti->type;
2392 /* Try to find referenced kernel object */
2393 error = rw->find_byname(ch, ti, &no);
2401 /* Found. bump refcount */
2404 pidx->kidx = no->kidx;
2410 * Adds one or more rules to ipfw @chain.
2411 * Data layout (version 0)(current):
2415 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2416 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2421 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2422 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2425 * Rules in reply are modified to store their actual ruleset number.
2427 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2428 * accoring to their idx field and there has to be no duplicates.
2429 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2430 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2432 * Returns 0 on success.
2435 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2436 struct sockopt_data *sd)
2438 ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2439 ipfw_obj_ntlv *ntlv;
2440 int clen, error, idx;
2441 uint32_t count, read;
2442 struct ip_fw_rule *r;
2443 struct rule_check_info rci, *ci, *cbuf;
2446 op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2447 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2449 read = sizeof(ip_fw3_opheader);
2453 memset(&rci, 0, sizeof(struct rule_check_info));
2455 if (read + sizeof(*ctlv) > sd->valsize)
2458 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2459 clen = ctlv->head.length;
2460 /* Check size and alignment */
2461 if (clen > sd->valsize || clen < sizeof(*ctlv))
2463 if ((clen % sizeof(uint64_t)) != 0)
2467 * Some table names or other named objects.
2468 * Check for validness.
2470 count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2471 if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2476 * Ensure TLVs are sorted ascending and
2477 * there are no duplicates.
2480 ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2482 if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2485 error = ipfw_check_object_name_generic(ntlv->name);
2489 if (ntlv->idx <= idx)
2498 read += ctlv->head.length;
2499 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2502 if (read + sizeof(*ctlv) > sd->valsize)
2505 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2506 clen = ctlv->head.length;
2507 if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2509 if ((clen % sizeof(uint64_t)) != 0)
2513 * TODO: Permit adding multiple rules at once
2515 if (ctlv->count != 1)
2518 clen -= sizeof(*ctlv);
2520 if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2523 /* Allocate state for each rule or use stack */
2524 if (ctlv->count == 1) {
2525 memset(&rci, 0, sizeof(struct rule_check_info));
2528 cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2533 * Check each rule for validness.
2534 * Ensure numbered rules are sorted ascending
2535 * and properly aligned
2538 r = (struct ip_fw_rule *)(ctlv + 1);
2542 rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
2543 if (rsize > clen || ctlv->count <= count) {
2549 error = check_ipfw_rule1(r, rsize, ci);
2554 if (r->rulenum != 0 && r->rulenum < idx) {
2555 printf("rulenum %d idx %d\n", r->rulenum, idx);
2561 ci->urule = (caddr_t)r;
2563 rsize = roundup2(rsize, sizeof(uint64_t));
2565 r = (struct ip_fw_rule *)((caddr_t)r + rsize);
2570 if (ctlv->count != count || error != 0) {
2577 read += ctlv->head.length;
2578 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2581 if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
2582 if (cbuf != NULL && cbuf != &rci)
2588 * Passed rules seems to be valid.
2589 * Allocate storage and try to add them to chain.
2591 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
2592 clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
2593 ci->krule = ipfw_alloc_rule(chain, clen);
2597 if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
2598 /* Free allocate krules */
2599 for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
2600 free(ci->krule, M_IPFW);
2603 if (cbuf != NULL && cbuf != &rci)
2610 * Lists all sopts currently registered.
2611 * Data layout (v0)(current):
2612 * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
2613 * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
2615 * Returns 0 on success
2618 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2619 struct sockopt_data *sd)
2621 struct _ipfw_obj_lheader *olh;
2623 struct ipfw_sopt_handler *sh;
2624 uint32_t count, n, size;
2626 olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
2629 if (sd->valsize < olh->size)
2634 size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
2636 /* Fill in header regadless of buffer size */
2638 olh->objsize = sizeof(ipfw_sopt_info);
2640 if (size > olh->size) {
2647 for (n = 1; n <= count; n++) {
2648 i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
2649 KASSERT(i != 0, ("previously checked buffer is not enough"));
2650 sh = &ctl3_handlers[n];
2651 i->opcode = sh->opcode;
2652 i->version = sh->version;
2653 i->refcnt = sh->refcnt;
2661 * Compares two opcodes.
2662 * Used both in qsort() and bsearch().
2664 * Returns 0 if match is found.
2667 compare_opcodes(const void *_a, const void *_b)
2669 const struct opcode_obj_rewrite *a, *b;
2671 a = (const struct opcode_obj_rewrite *)_a;
2672 b = (const struct opcode_obj_rewrite *)_b;
2674 if (a->opcode < b->opcode)
2676 else if (a->opcode > b->opcode)
2683 * Finds opcode object rewriter based on @code.
2685 * Returns pointer to handler or NULL.
2687 struct opcode_obj_rewrite *
2688 ipfw_find_op_rw(uint16_t opcode)
2690 struct opcode_obj_rewrite *rw, h;
2692 memset(&h, 0, sizeof(h));
2695 rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
2696 ctl3_rsize, sizeof(h), compare_opcodes);
2702 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
2704 struct opcode_obj_rewrite *rw;
2707 rw = ipfw_find_op_rw(cmd->opcode);
2711 return (rw->classifier(cmd, puidx, &subtype));
2715 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
2717 struct opcode_obj_rewrite *rw;
2719 rw = ipfw_find_op_rw(cmd->opcode);
2720 KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
2721 rw->update(cmd, idx);
2725 ipfw_init_obj_rewriter()
2728 ctl3_rewriters = NULL;
2733 ipfw_destroy_obj_rewriter()
2736 if (ctl3_rewriters != NULL)
2737 free(ctl3_rewriters, M_IPFW);
2738 ctl3_rewriters = NULL;
2743 * Adds one or more opcode object rewrite handlers to the global array.
2744 * Function may sleep.
2747 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
2750 struct opcode_obj_rewrite *tmp;
2755 sz = ctl3_rsize + count;
2757 tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
2759 if (ctl3_rsize + count <= sz)
2766 /* Merge old & new arrays */
2767 sz = ctl3_rsize + count;
2768 memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
2769 memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
2770 qsort(tmp, sz, sizeof(*rw), compare_opcodes);
2771 /* Switch new and free old */
2772 if (ctl3_rewriters != NULL)
2773 free(ctl3_rewriters, M_IPFW);
2774 ctl3_rewriters = tmp;
2781 * Removes one or more object rewrite handlers from the global array.
2784 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
2787 struct opcode_obj_rewrite *tmp, *h;
2792 for (i = 0; i < count; i++) {
2794 h = ipfw_find_op_rw(tmp->opcode);
2798 sz = (ctl3_rewriters + ctl3_rsize - (h + 1)) * sizeof(*h);
2799 memmove(h, h + 1, sz);
2803 if (ctl3_rsize == 0) {
2804 if (ctl3_rewriters != NULL)
2805 free(ctl3_rewriters, M_IPFW);
2806 ctl3_rewriters = NULL;
2815 export_objhash_ntlv_internal(struct namedobj_instance *ni,
2816 struct named_object *no, void *arg)
2818 struct sockopt_data *sd;
2819 ipfw_obj_ntlv *ntlv;
2821 sd = (struct sockopt_data *)arg;
2822 ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2825 ipfw_export_obj_ntlv(no, ntlv);
2829 * Lists all service objects.
2830 * Data layout (v0)(current):
2831 * Request: [ ipfw_obj_lheader ] size = ipfw_cfg_lheader.size
2832 * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
2833 * Returns 0 on success
2836 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2837 struct sockopt_data *sd)
2839 ipfw_obj_lheader *hdr;
2842 hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2846 IPFW_UH_RLOCK(chain);
2847 count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
2848 hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
2849 if (sd->valsize < hdr->size) {
2850 IPFW_UH_RUNLOCK(chain);
2854 hdr->objsize = sizeof(ipfw_obj_ntlv);
2856 ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
2857 export_objhash_ntlv_internal, sd);
2858 IPFW_UH_RUNLOCK(chain);
2863 * Compares two sopt handlers (code, version and handler ptr).
2864 * Used both as qsort() and bsearch().
2865 * Does not compare handler for latter case.
2867 * Returns 0 if match is found.
2870 compare_sh(const void *_a, const void *_b)
2872 const struct ipfw_sopt_handler *a, *b;
2874 a = (const struct ipfw_sopt_handler *)_a;
2875 b = (const struct ipfw_sopt_handler *)_b;
2877 if (a->opcode < b->opcode)
2879 else if (a->opcode > b->opcode)
2882 if (a->version < b->version)
2884 else if (a->version > b->version)
2887 /* bsearch helper */
2888 if (a->handler == NULL)
2891 if ((uintptr_t)a->handler < (uintptr_t)b->handler)
2893 else if ((uintptr_t)b->handler > (uintptr_t)b->handler)
2900 * Finds sopt handler based on @code and @version.
2902 * Returns pointer to handler or NULL.
2904 static struct ipfw_sopt_handler *
2905 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
2907 struct ipfw_sopt_handler *sh, h;
2909 memset(&h, 0, sizeof(h));
2911 h.version = version;
2912 h.handler = handler;
2914 sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
2915 ctl3_hsize, sizeof(h), compare_sh);
2921 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
2923 struct ipfw_sopt_handler *sh;
2926 if ((sh = find_sh(opcode, version, NULL)) == NULL) {
2928 printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
2934 /* Copy handler data to requested buffer */
2942 find_unref_sh(struct ipfw_sopt_handler *psh)
2944 struct ipfw_sopt_handler *sh;
2947 sh = find_sh(psh->opcode, psh->version, NULL);
2948 KASSERT(sh != NULL, ("ctl3 handler disappeared"));
2955 ipfw_init_sopt_handler()
2959 IPFW_ADD_SOPT_HANDLER(1, scodes);
2963 ipfw_destroy_sopt_handler()
2966 IPFW_DEL_SOPT_HANDLER(1, scodes);
2967 CTL3_LOCK_DESTROY();
2971 * Adds one or more sockopt handlers to the global array.
2972 * Function may sleep.
2975 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
2978 struct ipfw_sopt_handler *tmp;
2983 sz = ctl3_hsize + count;
2985 tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
2987 if (ctl3_hsize + count <= sz)
2994 /* Merge old & new arrays */
2995 sz = ctl3_hsize + count;
2996 memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
2997 memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
2998 qsort(tmp, sz, sizeof(*sh), compare_sh);
2999 /* Switch new and free old */
3000 if (ctl3_handlers != NULL)
3001 free(ctl3_handlers, M_IPFW);
3002 ctl3_handlers = tmp;
3010 * Removes one or more sockopt handlers from the global array.
3013 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3016 struct ipfw_sopt_handler *tmp, *h;
3021 for (i = 0; i < count; i++) {
3023 h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3027 sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3028 memmove(h, h + 1, sz);
3032 if (ctl3_hsize == 0) {
3033 if (ctl3_handlers != NULL)
3034 free(ctl3_handlers, M_IPFW);
3035 ctl3_handlers = NULL;
3046 * Writes data accumulated in @sd to sockopt buffer.
3047 * Zeroes internal @sd buffer.
3050 ipfw_flush_sopt_data(struct sockopt_data *sd)
3052 struct sockopt *sopt;
3062 if (sopt->sopt_dir == SOPT_GET) {
3063 error = copyout(sd->kbuf, sopt->sopt_val, sz);
3068 memset(sd->kbuf, 0, sd->ksize);
3071 if (sd->ktotal + sd->ksize < sd->valsize)
3072 sd->kavail = sd->ksize;
3074 sd->kavail = sd->valsize - sd->ktotal;
3076 /* Update sopt buffer data */
3077 sopt->sopt_valsize = sd->ktotal;
3078 sopt->sopt_val = sd->sopt_val + sd->ktotal;
3084 * Ensures that @sd buffer has contigious @neeeded number of
3087 * Returns pointer to requested space or NULL.
3090 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3095 if (sd->kavail < needed) {
3097 * Flush data and try another time.
3099 error = ipfw_flush_sopt_data(sd);
3101 if (sd->kavail < needed || error != 0)
3105 addr = sd->kbuf + sd->koff;
3107 sd->kavail -= needed;
3112 * Requests @needed contigious bytes from @sd buffer.
3113 * Function is used to notify subsystem that we are
3114 * interesed in first @needed bytes (request header)
3115 * and the rest buffer can be safely zeroed.
3117 * Returns pointer to requested space or NULL.
3120 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3124 if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3128 memset(sd->kbuf + sd->koff, 0, sd->kavail);
3134 * New sockopt handler.
3137 ipfw_ctl3(struct sockopt *sopt)
3140 size_t size, valsize;
3141 struct ip_fw_chain *chain;
3143 struct sockopt_data sdata;
3144 struct ipfw_sopt_handler h;
3145 ip_fw3_opheader *op3 = NULL;
3147 error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3151 if (sopt->sopt_name != IP_FW3)
3152 return (ipfw_ctl(sopt));
3154 chain = &V_layer3_chain;
3157 /* Save original valsize before it is altered via sooptcopyin() */
3158 valsize = sopt->sopt_valsize;
3159 memset(&sdata, 0, sizeof(sdata));
3160 /* Read op3 header first to determine actual operation */
3161 op3 = (ip_fw3_opheader *)xbuf;
3162 error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3165 sopt->sopt_valsize = valsize;
3168 * Find and reference command.
3170 error = find_ref_sh(op3->opcode, op3->version, &h);
3175 * Disallow modifications in really-really secure mode, but still allow
3176 * the logging counters to be reset.
3178 if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3179 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3187 * Fill in sockopt_data structure that may be useful for
3188 * IP_FW3 get requests.
3191 if (valsize <= sizeof(xbuf)) {
3192 /* use on-stack buffer */
3194 sdata.ksize = sizeof(xbuf);
3195 sdata.kavail = valsize;
3199 * Determine opcode type/buffer size:
3200 * allocate sliding-window buf for data export or
3201 * contigious buffer for special ops.
3203 if ((h.dir & HDIR_SET) != 0) {
3204 /* Set request. Allocate contigous buffer. */
3205 if (valsize > CTL3_LARGEBUF) {
3212 /* Get request. Allocate sliding window buffer */
3213 size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3215 if (size < valsize) {
3216 /* We have to wire user buffer */
3217 error = vslock(sopt->sopt_val, valsize);
3224 sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3226 sdata.kavail = size;
3230 sdata.sopt_val = sopt->sopt_val;
3231 sdata.valsize = valsize;
3234 * Copy either all request (if valsize < bsize_max)
3235 * or first bsize_max bytes to guarantee most consumers
3236 * that all necessary data has been copied).
3237 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3239 if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3240 sizeof(ip_fw3_opheader))) != 0)
3242 op3 = (ip_fw3_opheader *)sdata.kbuf;
3244 /* Finally, run handler */
3245 error = h.handler(chain, op3, &sdata);
3248 /* Flush state and free buffers */
3250 error = ipfw_flush_sopt_data(&sdata);
3252 ipfw_flush_sopt_data(&sdata);
3255 vsunlock(sdata.sopt_val, valsize);
3257 /* Restore original pointer and set number of bytes written */
3258 sopt->sopt_val = sdata.sopt_val;
3259 sopt->sopt_valsize = sdata.ktotal;
3260 if (sdata.kbuf != xbuf)
3261 free(sdata.kbuf, M_TEMP);
3267 * {set|get}sockopt parser.
3270 ipfw_ctl(struct sockopt *sopt)
3272 #define RULE_MAXSIZE (512*sizeof(u_int32_t))
3274 size_t size, valsize;
3276 struct ip_fw_rule0 *rule;
3277 struct ip_fw_chain *chain;
3278 u_int32_t rulenum[2];
3280 struct rule_check_info ci;
3283 chain = &V_layer3_chain;
3286 /* Save original valsize before it is altered via sooptcopyin() */
3287 valsize = sopt->sopt_valsize;
3288 opt = sopt->sopt_name;
3291 * Disallow modifications in really-really secure mode, but still allow
3292 * the logging counters to be reset.
3294 if (opt == IP_FW_ADD ||
3295 (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3296 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3304 * pass up a copy of the current rules. Static rules
3305 * come first (the last of which has number IPFW_DEFAULT_RULE),
3306 * followed by a possibly empty list of dynamic rule.
3307 * The last dynamic rule has NULL in the "next" field.
3309 * Note that the calculated size is used to bound the
3310 * amount of data returned to the user. The rule set may
3311 * change between calculating the size and returning the
3312 * data in which case we'll just return what fits.
3317 size = chain->static_len;
3318 size += ipfw_dyn_len();
3319 if (size >= sopt->sopt_valsize)
3321 buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3322 IPFW_UH_RLOCK(chain);
3323 /* check again how much space we need */
3324 want = chain->static_len + ipfw_dyn_len();
3326 len = ipfw_getrules(chain, buf, size);
3327 IPFW_UH_RUNLOCK(chain);
3329 error = sooptcopyout(sopt, buf, len);
3337 /* locking is done within del_entry() */
3338 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3342 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3343 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3344 sizeof(struct ip_fw7) );
3346 memset(&ci, 0, sizeof(struct rule_check_info));
3349 * If the size of commands equals RULESIZE7 then we assume
3350 * a FreeBSD7.2 binary is talking to us (set is7=1).
3351 * is7 is persistent so the next 'ipfw list' command
3352 * will use this format.
3353 * NOTE: If wrong version is guessed (this can happen if
3354 * the first ipfw command is 'ipfw [pipe] list')
3355 * the ipfw binary may crash or loop infinitly...
3357 size = sopt->sopt_valsize;
3358 if (size == RULESIZE7(rule)) {
3360 error = convert_rule_to_8(rule);
3365 size = RULESIZE(rule);
3369 error = check_ipfw_rule0(rule, size, &ci);
3371 /* locking is done within add_rule() */
3372 struct ip_fw *krule;
3373 krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3374 ci.urule = (caddr_t)rule;
3377 error = commit_rules(chain, &ci, 1);
3378 if (!error && sopt->sopt_dir == SOPT_GET) {
3380 error = convert_rule_to_7(rule);
3381 size = RULESIZE7(rule);
3387 error = sooptcopyout(sopt, rule, size);
3395 * IP_FW_DEL is used for deleting single rules or sets,
3396 * and (ab)used to atomically manipulate sets. Argument size
3397 * is used to distinguish between the two:
3399 * delete single rule or set of rules,
3400 * or reassign rules (or sets) to a different set.
3401 * 2*sizeof(u_int32_t)
3402 * atomic disable/enable sets.
3403 * first u_int32_t contains sets to be disabled,
3404 * second u_int32_t contains sets to be enabled.
3406 error = sooptcopyin(sopt, rulenum,
3407 2*sizeof(u_int32_t), sizeof(u_int32_t));
3410 size = sopt->sopt_valsize;
3411 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3412 /* delete or reassign, locking done in del_entry() */
3413 error = del_entry(chain, rulenum[0]);
3414 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3415 IPFW_UH_WLOCK(chain);
3417 (V_set_disable | rulenum[0]) & ~rulenum[1] &
3418 ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3419 IPFW_UH_WUNLOCK(chain);
3425 case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3427 if (sopt->sopt_val != 0) {
3428 error = sooptcopyin(sopt, rulenum,
3429 sizeof(u_int32_t), sizeof(u_int32_t));
3433 error = zero_entry(chain, rulenum[0],
3434 sopt->sopt_name == IP_FW_RESETLOG);
3437 /*--- TABLE opcodes ---*/
3438 case IP_FW_TABLE_ADD:
3439 case IP_FW_TABLE_DEL:
3441 ipfw_table_entry ent;
3442 struct tentry_info tei;
3444 struct table_value v;
3446 error = sooptcopyin(sopt, &ent,
3447 sizeof(ent), sizeof(ent));
3451 memset(&tei, 0, sizeof(tei));
3452 tei.paddr = &ent.addr;
3453 tei.subtype = AF_INET;
3454 tei.masklen = ent.masklen;
3455 ipfw_import_table_value_legacy(ent.value, &v);
3457 memset(&ti, 0, sizeof(ti));
3459 ti.type = IPFW_TABLE_CIDR;
3461 error = (opt == IP_FW_TABLE_ADD) ?
3462 add_table_entry(chain, &ti, &tei, 0, 1) :
3463 del_table_entry(chain, &ti, &tei, 0, 1);
3468 case IP_FW_TABLE_FLUSH:
3473 error = sooptcopyin(sopt, &tbl,
3474 sizeof(tbl), sizeof(tbl));
3477 memset(&ti, 0, sizeof(ti));
3479 error = flush_table(chain, &ti);
3483 case IP_FW_TABLE_GETSIZE:
3488 if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3491 memset(&ti, 0, sizeof(ti));
3494 error = ipfw_count_table(chain, &ti, &cnt);
3495 IPFW_RUNLOCK(chain);
3498 error = sooptcopyout(sopt, &cnt, sizeof(cnt));
3502 case IP_FW_TABLE_LIST:
3507 if (sopt->sopt_valsize < sizeof(*tbl)) {
3511 size = sopt->sopt_valsize;
3512 tbl = malloc(size, M_TEMP, M_WAITOK);
3513 error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
3518 tbl->size = (size - sizeof(*tbl)) /
3519 sizeof(ipfw_table_entry);
3520 memset(&ti, 0, sizeof(ti));
3523 error = ipfw_dump_table_legacy(chain, &ti, tbl);
3524 IPFW_RUNLOCK(chain);
3529 error = sooptcopyout(sopt, tbl, size);
3534 /*--- NAT operations are protected by the IPFW_LOCK ---*/
3536 if (IPFW_NAT_LOADED)
3537 error = ipfw_nat_cfg_ptr(sopt);
3539 printf("IP_FW_NAT_CFG: %s\n",
3540 "ipfw_nat not present, please load it");
3546 if (IPFW_NAT_LOADED)
3547 error = ipfw_nat_del_ptr(sopt);
3549 printf("IP_FW_NAT_DEL: %s\n",
3550 "ipfw_nat not present, please load it");
3555 case IP_FW_NAT_GET_CONFIG:
3556 if (IPFW_NAT_LOADED)
3557 error = ipfw_nat_get_cfg_ptr(sopt);
3559 printf("IP_FW_NAT_GET_CFG: %s\n",
3560 "ipfw_nat not present, please load it");
3565 case IP_FW_NAT_GET_LOG:
3566 if (IPFW_NAT_LOADED)
3567 error = ipfw_nat_get_log_ptr(sopt);
3569 printf("IP_FW_NAT_GET_LOG: %s\n",
3570 "ipfw_nat not present, please load it");
3576 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
3583 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
3585 /* Functions to convert rules 7.2 <==> 8.0 */
3587 convert_rule_to_7(struct ip_fw_rule0 *rule)
3589 /* Used to modify original rule */
3590 struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
3591 /* copy of original rule, version 8 */
3592 struct ip_fw_rule0 *tmp;
3594 /* Used to copy commands */
3595 ipfw_insn *ccmd, *dst;
3596 int ll = 0, ccmdlen = 0;
3598 tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
3600 return 1; //XXX error
3602 bcopy(rule, tmp, RULE_MAXSIZE);
3605 //rule7->_pad = tmp->_pad;
3606 rule7->set = tmp->set;
3607 rule7->rulenum = tmp->rulenum;
3608 rule7->cmd_len = tmp->cmd_len;
3609 rule7->act_ofs = tmp->act_ofs;
3610 rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
3611 rule7->cmd_len = tmp->cmd_len;
3612 rule7->pcnt = tmp->pcnt;
3613 rule7->bcnt = tmp->bcnt;
3614 rule7->timestamp = tmp->timestamp;
3617 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
3618 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
3619 ccmdlen = F_LEN(ccmd);
3621 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
3623 if (dst->opcode > O_NAT)
3624 /* O_REASS doesn't exists in 7.2 version, so
3625 * decrement opcode if it is after O_REASS
3630 printf("ipfw: opcode %d size truncated\n",
3641 convert_rule_to_8(struct ip_fw_rule0 *rule)
3643 /* Used to modify original rule */
3644 struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
3646 /* Used to copy commands */
3647 ipfw_insn *ccmd, *dst;
3648 int ll = 0, ccmdlen = 0;
3650 /* Copy of original rule */
3651 struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
3653 return 1; //XXX error
3656 bcopy(rule7, tmp, RULE_MAXSIZE);
3658 for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
3659 ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
3660 ccmdlen = F_LEN(ccmd);
3662 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
3664 if (dst->opcode > O_NAT)
3665 /* O_REASS doesn't exists in 7.2 version, so
3666 * increment opcode if it is after O_REASS
3671 printf("ipfw: opcode %d size truncated\n",
3677 rule->_pad = tmp->_pad;
3678 rule->set = tmp->set;
3679 rule->rulenum = tmp->rulenum;
3680 rule->cmd_len = tmp->cmd_len;
3681 rule->act_ofs = tmp->act_ofs;
3682 rule->next_rule = (struct ip_fw *)tmp->next_rule;
3683 rule->cmd_len = tmp->cmd_len;
3684 rule->id = 0; /* XXX see if is ok = 0 */
3685 rule->pcnt = tmp->pcnt;
3686 rule->bcnt = tmp->bcnt;
3687 rule->timestamp = tmp->timestamp;
3699 ipfw_init_srv(struct ip_fw_chain *ch)
3702 ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
3703 ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
3704 M_IPFW, M_WAITOK | M_ZERO);
3708 ipfw_destroy_srv(struct ip_fw_chain *ch)
3711 free(ch->srvstate, M_IPFW);
3712 ipfw_objhash_destroy(ch->srvmap);
3716 * Allocate new bitmask which can be used to enlarge/shrink
3717 * named instance index.
3720 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
3726 KASSERT((items % BLOCK_ITEMS) == 0,
3727 ("bitmask size needs to power of 2 and greater or equal to %zu",
3730 max_blocks = items / BLOCK_ITEMS;
3732 idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
3733 /* Mark all as free */
3734 memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
3735 *idx_mask &= ~(u_long)1; /* Skip index 0 */
3738 *pblocks = max_blocks;
3742 * Copy current bitmask index to new one.
3745 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
3747 int old_blocks, new_blocks;
3748 u_long *old_idx, *new_idx;
3751 old_idx = ni->idx_mask;
3752 old_blocks = ni->max_blocks;
3754 new_blocks = *blocks;
3756 for (i = 0; i < IPFW_MAX_SETS; i++) {
3757 memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
3758 old_blocks * sizeof(u_long));
3763 * Swaps current @ni index with new one.
3766 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
3771 old_idx = ni->idx_mask;
3772 old_blocks = ni->max_blocks;
3774 ni->idx_mask = *idx;
3775 ni->max_blocks = *blocks;
3777 /* Save old values */
3779 *blocks = old_blocks;
3783 ipfw_objhash_bitmap_free(void *idx, int blocks)
3790 * Creates named hash instance.
3791 * Must be called without holding any locks.
3792 * Return pointer to new instance.
3794 struct namedobj_instance *
3795 ipfw_objhash_create(uint32_t items)
3797 struct namedobj_instance *ni;
3801 size = sizeof(struct namedobj_instance) +
3802 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
3803 sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
3805 ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
3806 ni->nn_size = NAMEDOBJ_HASH_SIZE;
3807 ni->nv_size = NAMEDOBJ_HASH_SIZE;
3809 ni->names = (struct namedobjects_head *)(ni +1);
3810 ni->values = &ni->names[ni->nn_size];
3812 for (i = 0; i < ni->nn_size; i++)
3813 TAILQ_INIT(&ni->names[i]);
3815 for (i = 0; i < ni->nv_size; i++)
3816 TAILQ_INIT(&ni->values[i]);
3818 /* Set default hashing/comparison functions */
3819 ni->hash_f = objhash_hash_name;
3820 ni->cmp_f = objhash_cmp_name;
3822 /* Allocate bitmask separately due to possible resize */
3823 ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
3829 ipfw_objhash_destroy(struct namedobj_instance *ni)
3832 free(ni->idx_mask, M_IPFW);
3837 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
3838 objhash_cmp_f *cmp_f)
3841 ni->hash_f = hash_f;
3846 objhash_hash_name(struct namedobj_instance *ni, void *name, uint32_t set)
3849 return (fnv_32_str((char *)name, FNV1_32_INIT));
3853 objhash_cmp_name(struct named_object *no, void *name, uint32_t set)
3856 if ((strcmp(no->name, (char *)name) == 0) && (no->set == set))
3863 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
3867 v = val % (ni->nv_size - 1);
3872 struct named_object *
3873 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
3875 struct named_object *no;
3878 hash = ni->hash_f(ni, name, set) % ni->nn_size;
3880 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
3881 if (ni->cmp_f(no, name, set) == 0)
3889 * Find named object by name, considering also its TLV type.
3891 struct named_object *
3892 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
3893 uint32_t type, char *name)
3895 struct named_object *no;
3898 hash = ni->hash_f(ni, name, set) % ni->nn_size;
3900 TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
3901 if (ni->cmp_f(no, name, set) == 0 && no->etlv == type)
3908 struct named_object *
3909 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
3911 struct named_object *no;
3914 hash = objhash_hash_idx(ni, kidx);
3916 TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
3917 if (no->kidx == kidx)
3925 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
3926 struct named_object *b)
3929 if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
3936 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
3940 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
3941 TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
3943 hash = objhash_hash_idx(ni, no->kidx);
3944 TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
3950 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
3954 hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
3955 TAILQ_REMOVE(&ni->names[hash], no, nn_next);
3957 hash = objhash_hash_idx(ni, no->kidx);
3958 TAILQ_REMOVE(&ni->values[hash], no, nv_next);
3964 ipfw_objhash_count(struct namedobj_instance *ni)
3971 * Runs @func for each found named object.
3972 * It is safe to delete objects from callback
3975 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
3977 struct named_object *no, *no_tmp;
3980 for (i = 0; i < ni->nn_size; i++) {
3981 TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp)
3987 * Removes index from given set.
3988 * Returns 0 on success.
3991 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
3996 i = idx / BLOCK_ITEMS;
3997 v = idx % BLOCK_ITEMS;
3999 if (i >= ni->max_blocks)
4002 mask = &ni->idx_mask[i];
4004 if ((*mask & ((u_long)1 << v)) != 0)
4008 *mask |= (u_long)1 << v;
4010 /* Update free offset */
4011 if (ni->free_off[0] > i)
4012 ni->free_off[0] = i;
4018 * Allocate new index in given instance and stores in in @pidx.
4019 * Returns 0 on success.
4022 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4024 struct namedobj_instance *ni;
4028 ni = (struct namedobj_instance *)n;
4030 off = ni->free_off[0];
4031 mask = &ni->idx_mask[off];
4033 for (i = off; i < ni->max_blocks; i++, mask++) {
4034 if ((v = ffsl(*mask)) == 0)
4038 *mask &= ~ ((u_long)1 << (v - 1));
4040 ni->free_off[0] = i;
4042 v = BLOCK_ITEMS * i + v - 1;