xref: /freebsd/sys/netpfil/ipfw/ip_fw_sockopt.c (revision 0957b409)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
5  * Copyright (c) 2014 Yandex LLC
6  * Copyright (c) 2014 Alexander V. Chernikov
7  *
8  * Supported by: Valeria Paoli
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 /*
36  * Control socket and rule management routines for ipfw.
37  * Control is currently implemented via IP_FW3 setsockopt() code.
38  */
39 
40 #include "opt_ipfw.h"
41 #include "opt_inet.h"
42 #ifndef INET
43 #error IPFIREWALL requires INET.
44 #endif /* INET */
45 #include "opt_inet6.h"
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>	/* struct m_tag used by nested headers */
51 #include <sys/kernel.h>
52 #include <sys/lock.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/rwlock.h>
56 #include <sys/rmlock.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sysctl.h>
60 #include <sys/syslog.h>
61 #include <sys/fnv_hash.h>
62 #include <net/if.h>
63 #include <net/route.h>
64 #include <net/vnet.h>
65 #include <vm/vm.h>
66 #include <vm/vm_extern.h>
67 
68 #include <netinet/in.h>
69 #include <netinet/ip_var.h> /* hooks */
70 #include <netinet/ip_fw.h>
71 
72 #include <netpfil/ipfw/ip_fw_private.h>
73 #include <netpfil/ipfw/ip_fw_table.h>
74 
75 #ifdef MAC
76 #include <security/mac/mac_framework.h>
77 #endif
78 
79 static int ipfw_ctl(struct sockopt *sopt);
80 static int check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len,
81     struct rule_check_info *ci);
82 static int check_ipfw_rule1(struct ip_fw_rule *rule, int size,
83     struct rule_check_info *ci);
84 static int check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
85     struct rule_check_info *ci);
86 static int rewrite_rule_uidx(struct ip_fw_chain *chain,
87     struct rule_check_info *ci);
88 
89 #define	NAMEDOBJ_HASH_SIZE	32
90 
91 struct namedobj_instance {
92 	struct namedobjects_head	*names;
93 	struct namedobjects_head	*values;
94 	uint32_t nn_size;		/* names hash size */
95 	uint32_t nv_size;		/* number hash size */
96 	u_long *idx_mask;		/* used items bitmask */
97 	uint32_t max_blocks;		/* number of "long" blocks in bitmask */
98 	uint32_t count;			/* number of items */
99 	uint16_t free_off[IPFW_MAX_SETS];	/* first possible free offset */
100 	objhash_hash_f	*hash_f;
101 	objhash_cmp_f	*cmp_f;
102 };
103 #define	BLOCK_ITEMS	(8 * sizeof(u_long))	/* Number of items for ffsl() */
104 
105 static uint32_t objhash_hash_name(struct namedobj_instance *ni,
106     const void *key, uint32_t kopt);
107 static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val);
108 static int objhash_cmp_name(struct named_object *no, const void *name,
109     uint32_t set);
110 
111 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
112 
113 static int dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
114     struct sockopt_data *sd);
115 static int add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
116     struct sockopt_data *sd);
117 static int del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
118     struct sockopt_data *sd);
119 static int clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
120     struct sockopt_data *sd);
121 static int move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
122     struct sockopt_data *sd);
123 static int manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
124     struct sockopt_data *sd);
125 static int dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
126     struct sockopt_data *sd);
127 static int dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
128     struct sockopt_data *sd);
129 
130 /* ctl3 handler data */
131 struct mtx ctl3_lock;
132 #define	CTL3_LOCK_INIT()	mtx_init(&ctl3_lock, "ctl3_lock", NULL, MTX_DEF)
133 #define	CTL3_LOCK_DESTROY()	mtx_destroy(&ctl3_lock)
134 #define	CTL3_LOCK()		mtx_lock(&ctl3_lock)
135 #define	CTL3_UNLOCK()		mtx_unlock(&ctl3_lock)
136 
137 static struct ipfw_sopt_handler *ctl3_handlers;
138 static size_t ctl3_hsize;
139 static uint64_t ctl3_refct, ctl3_gencnt;
140 #define	CTL3_SMALLBUF	4096			/* small page-size write buffer */
141 #define	CTL3_LARGEBUF	16 * 1024 * 1024	/* handle large rulesets */
142 
143 static int ipfw_flush_sopt_data(struct sockopt_data *sd);
144 
145 static struct ipfw_sopt_handler	scodes[] = {
146 	{ IP_FW_XGET,		0,	HDIR_GET,	dump_config },
147 	{ IP_FW_XADD,		0,	HDIR_BOTH,	add_rules },
148 	{ IP_FW_XDEL,		0,	HDIR_BOTH,	del_rules },
149 	{ IP_FW_XZERO,		0,	HDIR_SET,	clear_rules },
150 	{ IP_FW_XRESETLOG,	0,	HDIR_SET,	clear_rules },
151 	{ IP_FW_XMOVE,		0,	HDIR_SET,	move_rules },
152 	{ IP_FW_SET_SWAP,	0,	HDIR_SET,	manage_sets },
153 	{ IP_FW_SET_MOVE,	0,	HDIR_SET,	manage_sets },
154 	{ IP_FW_SET_ENABLE,	0,	HDIR_SET,	manage_sets },
155 	{ IP_FW_DUMP_SOPTCODES,	0,	HDIR_GET,	dump_soptcodes },
156 	{ IP_FW_DUMP_SRVOBJECTS,0,	HDIR_GET,	dump_srvobjects },
157 };
158 
159 static int
160 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule);
161 static struct opcode_obj_rewrite *find_op_rw(ipfw_insn *cmd,
162     uint16_t *puidx, uint8_t *ptype);
163 static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
164     struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti);
165 static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd,
166     struct tid_info *ti, struct obj_idx *pidx, int *unresolved);
167 static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule);
168 static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd,
169     struct obj_idx *oib, struct obj_idx *end);
170 static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
171     struct sockopt_data *sd);
172 
173 /*
174  * Opcode object rewriter variables
175  */
176 struct opcode_obj_rewrite *ctl3_rewriters;
177 static size_t ctl3_rsize;
178 
179 /*
180  * static variables followed by global ones
181  */
182 
183 VNET_DEFINE_STATIC(uma_zone_t, ipfw_cntr_zone);
184 #define	V_ipfw_cntr_zone		VNET(ipfw_cntr_zone)
185 
186 void
187 ipfw_init_counters()
188 {
189 
190 	V_ipfw_cntr_zone = uma_zcreate("IPFW counters",
191 	    IPFW_RULE_CNTR_SIZE, NULL, NULL, NULL, NULL,
192 	    UMA_ALIGN_PTR, UMA_ZONE_PCPU);
193 }
194 
195 void
196 ipfw_destroy_counters()
197 {
198 
199 	uma_zdestroy(V_ipfw_cntr_zone);
200 }
201 
202 struct ip_fw *
203 ipfw_alloc_rule(struct ip_fw_chain *chain, size_t rulesize)
204 {
205 	struct ip_fw *rule;
206 
207 	rule = malloc(rulesize, M_IPFW, M_WAITOK | M_ZERO);
208 	rule->cntr = uma_zalloc_pcpu(V_ipfw_cntr_zone, M_WAITOK | M_ZERO);
209 	rule->refcnt = 1;
210 
211 	return (rule);
212 }
213 
214 void
215 ipfw_free_rule(struct ip_fw *rule)
216 {
217 
218 	/*
219 	 * We don't release refcnt here, since this function
220 	 * can be called without any locks held. The caller
221 	 * must release reference under IPFW_UH_WLOCK, and then
222 	 * call this function if refcount becomes 1.
223 	 */
224 	if (rule->refcnt > 1)
225 		return;
226 	uma_zfree_pcpu(V_ipfw_cntr_zone, rule->cntr);
227 	free(rule, M_IPFW);
228 }
229 
230 
231 /*
232  * Find the smallest rule >= key, id.
233  * We could use bsearch but it is so simple that we code it directly
234  */
235 int
236 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
237 {
238 	int i, lo, hi;
239 	struct ip_fw *r;
240 
241   	for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
242 		i = (lo + hi) / 2;
243 		r = chain->map[i];
244 		if (r->rulenum < key)
245 			lo = i + 1;	/* continue from the next one */
246 		else if (r->rulenum > key)
247 			hi = i;		/* this might be good */
248 		else if (r->id < id)
249 			lo = i + 1;	/* continue from the next one */
250 		else /* r->id >= id */
251 			hi = i;		/* this might be good */
252 	}
253 	return hi;
254 }
255 
256 /*
257  * Builds skipto cache on rule set @map.
258  */
259 static void
260 update_skipto_cache(struct ip_fw_chain *chain, struct ip_fw **map)
261 {
262 	int *smap, rulenum;
263 	int i, mi;
264 
265 	IPFW_UH_WLOCK_ASSERT(chain);
266 
267 	mi = 0;
268 	rulenum = map[mi]->rulenum;
269 	smap = chain->idxmap_back;
270 
271 	if (smap == NULL)
272 		return;
273 
274 	for (i = 0; i < 65536; i++) {
275 		smap[i] = mi;
276 		/* Use the same rule index until i < rulenum */
277 		if (i != rulenum || i == 65535)
278 			continue;
279 		/* Find next rule with num > i */
280 		rulenum = map[++mi]->rulenum;
281 		while (rulenum == i)
282 			rulenum = map[++mi]->rulenum;
283 	}
284 }
285 
286 /*
287  * Swaps prepared (backup) index with current one.
288  */
289 static void
290 swap_skipto_cache(struct ip_fw_chain *chain)
291 {
292 	int *map;
293 
294 	IPFW_UH_WLOCK_ASSERT(chain);
295 	IPFW_WLOCK_ASSERT(chain);
296 
297 	map = chain->idxmap;
298 	chain->idxmap = chain->idxmap_back;
299 	chain->idxmap_back = map;
300 }
301 
302 /*
303  * Allocate and initialize skipto cache.
304  */
305 void
306 ipfw_init_skipto_cache(struct ip_fw_chain *chain)
307 {
308 	int *idxmap, *idxmap_back;
309 
310 	idxmap = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK | M_ZERO);
311 	idxmap_back = malloc(65536 * sizeof(int), M_IPFW, M_WAITOK);
312 
313 	/*
314 	 * Note we may be called at any time after initialization,
315 	 * for example, on first skipto rule, so we need to
316 	 * provide valid chain->idxmap on return
317 	 */
318 
319 	IPFW_UH_WLOCK(chain);
320 	if (chain->idxmap != NULL) {
321 		IPFW_UH_WUNLOCK(chain);
322 		free(idxmap, M_IPFW);
323 		free(idxmap_back, M_IPFW);
324 		return;
325 	}
326 
327 	/* Set backup pointer first to permit building cache */
328 	chain->idxmap_back = idxmap_back;
329 	update_skipto_cache(chain, chain->map);
330 	IPFW_WLOCK(chain);
331 	/* It is now safe to set chain->idxmap ptr */
332 	chain->idxmap = idxmap;
333 	swap_skipto_cache(chain);
334 	IPFW_WUNLOCK(chain);
335 	IPFW_UH_WUNLOCK(chain);
336 }
337 
338 /*
339  * Destroys skipto cache.
340  */
341 void
342 ipfw_destroy_skipto_cache(struct ip_fw_chain *chain)
343 {
344 
345 	if (chain->idxmap != NULL)
346 		free(chain->idxmap, M_IPFW);
347 	if (chain->idxmap != NULL)
348 		free(chain->idxmap_back, M_IPFW);
349 }
350 
351 
352 /*
353  * allocate a new map, returns the chain locked. extra is the number
354  * of entries to add or delete.
355  */
356 static struct ip_fw **
357 get_map(struct ip_fw_chain *chain, int extra, int locked)
358 {
359 
360 	for (;;) {
361 		struct ip_fw **map;
362 		u_int i, mflags;
363 
364 		mflags = M_ZERO | ((locked != 0) ? M_NOWAIT : M_WAITOK);
365 
366 		i = chain->n_rules + extra;
367 		map = malloc(i * sizeof(struct ip_fw *), M_IPFW, mflags);
368 		if (map == NULL) {
369 			printf("%s: cannot allocate map\n", __FUNCTION__);
370 			return NULL;
371 		}
372 		if (!locked)
373 			IPFW_UH_WLOCK(chain);
374 		if (i >= chain->n_rules + extra) /* good */
375 			return map;
376 		/* otherwise we lost the race, free and retry */
377 		if (!locked)
378 			IPFW_UH_WUNLOCK(chain);
379 		free(map, M_IPFW);
380 	}
381 }
382 
383 /*
384  * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
385  */
386 static struct ip_fw **
387 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
388 {
389 	struct ip_fw **old_map;
390 
391 	IPFW_WLOCK(chain);
392 	chain->id++;
393 	chain->n_rules = new_len;
394 	old_map = chain->map;
395 	chain->map = new_map;
396 	swap_skipto_cache(chain);
397 	IPFW_WUNLOCK(chain);
398 	return old_map;
399 }
400 
401 
402 static void
403 export_cntr1_base(struct ip_fw *krule, struct ip_fw_bcounter *cntr)
404 {
405 	struct timeval boottime;
406 
407 	cntr->size = sizeof(*cntr);
408 
409 	if (krule->cntr != NULL) {
410 		cntr->pcnt = counter_u64_fetch(krule->cntr);
411 		cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
412 		cntr->timestamp = krule->timestamp;
413 	}
414 	if (cntr->timestamp > 0) {
415 		getboottime(&boottime);
416 		cntr->timestamp += boottime.tv_sec;
417 	}
418 }
419 
420 static void
421 export_cntr0_base(struct ip_fw *krule, struct ip_fw_bcounter0 *cntr)
422 {
423 	struct timeval boottime;
424 
425 	if (krule->cntr != NULL) {
426 		cntr->pcnt = counter_u64_fetch(krule->cntr);
427 		cntr->bcnt = counter_u64_fetch(krule->cntr + 1);
428 		cntr->timestamp = krule->timestamp;
429 	}
430 	if (cntr->timestamp > 0) {
431 		getboottime(&boottime);
432 		cntr->timestamp += boottime.tv_sec;
433 	}
434 }
435 
436 /*
437  * Copies rule @urule from v1 userland format (current).
438  * to kernel @krule.
439  * Assume @krule is zeroed.
440  */
441 static void
442 import_rule1(struct rule_check_info *ci)
443 {
444 	struct ip_fw_rule *urule;
445 	struct ip_fw *krule;
446 
447 	urule = (struct ip_fw_rule *)ci->urule;
448 	krule = (struct ip_fw *)ci->krule;
449 
450 	/* copy header */
451 	krule->act_ofs = urule->act_ofs;
452 	krule->cmd_len = urule->cmd_len;
453 	krule->rulenum = urule->rulenum;
454 	krule->set = urule->set;
455 	krule->flags = urule->flags;
456 
457 	/* Save rulenum offset */
458 	ci->urule_numoff = offsetof(struct ip_fw_rule, rulenum);
459 
460 	/* Copy opcodes */
461 	memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
462 }
463 
464 /*
465  * Export rule into v1 format (Current).
466  * Layout:
467  * [ ipfw_obj_tlv(IPFW_TLV_RULE_ENT)
468  *     [ ip_fw_rule ] OR
469  *     [ ip_fw_bcounter ip_fw_rule] (depends on rcntrs).
470  * ]
471  * Assume @data is zeroed.
472  */
473 static void
474 export_rule1(struct ip_fw *krule, caddr_t data, int len, int rcntrs)
475 {
476 	struct ip_fw_bcounter *cntr;
477 	struct ip_fw_rule *urule;
478 	ipfw_obj_tlv *tlv;
479 
480 	/* Fill in TLV header */
481 	tlv = (ipfw_obj_tlv *)data;
482 	tlv->type = IPFW_TLV_RULE_ENT;
483 	tlv->length = len;
484 
485 	if (rcntrs != 0) {
486 		/* Copy counters */
487 		cntr = (struct ip_fw_bcounter *)(tlv + 1);
488 		urule = (struct ip_fw_rule *)(cntr + 1);
489 		export_cntr1_base(krule, cntr);
490 	} else
491 		urule = (struct ip_fw_rule *)(tlv + 1);
492 
493 	/* copy header */
494 	urule->act_ofs = krule->act_ofs;
495 	urule->cmd_len = krule->cmd_len;
496 	urule->rulenum = krule->rulenum;
497 	urule->set = krule->set;
498 	urule->flags = krule->flags;
499 	urule->id = krule->id;
500 
501 	/* Copy opcodes */
502 	memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
503 }
504 
505 
506 /*
507  * Copies rule @urule from FreeBSD8 userland format (v0)
508  * to kernel @krule.
509  * Assume @krule is zeroed.
510  */
511 static void
512 import_rule0(struct rule_check_info *ci)
513 {
514 	struct ip_fw_rule0 *urule;
515 	struct ip_fw *krule;
516 	int cmdlen, l;
517 	ipfw_insn *cmd;
518 	ipfw_insn_limit *lcmd;
519 	ipfw_insn_if *cmdif;
520 
521 	urule = (struct ip_fw_rule0 *)ci->urule;
522 	krule = (struct ip_fw *)ci->krule;
523 
524 	/* copy header */
525 	krule->act_ofs = urule->act_ofs;
526 	krule->cmd_len = urule->cmd_len;
527 	krule->rulenum = urule->rulenum;
528 	krule->set = urule->set;
529 	if ((urule->_pad & 1) != 0)
530 		krule->flags |= IPFW_RULE_NOOPT;
531 
532 	/* Save rulenum offset */
533 	ci->urule_numoff = offsetof(struct ip_fw_rule0, rulenum);
534 
535 	/* Copy opcodes */
536 	memcpy(krule->cmd, urule->cmd, krule->cmd_len * sizeof(uint32_t));
537 
538 	/*
539 	 * Alter opcodes:
540 	 * 1) convert tablearg value from 65535 to 0
541 	 * 2) Add high bit to O_SETFIB/O_SETDSCP values (to make room
542 	 *    for targ).
543 	 * 3) convert table number in iface opcodes to u16
544 	 * 4) convert old `nat global` into new 65535
545 	 */
546 	l = krule->cmd_len;
547 	cmd = krule->cmd;
548 	cmdlen = 0;
549 
550 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
551 		cmdlen = F_LEN(cmd);
552 
553 		switch (cmd->opcode) {
554 		/* Opcodes supporting tablearg */
555 		case O_TAG:
556 		case O_TAGGED:
557 		case O_PIPE:
558 		case O_QUEUE:
559 		case O_DIVERT:
560 		case O_TEE:
561 		case O_SKIPTO:
562 		case O_CALLRETURN:
563 		case O_NETGRAPH:
564 		case O_NGTEE:
565 		case O_NAT:
566 			if (cmd->arg1 == IP_FW_TABLEARG)
567 				cmd->arg1 = IP_FW_TARG;
568 			else if (cmd->arg1 == 0)
569 				cmd->arg1 = IP_FW_NAT44_GLOBAL;
570 			break;
571 		case O_SETFIB:
572 		case O_SETDSCP:
573 			if (cmd->arg1 == IP_FW_TABLEARG)
574 				cmd->arg1 = IP_FW_TARG;
575 			else
576 				cmd->arg1 |= 0x8000;
577 			break;
578 		case O_LIMIT:
579 			lcmd = (ipfw_insn_limit *)cmd;
580 			if (lcmd->conn_limit == IP_FW_TABLEARG)
581 				lcmd->conn_limit = IP_FW_TARG;
582 			break;
583 		/* Interface tables */
584 		case O_XMIT:
585 		case O_RECV:
586 		case O_VIA:
587 			/* Interface table, possibly */
588 			cmdif = (ipfw_insn_if *)cmd;
589 			if (cmdif->name[0] != '\1')
590 				break;
591 
592 			cmdif->p.kidx = (uint16_t)cmdif->p.glob;
593 			break;
594 		}
595 	}
596 }
597 
598 /*
599  * Copies rule @krule from kernel to FreeBSD8 userland format (v0)
600  */
601 static void
602 export_rule0(struct ip_fw *krule, struct ip_fw_rule0 *urule, int len)
603 {
604 	int cmdlen, l;
605 	ipfw_insn *cmd;
606 	ipfw_insn_limit *lcmd;
607 	ipfw_insn_if *cmdif;
608 
609 	/* copy header */
610 	memset(urule, 0, len);
611 	urule->act_ofs = krule->act_ofs;
612 	urule->cmd_len = krule->cmd_len;
613 	urule->rulenum = krule->rulenum;
614 	urule->set = krule->set;
615 	if ((krule->flags & IPFW_RULE_NOOPT) != 0)
616 		urule->_pad |= 1;
617 
618 	/* Copy opcodes */
619 	memcpy(urule->cmd, krule->cmd, krule->cmd_len * sizeof(uint32_t));
620 
621 	/* Export counters */
622 	export_cntr0_base(krule, (struct ip_fw_bcounter0 *)&urule->pcnt);
623 
624 	/*
625 	 * Alter opcodes:
626 	 * 1) convert tablearg value from 0 to 65535
627 	 * 2) Remove highest bit from O_SETFIB/O_SETDSCP values.
628 	 * 3) convert table number in iface opcodes to int
629 	 */
630 	l = urule->cmd_len;
631 	cmd = urule->cmd;
632 	cmdlen = 0;
633 
634 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
635 		cmdlen = F_LEN(cmd);
636 
637 		switch (cmd->opcode) {
638 		/* Opcodes supporting tablearg */
639 		case O_TAG:
640 		case O_TAGGED:
641 		case O_PIPE:
642 		case O_QUEUE:
643 		case O_DIVERT:
644 		case O_TEE:
645 		case O_SKIPTO:
646 		case O_CALLRETURN:
647 		case O_NETGRAPH:
648 		case O_NGTEE:
649 		case O_NAT:
650 			if (cmd->arg1 == IP_FW_TARG)
651 				cmd->arg1 = IP_FW_TABLEARG;
652 			else if (cmd->arg1 == IP_FW_NAT44_GLOBAL)
653 				cmd->arg1 = 0;
654 			break;
655 		case O_SETFIB:
656 		case O_SETDSCP:
657 			if (cmd->arg1 == IP_FW_TARG)
658 				cmd->arg1 = IP_FW_TABLEARG;
659 			else
660 				cmd->arg1 &= ~0x8000;
661 			break;
662 		case O_LIMIT:
663 			lcmd = (ipfw_insn_limit *)cmd;
664 			if (lcmd->conn_limit == IP_FW_TARG)
665 				lcmd->conn_limit = IP_FW_TABLEARG;
666 			break;
667 		/* Interface tables */
668 		case O_XMIT:
669 		case O_RECV:
670 		case O_VIA:
671 			/* Interface table, possibly */
672 			cmdif = (ipfw_insn_if *)cmd;
673 			if (cmdif->name[0] != '\1')
674 				break;
675 
676 			cmdif->p.glob = cmdif->p.kidx;
677 			break;
678 		}
679 	}
680 }
681 
682 /*
683  * Add new rule(s) to the list possibly creating rule number for each.
684  * Update the rule_number in the input struct so the caller knows it as well.
685  * Must be called without IPFW_UH held
686  */
687 static int
688 commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count)
689 {
690 	int error, i, insert_before, tcount;
691 	uint16_t rulenum, *pnum;
692 	struct rule_check_info *ci;
693 	struct ip_fw *krule;
694 	struct ip_fw **map;	/* the new array of pointers */
695 
696 	/* Check if we need to do table/obj index remap */
697 	tcount = 0;
698 	for (ci = rci, i = 0; i < count; ci++, i++) {
699 		if (ci->object_opcodes == 0)
700 			continue;
701 
702 		/*
703 		 * Rule has some object opcodes.
704 		 * We need to find (and create non-existing)
705 		 * kernel objects, and reference existing ones.
706 		 */
707 		error = rewrite_rule_uidx(chain, ci);
708 		if (error != 0) {
709 
710 			/*
711 			 * rewrite failed, state for current rule
712 			 * has been reverted. Check if we need to
713 			 * revert more.
714 			 */
715 			if (tcount > 0) {
716 
717 				/*
718 				 * We have some more table rules
719 				 * we need to rollback.
720 				 */
721 
722 				IPFW_UH_WLOCK(chain);
723 				while (ci != rci) {
724 					ci--;
725 					if (ci->object_opcodes == 0)
726 						continue;
727 					unref_rule_objects(chain,ci->krule);
728 
729 				}
730 				IPFW_UH_WUNLOCK(chain);
731 
732 			}
733 
734 			return (error);
735 		}
736 
737 		tcount++;
738 	}
739 
740 	/* get_map returns with IPFW_UH_WLOCK if successful */
741 	map = get_map(chain, count, 0 /* not locked */);
742 	if (map == NULL) {
743 		if (tcount > 0) {
744 			/* Unbind tables */
745 			IPFW_UH_WLOCK(chain);
746 			for (ci = rci, i = 0; i < count; ci++, i++) {
747 				if (ci->object_opcodes == 0)
748 					continue;
749 
750 				unref_rule_objects(chain, ci->krule);
751 			}
752 			IPFW_UH_WUNLOCK(chain);
753 		}
754 
755 		return (ENOSPC);
756 	}
757 
758 	if (V_autoinc_step < 1)
759 		V_autoinc_step = 1;
760 	else if (V_autoinc_step > 1000)
761 		V_autoinc_step = 1000;
762 
763 	/* FIXME: Handle count > 1 */
764 	ci = rci;
765 	krule = ci->krule;
766 	rulenum = krule->rulenum;
767 
768 	/* find the insertion point, we will insert before */
769 	insert_before = rulenum ? rulenum + 1 : IPFW_DEFAULT_RULE;
770 	i = ipfw_find_rule(chain, insert_before, 0);
771 	/* duplicate first part */
772 	if (i > 0)
773 		bcopy(chain->map, map, i * sizeof(struct ip_fw *));
774 	map[i] = krule;
775 	/* duplicate remaining part, we always have the default rule */
776 	bcopy(chain->map + i, map + i + 1,
777 		sizeof(struct ip_fw *) *(chain->n_rules - i));
778 	if (rulenum == 0) {
779 		/* Compute rule number and write it back */
780 		rulenum = i > 0 ? map[i-1]->rulenum : 0;
781 		if (rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
782 			rulenum += V_autoinc_step;
783 		krule->rulenum = rulenum;
784 		/* Save number to userland rule */
785 		pnum = (uint16_t *)((caddr_t)ci->urule + ci->urule_numoff);
786 		*pnum = rulenum;
787 	}
788 
789 	krule->id = chain->id + 1;
790 	update_skipto_cache(chain, map);
791 	map = swap_map(chain, map, chain->n_rules + 1);
792 	chain->static_len += RULEUSIZE0(krule);
793 	IPFW_UH_WUNLOCK(chain);
794 	if (map)
795 		free(map, M_IPFW);
796 	return (0);
797 }
798 
799 int
800 ipfw_add_protected_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
801     int locked)
802 {
803 	struct ip_fw **map;
804 
805 	map = get_map(chain, 1, locked);
806 	if (map == NULL)
807 		return (ENOMEM);
808 	if (chain->n_rules > 0)
809 		bcopy(chain->map, map,
810 		    chain->n_rules * sizeof(struct ip_fw *));
811 	map[chain->n_rules] = rule;
812 	rule->rulenum = IPFW_DEFAULT_RULE;
813 	rule->set = RESVD_SET;
814 	rule->id = chain->id + 1;
815 	/* We add rule in the end of chain, no need to update skipto cache */
816 	map = swap_map(chain, map, chain->n_rules + 1);
817 	chain->static_len += RULEUSIZE0(rule);
818 	IPFW_UH_WUNLOCK(chain);
819 	free(map, M_IPFW);
820 	return (0);
821 }
822 
823 /*
824  * Adds @rule to the list of rules to reap
825  */
826 void
827 ipfw_reap_add(struct ip_fw_chain *chain, struct ip_fw **head,
828     struct ip_fw *rule)
829 {
830 
831 	IPFW_UH_WLOCK_ASSERT(chain);
832 
833 	/* Unlink rule from everywhere */
834 	unref_rule_objects(chain, rule);
835 
836 	rule->next = *head;
837 	*head = rule;
838 }
839 
840 /*
841  * Reclaim storage associated with a list of rules.  This is
842  * typically the list created using remove_rule.
843  * A NULL pointer on input is handled correctly.
844  */
845 void
846 ipfw_reap_rules(struct ip_fw *head)
847 {
848 	struct ip_fw *rule;
849 
850 	while ((rule = head) != NULL) {
851 		head = head->next;
852 		ipfw_free_rule(rule);
853 	}
854 }
855 
856 /*
857  * Rules to keep are
858  *	(default || reserved || !match_set || !match_number)
859  * where
860  *   default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
861  *	// the default rule is always protected
862  *
863  *   reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
864  *	// RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
865  *
866  *   match_set ::= (cmd == 0 || rule->set == set)
867  *	// set number is ignored for cmd == 0
868  *
869  *   match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
870  *	// number is ignored for cmd == 1 or n == 0
871  *
872  */
873 int
874 ipfw_match_range(struct ip_fw *rule, ipfw_range_tlv *rt)
875 {
876 
877 	/* Don't match default rule for modification queries */
878 	if (rule->rulenum == IPFW_DEFAULT_RULE &&
879 	    (rt->flags & IPFW_RCFLAG_DEFAULT) == 0)
880 		return (0);
881 
882 	/* Don't match rules in reserved set for flush requests */
883 	if ((rt->flags & IPFW_RCFLAG_ALL) != 0 && rule->set == RESVD_SET)
884 		return (0);
885 
886 	/* If we're filtering by set, don't match other sets */
887 	if ((rt->flags & IPFW_RCFLAG_SET) != 0 && rule->set != rt->set)
888 		return (0);
889 
890 	if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
891 	    (rule->rulenum < rt->start_rule || rule->rulenum > rt->end_rule))
892 		return (0);
893 
894 	return (1);
895 }
896 
897 struct manage_sets_args {
898 	uint16_t	set;
899 	uint8_t		new_set;
900 };
901 
902 static int
903 swap_sets_cb(struct namedobj_instance *ni, struct named_object *no,
904     void *arg)
905 {
906 	struct manage_sets_args *args;
907 
908 	args = (struct manage_sets_args *)arg;
909 	if (no->set == (uint8_t)args->set)
910 		no->set = args->new_set;
911 	else if (no->set == args->new_set)
912 		no->set = (uint8_t)args->set;
913 	return (0);
914 }
915 
916 static int
917 move_sets_cb(struct namedobj_instance *ni, struct named_object *no,
918     void *arg)
919 {
920 	struct manage_sets_args *args;
921 
922 	args = (struct manage_sets_args *)arg;
923 	if (no->set == (uint8_t)args->set)
924 		no->set = args->new_set;
925 	return (0);
926 }
927 
928 static int
929 test_sets_cb(struct namedobj_instance *ni, struct named_object *no,
930     void *arg)
931 {
932 	struct manage_sets_args *args;
933 
934 	args = (struct manage_sets_args *)arg;
935 	if (no->set != (uint8_t)args->set)
936 		return (0);
937 	if (ipfw_objhash_lookup_name_type(ni, args->new_set,
938 	    no->etlv, no->name) != NULL)
939 		return (EEXIST);
940 	return (0);
941 }
942 
943 /*
944  * Generic function to handler moving and swapping sets.
945  */
946 int
947 ipfw_obj_manage_sets(struct namedobj_instance *ni, uint16_t type,
948     uint16_t set, uint8_t new_set, enum ipfw_sets_cmd cmd)
949 {
950 	struct manage_sets_args args;
951 	struct named_object *no;
952 
953 	args.set = set;
954 	args.new_set = new_set;
955 	switch (cmd) {
956 	case SWAP_ALL:
957 		return (ipfw_objhash_foreach_type(ni, swap_sets_cb,
958 		    &args, type));
959 	case TEST_ALL:
960 		return (ipfw_objhash_foreach_type(ni, test_sets_cb,
961 		    &args, type));
962 	case MOVE_ALL:
963 		return (ipfw_objhash_foreach_type(ni, move_sets_cb,
964 		    &args, type));
965 	case COUNT_ONE:
966 		/*
967 		 * @set used to pass kidx.
968 		 * When @new_set is zero - reset object counter,
969 		 * otherwise increment it.
970 		 */
971 		no = ipfw_objhash_lookup_kidx(ni, set);
972 		if (new_set != 0)
973 			no->ocnt++;
974 		else
975 			no->ocnt = 0;
976 		return (0);
977 	case TEST_ONE:
978 		/* @set used to pass kidx */
979 		no = ipfw_objhash_lookup_kidx(ni, set);
980 		/*
981 		 * First check number of references:
982 		 * when it differs, this mean other rules are holding
983 		 * reference to given object, so it is not possible to
984 		 * change its set. Note that refcnt may account references
985 		 * to some going-to-be-added rules. Since we don't know
986 		 * their numbers (and even if they will be added) it is
987 		 * perfectly OK to return error here.
988 		 */
989 		if (no->ocnt != no->refcnt)
990 			return (EBUSY);
991 		if (ipfw_objhash_lookup_name_type(ni, new_set, type,
992 		    no->name) != NULL)
993 			return (EEXIST);
994 		return (0);
995 	case MOVE_ONE:
996 		/* @set used to pass kidx */
997 		no = ipfw_objhash_lookup_kidx(ni, set);
998 		no->set = new_set;
999 		return (0);
1000 	}
1001 	return (EINVAL);
1002 }
1003 
1004 /*
1005  * Delete rules matching range @rt.
1006  * Saves number of deleted rules in @ndel.
1007  *
1008  * Returns 0 on success.
1009  */
1010 static int
1011 delete_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int *ndel)
1012 {
1013 	struct ip_fw *reap, *rule, **map;
1014 	int end, start;
1015 	int i, n, ndyn, ofs;
1016 
1017 	reap = NULL;
1018 	IPFW_UH_WLOCK(chain);	/* arbitrate writers */
1019 
1020 	/*
1021 	 * Stage 1: Determine range to inspect.
1022 	 * Range is half-inclusive, e.g [start, end).
1023 	 */
1024 	start = 0;
1025 	end = chain->n_rules - 1;
1026 
1027 	if ((rt->flags & IPFW_RCFLAG_RANGE) != 0) {
1028 		start = ipfw_find_rule(chain, rt->start_rule, 0);
1029 
1030 		if (rt->end_rule >= IPFW_DEFAULT_RULE)
1031 			rt->end_rule = IPFW_DEFAULT_RULE - 1;
1032 		end = ipfw_find_rule(chain, rt->end_rule, UINT32_MAX);
1033 	}
1034 
1035 	if (rt->flags & IPFW_RCFLAG_DYNAMIC) {
1036 		/*
1037 		 * Requested deleting only for dynamic states.
1038 		 */
1039 		*ndel = 0;
1040 		ipfw_expire_dyn_states(chain, rt);
1041 		IPFW_UH_WUNLOCK(chain);
1042 		return (0);
1043 	}
1044 
1045 	/* Allocate new map of the same size */
1046 	map = get_map(chain, 0, 1 /* locked */);
1047 	if (map == NULL) {
1048 		IPFW_UH_WUNLOCK(chain);
1049 		return (ENOMEM);
1050 	}
1051 
1052 	n = 0;
1053 	ndyn = 0;
1054 	ofs = start;
1055 	/* 1. bcopy the initial part of the map */
1056 	if (start > 0)
1057 		bcopy(chain->map, map, start * sizeof(struct ip_fw *));
1058 	/* 2. copy active rules between start and end */
1059 	for (i = start; i < end; i++) {
1060 		rule = chain->map[i];
1061 		if (ipfw_match_range(rule, rt) == 0) {
1062 			map[ofs++] = rule;
1063 			continue;
1064 		}
1065 
1066 		n++;
1067 		if (ipfw_is_dyn_rule(rule) != 0)
1068 			ndyn++;
1069 	}
1070 	/* 3. copy the final part of the map */
1071 	bcopy(chain->map + end, map + ofs,
1072 		(chain->n_rules - end) * sizeof(struct ip_fw *));
1073 	/* 4. recalculate skipto cache */
1074 	update_skipto_cache(chain, map);
1075 	/* 5. swap the maps (under UH_WLOCK + WHLOCK) */
1076 	map = swap_map(chain, map, chain->n_rules - n);
1077 	/* 6. Remove all dynamic states originated by deleted rules */
1078 	if (ndyn > 0)
1079 		ipfw_expire_dyn_states(chain, rt);
1080 	/* 7. now remove the rules deleted from the old map */
1081 	for (i = start; i < end; i++) {
1082 		rule = map[i];
1083 		if (ipfw_match_range(rule, rt) == 0)
1084 			continue;
1085 		chain->static_len -= RULEUSIZE0(rule);
1086 		ipfw_reap_add(chain, &reap, rule);
1087 	}
1088 	IPFW_UH_WUNLOCK(chain);
1089 
1090 	ipfw_reap_rules(reap);
1091 	if (map != NULL)
1092 		free(map, M_IPFW);
1093 	*ndel = n;
1094 	return (0);
1095 }
1096 
1097 static int
1098 move_objects(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
1099 {
1100 	struct opcode_obj_rewrite *rw;
1101 	struct ip_fw *rule;
1102 	ipfw_insn *cmd;
1103 	int cmdlen, i, l, c;
1104 	uint16_t kidx;
1105 
1106 	IPFW_UH_WLOCK_ASSERT(ch);
1107 
1108 	/* Stage 1: count number of references by given rules */
1109 	for (c = 0, i = 0; i < ch->n_rules - 1; i++) {
1110 		rule = ch->map[i];
1111 		if (ipfw_match_range(rule, rt) == 0)
1112 			continue;
1113 		if (rule->set == rt->new_set) /* nothing to do */
1114 			continue;
1115 		/* Search opcodes with named objects */
1116 		for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1117 		    l > 0; l -= cmdlen, cmd += cmdlen) {
1118 			cmdlen = F_LEN(cmd);
1119 			rw = find_op_rw(cmd, &kidx, NULL);
1120 			if (rw == NULL || rw->manage_sets == NULL)
1121 				continue;
1122 			/*
1123 			 * When manage_sets() returns non-zero value to
1124 			 * COUNT_ONE command, consider this as an object
1125 			 * doesn't support sets (e.g. disabled with sysctl).
1126 			 * So, skip checks for this object.
1127 			 */
1128 			if (rw->manage_sets(ch, kidx, 1, COUNT_ONE) != 0)
1129 				continue;
1130 			c++;
1131 		}
1132 	}
1133 	if (c == 0) /* No objects found */
1134 		return (0);
1135 	/* Stage 2: verify "ownership" */
1136 	for (c = 0, i = 0; (i < ch->n_rules - 1) && c == 0; i++) {
1137 		rule = ch->map[i];
1138 		if (ipfw_match_range(rule, rt) == 0)
1139 			continue;
1140 		if (rule->set == rt->new_set) /* nothing to do */
1141 			continue;
1142 		/* Search opcodes with named objects */
1143 		for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1144 		    l > 0 && c == 0; l -= cmdlen, cmd += cmdlen) {
1145 			cmdlen = F_LEN(cmd);
1146 			rw = find_op_rw(cmd, &kidx, NULL);
1147 			if (rw == NULL || rw->manage_sets == NULL)
1148 				continue;
1149 			/* Test for ownership and conflicting names */
1150 			c = rw->manage_sets(ch, kidx,
1151 			    (uint8_t)rt->new_set, TEST_ONE);
1152 		}
1153 	}
1154 	/* Stage 3: change set and cleanup */
1155 	for (i = 0; i < ch->n_rules - 1; i++) {
1156 		rule = ch->map[i];
1157 		if (ipfw_match_range(rule, rt) == 0)
1158 			continue;
1159 		if (rule->set == rt->new_set) /* nothing to do */
1160 			continue;
1161 		/* Search opcodes with named objects */
1162 		for (l = rule->cmd_len, cmdlen = 0, cmd = rule->cmd;
1163 		    l > 0; l -= cmdlen, cmd += cmdlen) {
1164 			cmdlen = F_LEN(cmd);
1165 			rw = find_op_rw(cmd, &kidx, NULL);
1166 			if (rw == NULL || rw->manage_sets == NULL)
1167 				continue;
1168 			/* cleanup object counter */
1169 			rw->manage_sets(ch, kidx,
1170 			    0 /* reset counter */, COUNT_ONE);
1171 			if (c != 0)
1172 				continue;
1173 			/* change set */
1174 			rw->manage_sets(ch, kidx,
1175 			    (uint8_t)rt->new_set, MOVE_ONE);
1176 		}
1177 	}
1178 	return (c);
1179 }/*
1180  * Changes set of given rule rannge @rt
1181  * with each other.
1182  *
1183  * Returns 0 on success.
1184  */
1185 static int
1186 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1187 {
1188 	struct ip_fw *rule;
1189 	int i;
1190 
1191 	IPFW_UH_WLOCK(chain);
1192 
1193 	/*
1194 	 * Move rules with matching paramenerts to a new set.
1195 	 * This one is much more complex. We have to ensure
1196 	 * that all referenced tables (if any) are referenced
1197 	 * by given rule subset only. Otherwise, we can't move
1198 	 * them to new set and have to return error.
1199 	 */
1200 	if ((i = move_objects(chain, rt)) != 0) {
1201 		IPFW_UH_WUNLOCK(chain);
1202 		return (i);
1203 	}
1204 
1205 	/* XXX: We have to do swap holding WLOCK */
1206 	for (i = 0; i < chain->n_rules; i++) {
1207 		rule = chain->map[i];
1208 		if (ipfw_match_range(rule, rt) == 0)
1209 			continue;
1210 		rule->set = rt->new_set;
1211 	}
1212 
1213 	IPFW_UH_WUNLOCK(chain);
1214 
1215 	return (0);
1216 }
1217 
1218 /*
1219  * Clear counters for a specific rule.
1220  * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1221  * so we only care that rules do not disappear.
1222  */
1223 static void
1224 clear_counters(struct ip_fw *rule, int log_only)
1225 {
1226 	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1227 
1228 	if (log_only == 0)
1229 		IPFW_ZERO_RULE_COUNTER(rule);
1230 	if (l->o.opcode == O_LOG)
1231 		l->log_left = l->max_log;
1232 }
1233 
1234 /*
1235  * Flushes rules counters and/or log values on matching range.
1236  *
1237  * Returns number of items cleared.
1238  */
1239 static int
1240 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1241 {
1242 	struct ip_fw *rule;
1243 	int num;
1244 	int i;
1245 
1246 	num = 0;
1247 	rt->flags |= IPFW_RCFLAG_DEFAULT;
1248 
1249 	IPFW_UH_WLOCK(chain);	/* arbitrate writers */
1250 	for (i = 0; i < chain->n_rules; i++) {
1251 		rule = chain->map[i];
1252 		if (ipfw_match_range(rule, rt) == 0)
1253 			continue;
1254 		clear_counters(rule, log_only);
1255 		num++;
1256 	}
1257 	IPFW_UH_WUNLOCK(chain);
1258 
1259 	return (num);
1260 }
1261 
1262 static int
1263 check_range_tlv(ipfw_range_tlv *rt)
1264 {
1265 
1266 	if (rt->head.length != sizeof(*rt))
1267 		return (1);
1268 	if (rt->start_rule > rt->end_rule)
1269 		return (1);
1270 	if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1271 		return (1);
1272 
1273 	if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1274 		return (1);
1275 
1276 	return (0);
1277 }
1278 
1279 /*
1280  * Delete rules matching specified parameters
1281  * Data layout (v0)(current):
1282  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1283  * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1284  *
1285  * Saves number of deleted rules in ipfw_range_tlv->new_set.
1286  *
1287  * Returns 0 on success.
1288  */
1289 static int
1290 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1291     struct sockopt_data *sd)
1292 {
1293 	ipfw_range_header *rh;
1294 	int error, ndel;
1295 
1296 	if (sd->valsize != sizeof(*rh))
1297 		return (EINVAL);
1298 
1299 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1300 
1301 	if (check_range_tlv(&rh->range) != 0)
1302 		return (EINVAL);
1303 
1304 	ndel = 0;
1305 	if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1306 		return (error);
1307 
1308 	/* Save number of rules deleted */
1309 	rh->range.new_set = ndel;
1310 	return (0);
1311 }
1312 
1313 /*
1314  * Move rules/sets matching specified parameters
1315  * Data layout (v0)(current):
1316  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1317  *
1318  * Returns 0 on success.
1319  */
1320 static int
1321 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1322     struct sockopt_data *sd)
1323 {
1324 	ipfw_range_header *rh;
1325 
1326 	if (sd->valsize != sizeof(*rh))
1327 		return (EINVAL);
1328 
1329 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1330 
1331 	if (check_range_tlv(&rh->range) != 0)
1332 		return (EINVAL);
1333 
1334 	return (move_range(chain, &rh->range));
1335 }
1336 
1337 /*
1338  * Clear rule accounting data matching specified parameters
1339  * Data layout (v0)(current):
1340  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1341  * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1342  *
1343  * Saves number of cleared rules in ipfw_range_tlv->new_set.
1344  *
1345  * Returns 0 on success.
1346  */
1347 static int
1348 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1349     struct sockopt_data *sd)
1350 {
1351 	ipfw_range_header *rh;
1352 	int log_only, num;
1353 	char *msg;
1354 
1355 	if (sd->valsize != sizeof(*rh))
1356 		return (EINVAL);
1357 
1358 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1359 
1360 	if (check_range_tlv(&rh->range) != 0)
1361 		return (EINVAL);
1362 
1363 	log_only = (op3->opcode == IP_FW_XRESETLOG);
1364 
1365 	num = clear_range(chain, &rh->range, log_only);
1366 
1367 	if (rh->range.flags & IPFW_RCFLAG_ALL)
1368 		msg = log_only ? "All logging counts reset" :
1369 		    "Accounting cleared";
1370 	else
1371 		msg = log_only ? "logging count reset" : "cleared";
1372 
1373 	if (V_fw_verbose) {
1374 		int lev = LOG_SECURITY | LOG_NOTICE;
1375 		log(lev, "ipfw: %s.\n", msg);
1376 	}
1377 
1378 	/* Save number of rules cleared */
1379 	rh->range.new_set = num;
1380 	return (0);
1381 }
1382 
1383 static void
1384 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1385 {
1386 	uint32_t v_set;
1387 
1388 	IPFW_UH_WLOCK_ASSERT(chain);
1389 
1390 	/* Change enabled/disabled sets mask */
1391 	v_set = (V_set_disable | rt->set) & ~rt->new_set;
1392 	v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1393 	IPFW_WLOCK(chain);
1394 	V_set_disable = v_set;
1395 	IPFW_WUNLOCK(chain);
1396 }
1397 
1398 static int
1399 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1400 {
1401 	struct opcode_obj_rewrite *rw;
1402 	struct ip_fw *rule;
1403 	int i;
1404 
1405 	IPFW_UH_WLOCK_ASSERT(chain);
1406 
1407 	if (rt->set == rt->new_set) /* nothing to do */
1408 		return (0);
1409 
1410 	if (mv != 0) {
1411 		/*
1412 		 * Berfore moving the rules we need to check that
1413 		 * there aren't any conflicting named objects.
1414 		 */
1415 		for (rw = ctl3_rewriters;
1416 		    rw < ctl3_rewriters + ctl3_rsize; rw++) {
1417 			if (rw->manage_sets == NULL)
1418 				continue;
1419 			i = rw->manage_sets(chain, (uint8_t)rt->set,
1420 			    (uint8_t)rt->new_set, TEST_ALL);
1421 			if (i != 0)
1422 				return (EEXIST);
1423 		}
1424 	}
1425 	/* Swap or move two sets */
1426 	for (i = 0; i < chain->n_rules - 1; i++) {
1427 		rule = chain->map[i];
1428 		if (rule->set == (uint8_t)rt->set)
1429 			rule->set = (uint8_t)rt->new_set;
1430 		else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1431 			rule->set = (uint8_t)rt->set;
1432 	}
1433 	for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1434 		if (rw->manage_sets == NULL)
1435 			continue;
1436 		rw->manage_sets(chain, (uint8_t)rt->set,
1437 		    (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1438 	}
1439 	return (0);
1440 }
1441 
1442 /*
1443  * Swaps or moves set
1444  * Data layout (v0)(current):
1445  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1446  *
1447  * Returns 0 on success.
1448  */
1449 static int
1450 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1451     struct sockopt_data *sd)
1452 {
1453 	ipfw_range_header *rh;
1454 	int ret;
1455 
1456 	if (sd->valsize != sizeof(*rh))
1457 		return (EINVAL);
1458 
1459 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1460 
1461 	if (rh->range.head.length != sizeof(ipfw_range_tlv))
1462 		return (1);
1463 	/* enable_sets() expects bitmasks. */
1464 	if (op3->opcode != IP_FW_SET_ENABLE &&
1465 	    (rh->range.set >= IPFW_MAX_SETS ||
1466 	    rh->range.new_set >= IPFW_MAX_SETS))
1467 		return (EINVAL);
1468 
1469 	ret = 0;
1470 	IPFW_UH_WLOCK(chain);
1471 	switch (op3->opcode) {
1472 	case IP_FW_SET_SWAP:
1473 	case IP_FW_SET_MOVE:
1474 		ret = swap_sets(chain, &rh->range,
1475 		    op3->opcode == IP_FW_SET_MOVE);
1476 		break;
1477 	case IP_FW_SET_ENABLE:
1478 		enable_sets(chain, &rh->range);
1479 		break;
1480 	}
1481 	IPFW_UH_WUNLOCK(chain);
1482 
1483 	return (ret);
1484 }
1485 
1486 /**
1487  * Remove all rules with given number, or do set manipulation.
1488  * Assumes chain != NULL && *chain != NULL.
1489  *
1490  * The argument is an uint32_t. The low 16 bit are the rule or set number;
1491  * the next 8 bits are the new set; the top 8 bits indicate the command:
1492  *
1493  *	0	delete rules numbered "rulenum"
1494  *	1	delete rules in set "rulenum"
1495  *	2	move rules "rulenum" to set "new_set"
1496  *	3	move rules from set "rulenum" to set "new_set"
1497  *	4	swap sets "rulenum" and "new_set"
1498  *	5	delete rules "rulenum" and set "new_set"
1499  */
1500 static int
1501 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1502 {
1503 	uint32_t num;	/* rule number or old_set */
1504 	uint8_t cmd, new_set;
1505 	int do_del, ndel;
1506 	int error = 0;
1507 	ipfw_range_tlv rt;
1508 
1509 	num = arg & 0xffff;
1510 	cmd = (arg >> 24) & 0xff;
1511 	new_set = (arg >> 16) & 0xff;
1512 
1513 	if (cmd > 5 || new_set > RESVD_SET)
1514 		return EINVAL;
1515 	if (cmd == 0 || cmd == 2 || cmd == 5) {
1516 		if (num >= IPFW_DEFAULT_RULE)
1517 			return EINVAL;
1518 	} else {
1519 		if (num > RESVD_SET)	/* old_set */
1520 			return EINVAL;
1521 	}
1522 
1523 	/* Convert old requests into new representation */
1524 	memset(&rt, 0, sizeof(rt));
1525 	rt.start_rule = num;
1526 	rt.end_rule = num;
1527 	rt.set = num;
1528 	rt.new_set = new_set;
1529 	do_del = 0;
1530 
1531 	switch (cmd) {
1532 	case 0: /* delete rules numbered "rulenum" */
1533 		if (num == 0)
1534 			rt.flags |= IPFW_RCFLAG_ALL;
1535 		else
1536 			rt.flags |= IPFW_RCFLAG_RANGE;
1537 		do_del = 1;
1538 		break;
1539 	case 1: /* delete rules in set "rulenum" */
1540 		rt.flags |= IPFW_RCFLAG_SET;
1541 		do_del = 1;
1542 		break;
1543 	case 5: /* delete rules "rulenum" and set "new_set" */
1544 		rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1545 		rt.set = new_set;
1546 		rt.new_set = 0;
1547 		do_del = 1;
1548 		break;
1549 	case 2: /* move rules "rulenum" to set "new_set" */
1550 		rt.flags |= IPFW_RCFLAG_RANGE;
1551 		break;
1552 	case 3: /* move rules from set "rulenum" to set "new_set" */
1553 		IPFW_UH_WLOCK(chain);
1554 		error = swap_sets(chain, &rt, 1);
1555 		IPFW_UH_WUNLOCK(chain);
1556 		return (error);
1557 	case 4: /* swap sets "rulenum" and "new_set" */
1558 		IPFW_UH_WLOCK(chain);
1559 		error = swap_sets(chain, &rt, 0);
1560 		IPFW_UH_WUNLOCK(chain);
1561 		return (error);
1562 	default:
1563 		return (ENOTSUP);
1564 	}
1565 
1566 	if (do_del != 0) {
1567 		if ((error = delete_range(chain, &rt, &ndel)) != 0)
1568 			return (error);
1569 
1570 		if (ndel == 0 && (cmd != 1 && num != 0))
1571 			return (EINVAL);
1572 
1573 		return (0);
1574 	}
1575 
1576 	return (move_range(chain, &rt));
1577 }
1578 
1579 /**
1580  * Reset some or all counters on firewall rules.
1581  * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1582  * the next 8 bits are the set number, the top 8 bits are the command:
1583  *	0	work with rules from all set's;
1584  *	1	work with rules only from specified set.
1585  * Specified rule number is zero if we want to clear all entries.
1586  * log_only is 1 if we only want to reset logs, zero otherwise.
1587  */
1588 static int
1589 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1590 {
1591 	struct ip_fw *rule;
1592 	char *msg;
1593 	int i;
1594 
1595 	uint16_t rulenum = arg & 0xffff;
1596 	uint8_t set = (arg >> 16) & 0xff;
1597 	uint8_t cmd = (arg >> 24) & 0xff;
1598 
1599 	if (cmd > 1)
1600 		return (EINVAL);
1601 	if (cmd == 1 && set > RESVD_SET)
1602 		return (EINVAL);
1603 
1604 	IPFW_UH_RLOCK(chain);
1605 	if (rulenum == 0) {
1606 		V_norule_counter = 0;
1607 		for (i = 0; i < chain->n_rules; i++) {
1608 			rule = chain->map[i];
1609 			/* Skip rules not in our set. */
1610 			if (cmd == 1 && rule->set != set)
1611 				continue;
1612 			clear_counters(rule, log_only);
1613 		}
1614 		msg = log_only ? "All logging counts reset" :
1615 		    "Accounting cleared";
1616 	} else {
1617 		int cleared = 0;
1618 		for (i = 0; i < chain->n_rules; i++) {
1619 			rule = chain->map[i];
1620 			if (rule->rulenum == rulenum) {
1621 				if (cmd == 0 || rule->set == set)
1622 					clear_counters(rule, log_only);
1623 				cleared = 1;
1624 			}
1625 			if (rule->rulenum > rulenum)
1626 				break;
1627 		}
1628 		if (!cleared) {	/* we did not find any matching rules */
1629 			IPFW_UH_RUNLOCK(chain);
1630 			return (EINVAL);
1631 		}
1632 		msg = log_only ? "logging count reset" : "cleared";
1633 	}
1634 	IPFW_UH_RUNLOCK(chain);
1635 
1636 	if (V_fw_verbose) {
1637 		int lev = LOG_SECURITY | LOG_NOTICE;
1638 
1639 		if (rulenum)
1640 			log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1641 		else
1642 			log(lev, "ipfw: %s.\n", msg);
1643 	}
1644 	return (0);
1645 }
1646 
1647 
1648 /*
1649  * Check rule head in FreeBSD11 format
1650  *
1651  */
1652 static int
1653 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1654     struct rule_check_info *ci)
1655 {
1656 	int l;
1657 
1658 	if (size < sizeof(*rule)) {
1659 		printf("ipfw: rule too short\n");
1660 		return (EINVAL);
1661 	}
1662 
1663 	/* Check for valid cmd_len */
1664 	l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1665 	if (l != size) {
1666 		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1667 		return (EINVAL);
1668 	}
1669 	if (rule->act_ofs >= rule->cmd_len) {
1670 		printf("ipfw: bogus action offset (%u > %u)\n",
1671 		    rule->act_ofs, rule->cmd_len - 1);
1672 		return (EINVAL);
1673 	}
1674 
1675 	if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1676 		return (EINVAL);
1677 
1678 	return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1679 }
1680 
1681 /*
1682  * Check rule head in FreeBSD8 format
1683  *
1684  */
1685 static int
1686 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1687     struct rule_check_info *ci)
1688 {
1689 	int l;
1690 
1691 	if (size < sizeof(*rule)) {
1692 		printf("ipfw: rule too short\n");
1693 		return (EINVAL);
1694 	}
1695 
1696 	/* Check for valid cmd_len */
1697 	l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1698 	if (l != size) {
1699 		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1700 		return (EINVAL);
1701 	}
1702 	if (rule->act_ofs >= rule->cmd_len) {
1703 		printf("ipfw: bogus action offset (%u > %u)\n",
1704 		    rule->act_ofs, rule->cmd_len - 1);
1705 		return (EINVAL);
1706 	}
1707 
1708 	if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1709 		return (EINVAL);
1710 
1711 	return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1712 }
1713 
1714 static int
1715 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1716 {
1717 	int cmdlen, l;
1718 	int have_action;
1719 
1720 	have_action = 0;
1721 
1722 	/*
1723 	 * Now go for the individual checks. Very simple ones, basically only
1724 	 * instruction sizes.
1725 	 */
1726 	for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1727 		cmdlen = F_LEN(cmd);
1728 		if (cmdlen > l) {
1729 			printf("ipfw: opcode %d size truncated\n",
1730 			    cmd->opcode);
1731 			return EINVAL;
1732 		}
1733 		switch (cmd->opcode) {
1734 		case O_PROBE_STATE:
1735 		case O_KEEP_STATE:
1736 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1737 				goto bad_size;
1738 			ci->object_opcodes++;
1739 			break;
1740 		case O_PROTO:
1741 		case O_IP_SRC_ME:
1742 		case O_IP_DST_ME:
1743 		case O_LAYER2:
1744 		case O_IN:
1745 		case O_FRAG:
1746 		case O_DIVERTED:
1747 		case O_IPOPT:
1748 		case O_IPTOS:
1749 		case O_IPPRECEDENCE:
1750 		case O_IPVER:
1751 		case O_SOCKARG:
1752 		case O_TCPFLAGS:
1753 		case O_TCPOPTS:
1754 		case O_ESTAB:
1755 		case O_VERREVPATH:
1756 		case O_VERSRCREACH:
1757 		case O_ANTISPOOF:
1758 		case O_IPSEC:
1759 #ifdef INET6
1760 		case O_IP6_SRC_ME:
1761 		case O_IP6_DST_ME:
1762 		case O_EXT_HDR:
1763 		case O_IP6:
1764 #endif
1765 		case O_IP4:
1766 		case O_TAG:
1767 		case O_SKIP_ACTION:
1768 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1769 				goto bad_size;
1770 			break;
1771 
1772 		case O_EXTERNAL_ACTION:
1773 			if (cmd->arg1 == 0 ||
1774 			    cmdlen != F_INSN_SIZE(ipfw_insn)) {
1775 				printf("ipfw: invalid external "
1776 				    "action opcode\n");
1777 				return (EINVAL);
1778 			}
1779 			ci->object_opcodes++;
1780 			/*
1781 			 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1782 			 * opcode?
1783 			 */
1784 			if (l != cmdlen) {
1785 				l -= cmdlen;
1786 				cmd += cmdlen;
1787 				cmdlen = F_LEN(cmd);
1788 				if (cmd->opcode == O_EXTERNAL_DATA)
1789 					goto check_action;
1790 				if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1791 					printf("ipfw: invalid opcode "
1792 					    "next to external action %u\n",
1793 					    cmd->opcode);
1794 					return (EINVAL);
1795 				}
1796 				if (cmd->arg1 == 0 ||
1797 				    cmdlen != F_INSN_SIZE(ipfw_insn)) {
1798 					printf("ipfw: invalid external "
1799 					    "action instance opcode\n");
1800 					return (EINVAL);
1801 				}
1802 				ci->object_opcodes++;
1803 			}
1804 			goto check_action;
1805 
1806 		case O_FIB:
1807 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1808 				goto bad_size;
1809 			if (cmd->arg1 >= rt_numfibs) {
1810 				printf("ipfw: invalid fib number %d\n",
1811 					cmd->arg1);
1812 				return EINVAL;
1813 			}
1814 			break;
1815 
1816 		case O_SETFIB:
1817 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1818 				goto bad_size;
1819 			if ((cmd->arg1 != IP_FW_TARG) &&
1820 			    ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1821 				printf("ipfw: invalid fib number %d\n",
1822 					cmd->arg1 & 0x7FFF);
1823 				return EINVAL;
1824 			}
1825 			goto check_action;
1826 
1827 		case O_UID:
1828 		case O_GID:
1829 		case O_JAIL:
1830 		case O_IP_SRC:
1831 		case O_IP_DST:
1832 		case O_TCPSEQ:
1833 		case O_TCPACK:
1834 		case O_PROB:
1835 		case O_ICMPTYPE:
1836 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1837 				goto bad_size;
1838 			break;
1839 
1840 		case O_LIMIT:
1841 			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1842 				goto bad_size;
1843 			ci->object_opcodes++;
1844 			break;
1845 
1846 		case O_LOG:
1847 			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1848 				goto bad_size;
1849 
1850 			((ipfw_insn_log *)cmd)->log_left =
1851 			    ((ipfw_insn_log *)cmd)->max_log;
1852 
1853 			break;
1854 
1855 		case O_IP_SRC_MASK:
1856 		case O_IP_DST_MASK:
1857 			/* only odd command lengths */
1858 			if ((cmdlen & 1) == 0)
1859 				goto bad_size;
1860 			break;
1861 
1862 		case O_IP_SRC_SET:
1863 		case O_IP_DST_SET:
1864 			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1865 				printf("ipfw: invalid set size %d\n",
1866 					cmd->arg1);
1867 				return EINVAL;
1868 			}
1869 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1870 			    (cmd->arg1+31)/32 )
1871 				goto bad_size;
1872 			break;
1873 
1874 		case O_IP_SRC_LOOKUP:
1875 			if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1876 				goto bad_size;
1877 		case O_IP_DST_LOOKUP:
1878 			if (cmd->arg1 >= V_fw_tables_max) {
1879 				printf("ipfw: invalid table number %d\n",
1880 				    cmd->arg1);
1881 				return (EINVAL);
1882 			}
1883 			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1884 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1885 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1886 				goto bad_size;
1887 			ci->object_opcodes++;
1888 			break;
1889 		case O_IP_FLOW_LOOKUP:
1890 			if (cmd->arg1 >= V_fw_tables_max) {
1891 				printf("ipfw: invalid table number %d\n",
1892 				    cmd->arg1);
1893 				return (EINVAL);
1894 			}
1895 			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1896 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1897 				goto bad_size;
1898 			ci->object_opcodes++;
1899 			break;
1900 		case O_MACADDR2:
1901 			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1902 				goto bad_size;
1903 			break;
1904 
1905 		case O_NOP:
1906 		case O_IPID:
1907 		case O_IPTTL:
1908 		case O_IPLEN:
1909 		case O_TCPDATALEN:
1910 		case O_TCPWIN:
1911 		case O_TAGGED:
1912 			if (cmdlen < 1 || cmdlen > 31)
1913 				goto bad_size;
1914 			break;
1915 
1916 		case O_DSCP:
1917 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1918 				goto bad_size;
1919 			break;
1920 
1921 		case O_MAC_TYPE:
1922 		case O_IP_SRCPORT:
1923 		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1924 			if (cmdlen < 2 || cmdlen > 31)
1925 				goto bad_size;
1926 			break;
1927 
1928 		case O_RECV:
1929 		case O_XMIT:
1930 		case O_VIA:
1931 			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1932 				goto bad_size;
1933 			ci->object_opcodes++;
1934 			break;
1935 
1936 		case O_ALTQ:
1937 			if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1938 				goto bad_size;
1939 			break;
1940 
1941 		case O_PIPE:
1942 		case O_QUEUE:
1943 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1944 				goto bad_size;
1945 			goto check_action;
1946 
1947 		case O_FORWARD_IP:
1948 			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1949 				goto bad_size;
1950 			goto check_action;
1951 #ifdef INET6
1952 		case O_FORWARD_IP6:
1953 			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1954 				goto bad_size;
1955 			goto check_action;
1956 #endif /* INET6 */
1957 
1958 		case O_DIVERT:
1959 		case O_TEE:
1960 			if (ip_divert_ptr == NULL)
1961 				return EINVAL;
1962 			else
1963 				goto check_size;
1964 		case O_NETGRAPH:
1965 		case O_NGTEE:
1966 			if (ng_ipfw_input_p == NULL)
1967 				return EINVAL;
1968 			else
1969 				goto check_size;
1970 		case O_NAT:
1971 			if (!IPFW_NAT_LOADED)
1972 				return EINVAL;
1973 			if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1974  				goto bad_size;
1975  			goto check_action;
1976 		case O_CHECK_STATE:
1977 			ci->object_opcodes++;
1978 			/* FALLTHROUGH */
1979 		case O_FORWARD_MAC: /* XXX not implemented yet */
1980 		case O_COUNT:
1981 		case O_ACCEPT:
1982 		case O_DENY:
1983 		case O_REJECT:
1984 		case O_SETDSCP:
1985 #ifdef INET6
1986 		case O_UNREACH6:
1987 #endif
1988 		case O_SKIPTO:
1989 		case O_REASS:
1990 		case O_CALLRETURN:
1991 check_size:
1992 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1993 				goto bad_size;
1994 check_action:
1995 			if (have_action) {
1996 				printf("ipfw: opcode %d, multiple actions"
1997 					" not allowed\n",
1998 					cmd->opcode);
1999 				return (EINVAL);
2000 			}
2001 			have_action = 1;
2002 			if (l != cmdlen) {
2003 				printf("ipfw: opcode %d, action must be"
2004 					" last opcode\n",
2005 					cmd->opcode);
2006 				return (EINVAL);
2007 			}
2008 			break;
2009 #ifdef INET6
2010 		case O_IP6_SRC:
2011 		case O_IP6_DST:
2012 			if (cmdlen != F_INSN_SIZE(struct in6_addr) +
2013 			    F_INSN_SIZE(ipfw_insn))
2014 				goto bad_size;
2015 			break;
2016 
2017 		case O_FLOW6ID:
2018 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2019 			    ((ipfw_insn_u32 *)cmd)->o.arg1)
2020 				goto bad_size;
2021 			break;
2022 
2023 		case O_IP6_SRC_MASK:
2024 		case O_IP6_DST_MASK:
2025 			if ( !(cmdlen & 1) || cmdlen > 127)
2026 				goto bad_size;
2027 			break;
2028 		case O_ICMP6TYPE:
2029 			if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2030 				goto bad_size;
2031 			break;
2032 #endif
2033 
2034 		default:
2035 			switch (cmd->opcode) {
2036 #ifndef INET6
2037 			case O_IP6_SRC_ME:
2038 			case O_IP6_DST_ME:
2039 			case O_EXT_HDR:
2040 			case O_IP6:
2041 			case O_UNREACH6:
2042 			case O_IP6_SRC:
2043 			case O_IP6_DST:
2044 			case O_FLOW6ID:
2045 			case O_IP6_SRC_MASK:
2046 			case O_IP6_DST_MASK:
2047 			case O_ICMP6TYPE:
2048 				printf("ipfw: no IPv6 support in kernel\n");
2049 				return (EPROTONOSUPPORT);
2050 #endif
2051 			default:
2052 				printf("ipfw: opcode %d, unknown opcode\n",
2053 					cmd->opcode);
2054 				return (EINVAL);
2055 			}
2056 		}
2057 	}
2058 	if (have_action == 0) {
2059 		printf("ipfw: missing action\n");
2060 		return (EINVAL);
2061 	}
2062 	return 0;
2063 
2064 bad_size:
2065 	printf("ipfw: opcode %d size %d wrong\n",
2066 		cmd->opcode, cmdlen);
2067 	return (EINVAL);
2068 }
2069 
2070 
2071 /*
2072  * Translation of requests for compatibility with FreeBSD 7.2/8.
2073  * a static variable tells us if we have an old client from userland,
2074  * and if necessary we translate requests and responses between the
2075  * two formats.
2076  */
2077 static int is7 = 0;
2078 
2079 struct ip_fw7 {
2080 	struct ip_fw7	*next;		/* linked list of rules     */
2081 	struct ip_fw7	*next_rule;	/* ptr to next [skipto] rule    */
2082 	/* 'next_rule' is used to pass up 'set_disable' status      */
2083 
2084 	uint16_t	act_ofs;	/* offset of action in 32-bit units */
2085 	uint16_t	cmd_len;	/* # of 32-bit words in cmd */
2086 	uint16_t	rulenum;	/* rule number          */
2087 	uint8_t		set;		/* rule set (0..31)     */
2088 	// #define RESVD_SET   31  /* set for default and persistent rules */
2089 	uint8_t		_pad;		/* padding          */
2090 	// uint32_t        id;             /* rule id, only in v.8 */
2091 	/* These fields are present in all rules.           */
2092 	uint64_t	pcnt;		/* Packet counter       */
2093 	uint64_t	bcnt;		/* Byte counter         */
2094 	uint32_t	timestamp;	/* tv_sec of last match     */
2095 
2096 	ipfw_insn	cmd[1];		/* storage for commands     */
2097 };
2098 
2099 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2100 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2101 
2102 #ifndef RULESIZE7
2103 #define RULESIZE7(rule)  (sizeof(struct ip_fw7) + \
2104 	((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2105 #endif
2106 
2107 
2108 /*
2109  * Copy the static and dynamic rules to the supplied buffer
2110  * and return the amount of space actually used.
2111  * Must be run under IPFW_UH_RLOCK
2112  */
2113 static size_t
2114 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2115 {
2116 	char *bp = buf;
2117 	char *ep = bp + space;
2118 	struct ip_fw *rule;
2119 	struct ip_fw_rule0 *dst;
2120 	struct timeval boottime;
2121 	int error, i, l, warnflag;
2122 	time_t	boot_seconds;
2123 
2124 	warnflag = 0;
2125 
2126 	getboottime(&boottime);
2127         boot_seconds = boottime.tv_sec;
2128 	for (i = 0; i < chain->n_rules; i++) {
2129 		rule = chain->map[i];
2130 
2131 		if (is7) {
2132 		    /* Convert rule to FreeBSd 7.2 format */
2133 		    l = RULESIZE7(rule);
2134 		    if (bp + l + sizeof(uint32_t) <= ep) {
2135 			bcopy(rule, bp, l + sizeof(uint32_t));
2136 			error = set_legacy_obj_kidx(chain,
2137 			    (struct ip_fw_rule0 *)bp);
2138 			if (error != 0)
2139 				return (0);
2140 			error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2141 			if (error)
2142 				return 0; /*XXX correct? */
2143 			/*
2144 			 * XXX HACK. Store the disable mask in the "next"
2145 			 * pointer in a wild attempt to keep the ABI the same.
2146 			 * Why do we do this on EVERY rule?
2147 			 */
2148 			bcopy(&V_set_disable,
2149 				&(((struct ip_fw7 *)bp)->next_rule),
2150 				sizeof(V_set_disable));
2151 			if (((struct ip_fw7 *)bp)->timestamp)
2152 			    ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2153 			bp += l;
2154 		    }
2155 		    continue; /* go to next rule */
2156 		}
2157 
2158 		l = RULEUSIZE0(rule);
2159 		if (bp + l > ep) { /* should not happen */
2160 			printf("overflow dumping static rules\n");
2161 			break;
2162 		}
2163 		dst = (struct ip_fw_rule0 *)bp;
2164 		export_rule0(rule, dst, l);
2165 		error = set_legacy_obj_kidx(chain, dst);
2166 
2167 		/*
2168 		 * XXX HACK. Store the disable mask in the "next"
2169 		 * pointer in a wild attempt to keep the ABI the same.
2170 		 * Why do we do this on EVERY rule?
2171 		 *
2172 		 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2173 		 * so we need to fail _after_ saving at least one mask.
2174 		 */
2175 		bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2176 		if (dst->timestamp)
2177 			dst->timestamp += boot_seconds;
2178 		bp += l;
2179 
2180 		if (error != 0) {
2181 			if (error == 2) {
2182 				/* Non-fatal table rewrite error. */
2183 				warnflag = 1;
2184 				continue;
2185 			}
2186 			printf("Stop on rule %d. Fail to convert table\n",
2187 			    rule->rulenum);
2188 			break;
2189 		}
2190 	}
2191 	if (warnflag != 0)
2192 		printf("ipfw: process %s is using legacy interfaces,"
2193 		    " consider rebuilding\n", "");
2194 	ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2195 	return (bp - (char *)buf);
2196 }
2197 
2198 
2199 struct dump_args {
2200 	uint32_t	b;	/* start rule */
2201 	uint32_t	e;	/* end rule */
2202 	uint32_t	rcount;	/* number of rules */
2203 	uint32_t	rsize;	/* rules size */
2204 	uint32_t	tcount;	/* number of tables */
2205 	int		rcounters;	/* counters */
2206 	uint32_t	*bmask;	/* index bitmask of used named objects */
2207 };
2208 
2209 void
2210 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2211 {
2212 
2213 	ntlv->head.type = no->etlv;
2214 	ntlv->head.length = sizeof(*ntlv);
2215 	ntlv->idx = no->kidx;
2216 	strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2217 }
2218 
2219 /*
2220  * Export named object info in instance @ni, identified by @kidx
2221  * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2222  *
2223  * Returns 0 on success.
2224  */
2225 static int
2226 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2227     struct sockopt_data *sd)
2228 {
2229 	struct named_object *no;
2230 	ipfw_obj_ntlv *ntlv;
2231 
2232 	no = ipfw_objhash_lookup_kidx(ni, kidx);
2233 	KASSERT(no != NULL, ("invalid object kernel index passed"));
2234 
2235 	ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2236 	if (ntlv == NULL)
2237 		return (ENOMEM);
2238 
2239 	ipfw_export_obj_ntlv(no, ntlv);
2240 	return (0);
2241 }
2242 
2243 static int
2244 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
2245     struct sockopt_data *sd)
2246 {
2247 	int error, i;
2248 
2249 	for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
2250 		if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
2251 			continue;
2252 		if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2253 			return (error);
2254 		da->tcount--;
2255 	}
2256 	return (0);
2257 }
2258 
2259 static int
2260 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
2261     struct sockopt_data *sd)
2262 {
2263 	ipfw_obj_ctlv *ctlv;
2264 	int error;
2265 
2266 	MPASS(da->tcount > 0);
2267 	/* Header first */
2268 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2269 	if (ctlv == NULL)
2270 		return (ENOMEM);
2271 	ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2272 	ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2273 	    sizeof(*ctlv);
2274 	ctlv->count = da->tcount;
2275 	ctlv->objsize = sizeof(ipfw_obj_ntlv);
2276 
2277 	/* Dump table names first (if any) */
2278 	error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
2279 	if (error != 0)
2280 		return (error);
2281 	/* Then dump another named objects */
2282 	da->bmask += IPFW_TABLES_MAX / 32;
2283 	return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
2284 }
2285 
2286 /*
2287  * Dumps static rules with table TLVs in buffer @sd.
2288  *
2289  * Returns 0 on success.
2290  */
2291 static int
2292 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2293     struct sockopt_data *sd)
2294 {
2295 	ipfw_obj_ctlv *ctlv;
2296 	struct ip_fw *krule;
2297 	caddr_t dst;
2298 	int i, l;
2299 
2300 	/* Dump rules */
2301 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2302 	if (ctlv == NULL)
2303 		return (ENOMEM);
2304 	ctlv->head.type = IPFW_TLV_RULE_LIST;
2305 	ctlv->head.length = da->rsize + sizeof(*ctlv);
2306 	ctlv->count = da->rcount;
2307 
2308 	for (i = da->b; i < da->e; i++) {
2309 		krule = chain->map[i];
2310 
2311 		l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2312 		if (da->rcounters != 0)
2313 			l += sizeof(struct ip_fw_bcounter);
2314 		dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2315 		if (dst == NULL)
2316 			return (ENOMEM);
2317 
2318 		export_rule1(krule, dst, l, da->rcounters);
2319 	}
2320 
2321 	return (0);
2322 }
2323 
2324 int
2325 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint16_t kidx)
2326 {
2327 	uint32_t bidx;
2328 
2329 	/*
2330 	 * Maintain separate bitmasks for table and non-table objects.
2331 	 */
2332 	bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
2333 	bidx += kidx / 32;
2334 	if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
2335 		return (0);
2336 
2337 	bmask[bidx] |= 1 << (kidx % 32);
2338 	return (1);
2339 }
2340 
2341 /*
2342  * Marks every object index used in @rule with bit in @bmask.
2343  * Used to generate bitmask of referenced tables/objects for given ruleset
2344  * or its part.
2345  */
2346 static void
2347 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2348     struct dump_args *da)
2349 {
2350 	struct opcode_obj_rewrite *rw;
2351 	ipfw_insn *cmd;
2352 	int cmdlen, l;
2353 	uint16_t kidx;
2354 	uint8_t subtype;
2355 
2356 	l = rule->cmd_len;
2357 	cmd = rule->cmd;
2358 	cmdlen = 0;
2359 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2360 		cmdlen = F_LEN(cmd);
2361 
2362 		rw = find_op_rw(cmd, &kidx, &subtype);
2363 		if (rw == NULL)
2364 			continue;
2365 
2366 		if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
2367 			da->tcount++;
2368 	}
2369 }
2370 
2371 /*
2372  * Dumps requested objects data
2373  * Data layout (version 0)(current):
2374  * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2375  *   size = ipfw_cfg_lheader.size
2376  * Reply: [ ipfw_cfg_lheader
2377  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2378  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2379  *     ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2380  *   ] (optional)
2381  *   [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2382  * ]
2383  * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2384  * The rest (size, count) are set to zero and needs to be ignored.
2385  *
2386  * Returns 0 on success.
2387  */
2388 static int
2389 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2390     struct sockopt_data *sd)
2391 {
2392 	struct dump_args da;
2393 	ipfw_cfg_lheader *hdr;
2394 	struct ip_fw *rule;
2395 	size_t sz, rnum;
2396 	uint32_t hdr_flags, *bmask;
2397 	int error, i;
2398 
2399 	hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2400 	if (hdr == NULL)
2401 		return (EINVAL);
2402 
2403 	error = 0;
2404 	bmask = NULL;
2405 	memset(&da, 0, sizeof(da));
2406 	/*
2407 	 * Allocate needed state.
2408 	 * Note we allocate 2xspace mask, for table & srv
2409 	 */
2410 	if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
2411 		da.bmask = bmask = malloc(
2412 		    sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
2413 		    M_WAITOK | M_ZERO);
2414 	IPFW_UH_RLOCK(chain);
2415 
2416 	/*
2417 	 * STAGE 1: Determine size/count for objects in range.
2418 	 * Prepare used tables bitmask.
2419 	 */
2420 	sz = sizeof(ipfw_cfg_lheader);
2421 	da.e = chain->n_rules;
2422 
2423 	if (hdr->end_rule != 0) {
2424 		/* Handle custom range */
2425 		if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2426 			rnum = IPFW_DEFAULT_RULE;
2427 		da.b = ipfw_find_rule(chain, rnum, 0);
2428 		rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2429 		    hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2430 		da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2431 	}
2432 
2433 	if (hdr->flags & IPFW_CFG_GET_STATIC) {
2434 		for (i = da.b; i < da.e; i++) {
2435 			rule = chain->map[i];
2436 			da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2437 			da.rcount++;
2438 			/* Update bitmask of used objects for given range */
2439 			mark_rule_objects(chain, rule, &da);
2440 		}
2441 		/* Add counters if requested */
2442 		if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2443 			da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2444 			da.rcounters = 1;
2445 		}
2446 		sz += da.rsize + sizeof(ipfw_obj_ctlv);
2447 	}
2448 
2449 	if (hdr->flags & IPFW_CFG_GET_STATES) {
2450 		sz += sizeof(ipfw_obj_ctlv) +
2451 		    ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
2452 		da.tcount += i;
2453 	}
2454 
2455 	if (da.tcount > 0)
2456 		sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2457 		    sizeof(ipfw_obj_ctlv);
2458 
2459 	/*
2460 	 * Fill header anyway.
2461 	 * Note we have to save header fields to stable storage
2462 	 * buffer inside @sd can be flushed after dumping rules
2463 	 */
2464 	hdr->size = sz;
2465 	hdr->set_mask = ~V_set_disable;
2466 	hdr_flags = hdr->flags;
2467 	hdr = NULL;
2468 
2469 	if (sd->valsize < sz) {
2470 		error = ENOMEM;
2471 		goto cleanup;
2472 	}
2473 
2474 	/* STAGE2: Store actual data */
2475 	if (da.tcount > 0) {
2476 		error = dump_named_objects(chain, &da, sd);
2477 		if (error != 0)
2478 			goto cleanup;
2479 	}
2480 
2481 	if (hdr_flags & IPFW_CFG_GET_STATIC) {
2482 		error = dump_static_rules(chain, &da, sd);
2483 		if (error != 0)
2484 			goto cleanup;
2485 	}
2486 
2487 	if (hdr_flags & IPFW_CFG_GET_STATES)
2488 		error = ipfw_dump_states(chain, sd);
2489 
2490 cleanup:
2491 	IPFW_UH_RUNLOCK(chain);
2492 
2493 	if (bmask != NULL)
2494 		free(bmask, M_TEMP);
2495 
2496 	return (error);
2497 }
2498 
2499 int
2500 ipfw_check_object_name_generic(const char *name)
2501 {
2502 	int nsize;
2503 
2504 	nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2505 	if (strnlen(name, nsize) == nsize)
2506 		return (EINVAL);
2507 	if (name[0] == '\0')
2508 		return (EINVAL);
2509 	return (0);
2510 }
2511 
2512 /*
2513  * Creates non-existent objects referenced by rule.
2514  *
2515  * Return 0 on success.
2516  */
2517 int
2518 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2519     struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2520 {
2521 	struct opcode_obj_rewrite *rw;
2522 	struct obj_idx *p;
2523 	uint16_t kidx;
2524 	int error;
2525 
2526 	/*
2527 	 * Compatibility stuff: do actual creation for non-existing,
2528 	 * but referenced objects.
2529 	 */
2530 	for (p = oib; p < pidx; p++) {
2531 		if (p->kidx != 0)
2532 			continue;
2533 
2534 		ti->uidx = p->uidx;
2535 		ti->type = p->type;
2536 		ti->atype = 0;
2537 
2538 		rw = find_op_rw(cmd + p->off, NULL, NULL);
2539 		KASSERT(rw != NULL, ("Unable to find handler for op %d",
2540 		    (cmd + p->off)->opcode));
2541 
2542 		if (rw->create_object == NULL)
2543 			error = EOPNOTSUPP;
2544 		else
2545 			error = rw->create_object(ch, ti, &kidx);
2546 		if (error == 0) {
2547 			p->kidx = kidx;
2548 			continue;
2549 		}
2550 
2551 		/*
2552 		 * Error happened. We have to rollback everything.
2553 		 * Drop all already acquired references.
2554 		 */
2555 		IPFW_UH_WLOCK(ch);
2556 		unref_oib_objects(ch, cmd, oib, pidx);
2557 		IPFW_UH_WUNLOCK(ch);
2558 
2559 		return (error);
2560 	}
2561 
2562 	return (0);
2563 }
2564 
2565 /*
2566  * Compatibility function for old ipfw(8) binaries.
2567  * Rewrites table/nat kernel indices with userland ones.
2568  * Convert tables matching '/^\d+$/' to their atoi() value.
2569  * Use number 65535 for other tables.
2570  *
2571  * Returns 0 on success.
2572  */
2573 static int
2574 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2575 {
2576 	struct opcode_obj_rewrite *rw;
2577 	struct named_object *no;
2578 	ipfw_insn *cmd;
2579 	char *end;
2580 	long val;
2581 	int cmdlen, error, l;
2582 	uint16_t kidx, uidx;
2583 	uint8_t subtype;
2584 
2585 	error = 0;
2586 
2587 	l = rule->cmd_len;
2588 	cmd = rule->cmd;
2589 	cmdlen = 0;
2590 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2591 		cmdlen = F_LEN(cmd);
2592 
2593 		/* Check if is index in given opcode */
2594 		rw = find_op_rw(cmd, &kidx, &subtype);
2595 		if (rw == NULL)
2596 			continue;
2597 
2598 		/* Try to find referenced kernel object */
2599 		no = rw->find_bykidx(ch, kidx);
2600 		if (no == NULL)
2601 			continue;
2602 
2603 		val = strtol(no->name, &end, 10);
2604 		if (*end == '\0' && val < 65535) {
2605 			uidx = val;
2606 		} else {
2607 
2608 			/*
2609 			 * We are called via legacy opcode.
2610 			 * Save error and show table as fake number
2611 			 * not to make ipfw(8) hang.
2612 			 */
2613 			uidx = 65535;
2614 			error = 2;
2615 		}
2616 
2617 		rw->update(cmd, uidx);
2618 	}
2619 
2620 	return (error);
2621 }
2622 
2623 
2624 /*
2625  * Unreferences all already-referenced objects in given @cmd rule,
2626  * using information in @oib.
2627  *
2628  * Used to rollback partially converted rule on error.
2629  */
2630 static void
2631 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2632     struct obj_idx *end)
2633 {
2634 	struct opcode_obj_rewrite *rw;
2635 	struct named_object *no;
2636 	struct obj_idx *p;
2637 
2638 	IPFW_UH_WLOCK_ASSERT(ch);
2639 
2640 	for (p = oib; p < end; p++) {
2641 		if (p->kidx == 0)
2642 			continue;
2643 
2644 		rw = find_op_rw(cmd + p->off, NULL, NULL);
2645 		KASSERT(rw != NULL, ("Unable to find handler for op %d",
2646 		    (cmd + p->off)->opcode));
2647 
2648 		/* Find & unref by existing idx */
2649 		no = rw->find_bykidx(ch, p->kidx);
2650 		KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2651 		no->refcnt--;
2652 	}
2653 }
2654 
2655 /*
2656  * Remove references from every object used in @rule.
2657  * Used at rule removal code.
2658  */
2659 static void
2660 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2661 {
2662 	struct opcode_obj_rewrite *rw;
2663 	struct named_object *no;
2664 	ipfw_insn *cmd;
2665 	int cmdlen, l;
2666 	uint16_t kidx;
2667 	uint8_t subtype;
2668 
2669 	IPFW_UH_WLOCK_ASSERT(ch);
2670 
2671 	l = rule->cmd_len;
2672 	cmd = rule->cmd;
2673 	cmdlen = 0;
2674 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2675 		cmdlen = F_LEN(cmd);
2676 
2677 		rw = find_op_rw(cmd, &kidx, &subtype);
2678 		if (rw == NULL)
2679 			continue;
2680 		no = rw->find_bykidx(ch, kidx);
2681 
2682 		KASSERT(no != NULL, ("object id %d not found", kidx));
2683 		KASSERT(no->subtype == subtype,
2684 		    ("wrong type %d (%d) for object id %d",
2685 		    no->subtype, subtype, kidx));
2686 		KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2687 		    kidx, no->refcnt));
2688 
2689 		if (no->refcnt == 1 && rw->destroy_object != NULL)
2690 			rw->destroy_object(ch, no);
2691 		else
2692 			no->refcnt--;
2693 	}
2694 }
2695 
2696 
2697 /*
2698  * Find and reference object (if any) stored in instruction @cmd.
2699  *
2700  * Saves object info in @pidx, sets
2701  *  - @unresolved to 1 if object should exists but not found
2702  *
2703  * Returns non-zero value in case of error.
2704  */
2705 static int
2706 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2707     struct obj_idx *pidx, int *unresolved)
2708 {
2709 	struct named_object *no;
2710 	struct opcode_obj_rewrite *rw;
2711 	int error;
2712 
2713 	/* Check if this opcode is candidate for rewrite */
2714 	rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2715 	if (rw == NULL)
2716 		return (0);
2717 
2718 	/* Need to rewrite. Save necessary fields */
2719 	pidx->uidx = ti->uidx;
2720 	pidx->type = ti->type;
2721 
2722 	/* Try to find referenced kernel object */
2723 	error = rw->find_byname(ch, ti, &no);
2724 	if (error != 0)
2725 		return (error);
2726 	if (no == NULL) {
2727 		/*
2728 		 * Report about unresolved object for automaic
2729 		 * creation.
2730 		 */
2731 		*unresolved = 1;
2732 		return (0);
2733 	}
2734 
2735 	/*
2736 	 * Object is already exist.
2737 	 * Its subtype should match with expected value.
2738 	 */
2739 	if (ti->type != no->subtype)
2740 		return (EINVAL);
2741 
2742 	/* Bump refcount and update kidx. */
2743 	no->refcnt++;
2744 	rw->update(cmd, no->kidx);
2745 	return (0);
2746 }
2747 
2748 /*
2749  * Finds and bumps refcount for objects referenced by given @rule.
2750  * Auto-creates non-existing tables.
2751  * Fills in @oib array with userland/kernel indexes.
2752  *
2753  * Returns 0 on success.
2754  */
2755 static int
2756 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2757     struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2758 {
2759 	struct obj_idx *pidx;
2760 	ipfw_insn *cmd;
2761 	int cmdlen, error, l, unresolved;
2762 
2763 	pidx = oib;
2764 	l = rule->cmd_len;
2765 	cmd = rule->cmd;
2766 	cmdlen = 0;
2767 	error = 0;
2768 
2769 	IPFW_UH_WLOCK(ch);
2770 
2771 	/* Increase refcount on each existing referenced table. */
2772 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2773 		cmdlen = F_LEN(cmd);
2774 		unresolved = 0;
2775 
2776 		error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2777 		if (error != 0)
2778 			break;
2779 		/*
2780 		 * Compatibility stuff for old clients:
2781 		 * prepare to automaitcally create non-existing objects.
2782 		 */
2783 		if (unresolved != 0) {
2784 			pidx->off = rule->cmd_len - l;
2785 			pidx++;
2786 		}
2787 	}
2788 
2789 	if (error != 0) {
2790 		/* Unref everything we have already done */
2791 		unref_oib_objects(ch, rule->cmd, oib, pidx);
2792 		IPFW_UH_WUNLOCK(ch);
2793 		return (error);
2794 	}
2795 	IPFW_UH_WUNLOCK(ch);
2796 
2797 	/* Perform auto-creation for non-existing objects */
2798 	if (pidx != oib)
2799 		error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2800 
2801 	/* Calculate real number of dynamic objects */
2802 	ci->object_opcodes = (uint16_t)(pidx - oib);
2803 
2804 	return (error);
2805 }
2806 
2807 /*
2808  * Checks is opcode is referencing table of appropriate type.
2809  * Adds reference count for found table if true.
2810  * Rewrites user-supplied opcode values with kernel ones.
2811  *
2812  * Returns 0 on success and appropriate error code otherwise.
2813  */
2814 static int
2815 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2816 {
2817 	int error;
2818 	ipfw_insn *cmd;
2819 	uint8_t type;
2820 	struct obj_idx *p, *pidx_first, *pidx_last;
2821 	struct tid_info ti;
2822 
2823 	/*
2824 	 * Prepare an array for storing opcode indices.
2825 	 * Use stack allocation by default.
2826 	 */
2827 	if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2828 		/* Stack */
2829 		pidx_first = ci->obuf;
2830 	} else
2831 		pidx_first = malloc(
2832 		    ci->object_opcodes * sizeof(struct obj_idx),
2833 		    M_IPFW, M_WAITOK | M_ZERO);
2834 
2835 	error = 0;
2836 	type = 0;
2837 	memset(&ti, 0, sizeof(ti));
2838 
2839 	/* Use set rule is assigned to. */
2840 	ti.set = ci->krule->set;
2841 	if (ci->ctlv != NULL) {
2842 		ti.tlvs = (void *)(ci->ctlv + 1);
2843 		ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2844 	}
2845 
2846 	/* Reference all used tables and other objects */
2847 	error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2848 	if (error != 0)
2849 		goto free;
2850 	/*
2851 	 * Note that ref_rule_objects() might have updated ci->object_opcodes
2852 	 * to reflect actual number of object opcodes.
2853 	 */
2854 
2855 	/* Perform rewrite of remaining opcodes */
2856 	p = pidx_first;
2857 	pidx_last = pidx_first + ci->object_opcodes;
2858 	for (p = pidx_first; p < pidx_last; p++) {
2859 		cmd = ci->krule->cmd + p->off;
2860 		update_opcode_kidx(cmd, p->kidx);
2861 	}
2862 
2863 free:
2864 	if (pidx_first != ci->obuf)
2865 		free(pidx_first, M_IPFW);
2866 
2867 	return (error);
2868 }
2869 
2870 /*
2871  * Adds one or more rules to ipfw @chain.
2872  * Data layout (version 0)(current):
2873  * Request:
2874  * [
2875  *   ip_fw3_opheader
2876  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2877  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2878  * ]
2879  * Reply:
2880  * [
2881  *   ip_fw3_opheader
2882  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2883  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2884  * ]
2885  *
2886  * Rules in reply are modified to store their actual ruleset number.
2887  *
2888  * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2889  * according to their idx field and there has to be no duplicates.
2890  * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2891  * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2892  *
2893  * Returns 0 on success.
2894  */
2895 static int
2896 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2897     struct sockopt_data *sd)
2898 {
2899 	ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2900 	ipfw_obj_ntlv *ntlv;
2901 	int clen, error, idx;
2902 	uint32_t count, read;
2903 	struct ip_fw_rule *r;
2904 	struct rule_check_info rci, *ci, *cbuf;
2905 	int i, rsize;
2906 
2907 	op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2908 	ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2909 
2910 	read = sizeof(ip_fw3_opheader);
2911 	rtlv = NULL;
2912 	tstate = NULL;
2913 	cbuf = NULL;
2914 	memset(&rci, 0, sizeof(struct rule_check_info));
2915 
2916 	if (read + sizeof(*ctlv) > sd->valsize)
2917 		return (EINVAL);
2918 
2919 	if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2920 		clen = ctlv->head.length;
2921 		/* Check size and alignment */
2922 		if (clen > sd->valsize || clen < sizeof(*ctlv))
2923 			return (EINVAL);
2924 		if ((clen % sizeof(uint64_t)) != 0)
2925 			return (EINVAL);
2926 
2927 		/*
2928 		 * Some table names or other named objects.
2929 		 * Check for validness.
2930 		 */
2931 		count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2932 		if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2933 			return (EINVAL);
2934 
2935 		/*
2936 		 * Check each TLV.
2937 		 * Ensure TLVs are sorted ascending and
2938 		 * there are no duplicates.
2939 		 */
2940 		idx = -1;
2941 		ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2942 		while (count > 0) {
2943 			if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2944 				return (EINVAL);
2945 
2946 			error = ipfw_check_object_name_generic(ntlv->name);
2947 			if (error != 0)
2948 				return (error);
2949 
2950 			if (ntlv->idx <= idx)
2951 				return (EINVAL);
2952 
2953 			idx = ntlv->idx;
2954 			count--;
2955 			ntlv++;
2956 		}
2957 
2958 		tstate = ctlv;
2959 		read += ctlv->head.length;
2960 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2961 	}
2962 
2963 	if (read + sizeof(*ctlv) > sd->valsize)
2964 		return (EINVAL);
2965 
2966 	if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2967 		clen = ctlv->head.length;
2968 		if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2969 			return (EINVAL);
2970 		if ((clen % sizeof(uint64_t)) != 0)
2971 			return (EINVAL);
2972 
2973 		/*
2974 		 * TODO: Permit adding multiple rules at once
2975 		 */
2976 		if (ctlv->count != 1)
2977 			return (ENOTSUP);
2978 
2979 		clen -= sizeof(*ctlv);
2980 
2981 		if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2982 			return (EINVAL);
2983 
2984 		/* Allocate state for each rule or use stack */
2985 		if (ctlv->count == 1) {
2986 			memset(&rci, 0, sizeof(struct rule_check_info));
2987 			cbuf = &rci;
2988 		} else
2989 			cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2990 			    M_WAITOK | M_ZERO);
2991 		ci = cbuf;
2992 
2993 		/*
2994 		 * Check each rule for validness.
2995 		 * Ensure numbered rules are sorted ascending
2996 		 * and properly aligned
2997 		 */
2998 		idx = 0;
2999 		r = (struct ip_fw_rule *)(ctlv + 1);
3000 		count = 0;
3001 		error = 0;
3002 		while (clen > 0) {
3003 			rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
3004 			if (rsize > clen || ctlv->count <= count) {
3005 				error = EINVAL;
3006 				break;
3007 			}
3008 
3009 			ci->ctlv = tstate;
3010 			error = check_ipfw_rule1(r, rsize, ci);
3011 			if (error != 0)
3012 				break;
3013 
3014 			/* Check sorting */
3015 			if (r->rulenum != 0 && r->rulenum < idx) {
3016 				printf("rulenum %d idx %d\n", r->rulenum, idx);
3017 				error = EINVAL;
3018 				break;
3019 			}
3020 			idx = r->rulenum;
3021 
3022 			ci->urule = (caddr_t)r;
3023 
3024 			rsize = roundup2(rsize, sizeof(uint64_t));
3025 			clen -= rsize;
3026 			r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3027 			count++;
3028 			ci++;
3029 		}
3030 
3031 		if (ctlv->count != count || error != 0) {
3032 			if (cbuf != &rci)
3033 				free(cbuf, M_TEMP);
3034 			return (EINVAL);
3035 		}
3036 
3037 		rtlv = ctlv;
3038 		read += ctlv->head.length;
3039 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3040 	}
3041 
3042 	if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3043 		if (cbuf != NULL && cbuf != &rci)
3044 			free(cbuf, M_TEMP);
3045 		return (EINVAL);
3046 	}
3047 
3048 	/*
3049 	 * Passed rules seems to be valid.
3050 	 * Allocate storage and try to add them to chain.
3051 	 */
3052 	for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3053 		clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3054 		ci->krule = ipfw_alloc_rule(chain, clen);
3055 		import_rule1(ci);
3056 	}
3057 
3058 	if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3059 		/* Free allocate krules */
3060 		for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3061 			ipfw_free_rule(ci->krule);
3062 	}
3063 
3064 	if (cbuf != NULL && cbuf != &rci)
3065 		free(cbuf, M_TEMP);
3066 
3067 	return (error);
3068 }
3069 
3070 /*
3071  * Lists all sopts currently registered.
3072  * Data layout (v0)(current):
3073  * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3074  * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3075  *
3076  * Returns 0 on success
3077  */
3078 static int
3079 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3080     struct sockopt_data *sd)
3081 {
3082 	struct _ipfw_obj_lheader *olh;
3083 	ipfw_sopt_info *i;
3084 	struct ipfw_sopt_handler *sh;
3085 	uint32_t count, n, size;
3086 
3087 	olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3088 	if (olh == NULL)
3089 		return (EINVAL);
3090 	if (sd->valsize < olh->size)
3091 		return (EINVAL);
3092 
3093 	CTL3_LOCK();
3094 	count = ctl3_hsize;
3095 	size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3096 
3097 	/* Fill in header regadless of buffer size */
3098 	olh->count = count;
3099 	olh->objsize = sizeof(ipfw_sopt_info);
3100 
3101 	if (size > olh->size) {
3102 		olh->size = size;
3103 		CTL3_UNLOCK();
3104 		return (ENOMEM);
3105 	}
3106 	olh->size = size;
3107 
3108 	for (n = 1; n <= count; n++) {
3109 		i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3110 		KASSERT(i != NULL, ("previously checked buffer is not enough"));
3111 		sh = &ctl3_handlers[n];
3112 		i->opcode = sh->opcode;
3113 		i->version = sh->version;
3114 		i->refcnt = sh->refcnt;
3115 	}
3116 	CTL3_UNLOCK();
3117 
3118 	return (0);
3119 }
3120 
3121 /*
3122  * Compares two opcodes.
3123  * Used both in qsort() and bsearch().
3124  *
3125  * Returns 0 if match is found.
3126  */
3127 static int
3128 compare_opcodes(const void *_a, const void *_b)
3129 {
3130 	const struct opcode_obj_rewrite *a, *b;
3131 
3132 	a = (const struct opcode_obj_rewrite *)_a;
3133 	b = (const struct opcode_obj_rewrite *)_b;
3134 
3135 	if (a->opcode < b->opcode)
3136 		return (-1);
3137 	else if (a->opcode > b->opcode)
3138 		return (1);
3139 
3140 	return (0);
3141 }
3142 
3143 /*
3144  * XXX: Rewrite bsearch()
3145  */
3146 static int
3147 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3148     struct opcode_obj_rewrite **phi)
3149 {
3150 	struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3151 
3152 	memset(&h, 0, sizeof(h));
3153 	h.opcode = op;
3154 
3155 	rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3156 	    ctl3_rsize, sizeof(h), compare_opcodes);
3157 	if (rw == NULL)
3158 		return (1);
3159 
3160 	/* Find the first element matching the same opcode */
3161 	lo = rw;
3162 	for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3163 		;
3164 
3165 	/* Find the last element matching the same opcode */
3166 	hi = rw;
3167 	ctl3_max = ctl3_rewriters + ctl3_rsize;
3168 	for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3169 		;
3170 
3171 	*plo = lo;
3172 	*phi = hi;
3173 
3174 	return (0);
3175 }
3176 
3177 /*
3178  * Finds opcode object rewriter based on @code.
3179  *
3180  * Returns pointer to handler or NULL.
3181  */
3182 static struct opcode_obj_rewrite *
3183 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3184 {
3185 	struct opcode_obj_rewrite *rw, *lo, *hi;
3186 	uint16_t uidx;
3187 	uint8_t subtype;
3188 
3189 	if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3190 		return (NULL);
3191 
3192 	for (rw = lo; rw <= hi; rw++) {
3193 		if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3194 			if (puidx != NULL)
3195 				*puidx = uidx;
3196 			if (ptype != NULL)
3197 				*ptype = subtype;
3198 			return (rw);
3199 		}
3200 	}
3201 
3202 	return (NULL);
3203 }
3204 int
3205 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3206 {
3207 
3208 	if (find_op_rw(cmd, puidx, NULL) == NULL)
3209 		return (1);
3210 	return (0);
3211 }
3212 
3213 void
3214 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3215 {
3216 	struct opcode_obj_rewrite *rw;
3217 
3218 	rw = find_op_rw(cmd, NULL, NULL);
3219 	KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3220 	rw->update(cmd, idx);
3221 }
3222 
3223 void
3224 ipfw_init_obj_rewriter()
3225 {
3226 
3227 	ctl3_rewriters = NULL;
3228 	ctl3_rsize = 0;
3229 }
3230 
3231 void
3232 ipfw_destroy_obj_rewriter()
3233 {
3234 
3235 	if (ctl3_rewriters != NULL)
3236 		free(ctl3_rewriters, M_IPFW);
3237 	ctl3_rewriters = NULL;
3238 	ctl3_rsize = 0;
3239 }
3240 
3241 /*
3242  * Adds one or more opcode object rewrite handlers to the global array.
3243  * Function may sleep.
3244  */
3245 void
3246 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3247 {
3248 	size_t sz;
3249 	struct opcode_obj_rewrite *tmp;
3250 
3251 	CTL3_LOCK();
3252 
3253 	for (;;) {
3254 		sz = ctl3_rsize + count;
3255 		CTL3_UNLOCK();
3256 		tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3257 		CTL3_LOCK();
3258 		if (ctl3_rsize + count <= sz)
3259 			break;
3260 
3261 		/* Retry */
3262 		free(tmp, M_IPFW);
3263 	}
3264 
3265 	/* Merge old & new arrays */
3266 	sz = ctl3_rsize + count;
3267 	memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3268 	memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3269 	qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3270 	/* Switch new and free old */
3271 	if (ctl3_rewriters != NULL)
3272 		free(ctl3_rewriters, M_IPFW);
3273 	ctl3_rewriters = tmp;
3274 	ctl3_rsize = sz;
3275 
3276 	CTL3_UNLOCK();
3277 }
3278 
3279 /*
3280  * Removes one or more object rewrite handlers from the global array.
3281  */
3282 int
3283 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3284 {
3285 	size_t sz;
3286 	struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3287 	int i;
3288 
3289 	CTL3_LOCK();
3290 
3291 	for (i = 0; i < count; i++) {
3292 		if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3293 			continue;
3294 
3295 		for (ktmp = lo; ktmp <= hi; ktmp++) {
3296 			if (ktmp->classifier != rw[i].classifier)
3297 				continue;
3298 
3299 			ctl3_max = ctl3_rewriters + ctl3_rsize;
3300 			sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3301 			memmove(ktmp, ktmp + 1, sz);
3302 			ctl3_rsize--;
3303 			break;
3304 		}
3305 
3306 	}
3307 
3308 	if (ctl3_rsize == 0) {
3309 		if (ctl3_rewriters != NULL)
3310 			free(ctl3_rewriters, M_IPFW);
3311 		ctl3_rewriters = NULL;
3312 	}
3313 
3314 	CTL3_UNLOCK();
3315 
3316 	return (0);
3317 }
3318 
3319 static int
3320 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3321     struct named_object *no, void *arg)
3322 {
3323 	struct sockopt_data *sd;
3324 	ipfw_obj_ntlv *ntlv;
3325 
3326 	sd = (struct sockopt_data *)arg;
3327 	ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3328 	if (ntlv == NULL)
3329 		return (ENOMEM);
3330 	ipfw_export_obj_ntlv(no, ntlv);
3331 	return (0);
3332 }
3333 
3334 /*
3335  * Lists all service objects.
3336  * Data layout (v0)(current):
3337  * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3338  * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3339  * Returns 0 on success
3340  */
3341 static int
3342 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3343     struct sockopt_data *sd)
3344 {
3345 	ipfw_obj_lheader *hdr;
3346 	int count;
3347 
3348 	hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3349 	if (hdr == NULL)
3350 		return (EINVAL);
3351 
3352 	IPFW_UH_RLOCK(chain);
3353 	count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3354 	hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3355 	if (sd->valsize < hdr->size) {
3356 		IPFW_UH_RUNLOCK(chain);
3357 		return (ENOMEM);
3358 	}
3359 	hdr->count = count;
3360 	hdr->objsize = sizeof(ipfw_obj_ntlv);
3361 	if (count > 0)
3362 		ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3363 		    export_objhash_ntlv_internal, sd);
3364 	IPFW_UH_RUNLOCK(chain);
3365 	return (0);
3366 }
3367 
3368 /*
3369  * Compares two sopt handlers (code, version and handler ptr).
3370  * Used both as qsort() and bsearch().
3371  * Does not compare handler for latter case.
3372  *
3373  * Returns 0 if match is found.
3374  */
3375 static int
3376 compare_sh(const void *_a, const void *_b)
3377 {
3378 	const struct ipfw_sopt_handler *a, *b;
3379 
3380 	a = (const struct ipfw_sopt_handler *)_a;
3381 	b = (const struct ipfw_sopt_handler *)_b;
3382 
3383 	if (a->opcode < b->opcode)
3384 		return (-1);
3385 	else if (a->opcode > b->opcode)
3386 		return (1);
3387 
3388 	if (a->version < b->version)
3389 		return (-1);
3390 	else if (a->version > b->version)
3391 		return (1);
3392 
3393 	/* bsearch helper */
3394 	if (a->handler == NULL)
3395 		return (0);
3396 
3397 	if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3398 		return (-1);
3399 	else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3400 		return (1);
3401 
3402 	return (0);
3403 }
3404 
3405 /*
3406  * Finds sopt handler based on @code and @version.
3407  *
3408  * Returns pointer to handler or NULL.
3409  */
3410 static struct ipfw_sopt_handler *
3411 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3412 {
3413 	struct ipfw_sopt_handler *sh, h;
3414 
3415 	memset(&h, 0, sizeof(h));
3416 	h.opcode = code;
3417 	h.version = version;
3418 	h.handler = handler;
3419 
3420 	sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3421 	    ctl3_hsize, sizeof(h), compare_sh);
3422 
3423 	return (sh);
3424 }
3425 
3426 static int
3427 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3428 {
3429 	struct ipfw_sopt_handler *sh;
3430 
3431 	CTL3_LOCK();
3432 	if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3433 		CTL3_UNLOCK();
3434 		printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3435 		    opcode, version);
3436 		return (EINVAL);
3437 	}
3438 	sh->refcnt++;
3439 	ctl3_refct++;
3440 	/* Copy handler data to requested buffer */
3441 	*psh = *sh;
3442 	CTL3_UNLOCK();
3443 
3444 	return (0);
3445 }
3446 
3447 static void
3448 find_unref_sh(struct ipfw_sopt_handler *psh)
3449 {
3450 	struct ipfw_sopt_handler *sh;
3451 
3452 	CTL3_LOCK();
3453 	sh = find_sh(psh->opcode, psh->version, NULL);
3454 	KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3455 	sh->refcnt--;
3456 	ctl3_refct--;
3457 	CTL3_UNLOCK();
3458 }
3459 
3460 void
3461 ipfw_init_sopt_handler()
3462 {
3463 
3464 	CTL3_LOCK_INIT();
3465 	IPFW_ADD_SOPT_HANDLER(1, scodes);
3466 }
3467 
3468 void
3469 ipfw_destroy_sopt_handler()
3470 {
3471 
3472 	IPFW_DEL_SOPT_HANDLER(1, scodes);
3473 	CTL3_LOCK_DESTROY();
3474 }
3475 
3476 /*
3477  * Adds one or more sockopt handlers to the global array.
3478  * Function may sleep.
3479  */
3480 void
3481 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3482 {
3483 	size_t sz;
3484 	struct ipfw_sopt_handler *tmp;
3485 
3486 	CTL3_LOCK();
3487 
3488 	for (;;) {
3489 		sz = ctl3_hsize + count;
3490 		CTL3_UNLOCK();
3491 		tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3492 		CTL3_LOCK();
3493 		if (ctl3_hsize + count <= sz)
3494 			break;
3495 
3496 		/* Retry */
3497 		free(tmp, M_IPFW);
3498 	}
3499 
3500 	/* Merge old & new arrays */
3501 	sz = ctl3_hsize + count;
3502 	memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3503 	memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3504 	qsort(tmp, sz, sizeof(*sh), compare_sh);
3505 	/* Switch new and free old */
3506 	if (ctl3_handlers != NULL)
3507 		free(ctl3_handlers, M_IPFW);
3508 	ctl3_handlers = tmp;
3509 	ctl3_hsize = sz;
3510 	ctl3_gencnt++;
3511 
3512 	CTL3_UNLOCK();
3513 }
3514 
3515 /*
3516  * Removes one or more sockopt handlers from the global array.
3517  */
3518 int
3519 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3520 {
3521 	size_t sz;
3522 	struct ipfw_sopt_handler *tmp, *h;
3523 	int i;
3524 
3525 	CTL3_LOCK();
3526 
3527 	for (i = 0; i < count; i++) {
3528 		tmp = &sh[i];
3529 		h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3530 		if (h == NULL)
3531 			continue;
3532 
3533 		sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3534 		memmove(h, h + 1, sz);
3535 		ctl3_hsize--;
3536 	}
3537 
3538 	if (ctl3_hsize == 0) {
3539 		if (ctl3_handlers != NULL)
3540 			free(ctl3_handlers, M_IPFW);
3541 		ctl3_handlers = NULL;
3542 	}
3543 
3544 	ctl3_gencnt++;
3545 
3546 	CTL3_UNLOCK();
3547 
3548 	return (0);
3549 }
3550 
3551 /*
3552  * Writes data accumulated in @sd to sockopt buffer.
3553  * Zeroes internal @sd buffer.
3554  */
3555 static int
3556 ipfw_flush_sopt_data(struct sockopt_data *sd)
3557 {
3558 	struct sockopt *sopt;
3559 	int error;
3560 	size_t sz;
3561 
3562 	sz = sd->koff;
3563 	if (sz == 0)
3564 		return (0);
3565 
3566 	sopt = sd->sopt;
3567 
3568 	if (sopt->sopt_dir == SOPT_GET) {
3569 		error = copyout(sd->kbuf, sopt->sopt_val, sz);
3570 		if (error != 0)
3571 			return (error);
3572 	}
3573 
3574 	memset(sd->kbuf, 0, sd->ksize);
3575 	sd->ktotal += sz;
3576 	sd->koff = 0;
3577 	if (sd->ktotal + sd->ksize < sd->valsize)
3578 		sd->kavail = sd->ksize;
3579 	else
3580 		sd->kavail = sd->valsize - sd->ktotal;
3581 
3582 	/* Update sopt buffer data */
3583 	sopt->sopt_valsize = sd->ktotal;
3584 	sopt->sopt_val = sd->sopt_val + sd->ktotal;
3585 
3586 	return (0);
3587 }
3588 
3589 /*
3590  * Ensures that @sd buffer has contiguous @neeeded number of
3591  * bytes.
3592  *
3593  * Returns pointer to requested space or NULL.
3594  */
3595 caddr_t
3596 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3597 {
3598 	int error;
3599 	caddr_t addr;
3600 
3601 	if (sd->kavail < needed) {
3602 		/*
3603 		 * Flush data and try another time.
3604 		 */
3605 		error = ipfw_flush_sopt_data(sd);
3606 
3607 		if (sd->kavail < needed || error != 0)
3608 			return (NULL);
3609 	}
3610 
3611 	addr = sd->kbuf + sd->koff;
3612 	sd->koff += needed;
3613 	sd->kavail -= needed;
3614 	return (addr);
3615 }
3616 
3617 /*
3618  * Requests @needed contiguous bytes from @sd buffer.
3619  * Function is used to notify subsystem that we are
3620  * interesed in first @needed bytes (request header)
3621  * and the rest buffer can be safely zeroed.
3622  *
3623  * Returns pointer to requested space or NULL.
3624  */
3625 caddr_t
3626 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3627 {
3628 	caddr_t addr;
3629 
3630 	if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3631 		return (NULL);
3632 
3633 	if (sd->kavail > 0)
3634 		memset(sd->kbuf + sd->koff, 0, sd->kavail);
3635 
3636 	return (addr);
3637 }
3638 
3639 /*
3640  * New sockopt handler.
3641  */
3642 int
3643 ipfw_ctl3(struct sockopt *sopt)
3644 {
3645 	int error, locked;
3646 	size_t size, valsize;
3647 	struct ip_fw_chain *chain;
3648 	char xbuf[256];
3649 	struct sockopt_data sdata;
3650 	struct ipfw_sopt_handler h;
3651 	ip_fw3_opheader *op3 = NULL;
3652 
3653 	error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3654 	if (error != 0)
3655 		return (error);
3656 
3657 	if (sopt->sopt_name != IP_FW3)
3658 		return (ipfw_ctl(sopt));
3659 
3660 	chain = &V_layer3_chain;
3661 	error = 0;
3662 
3663 	/* Save original valsize before it is altered via sooptcopyin() */
3664 	valsize = sopt->sopt_valsize;
3665 	memset(&sdata, 0, sizeof(sdata));
3666 	/* Read op3 header first to determine actual operation */
3667 	op3 = (ip_fw3_opheader *)xbuf;
3668 	error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3669 	if (error != 0)
3670 		return (error);
3671 	sopt->sopt_valsize = valsize;
3672 
3673 	/*
3674 	 * Find and reference command.
3675 	 */
3676 	error = find_ref_sh(op3->opcode, op3->version, &h);
3677 	if (error != 0)
3678 		return (error);
3679 
3680 	/*
3681 	 * Disallow modifications in really-really secure mode, but still allow
3682 	 * the logging counters to be reset.
3683 	 */
3684 	if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3685 		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3686 		if (error != 0) {
3687 			find_unref_sh(&h);
3688 			return (error);
3689 		}
3690 	}
3691 
3692 	/*
3693 	 * Fill in sockopt_data structure that may be useful for
3694 	 * IP_FW3 get requests.
3695 	 */
3696 	locked = 0;
3697 	if (valsize <= sizeof(xbuf)) {
3698 		/* use on-stack buffer */
3699 		sdata.kbuf = xbuf;
3700 		sdata.ksize = sizeof(xbuf);
3701 		sdata.kavail = valsize;
3702 	} else {
3703 
3704 		/*
3705 		 * Determine opcode type/buffer size:
3706 		 * allocate sliding-window buf for data export or
3707 		 * contiguous buffer for special ops.
3708 		 */
3709 		if ((h.dir & HDIR_SET) != 0) {
3710 			/* Set request. Allocate contigous buffer. */
3711 			if (valsize > CTL3_LARGEBUF) {
3712 				find_unref_sh(&h);
3713 				return (EFBIG);
3714 			}
3715 
3716 			size = valsize;
3717 		} else {
3718 			/* Get request. Allocate sliding window buffer */
3719 			size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3720 
3721 			if (size < valsize) {
3722 				/* We have to wire user buffer */
3723 				error = vslock(sopt->sopt_val, valsize);
3724 				if (error != 0)
3725 					return (error);
3726 				locked = 1;
3727 			}
3728 		}
3729 
3730 		sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3731 		sdata.ksize = size;
3732 		sdata.kavail = size;
3733 	}
3734 
3735 	sdata.sopt = sopt;
3736 	sdata.sopt_val = sopt->sopt_val;
3737 	sdata.valsize = valsize;
3738 
3739 	/*
3740 	 * Copy either all request (if valsize < bsize_max)
3741 	 * or first bsize_max bytes to guarantee most consumers
3742 	 * that all necessary data has been copied).
3743 	 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3744 	 */
3745 	if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3746 	    sizeof(ip_fw3_opheader))) != 0)
3747 		return (error);
3748 	op3 = (ip_fw3_opheader *)sdata.kbuf;
3749 
3750 	/* Finally, run handler */
3751 	error = h.handler(chain, op3, &sdata);
3752 	find_unref_sh(&h);
3753 
3754 	/* Flush state and free buffers */
3755 	if (error == 0)
3756 		error = ipfw_flush_sopt_data(&sdata);
3757 	else
3758 		ipfw_flush_sopt_data(&sdata);
3759 
3760 	if (locked != 0)
3761 		vsunlock(sdata.sopt_val, valsize);
3762 
3763 	/* Restore original pointer and set number of bytes written */
3764 	sopt->sopt_val = sdata.sopt_val;
3765 	sopt->sopt_valsize = sdata.ktotal;
3766 	if (sdata.kbuf != xbuf)
3767 		free(sdata.kbuf, M_TEMP);
3768 
3769 	return (error);
3770 }
3771 
3772 /**
3773  * {set|get}sockopt parser.
3774  */
3775 int
3776 ipfw_ctl(struct sockopt *sopt)
3777 {
3778 #define	RULE_MAXSIZE	(512*sizeof(u_int32_t))
3779 	int error;
3780 	size_t size, valsize;
3781 	struct ip_fw *buf;
3782 	struct ip_fw_rule0 *rule;
3783 	struct ip_fw_chain *chain;
3784 	u_int32_t rulenum[2];
3785 	uint32_t opt;
3786 	struct rule_check_info ci;
3787 	IPFW_RLOCK_TRACKER;
3788 
3789 	chain = &V_layer3_chain;
3790 	error = 0;
3791 
3792 	/* Save original valsize before it is altered via sooptcopyin() */
3793 	valsize = sopt->sopt_valsize;
3794 	opt = sopt->sopt_name;
3795 
3796 	/*
3797 	 * Disallow modifications in really-really secure mode, but still allow
3798 	 * the logging counters to be reset.
3799 	 */
3800 	if (opt == IP_FW_ADD ||
3801 	    (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3802 		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3803 		if (error != 0)
3804 			return (error);
3805 	}
3806 
3807 	switch (opt) {
3808 	case IP_FW_GET:
3809 		/*
3810 		 * pass up a copy of the current rules. Static rules
3811 		 * come first (the last of which has number IPFW_DEFAULT_RULE),
3812 		 * followed by a possibly empty list of dynamic rule.
3813 		 * The last dynamic rule has NULL in the "next" field.
3814 		 *
3815 		 * Note that the calculated size is used to bound the
3816 		 * amount of data returned to the user.  The rule set may
3817 		 * change between calculating the size and returning the
3818 		 * data in which case we'll just return what fits.
3819 		 */
3820 		for (;;) {
3821 			int len = 0, want;
3822 
3823 			size = chain->static_len;
3824 			size += ipfw_dyn_len();
3825 			if (size >= sopt->sopt_valsize)
3826 				break;
3827 			buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3828 			IPFW_UH_RLOCK(chain);
3829 			/* check again how much space we need */
3830 			want = chain->static_len + ipfw_dyn_len();
3831 			if (size >= want)
3832 				len = ipfw_getrules(chain, buf, size);
3833 			IPFW_UH_RUNLOCK(chain);
3834 			if (size >= want)
3835 				error = sooptcopyout(sopt, buf, len);
3836 			free(buf, M_TEMP);
3837 			if (size >= want)
3838 				break;
3839 		}
3840 		break;
3841 
3842 	case IP_FW_FLUSH:
3843 		/* locking is done within del_entry() */
3844 		error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3845 		break;
3846 
3847 	case IP_FW_ADD:
3848 		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3849 		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3850 			sizeof(struct ip_fw7) );
3851 
3852 		memset(&ci, 0, sizeof(struct rule_check_info));
3853 
3854 		/*
3855 		 * If the size of commands equals RULESIZE7 then we assume
3856 		 * a FreeBSD7.2 binary is talking to us (set is7=1).
3857 		 * is7 is persistent so the next 'ipfw list' command
3858 		 * will use this format.
3859 		 * NOTE: If wrong version is guessed (this can happen if
3860 		 *       the first ipfw command is 'ipfw [pipe] list')
3861 		 *       the ipfw binary may crash or loop infinitly...
3862 		 */
3863 		size = sopt->sopt_valsize;
3864 		if (size == RULESIZE7(rule)) {
3865 		    is7 = 1;
3866 		    error = convert_rule_to_8(rule);
3867 		    if (error) {
3868 			free(rule, M_TEMP);
3869 			return error;
3870 		    }
3871 		    size = RULESIZE(rule);
3872 		} else
3873 		    is7 = 0;
3874 		if (error == 0)
3875 			error = check_ipfw_rule0(rule, size, &ci);
3876 		if (error == 0) {
3877 			/* locking is done within add_rule() */
3878 			struct ip_fw *krule;
3879 			krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3880 			ci.urule = (caddr_t)rule;
3881 			ci.krule = krule;
3882 			import_rule0(&ci);
3883 			error = commit_rules(chain, &ci, 1);
3884 			if (error != 0)
3885 				ipfw_free_rule(ci.krule);
3886 			else if (sopt->sopt_dir == SOPT_GET) {
3887 				if (is7) {
3888 					error = convert_rule_to_7(rule);
3889 					size = RULESIZE7(rule);
3890 					if (error) {
3891 						free(rule, M_TEMP);
3892 						return error;
3893 					}
3894 				}
3895 				error = sooptcopyout(sopt, rule, size);
3896 			}
3897 		}
3898 		free(rule, M_TEMP);
3899 		break;
3900 
3901 	case IP_FW_DEL:
3902 		/*
3903 		 * IP_FW_DEL is used for deleting single rules or sets,
3904 		 * and (ab)used to atomically manipulate sets. Argument size
3905 		 * is used to distinguish between the two:
3906 		 *    sizeof(u_int32_t)
3907 		 *	delete single rule or set of rules,
3908 		 *	or reassign rules (or sets) to a different set.
3909 		 *    2*sizeof(u_int32_t)
3910 		 *	atomic disable/enable sets.
3911 		 *	first u_int32_t contains sets to be disabled,
3912 		 *	second u_int32_t contains sets to be enabled.
3913 		 */
3914 		error = sooptcopyin(sopt, rulenum,
3915 			2*sizeof(u_int32_t), sizeof(u_int32_t));
3916 		if (error)
3917 			break;
3918 		size = sopt->sopt_valsize;
3919 		if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3920 			/* delete or reassign, locking done in del_entry() */
3921 			error = del_entry(chain, rulenum[0]);
3922 		} else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3923 			IPFW_UH_WLOCK(chain);
3924 			V_set_disable =
3925 			    (V_set_disable | rulenum[0]) & ~rulenum[1] &
3926 			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3927 			IPFW_UH_WUNLOCK(chain);
3928 		} else
3929 			error = EINVAL;
3930 		break;
3931 
3932 	case IP_FW_ZERO:
3933 	case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3934 		rulenum[0] = 0;
3935 		if (sopt->sopt_val != 0) {
3936 		    error = sooptcopyin(sopt, rulenum,
3937 			    sizeof(u_int32_t), sizeof(u_int32_t));
3938 		    if (error)
3939 			break;
3940 		}
3941 		error = zero_entry(chain, rulenum[0],
3942 			sopt->sopt_name == IP_FW_RESETLOG);
3943 		break;
3944 
3945 	/*--- TABLE opcodes ---*/
3946 	case IP_FW_TABLE_ADD:
3947 	case IP_FW_TABLE_DEL:
3948 		{
3949 			ipfw_table_entry ent;
3950 			struct tentry_info tei;
3951 			struct tid_info ti;
3952 			struct table_value v;
3953 
3954 			error = sooptcopyin(sopt, &ent,
3955 			    sizeof(ent), sizeof(ent));
3956 			if (error)
3957 				break;
3958 
3959 			memset(&tei, 0, sizeof(tei));
3960 			tei.paddr = &ent.addr;
3961 			tei.subtype = AF_INET;
3962 			tei.masklen = ent.masklen;
3963 			ipfw_import_table_value_legacy(ent.value, &v);
3964 			tei.pvalue = &v;
3965 			memset(&ti, 0, sizeof(ti));
3966 			ti.uidx = ent.tbl;
3967 			ti.type = IPFW_TABLE_CIDR;
3968 
3969 			error = (opt == IP_FW_TABLE_ADD) ?
3970 			    add_table_entry(chain, &ti, &tei, 0, 1) :
3971 			    del_table_entry(chain, &ti, &tei, 0, 1);
3972 		}
3973 		break;
3974 
3975 
3976 	case IP_FW_TABLE_FLUSH:
3977 		{
3978 			u_int16_t tbl;
3979 			struct tid_info ti;
3980 
3981 			error = sooptcopyin(sopt, &tbl,
3982 			    sizeof(tbl), sizeof(tbl));
3983 			if (error)
3984 				break;
3985 			memset(&ti, 0, sizeof(ti));
3986 			ti.uidx = tbl;
3987 			error = flush_table(chain, &ti);
3988 		}
3989 		break;
3990 
3991 	case IP_FW_TABLE_GETSIZE:
3992 		{
3993 			u_int32_t tbl, cnt;
3994 			struct tid_info ti;
3995 
3996 			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3997 			    sizeof(tbl))))
3998 				break;
3999 			memset(&ti, 0, sizeof(ti));
4000 			ti.uidx = tbl;
4001 			IPFW_RLOCK(chain);
4002 			error = ipfw_count_table(chain, &ti, &cnt);
4003 			IPFW_RUNLOCK(chain);
4004 			if (error)
4005 				break;
4006 			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4007 		}
4008 		break;
4009 
4010 	case IP_FW_TABLE_LIST:
4011 		{
4012 			ipfw_table *tbl;
4013 			struct tid_info ti;
4014 
4015 			if (sopt->sopt_valsize < sizeof(*tbl)) {
4016 				error = EINVAL;
4017 				break;
4018 			}
4019 			size = sopt->sopt_valsize;
4020 			tbl = malloc(size, M_TEMP, M_WAITOK);
4021 			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4022 			if (error) {
4023 				free(tbl, M_TEMP);
4024 				break;
4025 			}
4026 			tbl->size = (size - sizeof(*tbl)) /
4027 			    sizeof(ipfw_table_entry);
4028 			memset(&ti, 0, sizeof(ti));
4029 			ti.uidx = tbl->tbl;
4030 			IPFW_RLOCK(chain);
4031 			error = ipfw_dump_table_legacy(chain, &ti, tbl);
4032 			IPFW_RUNLOCK(chain);
4033 			if (error) {
4034 				free(tbl, M_TEMP);
4035 				break;
4036 			}
4037 			error = sooptcopyout(sopt, tbl, size);
4038 			free(tbl, M_TEMP);
4039 		}
4040 		break;
4041 
4042 	/*--- NAT operations are protected by the IPFW_LOCK ---*/
4043 	case IP_FW_NAT_CFG:
4044 		if (IPFW_NAT_LOADED)
4045 			error = ipfw_nat_cfg_ptr(sopt);
4046 		else {
4047 			printf("IP_FW_NAT_CFG: %s\n",
4048 			    "ipfw_nat not present, please load it");
4049 			error = EINVAL;
4050 		}
4051 		break;
4052 
4053 	case IP_FW_NAT_DEL:
4054 		if (IPFW_NAT_LOADED)
4055 			error = ipfw_nat_del_ptr(sopt);
4056 		else {
4057 			printf("IP_FW_NAT_DEL: %s\n",
4058 			    "ipfw_nat not present, please load it");
4059 			error = EINVAL;
4060 		}
4061 		break;
4062 
4063 	case IP_FW_NAT_GET_CONFIG:
4064 		if (IPFW_NAT_LOADED)
4065 			error = ipfw_nat_get_cfg_ptr(sopt);
4066 		else {
4067 			printf("IP_FW_NAT_GET_CFG: %s\n",
4068 			    "ipfw_nat not present, please load it");
4069 			error = EINVAL;
4070 		}
4071 		break;
4072 
4073 	case IP_FW_NAT_GET_LOG:
4074 		if (IPFW_NAT_LOADED)
4075 			error = ipfw_nat_get_log_ptr(sopt);
4076 		else {
4077 			printf("IP_FW_NAT_GET_LOG: %s\n",
4078 			    "ipfw_nat not present, please load it");
4079 			error = EINVAL;
4080 		}
4081 		break;
4082 
4083 	default:
4084 		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4085 		error = EINVAL;
4086 	}
4087 
4088 	return (error);
4089 #undef RULE_MAXSIZE
4090 }
4091 #define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
4092 
4093 /* Functions to convert rules 7.2 <==> 8.0 */
4094 static int
4095 convert_rule_to_7(struct ip_fw_rule0 *rule)
4096 {
4097 	/* Used to modify original rule */
4098 	struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4099 	/* copy of original rule, version 8 */
4100 	struct ip_fw_rule0 *tmp;
4101 
4102 	/* Used to copy commands */
4103 	ipfw_insn *ccmd, *dst;
4104 	int ll = 0, ccmdlen = 0;
4105 
4106 	tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4107 	if (tmp == NULL) {
4108 		return 1; //XXX error
4109 	}
4110 	bcopy(rule, tmp, RULE_MAXSIZE);
4111 
4112 	/* Copy fields */
4113 	//rule7->_pad = tmp->_pad;
4114 	rule7->set = tmp->set;
4115 	rule7->rulenum = tmp->rulenum;
4116 	rule7->cmd_len = tmp->cmd_len;
4117 	rule7->act_ofs = tmp->act_ofs;
4118 	rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4119 	rule7->cmd_len = tmp->cmd_len;
4120 	rule7->pcnt = tmp->pcnt;
4121 	rule7->bcnt = tmp->bcnt;
4122 	rule7->timestamp = tmp->timestamp;
4123 
4124 	/* Copy commands */
4125 	for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4126 			ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4127 		ccmdlen = F_LEN(ccmd);
4128 
4129 		bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4130 
4131 		if (dst->opcode > O_NAT)
4132 			/* O_REASS doesn't exists in 7.2 version, so
4133 			 * decrement opcode if it is after O_REASS
4134 			 */
4135 			dst->opcode--;
4136 
4137 		if (ccmdlen > ll) {
4138 			printf("ipfw: opcode %d size truncated\n",
4139 				ccmd->opcode);
4140 			return EINVAL;
4141 		}
4142 	}
4143 	free(tmp, M_TEMP);
4144 
4145 	return 0;
4146 }
4147 
4148 static int
4149 convert_rule_to_8(struct ip_fw_rule0 *rule)
4150 {
4151 	/* Used to modify original rule */
4152 	struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4153 
4154 	/* Used to copy commands */
4155 	ipfw_insn *ccmd, *dst;
4156 	int ll = 0, ccmdlen = 0;
4157 
4158 	/* Copy of original rule */
4159 	struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4160 	if (tmp == NULL) {
4161 		return 1; //XXX error
4162 	}
4163 
4164 	bcopy(rule7, tmp, RULE_MAXSIZE);
4165 
4166 	for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4167 			ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4168 		ccmdlen = F_LEN(ccmd);
4169 
4170 		bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4171 
4172 		if (dst->opcode > O_NAT)
4173 			/* O_REASS doesn't exists in 7.2 version, so
4174 			 * increment opcode if it is after O_REASS
4175 			 */
4176 			dst->opcode++;
4177 
4178 		if (ccmdlen > ll) {
4179 			printf("ipfw: opcode %d size truncated\n",
4180 			    ccmd->opcode);
4181 			return EINVAL;
4182 		}
4183 	}
4184 
4185 	rule->_pad = tmp->_pad;
4186 	rule->set = tmp->set;
4187 	rule->rulenum = tmp->rulenum;
4188 	rule->cmd_len = tmp->cmd_len;
4189 	rule->act_ofs = tmp->act_ofs;
4190 	rule->next_rule = (struct ip_fw *)tmp->next_rule;
4191 	rule->cmd_len = tmp->cmd_len;
4192 	rule->id = 0; /* XXX see if is ok = 0 */
4193 	rule->pcnt = tmp->pcnt;
4194 	rule->bcnt = tmp->bcnt;
4195 	rule->timestamp = tmp->timestamp;
4196 
4197 	free (tmp, M_TEMP);
4198 	return 0;
4199 }
4200 
4201 /*
4202  * Named object api
4203  *
4204  */
4205 
4206 void
4207 ipfw_init_srv(struct ip_fw_chain *ch)
4208 {
4209 
4210 	ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4211 	ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4212 	    M_IPFW, M_WAITOK | M_ZERO);
4213 }
4214 
4215 void
4216 ipfw_destroy_srv(struct ip_fw_chain *ch)
4217 {
4218 
4219 	free(ch->srvstate, M_IPFW);
4220 	ipfw_objhash_destroy(ch->srvmap);
4221 }
4222 
4223 /*
4224  * Allocate new bitmask which can be used to enlarge/shrink
4225  * named instance index.
4226  */
4227 void
4228 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4229 {
4230 	size_t size;
4231 	int max_blocks;
4232 	u_long *idx_mask;
4233 
4234 	KASSERT((items % BLOCK_ITEMS) == 0,
4235 	   ("bitmask size needs to power of 2 and greater or equal to %zu",
4236 	    BLOCK_ITEMS));
4237 
4238 	max_blocks = items / BLOCK_ITEMS;
4239 	size = items / 8;
4240 	idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4241 	/* Mark all as free */
4242 	memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4243 	*idx_mask &= ~(u_long)1; /* Skip index 0 */
4244 
4245 	*idx = idx_mask;
4246 	*pblocks = max_blocks;
4247 }
4248 
4249 /*
4250  * Copy current bitmask index to new one.
4251  */
4252 void
4253 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4254 {
4255 	int old_blocks, new_blocks;
4256 	u_long *old_idx, *new_idx;
4257 	int i;
4258 
4259 	old_idx = ni->idx_mask;
4260 	old_blocks = ni->max_blocks;
4261 	new_idx = *idx;
4262 	new_blocks = *blocks;
4263 
4264 	for (i = 0; i < IPFW_MAX_SETS; i++) {
4265 		memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4266 		    old_blocks * sizeof(u_long));
4267 	}
4268 }
4269 
4270 /*
4271  * Swaps current @ni index with new one.
4272  */
4273 void
4274 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4275 {
4276 	int old_blocks;
4277 	u_long *old_idx;
4278 
4279 	old_idx = ni->idx_mask;
4280 	old_blocks = ni->max_blocks;
4281 
4282 	ni->idx_mask = *idx;
4283 	ni->max_blocks = *blocks;
4284 
4285 	/* Save old values */
4286 	*idx = old_idx;
4287 	*blocks = old_blocks;
4288 }
4289 
4290 void
4291 ipfw_objhash_bitmap_free(void *idx, int blocks)
4292 {
4293 
4294 	free(idx, M_IPFW);
4295 }
4296 
4297 /*
4298  * Creates named hash instance.
4299  * Must be called without holding any locks.
4300  * Return pointer to new instance.
4301  */
4302 struct namedobj_instance *
4303 ipfw_objhash_create(uint32_t items)
4304 {
4305 	struct namedobj_instance *ni;
4306 	int i;
4307 	size_t size;
4308 
4309 	size = sizeof(struct namedobj_instance) +
4310 	    sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4311 	    sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4312 
4313 	ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4314 	ni->nn_size = NAMEDOBJ_HASH_SIZE;
4315 	ni->nv_size = NAMEDOBJ_HASH_SIZE;
4316 
4317 	ni->names = (struct namedobjects_head *)(ni +1);
4318 	ni->values = &ni->names[ni->nn_size];
4319 
4320 	for (i = 0; i < ni->nn_size; i++)
4321 		TAILQ_INIT(&ni->names[i]);
4322 
4323 	for (i = 0; i < ni->nv_size; i++)
4324 		TAILQ_INIT(&ni->values[i]);
4325 
4326 	/* Set default hashing/comparison functions */
4327 	ni->hash_f = objhash_hash_name;
4328 	ni->cmp_f = objhash_cmp_name;
4329 
4330 	/* Allocate bitmask separately due to possible resize */
4331 	ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4332 
4333 	return (ni);
4334 }
4335 
4336 void
4337 ipfw_objhash_destroy(struct namedobj_instance *ni)
4338 {
4339 
4340 	free(ni->idx_mask, M_IPFW);
4341 	free(ni, M_IPFW);
4342 }
4343 
4344 void
4345 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4346     objhash_cmp_f *cmp_f)
4347 {
4348 
4349 	ni->hash_f = hash_f;
4350 	ni->cmp_f = cmp_f;
4351 }
4352 
4353 static uint32_t
4354 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4355 {
4356 
4357 	return (fnv_32_str((const char *)name, FNV1_32_INIT));
4358 }
4359 
4360 static int
4361 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4362 {
4363 
4364 	if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4365 		return (0);
4366 
4367 	return (1);
4368 }
4369 
4370 static uint32_t
4371 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4372 {
4373 	uint32_t v;
4374 
4375 	v = val % (ni->nv_size - 1);
4376 
4377 	return (v);
4378 }
4379 
4380 struct named_object *
4381 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4382 {
4383 	struct named_object *no;
4384 	uint32_t hash;
4385 
4386 	hash = ni->hash_f(ni, name, set) % ni->nn_size;
4387 
4388 	TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4389 		if (ni->cmp_f(no, name, set) == 0)
4390 			return (no);
4391 	}
4392 
4393 	return (NULL);
4394 }
4395 
4396 /*
4397  * Find named object by @uid.
4398  * Check @tlvs for valid data inside.
4399  *
4400  * Returns pointer to found TLV or NULL.
4401  */
4402 ipfw_obj_ntlv *
4403 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4404 {
4405 	ipfw_obj_ntlv *ntlv;
4406 	uintptr_t pa, pe;
4407 	int l;
4408 
4409 	pa = (uintptr_t)tlvs;
4410 	pe = pa + len;
4411 	l = 0;
4412 	for (; pa < pe; pa += l) {
4413 		ntlv = (ipfw_obj_ntlv *)pa;
4414 		l = ntlv->head.length;
4415 
4416 		if (l != sizeof(*ntlv))
4417 			return (NULL);
4418 
4419 		if (ntlv->idx != uidx)
4420 			continue;
4421 		/*
4422 		 * When userland has specified zero TLV type, do
4423 		 * not compare it with eltv. In some cases userland
4424 		 * doesn't know what type should it have. Use only
4425 		 * uidx and name for search named_object.
4426 		 */
4427 		if (ntlv->head.type != 0 &&
4428 		    ntlv->head.type != (uint16_t)etlv)
4429 			continue;
4430 
4431 		if (ipfw_check_object_name_generic(ntlv->name) != 0)
4432 			return (NULL);
4433 
4434 		return (ntlv);
4435 	}
4436 
4437 	return (NULL);
4438 }
4439 
4440 /*
4441  * Finds object config based on either legacy index
4442  * or name in ntlv.
4443  * Note @ti structure contains unchecked data from userland.
4444  *
4445  * Returns 0 in success and fills in @pno with found config
4446  */
4447 int
4448 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4449     uint32_t etlv, struct named_object **pno)
4450 {
4451 	char *name;
4452 	ipfw_obj_ntlv *ntlv;
4453 	uint32_t set;
4454 
4455 	if (ti->tlvs == NULL)
4456 		return (EINVAL);
4457 
4458 	ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4459 	if (ntlv == NULL)
4460 		return (EINVAL);
4461 	name = ntlv->name;
4462 
4463 	/*
4464 	 * Use set provided by @ti instead of @ntlv one.
4465 	 * This is needed due to different sets behavior
4466 	 * controlled by V_fw_tables_sets.
4467 	 */
4468 	set = ti->set;
4469 	*pno = ipfw_objhash_lookup_name(ni, set, name);
4470 	if (*pno == NULL)
4471 		return (ESRCH);
4472 	return (0);
4473 }
4474 
4475 /*
4476  * Find named object by name, considering also its TLV type.
4477  */
4478 struct named_object *
4479 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4480     uint32_t type, const char *name)
4481 {
4482 	struct named_object *no;
4483 	uint32_t hash;
4484 
4485 	hash = ni->hash_f(ni, name, set) % ni->nn_size;
4486 
4487 	TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4488 		if (ni->cmp_f(no, name, set) == 0 &&
4489 		    no->etlv == (uint16_t)type)
4490 			return (no);
4491 	}
4492 
4493 	return (NULL);
4494 }
4495 
4496 struct named_object *
4497 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4498 {
4499 	struct named_object *no;
4500 	uint32_t hash;
4501 
4502 	hash = objhash_hash_idx(ni, kidx);
4503 
4504 	TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4505 		if (no->kidx == kidx)
4506 			return (no);
4507 	}
4508 
4509 	return (NULL);
4510 }
4511 
4512 int
4513 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4514     struct named_object *b)
4515 {
4516 
4517 	if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4518 		return (1);
4519 
4520 	return (0);
4521 }
4522 
4523 void
4524 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4525 {
4526 	uint32_t hash;
4527 
4528 	hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4529 	TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4530 
4531 	hash = objhash_hash_idx(ni, no->kidx);
4532 	TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4533 
4534 	ni->count++;
4535 }
4536 
4537 void
4538 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4539 {
4540 	uint32_t hash;
4541 
4542 	hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4543 	TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4544 
4545 	hash = objhash_hash_idx(ni, no->kidx);
4546 	TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4547 
4548 	ni->count--;
4549 }
4550 
4551 uint32_t
4552 ipfw_objhash_count(struct namedobj_instance *ni)
4553 {
4554 
4555 	return (ni->count);
4556 }
4557 
4558 uint32_t
4559 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4560 {
4561 	struct named_object *no;
4562 	uint32_t count;
4563 	int i;
4564 
4565 	count = 0;
4566 	for (i = 0; i < ni->nn_size; i++) {
4567 		TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4568 			if (no->etlv == type)
4569 				count++;
4570 		}
4571 	}
4572 	return (count);
4573 }
4574 
4575 /*
4576  * Runs @func for each found named object.
4577  * It is safe to delete objects from callback
4578  */
4579 int
4580 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4581 {
4582 	struct named_object *no, *no_tmp;
4583 	int i, ret;
4584 
4585 	for (i = 0; i < ni->nn_size; i++) {
4586 		TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4587 			ret = f(ni, no, arg);
4588 			if (ret != 0)
4589 				return (ret);
4590 		}
4591 	}
4592 	return (0);
4593 }
4594 
4595 /*
4596  * Runs @f for each found named object with type @type.
4597  * It is safe to delete objects from callback
4598  */
4599 int
4600 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4601     void *arg, uint16_t type)
4602 {
4603 	struct named_object *no, *no_tmp;
4604 	int i, ret;
4605 
4606 	for (i = 0; i < ni->nn_size; i++) {
4607 		TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4608 			if (no->etlv != type)
4609 				continue;
4610 			ret = f(ni, no, arg);
4611 			if (ret != 0)
4612 				return (ret);
4613 		}
4614 	}
4615 	return (0);
4616 }
4617 
4618 /*
4619  * Removes index from given set.
4620  * Returns 0 on success.
4621  */
4622 int
4623 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4624 {
4625 	u_long *mask;
4626 	int i, v;
4627 
4628 	i = idx / BLOCK_ITEMS;
4629 	v = idx % BLOCK_ITEMS;
4630 
4631 	if (i >= ni->max_blocks)
4632 		return (1);
4633 
4634 	mask = &ni->idx_mask[i];
4635 
4636 	if ((*mask & ((u_long)1 << v)) != 0)
4637 		return (1);
4638 
4639 	/* Mark as free */
4640 	*mask |= (u_long)1 << v;
4641 
4642 	/* Update free offset */
4643 	if (ni->free_off[0] > i)
4644 		ni->free_off[0] = i;
4645 
4646 	return (0);
4647 }
4648 
4649 /*
4650  * Allocate new index in given instance and stores in in @pidx.
4651  * Returns 0 on success.
4652  */
4653 int
4654 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4655 {
4656 	struct namedobj_instance *ni;
4657 	u_long *mask;
4658 	int i, off, v;
4659 
4660 	ni = (struct namedobj_instance *)n;
4661 
4662 	off = ni->free_off[0];
4663 	mask = &ni->idx_mask[off];
4664 
4665 	for (i = off; i < ni->max_blocks; i++, mask++) {
4666 		if ((v = ffsl(*mask)) == 0)
4667 			continue;
4668 
4669 		/* Mark as busy */
4670 		*mask &= ~ ((u_long)1 << (v - 1));
4671 
4672 		ni->free_off[0] = i;
4673 
4674 		v = BLOCK_ITEMS * i + v - 1;
4675 
4676 		*pidx = v;
4677 		return (0);
4678 	}
4679 
4680 	return (1);
4681 }
4682 
4683 /* end of file */
4684