xref: /freebsd/sys/netpfil/ipfw/ip_fw_sockopt.c (revision d6eb98610fa65663bf0df4574b7cb2c5c4ffda71)
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 
1181 /*
1182  * Changes set of given rule rannge @rt
1183  * with each other.
1184  *
1185  * Returns 0 on success.
1186  */
1187 static int
1188 move_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1189 {
1190 	struct ip_fw *rule;
1191 	int i;
1192 
1193 	IPFW_UH_WLOCK(chain);
1194 
1195 	/*
1196 	 * Move rules with matching paramenerts to a new set.
1197 	 * This one is much more complex. We have to ensure
1198 	 * that all referenced tables (if any) are referenced
1199 	 * by given rule subset only. Otherwise, we can't move
1200 	 * them to new set and have to return error.
1201 	 */
1202 	if ((i = move_objects(chain, rt)) != 0) {
1203 		IPFW_UH_WUNLOCK(chain);
1204 		return (i);
1205 	}
1206 
1207 	/* XXX: We have to do swap holding WLOCK */
1208 	for (i = 0; i < chain->n_rules; i++) {
1209 		rule = chain->map[i];
1210 		if (ipfw_match_range(rule, rt) == 0)
1211 			continue;
1212 		rule->set = rt->new_set;
1213 	}
1214 
1215 	IPFW_UH_WUNLOCK(chain);
1216 
1217 	return (0);
1218 }
1219 
1220 /*
1221  * Clear counters for a specific rule.
1222  * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
1223  * so we only care that rules do not disappear.
1224  */
1225 static void
1226 clear_counters(struct ip_fw *rule, int log_only)
1227 {
1228 	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
1229 
1230 	if (log_only == 0)
1231 		IPFW_ZERO_RULE_COUNTER(rule);
1232 	if (l->o.opcode == O_LOG)
1233 		l->log_left = l->max_log;
1234 }
1235 
1236 /*
1237  * Flushes rules counters and/or log values on matching range.
1238  *
1239  * Returns number of items cleared.
1240  */
1241 static int
1242 clear_range(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int log_only)
1243 {
1244 	struct ip_fw *rule;
1245 	int num;
1246 	int i;
1247 
1248 	num = 0;
1249 	rt->flags |= IPFW_RCFLAG_DEFAULT;
1250 
1251 	IPFW_UH_WLOCK(chain);	/* arbitrate writers */
1252 	for (i = 0; i < chain->n_rules; i++) {
1253 		rule = chain->map[i];
1254 		if (ipfw_match_range(rule, rt) == 0)
1255 			continue;
1256 		clear_counters(rule, log_only);
1257 		num++;
1258 	}
1259 	IPFW_UH_WUNLOCK(chain);
1260 
1261 	return (num);
1262 }
1263 
1264 static int
1265 check_range_tlv(ipfw_range_tlv *rt)
1266 {
1267 
1268 	if (rt->head.length != sizeof(*rt))
1269 		return (1);
1270 	if (rt->start_rule > rt->end_rule)
1271 		return (1);
1272 	if (rt->set >= IPFW_MAX_SETS || rt->new_set >= IPFW_MAX_SETS)
1273 		return (1);
1274 
1275 	if ((rt->flags & IPFW_RCFLAG_USER) != rt->flags)
1276 		return (1);
1277 
1278 	return (0);
1279 }
1280 
1281 /*
1282  * Delete rules matching specified parameters
1283  * Data layout (v0)(current):
1284  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1285  * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1286  *
1287  * Saves number of deleted rules in ipfw_range_tlv->new_set.
1288  *
1289  * Returns 0 on success.
1290  */
1291 static int
1292 del_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1293     struct sockopt_data *sd)
1294 {
1295 	ipfw_range_header *rh;
1296 	int error, ndel;
1297 
1298 	if (sd->valsize != sizeof(*rh))
1299 		return (EINVAL);
1300 
1301 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1302 
1303 	if (check_range_tlv(&rh->range) != 0)
1304 		return (EINVAL);
1305 
1306 	ndel = 0;
1307 	if ((error = delete_range(chain, &rh->range, &ndel)) != 0)
1308 		return (error);
1309 
1310 	/* Save number of rules deleted */
1311 	rh->range.new_set = ndel;
1312 	return (0);
1313 }
1314 
1315 /*
1316  * Move rules/sets matching specified parameters
1317  * Data layout (v0)(current):
1318  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1319  *
1320  * Returns 0 on success.
1321  */
1322 static int
1323 move_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1324     struct sockopt_data *sd)
1325 {
1326 	ipfw_range_header *rh;
1327 
1328 	if (sd->valsize != sizeof(*rh))
1329 		return (EINVAL);
1330 
1331 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1332 
1333 	if (check_range_tlv(&rh->range) != 0)
1334 		return (EINVAL);
1335 
1336 	return (move_range(chain, &rh->range));
1337 }
1338 
1339 /*
1340  * Clear rule accounting data matching specified parameters
1341  * Data layout (v0)(current):
1342  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1343  * Reply: [ ipfw_obj_header ipfw_range_tlv ]
1344  *
1345  * Saves number of cleared rules in ipfw_range_tlv->new_set.
1346  *
1347  * Returns 0 on success.
1348  */
1349 static int
1350 clear_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1351     struct sockopt_data *sd)
1352 {
1353 	ipfw_range_header *rh;
1354 	int log_only, num;
1355 	char *msg;
1356 
1357 	if (sd->valsize != sizeof(*rh))
1358 		return (EINVAL);
1359 
1360 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1361 
1362 	if (check_range_tlv(&rh->range) != 0)
1363 		return (EINVAL);
1364 
1365 	log_only = (op3->opcode == IP_FW_XRESETLOG);
1366 
1367 	num = clear_range(chain, &rh->range, log_only);
1368 
1369 	if (rh->range.flags & IPFW_RCFLAG_ALL)
1370 		msg = log_only ? "All logging counts reset" :
1371 		    "Accounting cleared";
1372 	else
1373 		msg = log_only ? "logging count reset" : "cleared";
1374 
1375 	if (V_fw_verbose) {
1376 		int lev = LOG_SECURITY | LOG_NOTICE;
1377 		log(lev, "ipfw: %s.\n", msg);
1378 	}
1379 
1380 	/* Save number of rules cleared */
1381 	rh->range.new_set = num;
1382 	return (0);
1383 }
1384 
1385 static void
1386 enable_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1387 {
1388 	uint32_t v_set;
1389 
1390 	IPFW_UH_WLOCK_ASSERT(chain);
1391 
1392 	/* Change enabled/disabled sets mask */
1393 	v_set = (V_set_disable | rt->set) & ~rt->new_set;
1394 	v_set &= ~(1 << RESVD_SET); /* set RESVD_SET always enabled */
1395 	IPFW_WLOCK(chain);
1396 	V_set_disable = v_set;
1397 	IPFW_WUNLOCK(chain);
1398 }
1399 
1400 static int
1401 swap_sets(struct ip_fw_chain *chain, ipfw_range_tlv *rt, int mv)
1402 {
1403 	struct opcode_obj_rewrite *rw;
1404 	struct ip_fw *rule;
1405 	int i;
1406 
1407 	IPFW_UH_WLOCK_ASSERT(chain);
1408 
1409 	if (rt->set == rt->new_set) /* nothing to do */
1410 		return (0);
1411 
1412 	if (mv != 0) {
1413 		/*
1414 		 * Berfore moving the rules we need to check that
1415 		 * there aren't any conflicting named objects.
1416 		 */
1417 		for (rw = ctl3_rewriters;
1418 		    rw < ctl3_rewriters + ctl3_rsize; rw++) {
1419 			if (rw->manage_sets == NULL)
1420 				continue;
1421 			i = rw->manage_sets(chain, (uint8_t)rt->set,
1422 			    (uint8_t)rt->new_set, TEST_ALL);
1423 			if (i != 0)
1424 				return (EEXIST);
1425 		}
1426 	}
1427 	/* Swap or move two sets */
1428 	for (i = 0; i < chain->n_rules - 1; i++) {
1429 		rule = chain->map[i];
1430 		if (rule->set == (uint8_t)rt->set)
1431 			rule->set = (uint8_t)rt->new_set;
1432 		else if (rule->set == (uint8_t)rt->new_set && mv == 0)
1433 			rule->set = (uint8_t)rt->set;
1434 	}
1435 	for (rw = ctl3_rewriters; rw < ctl3_rewriters + ctl3_rsize; rw++) {
1436 		if (rw->manage_sets == NULL)
1437 			continue;
1438 		rw->manage_sets(chain, (uint8_t)rt->set,
1439 		    (uint8_t)rt->new_set, mv != 0 ? MOVE_ALL: SWAP_ALL);
1440 	}
1441 	return (0);
1442 }
1443 
1444 /*
1445  * Swaps or moves set
1446  * Data layout (v0)(current):
1447  * Request: [ ipfw_obj_header ipfw_range_tlv ]
1448  *
1449  * Returns 0 on success.
1450  */
1451 static int
1452 manage_sets(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
1453     struct sockopt_data *sd)
1454 {
1455 	ipfw_range_header *rh;
1456 	int ret;
1457 
1458 	if (sd->valsize != sizeof(*rh))
1459 		return (EINVAL);
1460 
1461 	rh = (ipfw_range_header *)ipfw_get_sopt_space(sd, sd->valsize);
1462 
1463 	if (rh->range.head.length != sizeof(ipfw_range_tlv))
1464 		return (1);
1465 	/* enable_sets() expects bitmasks. */
1466 	if (op3->opcode != IP_FW_SET_ENABLE &&
1467 	    (rh->range.set >= IPFW_MAX_SETS ||
1468 	    rh->range.new_set >= IPFW_MAX_SETS))
1469 		return (EINVAL);
1470 
1471 	ret = 0;
1472 	IPFW_UH_WLOCK(chain);
1473 	switch (op3->opcode) {
1474 	case IP_FW_SET_SWAP:
1475 	case IP_FW_SET_MOVE:
1476 		ret = swap_sets(chain, &rh->range,
1477 		    op3->opcode == IP_FW_SET_MOVE);
1478 		break;
1479 	case IP_FW_SET_ENABLE:
1480 		enable_sets(chain, &rh->range);
1481 		break;
1482 	}
1483 	IPFW_UH_WUNLOCK(chain);
1484 
1485 	return (ret);
1486 }
1487 
1488 /**
1489  * Remove all rules with given number, or do set manipulation.
1490  * Assumes chain != NULL && *chain != NULL.
1491  *
1492  * The argument is an uint32_t. The low 16 bit are the rule or set number;
1493  * the next 8 bits are the new set; the top 8 bits indicate the command:
1494  *
1495  *	0	delete rules numbered "rulenum"
1496  *	1	delete rules in set "rulenum"
1497  *	2	move rules "rulenum" to set "new_set"
1498  *	3	move rules from set "rulenum" to set "new_set"
1499  *	4	swap sets "rulenum" and "new_set"
1500  *	5	delete rules "rulenum" and set "new_set"
1501  */
1502 static int
1503 del_entry(struct ip_fw_chain *chain, uint32_t arg)
1504 {
1505 	uint32_t num;	/* rule number or old_set */
1506 	uint8_t cmd, new_set;
1507 	int do_del, ndel;
1508 	int error = 0;
1509 	ipfw_range_tlv rt;
1510 
1511 	num = arg & 0xffff;
1512 	cmd = (arg >> 24) & 0xff;
1513 	new_set = (arg >> 16) & 0xff;
1514 
1515 	if (cmd > 5 || new_set > RESVD_SET)
1516 		return EINVAL;
1517 	if (cmd == 0 || cmd == 2 || cmd == 5) {
1518 		if (num >= IPFW_DEFAULT_RULE)
1519 			return EINVAL;
1520 	} else {
1521 		if (num > RESVD_SET)	/* old_set */
1522 			return EINVAL;
1523 	}
1524 
1525 	/* Convert old requests into new representation */
1526 	memset(&rt, 0, sizeof(rt));
1527 	rt.start_rule = num;
1528 	rt.end_rule = num;
1529 	rt.set = num;
1530 	rt.new_set = new_set;
1531 	do_del = 0;
1532 
1533 	switch (cmd) {
1534 	case 0: /* delete rules numbered "rulenum" */
1535 		if (num == 0)
1536 			rt.flags |= IPFW_RCFLAG_ALL;
1537 		else
1538 			rt.flags |= IPFW_RCFLAG_RANGE;
1539 		do_del = 1;
1540 		break;
1541 	case 1: /* delete rules in set "rulenum" */
1542 		rt.flags |= IPFW_RCFLAG_SET;
1543 		do_del = 1;
1544 		break;
1545 	case 5: /* delete rules "rulenum" and set "new_set" */
1546 		rt.flags |= IPFW_RCFLAG_RANGE | IPFW_RCFLAG_SET;
1547 		rt.set = new_set;
1548 		rt.new_set = 0;
1549 		do_del = 1;
1550 		break;
1551 	case 2: /* move rules "rulenum" to set "new_set" */
1552 		rt.flags |= IPFW_RCFLAG_RANGE;
1553 		break;
1554 	case 3: /* move rules from set "rulenum" to set "new_set" */
1555 		IPFW_UH_WLOCK(chain);
1556 		error = swap_sets(chain, &rt, 1);
1557 		IPFW_UH_WUNLOCK(chain);
1558 		return (error);
1559 	case 4: /* swap sets "rulenum" and "new_set" */
1560 		IPFW_UH_WLOCK(chain);
1561 		error = swap_sets(chain, &rt, 0);
1562 		IPFW_UH_WUNLOCK(chain);
1563 		return (error);
1564 	default:
1565 		return (ENOTSUP);
1566 	}
1567 
1568 	if (do_del != 0) {
1569 		if ((error = delete_range(chain, &rt, &ndel)) != 0)
1570 			return (error);
1571 
1572 		if (ndel == 0 && (cmd != 1 && num != 0))
1573 			return (EINVAL);
1574 
1575 		return (0);
1576 	}
1577 
1578 	return (move_range(chain, &rt));
1579 }
1580 
1581 /**
1582  * Reset some or all counters on firewall rules.
1583  * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
1584  * the next 8 bits are the set number, the top 8 bits are the command:
1585  *	0	work with rules from all set's;
1586  *	1	work with rules only from specified set.
1587  * Specified rule number is zero if we want to clear all entries.
1588  * log_only is 1 if we only want to reset logs, zero otherwise.
1589  */
1590 static int
1591 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
1592 {
1593 	struct ip_fw *rule;
1594 	char *msg;
1595 	int i;
1596 
1597 	uint16_t rulenum = arg & 0xffff;
1598 	uint8_t set = (arg >> 16) & 0xff;
1599 	uint8_t cmd = (arg >> 24) & 0xff;
1600 
1601 	if (cmd > 1)
1602 		return (EINVAL);
1603 	if (cmd == 1 && set > RESVD_SET)
1604 		return (EINVAL);
1605 
1606 	IPFW_UH_RLOCK(chain);
1607 	if (rulenum == 0) {
1608 		V_norule_counter = 0;
1609 		for (i = 0; i < chain->n_rules; i++) {
1610 			rule = chain->map[i];
1611 			/* Skip rules not in our set. */
1612 			if (cmd == 1 && rule->set != set)
1613 				continue;
1614 			clear_counters(rule, log_only);
1615 		}
1616 		msg = log_only ? "All logging counts reset" :
1617 		    "Accounting cleared";
1618 	} else {
1619 		int cleared = 0;
1620 		for (i = 0; i < chain->n_rules; i++) {
1621 			rule = chain->map[i];
1622 			if (rule->rulenum == rulenum) {
1623 				if (cmd == 0 || rule->set == set)
1624 					clear_counters(rule, log_only);
1625 				cleared = 1;
1626 			}
1627 			if (rule->rulenum > rulenum)
1628 				break;
1629 		}
1630 		if (!cleared) {	/* we did not find any matching rules */
1631 			IPFW_UH_RUNLOCK(chain);
1632 			return (EINVAL);
1633 		}
1634 		msg = log_only ? "logging count reset" : "cleared";
1635 	}
1636 	IPFW_UH_RUNLOCK(chain);
1637 
1638 	if (V_fw_verbose) {
1639 		int lev = LOG_SECURITY | LOG_NOTICE;
1640 
1641 		if (rulenum)
1642 			log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
1643 		else
1644 			log(lev, "ipfw: %s.\n", msg);
1645 	}
1646 	return (0);
1647 }
1648 
1649 
1650 /*
1651  * Check rule head in FreeBSD11 format
1652  *
1653  */
1654 static int
1655 check_ipfw_rule1(struct ip_fw_rule *rule, int size,
1656     struct rule_check_info *ci)
1657 {
1658 	int l;
1659 
1660 	if (size < sizeof(*rule)) {
1661 		printf("ipfw: rule too short\n");
1662 		return (EINVAL);
1663 	}
1664 
1665 	/* Check for valid cmd_len */
1666 	l = roundup2(RULESIZE(rule), sizeof(uint64_t));
1667 	if (l != size) {
1668 		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1669 		return (EINVAL);
1670 	}
1671 	if (rule->act_ofs >= rule->cmd_len) {
1672 		printf("ipfw: bogus action offset (%u > %u)\n",
1673 		    rule->act_ofs, rule->cmd_len - 1);
1674 		return (EINVAL);
1675 	}
1676 
1677 	if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1678 		return (EINVAL);
1679 
1680 	return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1681 }
1682 
1683 /*
1684  * Check rule head in FreeBSD8 format
1685  *
1686  */
1687 static int
1688 check_ipfw_rule0(struct ip_fw_rule0 *rule, int size,
1689     struct rule_check_info *ci)
1690 {
1691 	int l;
1692 
1693 	if (size < sizeof(*rule)) {
1694 		printf("ipfw: rule too short\n");
1695 		return (EINVAL);
1696 	}
1697 
1698 	/* Check for valid cmd_len */
1699 	l = sizeof(*rule) + rule->cmd_len * 4 - 4;
1700 	if (l != size) {
1701 		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
1702 		return (EINVAL);
1703 	}
1704 	if (rule->act_ofs >= rule->cmd_len) {
1705 		printf("ipfw: bogus action offset (%u > %u)\n",
1706 		    rule->act_ofs, rule->cmd_len - 1);
1707 		return (EINVAL);
1708 	}
1709 
1710 	if (rule->rulenum > IPFW_DEFAULT_RULE - 1)
1711 		return (EINVAL);
1712 
1713 	return (check_ipfw_rule_body(rule->cmd, rule->cmd_len, ci));
1714 }
1715 
1716 static int
1717 check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci)
1718 {
1719 	int cmdlen, l;
1720 	int have_action;
1721 
1722 	have_action = 0;
1723 
1724 	/*
1725 	 * Now go for the individual checks. Very simple ones, basically only
1726 	 * instruction sizes.
1727 	 */
1728 	for (l = cmd_len; l > 0 ; l -= cmdlen, cmd += cmdlen) {
1729 		cmdlen = F_LEN(cmd);
1730 		if (cmdlen > l) {
1731 			printf("ipfw: opcode %d size truncated\n",
1732 			    cmd->opcode);
1733 			return EINVAL;
1734 		}
1735 		switch (cmd->opcode) {
1736 		case O_PROBE_STATE:
1737 		case O_KEEP_STATE:
1738 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1739 				goto bad_size;
1740 			ci->object_opcodes++;
1741 			break;
1742 		case O_PROTO:
1743 		case O_IP_SRC_ME:
1744 		case O_IP_DST_ME:
1745 		case O_LAYER2:
1746 		case O_IN:
1747 		case O_FRAG:
1748 		case O_DIVERTED:
1749 		case O_IPOPT:
1750 		case O_IPTOS:
1751 		case O_IPPRECEDENCE:
1752 		case O_IPVER:
1753 		case O_SOCKARG:
1754 		case O_TCPFLAGS:
1755 		case O_TCPOPTS:
1756 		case O_ESTAB:
1757 		case O_VERREVPATH:
1758 		case O_VERSRCREACH:
1759 		case O_ANTISPOOF:
1760 		case O_IPSEC:
1761 #ifdef INET6
1762 		case O_IP6_SRC_ME:
1763 		case O_IP6_DST_ME:
1764 		case O_EXT_HDR:
1765 		case O_IP6:
1766 #endif
1767 		case O_IP4:
1768 		case O_TAG:
1769 		case O_SKIP_ACTION:
1770 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1771 				goto bad_size;
1772 			break;
1773 
1774 		case O_EXTERNAL_ACTION:
1775 			if (cmd->arg1 == 0 ||
1776 			    cmdlen != F_INSN_SIZE(ipfw_insn)) {
1777 				printf("ipfw: invalid external "
1778 				    "action opcode\n");
1779 				return (EINVAL);
1780 			}
1781 			ci->object_opcodes++;
1782 			/*
1783 			 * Do we have O_EXTERNAL_INSTANCE or O_EXTERNAL_DATA
1784 			 * opcode?
1785 			 */
1786 			if (l != cmdlen) {
1787 				l -= cmdlen;
1788 				cmd += cmdlen;
1789 				cmdlen = F_LEN(cmd);
1790 				if (cmd->opcode == O_EXTERNAL_DATA)
1791 					goto check_action;
1792 				if (cmd->opcode != O_EXTERNAL_INSTANCE) {
1793 					printf("ipfw: invalid opcode "
1794 					    "next to external action %u\n",
1795 					    cmd->opcode);
1796 					return (EINVAL);
1797 				}
1798 				if (cmd->arg1 == 0 ||
1799 				    cmdlen != F_INSN_SIZE(ipfw_insn)) {
1800 					printf("ipfw: invalid external "
1801 					    "action instance opcode\n");
1802 					return (EINVAL);
1803 				}
1804 				ci->object_opcodes++;
1805 			}
1806 			goto check_action;
1807 
1808 		case O_FIB:
1809 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1810 				goto bad_size;
1811 			if (cmd->arg1 >= rt_numfibs) {
1812 				printf("ipfw: invalid fib number %d\n",
1813 					cmd->arg1);
1814 				return EINVAL;
1815 			}
1816 			break;
1817 
1818 		case O_SETFIB:
1819 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1820 				goto bad_size;
1821 			if ((cmd->arg1 != IP_FW_TARG) &&
1822 			    ((cmd->arg1 & 0x7FFF) >= rt_numfibs)) {
1823 				printf("ipfw: invalid fib number %d\n",
1824 					cmd->arg1 & 0x7FFF);
1825 				return EINVAL;
1826 			}
1827 			goto check_action;
1828 
1829 		case O_UID:
1830 		case O_GID:
1831 		case O_JAIL:
1832 		case O_IP_SRC:
1833 		case O_IP_DST:
1834 		case O_TCPSEQ:
1835 		case O_TCPACK:
1836 		case O_PROB:
1837 		case O_ICMPTYPE:
1838 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1839 				goto bad_size;
1840 			break;
1841 
1842 		case O_LIMIT:
1843 			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
1844 				goto bad_size;
1845 			ci->object_opcodes++;
1846 			break;
1847 
1848 		case O_LOG:
1849 			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
1850 				goto bad_size;
1851 
1852 			((ipfw_insn_log *)cmd)->log_left =
1853 			    ((ipfw_insn_log *)cmd)->max_log;
1854 
1855 			break;
1856 
1857 		case O_IP_SRC_MASK:
1858 		case O_IP_DST_MASK:
1859 			/* only odd command lengths */
1860 			if ((cmdlen & 1) == 0)
1861 				goto bad_size;
1862 			break;
1863 
1864 		case O_IP_SRC_SET:
1865 		case O_IP_DST_SET:
1866 			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
1867 				printf("ipfw: invalid set size %d\n",
1868 					cmd->arg1);
1869 				return EINVAL;
1870 			}
1871 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
1872 			    (cmd->arg1+31)/32 )
1873 				goto bad_size;
1874 			break;
1875 
1876 		case O_IP_SRC_LOOKUP:
1877 			if (cmdlen > F_INSN_SIZE(ipfw_insn_u32))
1878 				goto bad_size;
1879 		case O_IP_DST_LOOKUP:
1880 			if (cmd->arg1 >= V_fw_tables_max) {
1881 				printf("ipfw: invalid table number %d\n",
1882 				    cmd->arg1);
1883 				return (EINVAL);
1884 			}
1885 			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1886 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
1887 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1888 				goto bad_size;
1889 			ci->object_opcodes++;
1890 			break;
1891 		case O_IP_FLOW_LOOKUP:
1892 			if (cmd->arg1 >= V_fw_tables_max) {
1893 				printf("ipfw: invalid table number %d\n",
1894 				    cmd->arg1);
1895 				return (EINVAL);
1896 			}
1897 			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
1898 			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
1899 				goto bad_size;
1900 			ci->object_opcodes++;
1901 			break;
1902 		case O_MACADDR2:
1903 			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
1904 				goto bad_size;
1905 			break;
1906 
1907 		case O_NOP:
1908 		case O_IPID:
1909 		case O_IPTTL:
1910 		case O_IPLEN:
1911 		case O_TCPDATALEN:
1912 		case O_TCPMSS:
1913 		case O_TCPWIN:
1914 		case O_TAGGED:
1915 			if (cmdlen < 1 || cmdlen > 31)
1916 				goto bad_size;
1917 			break;
1918 
1919 		case O_DSCP:
1920 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
1921 				goto bad_size;
1922 			break;
1923 
1924 		case O_MAC_TYPE:
1925 		case O_IP_SRCPORT:
1926 		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
1927 			if (cmdlen < 2 || cmdlen > 31)
1928 				goto bad_size;
1929 			break;
1930 
1931 		case O_RECV:
1932 		case O_XMIT:
1933 		case O_VIA:
1934 			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
1935 				goto bad_size;
1936 			ci->object_opcodes++;
1937 			break;
1938 
1939 		case O_ALTQ:
1940 			if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
1941 				goto bad_size;
1942 			break;
1943 
1944 		case O_PIPE:
1945 		case O_QUEUE:
1946 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1947 				goto bad_size;
1948 			goto check_action;
1949 
1950 		case O_FORWARD_IP:
1951 			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
1952 				goto bad_size;
1953 			goto check_action;
1954 #ifdef INET6
1955 		case O_FORWARD_IP6:
1956 			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
1957 				goto bad_size;
1958 			goto check_action;
1959 #endif /* INET6 */
1960 
1961 		case O_DIVERT:
1962 		case O_TEE:
1963 			if (ip_divert_ptr == NULL)
1964 				return EINVAL;
1965 			else
1966 				goto check_size;
1967 		case O_NETGRAPH:
1968 		case O_NGTEE:
1969 			if (ng_ipfw_input_p == NULL)
1970 				return EINVAL;
1971 			else
1972 				goto check_size;
1973 		case O_NAT:
1974 			if (!IPFW_NAT_LOADED)
1975 				return EINVAL;
1976 			if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
1977  				goto bad_size;
1978  			goto check_action;
1979 		case O_CHECK_STATE:
1980 			ci->object_opcodes++;
1981 			/* FALLTHROUGH */
1982 		case O_FORWARD_MAC: /* XXX not implemented yet */
1983 		case O_COUNT:
1984 		case O_ACCEPT:
1985 		case O_DENY:
1986 		case O_REJECT:
1987 		case O_SETDSCP:
1988 #ifdef INET6
1989 		case O_UNREACH6:
1990 #endif
1991 		case O_SKIPTO:
1992 		case O_REASS:
1993 		case O_CALLRETURN:
1994 check_size:
1995 			if (cmdlen != F_INSN_SIZE(ipfw_insn))
1996 				goto bad_size;
1997 check_action:
1998 			if (have_action) {
1999 				printf("ipfw: opcode %d, multiple actions"
2000 					" not allowed\n",
2001 					cmd->opcode);
2002 				return (EINVAL);
2003 			}
2004 			have_action = 1;
2005 			if (l != cmdlen) {
2006 				printf("ipfw: opcode %d, action must be"
2007 					" last opcode\n",
2008 					cmd->opcode);
2009 				return (EINVAL);
2010 			}
2011 			break;
2012 #ifdef INET6
2013 		case O_IP6_SRC:
2014 		case O_IP6_DST:
2015 			if (cmdlen != F_INSN_SIZE(struct in6_addr) +
2016 			    F_INSN_SIZE(ipfw_insn))
2017 				goto bad_size;
2018 			break;
2019 
2020 		case O_FLOW6ID:
2021 			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2022 			    ((ipfw_insn_u32 *)cmd)->o.arg1)
2023 				goto bad_size;
2024 			break;
2025 
2026 		case O_IP6_SRC_MASK:
2027 		case O_IP6_DST_MASK:
2028 			if ( !(cmdlen & 1) || cmdlen > 127)
2029 				goto bad_size;
2030 			break;
2031 		case O_ICMP6TYPE:
2032 			if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
2033 				goto bad_size;
2034 			break;
2035 #endif
2036 
2037 		default:
2038 			switch (cmd->opcode) {
2039 #ifndef INET6
2040 			case O_IP6_SRC_ME:
2041 			case O_IP6_DST_ME:
2042 			case O_EXT_HDR:
2043 			case O_IP6:
2044 			case O_UNREACH6:
2045 			case O_IP6_SRC:
2046 			case O_IP6_DST:
2047 			case O_FLOW6ID:
2048 			case O_IP6_SRC_MASK:
2049 			case O_IP6_DST_MASK:
2050 			case O_ICMP6TYPE:
2051 				printf("ipfw: no IPv6 support in kernel\n");
2052 				return (EPROTONOSUPPORT);
2053 #endif
2054 			default:
2055 				printf("ipfw: opcode %d, unknown opcode\n",
2056 					cmd->opcode);
2057 				return (EINVAL);
2058 			}
2059 		}
2060 	}
2061 	if (have_action == 0) {
2062 		printf("ipfw: missing action\n");
2063 		return (EINVAL);
2064 	}
2065 	return 0;
2066 
2067 bad_size:
2068 	printf("ipfw: opcode %d size %d wrong\n",
2069 		cmd->opcode, cmdlen);
2070 	return (EINVAL);
2071 }
2072 
2073 
2074 /*
2075  * Translation of requests for compatibility with FreeBSD 7.2/8.
2076  * a static variable tells us if we have an old client from userland,
2077  * and if necessary we translate requests and responses between the
2078  * two formats.
2079  */
2080 static int is7 = 0;
2081 
2082 struct ip_fw7 {
2083 	struct ip_fw7	*next;		/* linked list of rules     */
2084 	struct ip_fw7	*next_rule;	/* ptr to next [skipto] rule    */
2085 	/* 'next_rule' is used to pass up 'set_disable' status      */
2086 
2087 	uint16_t	act_ofs;	/* offset of action in 32-bit units */
2088 	uint16_t	cmd_len;	/* # of 32-bit words in cmd */
2089 	uint16_t	rulenum;	/* rule number          */
2090 	uint8_t		set;		/* rule set (0..31)     */
2091 	// #define RESVD_SET   31  /* set for default and persistent rules */
2092 	uint8_t		_pad;		/* padding          */
2093 	// uint32_t        id;             /* rule id, only in v.8 */
2094 	/* These fields are present in all rules.           */
2095 	uint64_t	pcnt;		/* Packet counter       */
2096 	uint64_t	bcnt;		/* Byte counter         */
2097 	uint32_t	timestamp;	/* tv_sec of last match     */
2098 
2099 	ipfw_insn	cmd[1];		/* storage for commands     */
2100 };
2101 
2102 static int convert_rule_to_7(struct ip_fw_rule0 *rule);
2103 static int convert_rule_to_8(struct ip_fw_rule0 *rule);
2104 
2105 #ifndef RULESIZE7
2106 #define RULESIZE7(rule)  (sizeof(struct ip_fw7) + \
2107 	((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
2108 #endif
2109 
2110 
2111 /*
2112  * Copy the static and dynamic rules to the supplied buffer
2113  * and return the amount of space actually used.
2114  * Must be run under IPFW_UH_RLOCK
2115  */
2116 static size_t
2117 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2118 {
2119 	char *bp = buf;
2120 	char *ep = bp + space;
2121 	struct ip_fw *rule;
2122 	struct ip_fw_rule0 *dst;
2123 	struct timeval boottime;
2124 	int error, i, l, warnflag;
2125 	time_t	boot_seconds;
2126 
2127 	warnflag = 0;
2128 
2129 	getboottime(&boottime);
2130         boot_seconds = boottime.tv_sec;
2131 	for (i = 0; i < chain->n_rules; i++) {
2132 		rule = chain->map[i];
2133 
2134 		if (is7) {
2135 		    /* Convert rule to FreeBSd 7.2 format */
2136 		    l = RULESIZE7(rule);
2137 		    if (bp + l + sizeof(uint32_t) <= ep) {
2138 			bcopy(rule, bp, l + sizeof(uint32_t));
2139 			error = set_legacy_obj_kidx(chain,
2140 			    (struct ip_fw_rule0 *)bp);
2141 			if (error != 0)
2142 				return (0);
2143 			error = convert_rule_to_7((struct ip_fw_rule0 *) bp);
2144 			if (error)
2145 				return 0; /*XXX correct? */
2146 			/*
2147 			 * XXX HACK. Store the disable mask in the "next"
2148 			 * pointer in a wild attempt to keep the ABI the same.
2149 			 * Why do we do this on EVERY rule?
2150 			 */
2151 			bcopy(&V_set_disable,
2152 				&(((struct ip_fw7 *)bp)->next_rule),
2153 				sizeof(V_set_disable));
2154 			if (((struct ip_fw7 *)bp)->timestamp)
2155 			    ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
2156 			bp += l;
2157 		    }
2158 		    continue; /* go to next rule */
2159 		}
2160 
2161 		l = RULEUSIZE0(rule);
2162 		if (bp + l > ep) { /* should not happen */
2163 			printf("overflow dumping static rules\n");
2164 			break;
2165 		}
2166 		dst = (struct ip_fw_rule0 *)bp;
2167 		export_rule0(rule, dst, l);
2168 		error = set_legacy_obj_kidx(chain, dst);
2169 
2170 		/*
2171 		 * XXX HACK. Store the disable mask in the "next"
2172 		 * pointer in a wild attempt to keep the ABI the same.
2173 		 * Why do we do this on EVERY rule?
2174 		 *
2175 		 * XXX: "ipfw set show" (ab)uses IP_FW_GET to read disabled mask
2176 		 * so we need to fail _after_ saving at least one mask.
2177 		 */
2178 		bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
2179 		if (dst->timestamp)
2180 			dst->timestamp += boot_seconds;
2181 		bp += l;
2182 
2183 		if (error != 0) {
2184 			if (error == 2) {
2185 				/* Non-fatal table rewrite error. */
2186 				warnflag = 1;
2187 				continue;
2188 			}
2189 			printf("Stop on rule %d. Fail to convert table\n",
2190 			    rule->rulenum);
2191 			break;
2192 		}
2193 	}
2194 	if (warnflag != 0)
2195 		printf("ipfw: process %s is using legacy interfaces,"
2196 		    " consider rebuilding\n", "");
2197 	ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
2198 	return (bp - (char *)buf);
2199 }
2200 
2201 
2202 struct dump_args {
2203 	uint32_t	b;	/* start rule */
2204 	uint32_t	e;	/* end rule */
2205 	uint32_t	rcount;	/* number of rules */
2206 	uint32_t	rsize;	/* rules size */
2207 	uint32_t	tcount;	/* number of tables */
2208 	int		rcounters;	/* counters */
2209 	uint32_t	*bmask;	/* index bitmask of used named objects */
2210 };
2211 
2212 void
2213 ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv)
2214 {
2215 
2216 	ntlv->head.type = no->etlv;
2217 	ntlv->head.length = sizeof(*ntlv);
2218 	ntlv->idx = no->kidx;
2219 	strlcpy(ntlv->name, no->name, sizeof(ntlv->name));
2220 }
2221 
2222 /*
2223  * Export named object info in instance @ni, identified by @kidx
2224  * to ipfw_obj_ntlv. TLV is allocated from @sd space.
2225  *
2226  * Returns 0 on success.
2227  */
2228 static int
2229 export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx,
2230     struct sockopt_data *sd)
2231 {
2232 	struct named_object *no;
2233 	ipfw_obj_ntlv *ntlv;
2234 
2235 	no = ipfw_objhash_lookup_kidx(ni, kidx);
2236 	KASSERT(no != NULL, ("invalid object kernel index passed"));
2237 
2238 	ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
2239 	if (ntlv == NULL)
2240 		return (ENOMEM);
2241 
2242 	ipfw_export_obj_ntlv(no, ntlv);
2243 	return (0);
2244 }
2245 
2246 static int
2247 export_named_objects(struct namedobj_instance *ni, struct dump_args *da,
2248     struct sockopt_data *sd)
2249 {
2250 	int error, i;
2251 
2252 	for (i = 0; i < IPFW_TABLES_MAX && da->tcount > 0; i++) {
2253 		if ((da->bmask[i / 32] & (1 << (i % 32))) == 0)
2254 			continue;
2255 		if ((error = export_objhash_ntlv(ni, i, sd)) != 0)
2256 			return (error);
2257 		da->tcount--;
2258 	}
2259 	return (0);
2260 }
2261 
2262 static int
2263 dump_named_objects(struct ip_fw_chain *ch, struct dump_args *da,
2264     struct sockopt_data *sd)
2265 {
2266 	ipfw_obj_ctlv *ctlv;
2267 	int error;
2268 
2269 	MPASS(da->tcount > 0);
2270 	/* Header first */
2271 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2272 	if (ctlv == NULL)
2273 		return (ENOMEM);
2274 	ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
2275 	ctlv->head.length = da->tcount * sizeof(ipfw_obj_ntlv) +
2276 	    sizeof(*ctlv);
2277 	ctlv->count = da->tcount;
2278 	ctlv->objsize = sizeof(ipfw_obj_ntlv);
2279 
2280 	/* Dump table names first (if any) */
2281 	error = export_named_objects(ipfw_get_table_objhash(ch), da, sd);
2282 	if (error != 0)
2283 		return (error);
2284 	/* Then dump another named objects */
2285 	da->bmask += IPFW_TABLES_MAX / 32;
2286 	return (export_named_objects(CHAIN_TO_SRV(ch), da, sd));
2287 }
2288 
2289 /*
2290  * Dumps static rules with table TLVs in buffer @sd.
2291  *
2292  * Returns 0 on success.
2293  */
2294 static int
2295 dump_static_rules(struct ip_fw_chain *chain, struct dump_args *da,
2296     struct sockopt_data *sd)
2297 {
2298 	ipfw_obj_ctlv *ctlv;
2299 	struct ip_fw *krule;
2300 	caddr_t dst;
2301 	int i, l;
2302 
2303 	/* Dump rules */
2304 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2305 	if (ctlv == NULL)
2306 		return (ENOMEM);
2307 	ctlv->head.type = IPFW_TLV_RULE_LIST;
2308 	ctlv->head.length = da->rsize + sizeof(*ctlv);
2309 	ctlv->count = da->rcount;
2310 
2311 	for (i = da->b; i < da->e; i++) {
2312 		krule = chain->map[i];
2313 
2314 		l = RULEUSIZE1(krule) + sizeof(ipfw_obj_tlv);
2315 		if (da->rcounters != 0)
2316 			l += sizeof(struct ip_fw_bcounter);
2317 		dst = (caddr_t)ipfw_get_sopt_space(sd, l);
2318 		if (dst == NULL)
2319 			return (ENOMEM);
2320 
2321 		export_rule1(krule, dst, l, da->rcounters);
2322 	}
2323 
2324 	return (0);
2325 }
2326 
2327 int
2328 ipfw_mark_object_kidx(uint32_t *bmask, uint16_t etlv, uint16_t kidx)
2329 {
2330 	uint32_t bidx;
2331 
2332 	/*
2333 	 * Maintain separate bitmasks for table and non-table objects.
2334 	 */
2335 	bidx = (etlv == IPFW_TLV_TBL_NAME) ? 0: IPFW_TABLES_MAX / 32;
2336 	bidx += kidx / 32;
2337 	if ((bmask[bidx] & (1 << (kidx % 32))) != 0)
2338 		return (0);
2339 
2340 	bmask[bidx] |= 1 << (kidx % 32);
2341 	return (1);
2342 }
2343 
2344 /*
2345  * Marks every object index used in @rule with bit in @bmask.
2346  * Used to generate bitmask of referenced tables/objects for given ruleset
2347  * or its part.
2348  */
2349 static void
2350 mark_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2351     struct dump_args *da)
2352 {
2353 	struct opcode_obj_rewrite *rw;
2354 	ipfw_insn *cmd;
2355 	int cmdlen, l;
2356 	uint16_t kidx;
2357 	uint8_t subtype;
2358 
2359 	l = rule->cmd_len;
2360 	cmd = rule->cmd;
2361 	cmdlen = 0;
2362 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2363 		cmdlen = F_LEN(cmd);
2364 
2365 		rw = find_op_rw(cmd, &kidx, &subtype);
2366 		if (rw == NULL)
2367 			continue;
2368 
2369 		if (ipfw_mark_object_kidx(da->bmask, rw->etlv, kidx))
2370 			da->tcount++;
2371 	}
2372 }
2373 
2374 /*
2375  * Dumps requested objects data
2376  * Data layout (version 0)(current):
2377  * Request: [ ipfw_cfg_lheader ] + IPFW_CFG_GET_* flags
2378  *   size = ipfw_cfg_lheader.size
2379  * Reply: [ ipfw_cfg_lheader
2380  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2381  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST)
2382  *     ipfw_obj_tlv(IPFW_TLV_RULE_ENT) [ ip_fw_bcounter (optional) ip_fw_rule ]
2383  *   ] (optional)
2384  *   [ ipfw_obj_ctlv(IPFW_TLV_STATE_LIST) ipfw_obj_dyntlv x N ] (optional)
2385  * ]
2386  * * NOTE IPFW_TLV_STATE_LIST has the single valid field: objsize.
2387  * The rest (size, count) are set to zero and needs to be ignored.
2388  *
2389  * Returns 0 on success.
2390  */
2391 static int
2392 dump_config(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2393     struct sockopt_data *sd)
2394 {
2395 	struct dump_args da;
2396 	ipfw_cfg_lheader *hdr;
2397 	struct ip_fw *rule;
2398 	size_t sz, rnum;
2399 	uint32_t hdr_flags, *bmask;
2400 	int error, i;
2401 
2402 	hdr = (ipfw_cfg_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
2403 	if (hdr == NULL)
2404 		return (EINVAL);
2405 
2406 	error = 0;
2407 	bmask = NULL;
2408 	memset(&da, 0, sizeof(da));
2409 	/*
2410 	 * Allocate needed state.
2411 	 * Note we allocate 2xspace mask, for table & srv
2412 	 */
2413 	if (hdr->flags & (IPFW_CFG_GET_STATIC | IPFW_CFG_GET_STATES))
2414 		da.bmask = bmask = malloc(
2415 		    sizeof(uint32_t) * IPFW_TABLES_MAX * 2 / 32, M_TEMP,
2416 		    M_WAITOK | M_ZERO);
2417 	IPFW_UH_RLOCK(chain);
2418 
2419 	/*
2420 	 * STAGE 1: Determine size/count for objects in range.
2421 	 * Prepare used tables bitmask.
2422 	 */
2423 	sz = sizeof(ipfw_cfg_lheader);
2424 	da.e = chain->n_rules;
2425 
2426 	if (hdr->end_rule != 0) {
2427 		/* Handle custom range */
2428 		if ((rnum = hdr->start_rule) > IPFW_DEFAULT_RULE)
2429 			rnum = IPFW_DEFAULT_RULE;
2430 		da.b = ipfw_find_rule(chain, rnum, 0);
2431 		rnum = (hdr->end_rule < IPFW_DEFAULT_RULE) ?
2432 		    hdr->end_rule + 1: IPFW_DEFAULT_RULE;
2433 		da.e = ipfw_find_rule(chain, rnum, UINT32_MAX) + 1;
2434 	}
2435 
2436 	if (hdr->flags & IPFW_CFG_GET_STATIC) {
2437 		for (i = da.b; i < da.e; i++) {
2438 			rule = chain->map[i];
2439 			da.rsize += RULEUSIZE1(rule) + sizeof(ipfw_obj_tlv);
2440 			da.rcount++;
2441 			/* Update bitmask of used objects for given range */
2442 			mark_rule_objects(chain, rule, &da);
2443 		}
2444 		/* Add counters if requested */
2445 		if (hdr->flags & IPFW_CFG_GET_COUNTERS) {
2446 			da.rsize += sizeof(struct ip_fw_bcounter) * da.rcount;
2447 			da.rcounters = 1;
2448 		}
2449 		sz += da.rsize + sizeof(ipfw_obj_ctlv);
2450 	}
2451 
2452 	if (hdr->flags & IPFW_CFG_GET_STATES) {
2453 		sz += sizeof(ipfw_obj_ctlv) +
2454 		    ipfw_dyn_get_count(bmask, &i) * sizeof(ipfw_obj_dyntlv);
2455 		da.tcount += i;
2456 	}
2457 
2458 	if (da.tcount > 0)
2459 		sz += da.tcount * sizeof(ipfw_obj_ntlv) +
2460 		    sizeof(ipfw_obj_ctlv);
2461 
2462 	/*
2463 	 * Fill header anyway.
2464 	 * Note we have to save header fields to stable storage
2465 	 * buffer inside @sd can be flushed after dumping rules
2466 	 */
2467 	hdr->size = sz;
2468 	hdr->set_mask = ~V_set_disable;
2469 	hdr_flags = hdr->flags;
2470 	hdr = NULL;
2471 
2472 	if (sd->valsize < sz) {
2473 		error = ENOMEM;
2474 		goto cleanup;
2475 	}
2476 
2477 	/* STAGE2: Store actual data */
2478 	if (da.tcount > 0) {
2479 		error = dump_named_objects(chain, &da, sd);
2480 		if (error != 0)
2481 			goto cleanup;
2482 	}
2483 
2484 	if (hdr_flags & IPFW_CFG_GET_STATIC) {
2485 		error = dump_static_rules(chain, &da, sd);
2486 		if (error != 0)
2487 			goto cleanup;
2488 	}
2489 
2490 	if (hdr_flags & IPFW_CFG_GET_STATES)
2491 		error = ipfw_dump_states(chain, sd);
2492 
2493 cleanup:
2494 	IPFW_UH_RUNLOCK(chain);
2495 
2496 	if (bmask != NULL)
2497 		free(bmask, M_TEMP);
2498 
2499 	return (error);
2500 }
2501 
2502 int
2503 ipfw_check_object_name_generic(const char *name)
2504 {
2505 	int nsize;
2506 
2507 	nsize = sizeof(((ipfw_obj_ntlv *)0)->name);
2508 	if (strnlen(name, nsize) == nsize)
2509 		return (EINVAL);
2510 	if (name[0] == '\0')
2511 		return (EINVAL);
2512 	return (0);
2513 }
2514 
2515 /*
2516  * Creates non-existent objects referenced by rule.
2517  *
2518  * Return 0 on success.
2519  */
2520 int
2521 create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd,
2522     struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti)
2523 {
2524 	struct opcode_obj_rewrite *rw;
2525 	struct obj_idx *p;
2526 	uint16_t kidx;
2527 	int error;
2528 
2529 	/*
2530 	 * Compatibility stuff: do actual creation for non-existing,
2531 	 * but referenced objects.
2532 	 */
2533 	for (p = oib; p < pidx; p++) {
2534 		if (p->kidx != 0)
2535 			continue;
2536 
2537 		ti->uidx = p->uidx;
2538 		ti->type = p->type;
2539 		ti->atype = 0;
2540 
2541 		rw = find_op_rw(cmd + p->off, NULL, NULL);
2542 		KASSERT(rw != NULL, ("Unable to find handler for op %d",
2543 		    (cmd + p->off)->opcode));
2544 
2545 		if (rw->create_object == NULL)
2546 			error = EOPNOTSUPP;
2547 		else
2548 			error = rw->create_object(ch, ti, &kidx);
2549 		if (error == 0) {
2550 			p->kidx = kidx;
2551 			continue;
2552 		}
2553 
2554 		/*
2555 		 * Error happened. We have to rollback everything.
2556 		 * Drop all already acquired references.
2557 		 */
2558 		IPFW_UH_WLOCK(ch);
2559 		unref_oib_objects(ch, cmd, oib, pidx);
2560 		IPFW_UH_WUNLOCK(ch);
2561 
2562 		return (error);
2563 	}
2564 
2565 	return (0);
2566 }
2567 
2568 /*
2569  * Compatibility function for old ipfw(8) binaries.
2570  * Rewrites table/nat kernel indices with userland ones.
2571  * Convert tables matching '/^\d+$/' to their atoi() value.
2572  * Use number 65535 for other tables.
2573  *
2574  * Returns 0 on success.
2575  */
2576 static int
2577 set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule)
2578 {
2579 	struct opcode_obj_rewrite *rw;
2580 	struct named_object *no;
2581 	ipfw_insn *cmd;
2582 	char *end;
2583 	long val;
2584 	int cmdlen, error, l;
2585 	uint16_t kidx, uidx;
2586 	uint8_t subtype;
2587 
2588 	error = 0;
2589 
2590 	l = rule->cmd_len;
2591 	cmd = rule->cmd;
2592 	cmdlen = 0;
2593 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2594 		cmdlen = F_LEN(cmd);
2595 
2596 		/* Check if is index in given opcode */
2597 		rw = find_op_rw(cmd, &kidx, &subtype);
2598 		if (rw == NULL)
2599 			continue;
2600 
2601 		/* Try to find referenced kernel object */
2602 		no = rw->find_bykidx(ch, kidx);
2603 		if (no == NULL)
2604 			continue;
2605 
2606 		val = strtol(no->name, &end, 10);
2607 		if (*end == '\0' && val < 65535) {
2608 			uidx = val;
2609 		} else {
2610 
2611 			/*
2612 			 * We are called via legacy opcode.
2613 			 * Save error and show table as fake number
2614 			 * not to make ipfw(8) hang.
2615 			 */
2616 			uidx = 65535;
2617 			error = 2;
2618 		}
2619 
2620 		rw->update(cmd, uidx);
2621 	}
2622 
2623 	return (error);
2624 }
2625 
2626 
2627 /*
2628  * Unreferences all already-referenced objects in given @cmd rule,
2629  * using information in @oib.
2630  *
2631  * Used to rollback partially converted rule on error.
2632  */
2633 static void
2634 unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib,
2635     struct obj_idx *end)
2636 {
2637 	struct opcode_obj_rewrite *rw;
2638 	struct named_object *no;
2639 	struct obj_idx *p;
2640 
2641 	IPFW_UH_WLOCK_ASSERT(ch);
2642 
2643 	for (p = oib; p < end; p++) {
2644 		if (p->kidx == 0)
2645 			continue;
2646 
2647 		rw = find_op_rw(cmd + p->off, NULL, NULL);
2648 		KASSERT(rw != NULL, ("Unable to find handler for op %d",
2649 		    (cmd + p->off)->opcode));
2650 
2651 		/* Find & unref by existing idx */
2652 		no = rw->find_bykidx(ch, p->kidx);
2653 		KASSERT(no != NULL, ("Ref'd object %d disappeared", p->kidx));
2654 		no->refcnt--;
2655 	}
2656 }
2657 
2658 /*
2659  * Remove references from every object used in @rule.
2660  * Used at rule removal code.
2661  */
2662 static void
2663 unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule)
2664 {
2665 	struct opcode_obj_rewrite *rw;
2666 	struct named_object *no;
2667 	ipfw_insn *cmd;
2668 	int cmdlen, l;
2669 	uint16_t kidx;
2670 	uint8_t subtype;
2671 
2672 	IPFW_UH_WLOCK_ASSERT(ch);
2673 
2674 	l = rule->cmd_len;
2675 	cmd = rule->cmd;
2676 	cmdlen = 0;
2677 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2678 		cmdlen = F_LEN(cmd);
2679 
2680 		rw = find_op_rw(cmd, &kidx, &subtype);
2681 		if (rw == NULL)
2682 			continue;
2683 		no = rw->find_bykidx(ch, kidx);
2684 
2685 		KASSERT(no != NULL, ("object id %d not found", kidx));
2686 		KASSERT(no->subtype == subtype,
2687 		    ("wrong type %d (%d) for object id %d",
2688 		    no->subtype, subtype, kidx));
2689 		KASSERT(no->refcnt > 0, ("refcount for object %d is %d",
2690 		    kidx, no->refcnt));
2691 
2692 		if (no->refcnt == 1 && rw->destroy_object != NULL)
2693 			rw->destroy_object(ch, no);
2694 		else
2695 			no->refcnt--;
2696 	}
2697 }
2698 
2699 
2700 /*
2701  * Find and reference object (if any) stored in instruction @cmd.
2702  *
2703  * Saves object info in @pidx, sets
2704  *  - @unresolved to 1 if object should exists but not found
2705  *
2706  * Returns non-zero value in case of error.
2707  */
2708 static int
2709 ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti,
2710     struct obj_idx *pidx, int *unresolved)
2711 {
2712 	struct named_object *no;
2713 	struct opcode_obj_rewrite *rw;
2714 	int error;
2715 
2716 	/* Check if this opcode is candidate for rewrite */
2717 	rw = find_op_rw(cmd, &ti->uidx, &ti->type);
2718 	if (rw == NULL)
2719 		return (0);
2720 
2721 	/* Need to rewrite. Save necessary fields */
2722 	pidx->uidx = ti->uidx;
2723 	pidx->type = ti->type;
2724 
2725 	/* Try to find referenced kernel object */
2726 	error = rw->find_byname(ch, ti, &no);
2727 	if (error != 0)
2728 		return (error);
2729 	if (no == NULL) {
2730 		/*
2731 		 * Report about unresolved object for automaic
2732 		 * creation.
2733 		 */
2734 		*unresolved = 1;
2735 		return (0);
2736 	}
2737 
2738 	/*
2739 	 * Object is already exist.
2740 	 * Its subtype should match with expected value.
2741 	 */
2742 	if (ti->type != no->subtype)
2743 		return (EINVAL);
2744 
2745 	/* Bump refcount and update kidx. */
2746 	no->refcnt++;
2747 	rw->update(cmd, no->kidx);
2748 	return (0);
2749 }
2750 
2751 /*
2752  * Finds and bumps refcount for objects referenced by given @rule.
2753  * Auto-creates non-existing tables.
2754  * Fills in @oib array with userland/kernel indexes.
2755  *
2756  * Returns 0 on success.
2757  */
2758 static int
2759 ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule,
2760     struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti)
2761 {
2762 	struct obj_idx *pidx;
2763 	ipfw_insn *cmd;
2764 	int cmdlen, error, l, unresolved;
2765 
2766 	pidx = oib;
2767 	l = rule->cmd_len;
2768 	cmd = rule->cmd;
2769 	cmdlen = 0;
2770 	error = 0;
2771 
2772 	IPFW_UH_WLOCK(ch);
2773 
2774 	/* Increase refcount on each existing referenced table. */
2775 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2776 		cmdlen = F_LEN(cmd);
2777 		unresolved = 0;
2778 
2779 		error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved);
2780 		if (error != 0)
2781 			break;
2782 		/*
2783 		 * Compatibility stuff for old clients:
2784 		 * prepare to automaitcally create non-existing objects.
2785 		 */
2786 		if (unresolved != 0) {
2787 			pidx->off = rule->cmd_len - l;
2788 			pidx++;
2789 		}
2790 	}
2791 
2792 	if (error != 0) {
2793 		/* Unref everything we have already done */
2794 		unref_oib_objects(ch, rule->cmd, oib, pidx);
2795 		IPFW_UH_WUNLOCK(ch);
2796 		return (error);
2797 	}
2798 	IPFW_UH_WUNLOCK(ch);
2799 
2800 	/* Perform auto-creation for non-existing objects */
2801 	if (pidx != oib)
2802 		error = create_objects_compat(ch, rule->cmd, oib, pidx, ti);
2803 
2804 	/* Calculate real number of dynamic objects */
2805 	ci->object_opcodes = (uint16_t)(pidx - oib);
2806 
2807 	return (error);
2808 }
2809 
2810 /*
2811  * Checks is opcode is referencing table of appropriate type.
2812  * Adds reference count for found table if true.
2813  * Rewrites user-supplied opcode values with kernel ones.
2814  *
2815  * Returns 0 on success and appropriate error code otherwise.
2816  */
2817 static int
2818 rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci)
2819 {
2820 	int error;
2821 	ipfw_insn *cmd;
2822 	uint8_t type;
2823 	struct obj_idx *p, *pidx_first, *pidx_last;
2824 	struct tid_info ti;
2825 
2826 	/*
2827 	 * Prepare an array for storing opcode indices.
2828 	 * Use stack allocation by default.
2829 	 */
2830 	if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) {
2831 		/* Stack */
2832 		pidx_first = ci->obuf;
2833 	} else
2834 		pidx_first = malloc(
2835 		    ci->object_opcodes * sizeof(struct obj_idx),
2836 		    M_IPFW, M_WAITOK | M_ZERO);
2837 
2838 	error = 0;
2839 	type = 0;
2840 	memset(&ti, 0, sizeof(ti));
2841 
2842 	/* Use set rule is assigned to. */
2843 	ti.set = ci->krule->set;
2844 	if (ci->ctlv != NULL) {
2845 		ti.tlvs = (void *)(ci->ctlv + 1);
2846 		ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv);
2847 	}
2848 
2849 	/* Reference all used tables and other objects */
2850 	error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti);
2851 	if (error != 0)
2852 		goto free;
2853 	/*
2854 	 * Note that ref_rule_objects() might have updated ci->object_opcodes
2855 	 * to reflect actual number of object opcodes.
2856 	 */
2857 
2858 	/* Perform rewrite of remaining opcodes */
2859 	p = pidx_first;
2860 	pidx_last = pidx_first + ci->object_opcodes;
2861 	for (p = pidx_first; p < pidx_last; p++) {
2862 		cmd = ci->krule->cmd + p->off;
2863 		update_opcode_kidx(cmd, p->kidx);
2864 	}
2865 
2866 free:
2867 	if (pidx_first != ci->obuf)
2868 		free(pidx_first, M_IPFW);
2869 
2870 	return (error);
2871 }
2872 
2873 /*
2874  * Adds one or more rules to ipfw @chain.
2875  * Data layout (version 0)(current):
2876  * Request:
2877  * [
2878  *   ip_fw3_opheader
2879  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
2880  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ] (*2) (*3)
2881  * ]
2882  * Reply:
2883  * [
2884  *   ip_fw3_opheader
2885  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
2886  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) ip_fw x N ]
2887  * ]
2888  *
2889  * Rules in reply are modified to store their actual ruleset number.
2890  *
2891  * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
2892  * according to their idx field and there has to be no duplicates.
2893  * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
2894  * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
2895  *
2896  * Returns 0 on success.
2897  */
2898 static int
2899 add_rules(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
2900     struct sockopt_data *sd)
2901 {
2902 	ipfw_obj_ctlv *ctlv, *rtlv, *tstate;
2903 	ipfw_obj_ntlv *ntlv;
2904 	int clen, error, idx;
2905 	uint32_t count, read;
2906 	struct ip_fw_rule *r;
2907 	struct rule_check_info rci, *ci, *cbuf;
2908 	int i, rsize;
2909 
2910 	op3 = (ip_fw3_opheader *)ipfw_get_sopt_space(sd, sd->valsize);
2911 	ctlv = (ipfw_obj_ctlv *)(op3 + 1);
2912 
2913 	read = sizeof(ip_fw3_opheader);
2914 	rtlv = NULL;
2915 	tstate = NULL;
2916 	cbuf = NULL;
2917 	memset(&rci, 0, sizeof(struct rule_check_info));
2918 
2919 	if (read + sizeof(*ctlv) > sd->valsize)
2920 		return (EINVAL);
2921 
2922 	if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2923 		clen = ctlv->head.length;
2924 		/* Check size and alignment */
2925 		if (clen > sd->valsize || clen < sizeof(*ctlv))
2926 			return (EINVAL);
2927 		if ((clen % sizeof(uint64_t)) != 0)
2928 			return (EINVAL);
2929 
2930 		/*
2931 		 * Some table names or other named objects.
2932 		 * Check for validness.
2933 		 */
2934 		count = (ctlv->head.length - sizeof(*ctlv)) / sizeof(*ntlv);
2935 		if (ctlv->count != count || ctlv->objsize != sizeof(*ntlv))
2936 			return (EINVAL);
2937 
2938 		/*
2939 		 * Check each TLV.
2940 		 * Ensure TLVs are sorted ascending and
2941 		 * there are no duplicates.
2942 		 */
2943 		idx = -1;
2944 		ntlv = (ipfw_obj_ntlv *)(ctlv + 1);
2945 		while (count > 0) {
2946 			if (ntlv->head.length != sizeof(ipfw_obj_ntlv))
2947 				return (EINVAL);
2948 
2949 			error = ipfw_check_object_name_generic(ntlv->name);
2950 			if (error != 0)
2951 				return (error);
2952 
2953 			if (ntlv->idx <= idx)
2954 				return (EINVAL);
2955 
2956 			idx = ntlv->idx;
2957 			count--;
2958 			ntlv++;
2959 		}
2960 
2961 		tstate = ctlv;
2962 		read += ctlv->head.length;
2963 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2964 	}
2965 
2966 	if (read + sizeof(*ctlv) > sd->valsize)
2967 		return (EINVAL);
2968 
2969 	if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2970 		clen = ctlv->head.length;
2971 		if (clen + read > sd->valsize || clen < sizeof(*ctlv))
2972 			return (EINVAL);
2973 		if ((clen % sizeof(uint64_t)) != 0)
2974 			return (EINVAL);
2975 
2976 		/*
2977 		 * TODO: Permit adding multiple rules at once
2978 		 */
2979 		if (ctlv->count != 1)
2980 			return (ENOTSUP);
2981 
2982 		clen -= sizeof(*ctlv);
2983 
2984 		if (ctlv->count > clen / sizeof(struct ip_fw_rule))
2985 			return (EINVAL);
2986 
2987 		/* Allocate state for each rule or use stack */
2988 		if (ctlv->count == 1) {
2989 			memset(&rci, 0, sizeof(struct rule_check_info));
2990 			cbuf = &rci;
2991 		} else
2992 			cbuf = malloc(ctlv->count * sizeof(*ci), M_TEMP,
2993 			    M_WAITOK | M_ZERO);
2994 		ci = cbuf;
2995 
2996 		/*
2997 		 * Check each rule for validness.
2998 		 * Ensure numbered rules are sorted ascending
2999 		 * and properly aligned
3000 		 */
3001 		idx = 0;
3002 		r = (struct ip_fw_rule *)(ctlv + 1);
3003 		count = 0;
3004 		error = 0;
3005 		while (clen > 0) {
3006 			rsize = roundup2(RULESIZE(r), sizeof(uint64_t));
3007 			if (rsize > clen || ctlv->count <= count) {
3008 				error = EINVAL;
3009 				break;
3010 			}
3011 
3012 			ci->ctlv = tstate;
3013 			error = check_ipfw_rule1(r, rsize, ci);
3014 			if (error != 0)
3015 				break;
3016 
3017 			/* Check sorting */
3018 			if (r->rulenum != 0 && r->rulenum < idx) {
3019 				printf("rulenum %d idx %d\n", r->rulenum, idx);
3020 				error = EINVAL;
3021 				break;
3022 			}
3023 			idx = r->rulenum;
3024 
3025 			ci->urule = (caddr_t)r;
3026 
3027 			rsize = roundup2(rsize, sizeof(uint64_t));
3028 			clen -= rsize;
3029 			r = (struct ip_fw_rule *)((caddr_t)r + rsize);
3030 			count++;
3031 			ci++;
3032 		}
3033 
3034 		if (ctlv->count != count || error != 0) {
3035 			if (cbuf != &rci)
3036 				free(cbuf, M_TEMP);
3037 			return (EINVAL);
3038 		}
3039 
3040 		rtlv = ctlv;
3041 		read += ctlv->head.length;
3042 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3043 	}
3044 
3045 	if (read != sd->valsize || rtlv == NULL || rtlv->count == 0) {
3046 		if (cbuf != NULL && cbuf != &rci)
3047 			free(cbuf, M_TEMP);
3048 		return (EINVAL);
3049 	}
3050 
3051 	/*
3052 	 * Passed rules seems to be valid.
3053 	 * Allocate storage and try to add them to chain.
3054 	 */
3055 	for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++) {
3056 		clen = RULEKSIZE1((struct ip_fw_rule *)ci->urule);
3057 		ci->krule = ipfw_alloc_rule(chain, clen);
3058 		import_rule1(ci);
3059 	}
3060 
3061 	if ((error = commit_rules(chain, cbuf, rtlv->count)) != 0) {
3062 		/* Free allocate krules */
3063 		for (i = 0, ci = cbuf; i < rtlv->count; i++, ci++)
3064 			ipfw_free_rule(ci->krule);
3065 	}
3066 
3067 	if (cbuf != NULL && cbuf != &rci)
3068 		free(cbuf, M_TEMP);
3069 
3070 	return (error);
3071 }
3072 
3073 /*
3074  * Lists all sopts currently registered.
3075  * Data layout (v0)(current):
3076  * Request: [ ipfw_obj_lheader ], size = ipfw_obj_lheader.size
3077  * Reply: [ ipfw_obj_lheader ipfw_sopt_info x N ]
3078  *
3079  * Returns 0 on success
3080  */
3081 static int
3082 dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3083     struct sockopt_data *sd)
3084 {
3085 	struct _ipfw_obj_lheader *olh;
3086 	ipfw_sopt_info *i;
3087 	struct ipfw_sopt_handler *sh;
3088 	uint32_t count, n, size;
3089 
3090 	olh = (struct _ipfw_obj_lheader *)ipfw_get_sopt_header(sd,sizeof(*olh));
3091 	if (olh == NULL)
3092 		return (EINVAL);
3093 	if (sd->valsize < olh->size)
3094 		return (EINVAL);
3095 
3096 	CTL3_LOCK();
3097 	count = ctl3_hsize;
3098 	size = count * sizeof(ipfw_sopt_info) + sizeof(ipfw_obj_lheader);
3099 
3100 	/* Fill in header regadless of buffer size */
3101 	olh->count = count;
3102 	olh->objsize = sizeof(ipfw_sopt_info);
3103 
3104 	if (size > olh->size) {
3105 		olh->size = size;
3106 		CTL3_UNLOCK();
3107 		return (ENOMEM);
3108 	}
3109 	olh->size = size;
3110 
3111 	for (n = 1; n <= count; n++) {
3112 		i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i));
3113 		KASSERT(i != NULL, ("previously checked buffer is not enough"));
3114 		sh = &ctl3_handlers[n];
3115 		i->opcode = sh->opcode;
3116 		i->version = sh->version;
3117 		i->refcnt = sh->refcnt;
3118 	}
3119 	CTL3_UNLOCK();
3120 
3121 	return (0);
3122 }
3123 
3124 /*
3125  * Compares two opcodes.
3126  * Used both in qsort() and bsearch().
3127  *
3128  * Returns 0 if match is found.
3129  */
3130 static int
3131 compare_opcodes(const void *_a, const void *_b)
3132 {
3133 	const struct opcode_obj_rewrite *a, *b;
3134 
3135 	a = (const struct opcode_obj_rewrite *)_a;
3136 	b = (const struct opcode_obj_rewrite *)_b;
3137 
3138 	if (a->opcode < b->opcode)
3139 		return (-1);
3140 	else if (a->opcode > b->opcode)
3141 		return (1);
3142 
3143 	return (0);
3144 }
3145 
3146 /*
3147  * XXX: Rewrite bsearch()
3148  */
3149 static int
3150 find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo,
3151     struct opcode_obj_rewrite **phi)
3152 {
3153 	struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw;
3154 
3155 	memset(&h, 0, sizeof(h));
3156 	h.opcode = op;
3157 
3158 	rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters,
3159 	    ctl3_rsize, sizeof(h), compare_opcodes);
3160 	if (rw == NULL)
3161 		return (1);
3162 
3163 	/* Find the first element matching the same opcode */
3164 	lo = rw;
3165 	for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--)
3166 		;
3167 
3168 	/* Find the last element matching the same opcode */
3169 	hi = rw;
3170 	ctl3_max = ctl3_rewriters + ctl3_rsize;
3171 	for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++)
3172 		;
3173 
3174 	*plo = lo;
3175 	*phi = hi;
3176 
3177 	return (0);
3178 }
3179 
3180 /*
3181  * Finds opcode object rewriter based on @code.
3182  *
3183  * Returns pointer to handler or NULL.
3184  */
3185 static struct opcode_obj_rewrite *
3186 find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
3187 {
3188 	struct opcode_obj_rewrite *rw, *lo, *hi;
3189 	uint16_t uidx;
3190 	uint8_t subtype;
3191 
3192 	if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0)
3193 		return (NULL);
3194 
3195 	for (rw = lo; rw <= hi; rw++) {
3196 		if (rw->classifier(cmd, &uidx, &subtype) == 0) {
3197 			if (puidx != NULL)
3198 				*puidx = uidx;
3199 			if (ptype != NULL)
3200 				*ptype = subtype;
3201 			return (rw);
3202 		}
3203 	}
3204 
3205 	return (NULL);
3206 }
3207 int
3208 classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx)
3209 {
3210 
3211 	if (find_op_rw(cmd, puidx, NULL) == NULL)
3212 		return (1);
3213 	return (0);
3214 }
3215 
3216 void
3217 update_opcode_kidx(ipfw_insn *cmd, uint16_t idx)
3218 {
3219 	struct opcode_obj_rewrite *rw;
3220 
3221 	rw = find_op_rw(cmd, NULL, NULL);
3222 	KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode));
3223 	rw->update(cmd, idx);
3224 }
3225 
3226 void
3227 ipfw_init_obj_rewriter()
3228 {
3229 
3230 	ctl3_rewriters = NULL;
3231 	ctl3_rsize = 0;
3232 }
3233 
3234 void
3235 ipfw_destroy_obj_rewriter()
3236 {
3237 
3238 	if (ctl3_rewriters != NULL)
3239 		free(ctl3_rewriters, M_IPFW);
3240 	ctl3_rewriters = NULL;
3241 	ctl3_rsize = 0;
3242 }
3243 
3244 /*
3245  * Adds one or more opcode object rewrite handlers to the global array.
3246  * Function may sleep.
3247  */
3248 void
3249 ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3250 {
3251 	size_t sz;
3252 	struct opcode_obj_rewrite *tmp;
3253 
3254 	CTL3_LOCK();
3255 
3256 	for (;;) {
3257 		sz = ctl3_rsize + count;
3258 		CTL3_UNLOCK();
3259 		tmp = malloc(sizeof(*rw) * sz, M_IPFW, M_WAITOK | M_ZERO);
3260 		CTL3_LOCK();
3261 		if (ctl3_rsize + count <= sz)
3262 			break;
3263 
3264 		/* Retry */
3265 		free(tmp, M_IPFW);
3266 	}
3267 
3268 	/* Merge old & new arrays */
3269 	sz = ctl3_rsize + count;
3270 	memcpy(tmp, ctl3_rewriters, ctl3_rsize * sizeof(*rw));
3271 	memcpy(&tmp[ctl3_rsize], rw, count * sizeof(*rw));
3272 	qsort(tmp, sz, sizeof(*rw), compare_opcodes);
3273 	/* Switch new and free old */
3274 	if (ctl3_rewriters != NULL)
3275 		free(ctl3_rewriters, M_IPFW);
3276 	ctl3_rewriters = tmp;
3277 	ctl3_rsize = sz;
3278 
3279 	CTL3_UNLOCK();
3280 }
3281 
3282 /*
3283  * Removes one or more object rewrite handlers from the global array.
3284  */
3285 int
3286 ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count)
3287 {
3288 	size_t sz;
3289 	struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi;
3290 	int i;
3291 
3292 	CTL3_LOCK();
3293 
3294 	for (i = 0; i < count; i++) {
3295 		if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0)
3296 			continue;
3297 
3298 		for (ktmp = lo; ktmp <= hi; ktmp++) {
3299 			if (ktmp->classifier != rw[i].classifier)
3300 				continue;
3301 
3302 			ctl3_max = ctl3_rewriters + ctl3_rsize;
3303 			sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp);
3304 			memmove(ktmp, ktmp + 1, sz);
3305 			ctl3_rsize--;
3306 			break;
3307 		}
3308 
3309 	}
3310 
3311 	if (ctl3_rsize == 0) {
3312 		if (ctl3_rewriters != NULL)
3313 			free(ctl3_rewriters, M_IPFW);
3314 		ctl3_rewriters = NULL;
3315 	}
3316 
3317 	CTL3_UNLOCK();
3318 
3319 	return (0);
3320 }
3321 
3322 static int
3323 export_objhash_ntlv_internal(struct namedobj_instance *ni,
3324     struct named_object *no, void *arg)
3325 {
3326 	struct sockopt_data *sd;
3327 	ipfw_obj_ntlv *ntlv;
3328 
3329 	sd = (struct sockopt_data *)arg;
3330 	ntlv = (ipfw_obj_ntlv *)ipfw_get_sopt_space(sd, sizeof(*ntlv));
3331 	if (ntlv == NULL)
3332 		return (ENOMEM);
3333 	ipfw_export_obj_ntlv(no, ntlv);
3334 	return (0);
3335 }
3336 
3337 /*
3338  * Lists all service objects.
3339  * Data layout (v0)(current):
3340  * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size
3341  * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ]
3342  * Returns 0 on success
3343  */
3344 static int
3345 dump_srvobjects(struct ip_fw_chain *chain, ip_fw3_opheader *op3,
3346     struct sockopt_data *sd)
3347 {
3348 	ipfw_obj_lheader *hdr;
3349 	int count;
3350 
3351 	hdr = (ipfw_obj_lheader *)ipfw_get_sopt_header(sd, sizeof(*hdr));
3352 	if (hdr == NULL)
3353 		return (EINVAL);
3354 
3355 	IPFW_UH_RLOCK(chain);
3356 	count = ipfw_objhash_count(CHAIN_TO_SRV(chain));
3357 	hdr->size = sizeof(ipfw_obj_lheader) + count * sizeof(ipfw_obj_ntlv);
3358 	if (sd->valsize < hdr->size) {
3359 		IPFW_UH_RUNLOCK(chain);
3360 		return (ENOMEM);
3361 	}
3362 	hdr->count = count;
3363 	hdr->objsize = sizeof(ipfw_obj_ntlv);
3364 	if (count > 0)
3365 		ipfw_objhash_foreach(CHAIN_TO_SRV(chain),
3366 		    export_objhash_ntlv_internal, sd);
3367 	IPFW_UH_RUNLOCK(chain);
3368 	return (0);
3369 }
3370 
3371 /*
3372  * Compares two sopt handlers (code, version and handler ptr).
3373  * Used both as qsort() and bsearch().
3374  * Does not compare handler for latter case.
3375  *
3376  * Returns 0 if match is found.
3377  */
3378 static int
3379 compare_sh(const void *_a, const void *_b)
3380 {
3381 	const struct ipfw_sopt_handler *a, *b;
3382 
3383 	a = (const struct ipfw_sopt_handler *)_a;
3384 	b = (const struct ipfw_sopt_handler *)_b;
3385 
3386 	if (a->opcode < b->opcode)
3387 		return (-1);
3388 	else if (a->opcode > b->opcode)
3389 		return (1);
3390 
3391 	if (a->version < b->version)
3392 		return (-1);
3393 	else if (a->version > b->version)
3394 		return (1);
3395 
3396 	/* bsearch helper */
3397 	if (a->handler == NULL)
3398 		return (0);
3399 
3400 	if ((uintptr_t)a->handler < (uintptr_t)b->handler)
3401 		return (-1);
3402 	else if ((uintptr_t)a->handler > (uintptr_t)b->handler)
3403 		return (1);
3404 
3405 	return (0);
3406 }
3407 
3408 /*
3409  * Finds sopt handler based on @code and @version.
3410  *
3411  * Returns pointer to handler or NULL.
3412  */
3413 static struct ipfw_sopt_handler *
3414 find_sh(uint16_t code, uint8_t version, sopt_handler_f *handler)
3415 {
3416 	struct ipfw_sopt_handler *sh, h;
3417 
3418 	memset(&h, 0, sizeof(h));
3419 	h.opcode = code;
3420 	h.version = version;
3421 	h.handler = handler;
3422 
3423 	sh = (struct ipfw_sopt_handler *)bsearch(&h, ctl3_handlers,
3424 	    ctl3_hsize, sizeof(h), compare_sh);
3425 
3426 	return (sh);
3427 }
3428 
3429 static int
3430 find_ref_sh(uint16_t opcode, uint8_t version, struct ipfw_sopt_handler *psh)
3431 {
3432 	struct ipfw_sopt_handler *sh;
3433 
3434 	CTL3_LOCK();
3435 	if ((sh = find_sh(opcode, version, NULL)) == NULL) {
3436 		CTL3_UNLOCK();
3437 		printf("ipfw: ipfw_ctl3 invalid option %d""v""%d\n",
3438 		    opcode, version);
3439 		return (EINVAL);
3440 	}
3441 	sh->refcnt++;
3442 	ctl3_refct++;
3443 	/* Copy handler data to requested buffer */
3444 	*psh = *sh;
3445 	CTL3_UNLOCK();
3446 
3447 	return (0);
3448 }
3449 
3450 static void
3451 find_unref_sh(struct ipfw_sopt_handler *psh)
3452 {
3453 	struct ipfw_sopt_handler *sh;
3454 
3455 	CTL3_LOCK();
3456 	sh = find_sh(psh->opcode, psh->version, NULL);
3457 	KASSERT(sh != NULL, ("ctl3 handler disappeared"));
3458 	sh->refcnt--;
3459 	ctl3_refct--;
3460 	CTL3_UNLOCK();
3461 }
3462 
3463 void
3464 ipfw_init_sopt_handler()
3465 {
3466 
3467 	CTL3_LOCK_INIT();
3468 	IPFW_ADD_SOPT_HANDLER(1, scodes);
3469 }
3470 
3471 void
3472 ipfw_destroy_sopt_handler()
3473 {
3474 
3475 	IPFW_DEL_SOPT_HANDLER(1, scodes);
3476 	CTL3_LOCK_DESTROY();
3477 }
3478 
3479 /*
3480  * Adds one or more sockopt handlers to the global array.
3481  * Function may sleep.
3482  */
3483 void
3484 ipfw_add_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3485 {
3486 	size_t sz;
3487 	struct ipfw_sopt_handler *tmp;
3488 
3489 	CTL3_LOCK();
3490 
3491 	for (;;) {
3492 		sz = ctl3_hsize + count;
3493 		CTL3_UNLOCK();
3494 		tmp = malloc(sizeof(*sh) * sz, M_IPFW, M_WAITOK | M_ZERO);
3495 		CTL3_LOCK();
3496 		if (ctl3_hsize + count <= sz)
3497 			break;
3498 
3499 		/* Retry */
3500 		free(tmp, M_IPFW);
3501 	}
3502 
3503 	/* Merge old & new arrays */
3504 	sz = ctl3_hsize + count;
3505 	memcpy(tmp, ctl3_handlers, ctl3_hsize * sizeof(*sh));
3506 	memcpy(&tmp[ctl3_hsize], sh, count * sizeof(*sh));
3507 	qsort(tmp, sz, sizeof(*sh), compare_sh);
3508 	/* Switch new and free old */
3509 	if (ctl3_handlers != NULL)
3510 		free(ctl3_handlers, M_IPFW);
3511 	ctl3_handlers = tmp;
3512 	ctl3_hsize = sz;
3513 	ctl3_gencnt++;
3514 
3515 	CTL3_UNLOCK();
3516 }
3517 
3518 /*
3519  * Removes one or more sockopt handlers from the global array.
3520  */
3521 int
3522 ipfw_del_sopt_handler(struct ipfw_sopt_handler *sh, size_t count)
3523 {
3524 	size_t sz;
3525 	struct ipfw_sopt_handler *tmp, *h;
3526 	int i;
3527 
3528 	CTL3_LOCK();
3529 
3530 	for (i = 0; i < count; i++) {
3531 		tmp = &sh[i];
3532 		h = find_sh(tmp->opcode, tmp->version, tmp->handler);
3533 		if (h == NULL)
3534 			continue;
3535 
3536 		sz = (ctl3_handlers + ctl3_hsize - (h + 1)) * sizeof(*h);
3537 		memmove(h, h + 1, sz);
3538 		ctl3_hsize--;
3539 	}
3540 
3541 	if (ctl3_hsize == 0) {
3542 		if (ctl3_handlers != NULL)
3543 			free(ctl3_handlers, M_IPFW);
3544 		ctl3_handlers = NULL;
3545 	}
3546 
3547 	ctl3_gencnt++;
3548 
3549 	CTL3_UNLOCK();
3550 
3551 	return (0);
3552 }
3553 
3554 /*
3555  * Writes data accumulated in @sd to sockopt buffer.
3556  * Zeroes internal @sd buffer.
3557  */
3558 static int
3559 ipfw_flush_sopt_data(struct sockopt_data *sd)
3560 {
3561 	struct sockopt *sopt;
3562 	int error;
3563 	size_t sz;
3564 
3565 	sz = sd->koff;
3566 	if (sz == 0)
3567 		return (0);
3568 
3569 	sopt = sd->sopt;
3570 
3571 	if (sopt->sopt_dir == SOPT_GET) {
3572 		error = copyout(sd->kbuf, sopt->sopt_val, sz);
3573 		if (error != 0)
3574 			return (error);
3575 	}
3576 
3577 	memset(sd->kbuf, 0, sd->ksize);
3578 	sd->ktotal += sz;
3579 	sd->koff = 0;
3580 	if (sd->ktotal + sd->ksize < sd->valsize)
3581 		sd->kavail = sd->ksize;
3582 	else
3583 		sd->kavail = sd->valsize - sd->ktotal;
3584 
3585 	/* Update sopt buffer data */
3586 	sopt->sopt_valsize = sd->ktotal;
3587 	sopt->sopt_val = sd->sopt_val + sd->ktotal;
3588 
3589 	return (0);
3590 }
3591 
3592 /*
3593  * Ensures that @sd buffer has contiguous @neeeded number of
3594  * bytes.
3595  *
3596  * Returns pointer to requested space or NULL.
3597  */
3598 caddr_t
3599 ipfw_get_sopt_space(struct sockopt_data *sd, size_t needed)
3600 {
3601 	int error;
3602 	caddr_t addr;
3603 
3604 	if (sd->kavail < needed) {
3605 		/*
3606 		 * Flush data and try another time.
3607 		 */
3608 		error = ipfw_flush_sopt_data(sd);
3609 
3610 		if (sd->kavail < needed || error != 0)
3611 			return (NULL);
3612 	}
3613 
3614 	addr = sd->kbuf + sd->koff;
3615 	sd->koff += needed;
3616 	sd->kavail -= needed;
3617 	return (addr);
3618 }
3619 
3620 /*
3621  * Requests @needed contiguous bytes from @sd buffer.
3622  * Function is used to notify subsystem that we are
3623  * interesed in first @needed bytes (request header)
3624  * and the rest buffer can be safely zeroed.
3625  *
3626  * Returns pointer to requested space or NULL.
3627  */
3628 caddr_t
3629 ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed)
3630 {
3631 	caddr_t addr;
3632 
3633 	if ((addr = ipfw_get_sopt_space(sd, needed)) == NULL)
3634 		return (NULL);
3635 
3636 	if (sd->kavail > 0)
3637 		memset(sd->kbuf + sd->koff, 0, sd->kavail);
3638 
3639 	return (addr);
3640 }
3641 
3642 /*
3643  * New sockopt handler.
3644  */
3645 int
3646 ipfw_ctl3(struct sockopt *sopt)
3647 {
3648 	int error, locked;
3649 	size_t size, valsize;
3650 	struct ip_fw_chain *chain;
3651 	char xbuf[256];
3652 	struct sockopt_data sdata;
3653 	struct ipfw_sopt_handler h;
3654 	ip_fw3_opheader *op3 = NULL;
3655 
3656 	error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
3657 	if (error != 0)
3658 		return (error);
3659 
3660 	if (sopt->sopt_name != IP_FW3)
3661 		return (ipfw_ctl(sopt));
3662 
3663 	chain = &V_layer3_chain;
3664 	error = 0;
3665 
3666 	/* Save original valsize before it is altered via sooptcopyin() */
3667 	valsize = sopt->sopt_valsize;
3668 	memset(&sdata, 0, sizeof(sdata));
3669 	/* Read op3 header first to determine actual operation */
3670 	op3 = (ip_fw3_opheader *)xbuf;
3671 	error = sooptcopyin(sopt, op3, sizeof(*op3), sizeof(*op3));
3672 	if (error != 0)
3673 		return (error);
3674 	sopt->sopt_valsize = valsize;
3675 
3676 	/*
3677 	 * Find and reference command.
3678 	 */
3679 	error = find_ref_sh(op3->opcode, op3->version, &h);
3680 	if (error != 0)
3681 		return (error);
3682 
3683 	/*
3684 	 * Disallow modifications in really-really secure mode, but still allow
3685 	 * the logging counters to be reset.
3686 	 */
3687 	if ((h.dir & HDIR_SET) != 0 && h.opcode != IP_FW_XRESETLOG) {
3688 		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3689 		if (error != 0) {
3690 			find_unref_sh(&h);
3691 			return (error);
3692 		}
3693 	}
3694 
3695 	/*
3696 	 * Fill in sockopt_data structure that may be useful for
3697 	 * IP_FW3 get requests.
3698 	 */
3699 	locked = 0;
3700 	if (valsize <= sizeof(xbuf)) {
3701 		/* use on-stack buffer */
3702 		sdata.kbuf = xbuf;
3703 		sdata.ksize = sizeof(xbuf);
3704 		sdata.kavail = valsize;
3705 	} else {
3706 
3707 		/*
3708 		 * Determine opcode type/buffer size:
3709 		 * allocate sliding-window buf for data export or
3710 		 * contiguous buffer for special ops.
3711 		 */
3712 		if ((h.dir & HDIR_SET) != 0) {
3713 			/* Set request. Allocate contigous buffer. */
3714 			if (valsize > CTL3_LARGEBUF) {
3715 				find_unref_sh(&h);
3716 				return (EFBIG);
3717 			}
3718 
3719 			size = valsize;
3720 		} else {
3721 			/* Get request. Allocate sliding window buffer */
3722 			size = (valsize<CTL3_SMALLBUF) ? valsize:CTL3_SMALLBUF;
3723 
3724 			if (size < valsize) {
3725 				/* We have to wire user buffer */
3726 				error = vslock(sopt->sopt_val, valsize);
3727 				if (error != 0)
3728 					return (error);
3729 				locked = 1;
3730 			}
3731 		}
3732 
3733 		sdata.kbuf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3734 		sdata.ksize = size;
3735 		sdata.kavail = size;
3736 	}
3737 
3738 	sdata.sopt = sopt;
3739 	sdata.sopt_val = sopt->sopt_val;
3740 	sdata.valsize = valsize;
3741 
3742 	/*
3743 	 * Copy either all request (if valsize < bsize_max)
3744 	 * or first bsize_max bytes to guarantee most consumers
3745 	 * that all necessary data has been copied).
3746 	 * Anyway, copy not less than sizeof(ip_fw3_opheader).
3747 	 */
3748 	if ((error = sooptcopyin(sopt, sdata.kbuf, sdata.ksize,
3749 	    sizeof(ip_fw3_opheader))) != 0)
3750 		return (error);
3751 	op3 = (ip_fw3_opheader *)sdata.kbuf;
3752 
3753 	/* Finally, run handler */
3754 	error = h.handler(chain, op3, &sdata);
3755 	find_unref_sh(&h);
3756 
3757 	/* Flush state and free buffers */
3758 	if (error == 0)
3759 		error = ipfw_flush_sopt_data(&sdata);
3760 	else
3761 		ipfw_flush_sopt_data(&sdata);
3762 
3763 	if (locked != 0)
3764 		vsunlock(sdata.sopt_val, valsize);
3765 
3766 	/* Restore original pointer and set number of bytes written */
3767 	sopt->sopt_val = sdata.sopt_val;
3768 	sopt->sopt_valsize = sdata.ktotal;
3769 	if (sdata.kbuf != xbuf)
3770 		free(sdata.kbuf, M_TEMP);
3771 
3772 	return (error);
3773 }
3774 
3775 /**
3776  * {set|get}sockopt parser.
3777  */
3778 int
3779 ipfw_ctl(struct sockopt *sopt)
3780 {
3781 #define	RULE_MAXSIZE	(512*sizeof(u_int32_t))
3782 	int error;
3783 	size_t size, valsize;
3784 	struct ip_fw *buf;
3785 	struct ip_fw_rule0 *rule;
3786 	struct ip_fw_chain *chain;
3787 	u_int32_t rulenum[2];
3788 	uint32_t opt;
3789 	struct rule_check_info ci;
3790 	IPFW_RLOCK_TRACKER;
3791 
3792 	chain = &V_layer3_chain;
3793 	error = 0;
3794 
3795 	/* Save original valsize before it is altered via sooptcopyin() */
3796 	valsize = sopt->sopt_valsize;
3797 	opt = sopt->sopt_name;
3798 
3799 	/*
3800 	 * Disallow modifications in really-really secure mode, but still allow
3801 	 * the logging counters to be reset.
3802 	 */
3803 	if (opt == IP_FW_ADD ||
3804 	    (sopt->sopt_dir == SOPT_SET && opt != IP_FW_RESETLOG)) {
3805 		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3806 		if (error != 0)
3807 			return (error);
3808 	}
3809 
3810 	switch (opt) {
3811 	case IP_FW_GET:
3812 		/*
3813 		 * pass up a copy of the current rules. Static rules
3814 		 * come first (the last of which has number IPFW_DEFAULT_RULE),
3815 		 * followed by a possibly empty list of dynamic rule.
3816 		 * The last dynamic rule has NULL in the "next" field.
3817 		 *
3818 		 * Note that the calculated size is used to bound the
3819 		 * amount of data returned to the user.  The rule set may
3820 		 * change between calculating the size and returning the
3821 		 * data in which case we'll just return what fits.
3822 		 */
3823 		for (;;) {
3824 			int len = 0, want;
3825 
3826 			size = chain->static_len;
3827 			size += ipfw_dyn_len();
3828 			if (size >= sopt->sopt_valsize)
3829 				break;
3830 			buf = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
3831 			IPFW_UH_RLOCK(chain);
3832 			/* check again how much space we need */
3833 			want = chain->static_len + ipfw_dyn_len();
3834 			if (size >= want)
3835 				len = ipfw_getrules(chain, buf, size);
3836 			IPFW_UH_RUNLOCK(chain);
3837 			if (size >= want)
3838 				error = sooptcopyout(sopt, buf, len);
3839 			free(buf, M_TEMP);
3840 			if (size >= want)
3841 				break;
3842 		}
3843 		break;
3844 
3845 	case IP_FW_FLUSH:
3846 		/* locking is done within del_entry() */
3847 		error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
3848 		break;
3849 
3850 	case IP_FW_ADD:
3851 		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3852 		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3853 			sizeof(struct ip_fw7) );
3854 
3855 		memset(&ci, 0, sizeof(struct rule_check_info));
3856 
3857 		/*
3858 		 * If the size of commands equals RULESIZE7 then we assume
3859 		 * a FreeBSD7.2 binary is talking to us (set is7=1).
3860 		 * is7 is persistent so the next 'ipfw list' command
3861 		 * will use this format.
3862 		 * NOTE: If wrong version is guessed (this can happen if
3863 		 *       the first ipfw command is 'ipfw [pipe] list')
3864 		 *       the ipfw binary may crash or loop infinitly...
3865 		 */
3866 		size = sopt->sopt_valsize;
3867 		if (size == RULESIZE7(rule)) {
3868 		    is7 = 1;
3869 		    error = convert_rule_to_8(rule);
3870 		    if (error) {
3871 			free(rule, M_TEMP);
3872 			return error;
3873 		    }
3874 		    size = RULESIZE(rule);
3875 		} else
3876 		    is7 = 0;
3877 		if (error == 0)
3878 			error = check_ipfw_rule0(rule, size, &ci);
3879 		if (error == 0) {
3880 			/* locking is done within add_rule() */
3881 			struct ip_fw *krule;
3882 			krule = ipfw_alloc_rule(chain, RULEKSIZE0(rule));
3883 			ci.urule = (caddr_t)rule;
3884 			ci.krule = krule;
3885 			import_rule0(&ci);
3886 			error = commit_rules(chain, &ci, 1);
3887 			if (error != 0)
3888 				ipfw_free_rule(ci.krule);
3889 			else if (sopt->sopt_dir == SOPT_GET) {
3890 				if (is7) {
3891 					error = convert_rule_to_7(rule);
3892 					size = RULESIZE7(rule);
3893 					if (error) {
3894 						free(rule, M_TEMP);
3895 						return error;
3896 					}
3897 				}
3898 				error = sooptcopyout(sopt, rule, size);
3899 			}
3900 		}
3901 		free(rule, M_TEMP);
3902 		break;
3903 
3904 	case IP_FW_DEL:
3905 		/*
3906 		 * IP_FW_DEL is used for deleting single rules or sets,
3907 		 * and (ab)used to atomically manipulate sets. Argument size
3908 		 * is used to distinguish between the two:
3909 		 *    sizeof(u_int32_t)
3910 		 *	delete single rule or set of rules,
3911 		 *	or reassign rules (or sets) to a different set.
3912 		 *    2*sizeof(u_int32_t)
3913 		 *	atomic disable/enable sets.
3914 		 *	first u_int32_t contains sets to be disabled,
3915 		 *	second u_int32_t contains sets to be enabled.
3916 		 */
3917 		error = sooptcopyin(sopt, rulenum,
3918 			2*sizeof(u_int32_t), sizeof(u_int32_t));
3919 		if (error)
3920 			break;
3921 		size = sopt->sopt_valsize;
3922 		if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
3923 			/* delete or reassign, locking done in del_entry() */
3924 			error = del_entry(chain, rulenum[0]);
3925 		} else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
3926 			IPFW_UH_WLOCK(chain);
3927 			V_set_disable =
3928 			    (V_set_disable | rulenum[0]) & ~rulenum[1] &
3929 			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3930 			IPFW_UH_WUNLOCK(chain);
3931 		} else
3932 			error = EINVAL;
3933 		break;
3934 
3935 	case IP_FW_ZERO:
3936 	case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
3937 		rulenum[0] = 0;
3938 		if (sopt->sopt_val != 0) {
3939 		    error = sooptcopyin(sopt, rulenum,
3940 			    sizeof(u_int32_t), sizeof(u_int32_t));
3941 		    if (error)
3942 			break;
3943 		}
3944 		error = zero_entry(chain, rulenum[0],
3945 			sopt->sopt_name == IP_FW_RESETLOG);
3946 		break;
3947 
3948 	/*--- TABLE opcodes ---*/
3949 	case IP_FW_TABLE_ADD:
3950 	case IP_FW_TABLE_DEL:
3951 		{
3952 			ipfw_table_entry ent;
3953 			struct tentry_info tei;
3954 			struct tid_info ti;
3955 			struct table_value v;
3956 
3957 			error = sooptcopyin(sopt, &ent,
3958 			    sizeof(ent), sizeof(ent));
3959 			if (error)
3960 				break;
3961 
3962 			memset(&tei, 0, sizeof(tei));
3963 			tei.paddr = &ent.addr;
3964 			tei.subtype = AF_INET;
3965 			tei.masklen = ent.masklen;
3966 			ipfw_import_table_value_legacy(ent.value, &v);
3967 			tei.pvalue = &v;
3968 			memset(&ti, 0, sizeof(ti));
3969 			ti.uidx = ent.tbl;
3970 			ti.type = IPFW_TABLE_CIDR;
3971 
3972 			error = (opt == IP_FW_TABLE_ADD) ?
3973 			    add_table_entry(chain, &ti, &tei, 0, 1) :
3974 			    del_table_entry(chain, &ti, &tei, 0, 1);
3975 		}
3976 		break;
3977 
3978 
3979 	case IP_FW_TABLE_FLUSH:
3980 		{
3981 			u_int16_t tbl;
3982 			struct tid_info ti;
3983 
3984 			error = sooptcopyin(sopt, &tbl,
3985 			    sizeof(tbl), sizeof(tbl));
3986 			if (error)
3987 				break;
3988 			memset(&ti, 0, sizeof(ti));
3989 			ti.uidx = tbl;
3990 			error = flush_table(chain, &ti);
3991 		}
3992 		break;
3993 
3994 	case IP_FW_TABLE_GETSIZE:
3995 		{
3996 			u_int32_t tbl, cnt;
3997 			struct tid_info ti;
3998 
3999 			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4000 			    sizeof(tbl))))
4001 				break;
4002 			memset(&ti, 0, sizeof(ti));
4003 			ti.uidx = tbl;
4004 			IPFW_RLOCK(chain);
4005 			error = ipfw_count_table(chain, &ti, &cnt);
4006 			IPFW_RUNLOCK(chain);
4007 			if (error)
4008 				break;
4009 			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4010 		}
4011 		break;
4012 
4013 	case IP_FW_TABLE_LIST:
4014 		{
4015 			ipfw_table *tbl;
4016 			struct tid_info ti;
4017 
4018 			if (sopt->sopt_valsize < sizeof(*tbl)) {
4019 				error = EINVAL;
4020 				break;
4021 			}
4022 			size = sopt->sopt_valsize;
4023 			tbl = malloc(size, M_TEMP, M_WAITOK);
4024 			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4025 			if (error) {
4026 				free(tbl, M_TEMP);
4027 				break;
4028 			}
4029 			tbl->size = (size - sizeof(*tbl)) /
4030 			    sizeof(ipfw_table_entry);
4031 			memset(&ti, 0, sizeof(ti));
4032 			ti.uidx = tbl->tbl;
4033 			IPFW_RLOCK(chain);
4034 			error = ipfw_dump_table_legacy(chain, &ti, tbl);
4035 			IPFW_RUNLOCK(chain);
4036 			if (error) {
4037 				free(tbl, M_TEMP);
4038 				break;
4039 			}
4040 			error = sooptcopyout(sopt, tbl, size);
4041 			free(tbl, M_TEMP);
4042 		}
4043 		break;
4044 
4045 	/*--- NAT operations are protected by the IPFW_LOCK ---*/
4046 	case IP_FW_NAT_CFG:
4047 		if (IPFW_NAT_LOADED)
4048 			error = ipfw_nat_cfg_ptr(sopt);
4049 		else {
4050 			printf("IP_FW_NAT_CFG: %s\n",
4051 			    "ipfw_nat not present, please load it");
4052 			error = EINVAL;
4053 		}
4054 		break;
4055 
4056 	case IP_FW_NAT_DEL:
4057 		if (IPFW_NAT_LOADED)
4058 			error = ipfw_nat_del_ptr(sopt);
4059 		else {
4060 			printf("IP_FW_NAT_DEL: %s\n",
4061 			    "ipfw_nat not present, please load it");
4062 			error = EINVAL;
4063 		}
4064 		break;
4065 
4066 	case IP_FW_NAT_GET_CONFIG:
4067 		if (IPFW_NAT_LOADED)
4068 			error = ipfw_nat_get_cfg_ptr(sopt);
4069 		else {
4070 			printf("IP_FW_NAT_GET_CFG: %s\n",
4071 			    "ipfw_nat not present, please load it");
4072 			error = EINVAL;
4073 		}
4074 		break;
4075 
4076 	case IP_FW_NAT_GET_LOG:
4077 		if (IPFW_NAT_LOADED)
4078 			error = ipfw_nat_get_log_ptr(sopt);
4079 		else {
4080 			printf("IP_FW_NAT_GET_LOG: %s\n",
4081 			    "ipfw_nat not present, please load it");
4082 			error = EINVAL;
4083 		}
4084 		break;
4085 
4086 	default:
4087 		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4088 		error = EINVAL;
4089 	}
4090 
4091 	return (error);
4092 #undef RULE_MAXSIZE
4093 }
4094 #define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
4095 
4096 /* Functions to convert rules 7.2 <==> 8.0 */
4097 static int
4098 convert_rule_to_7(struct ip_fw_rule0 *rule)
4099 {
4100 	/* Used to modify original rule */
4101 	struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
4102 	/* copy of original rule, version 8 */
4103 	struct ip_fw_rule0 *tmp;
4104 
4105 	/* Used to copy commands */
4106 	ipfw_insn *ccmd, *dst;
4107 	int ll = 0, ccmdlen = 0;
4108 
4109 	tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4110 	if (tmp == NULL) {
4111 		return 1; //XXX error
4112 	}
4113 	bcopy(rule, tmp, RULE_MAXSIZE);
4114 
4115 	/* Copy fields */
4116 	//rule7->_pad = tmp->_pad;
4117 	rule7->set = tmp->set;
4118 	rule7->rulenum = tmp->rulenum;
4119 	rule7->cmd_len = tmp->cmd_len;
4120 	rule7->act_ofs = tmp->act_ofs;
4121 	rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
4122 	rule7->cmd_len = tmp->cmd_len;
4123 	rule7->pcnt = tmp->pcnt;
4124 	rule7->bcnt = tmp->bcnt;
4125 	rule7->timestamp = tmp->timestamp;
4126 
4127 	/* Copy commands */
4128 	for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
4129 			ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4130 		ccmdlen = F_LEN(ccmd);
4131 
4132 		bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4133 
4134 		if (dst->opcode > O_NAT)
4135 			/* O_REASS doesn't exists in 7.2 version, so
4136 			 * decrement opcode if it is after O_REASS
4137 			 */
4138 			dst->opcode--;
4139 
4140 		if (ccmdlen > ll) {
4141 			printf("ipfw: opcode %d size truncated\n",
4142 				ccmd->opcode);
4143 			return EINVAL;
4144 		}
4145 	}
4146 	free(tmp, M_TEMP);
4147 
4148 	return 0;
4149 }
4150 
4151 static int
4152 convert_rule_to_8(struct ip_fw_rule0 *rule)
4153 {
4154 	/* Used to modify original rule */
4155 	struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
4156 
4157 	/* Used to copy commands */
4158 	ipfw_insn *ccmd, *dst;
4159 	int ll = 0, ccmdlen = 0;
4160 
4161 	/* Copy of original rule */
4162 	struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
4163 	if (tmp == NULL) {
4164 		return 1; //XXX error
4165 	}
4166 
4167 	bcopy(rule7, tmp, RULE_MAXSIZE);
4168 
4169 	for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
4170 			ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
4171 		ccmdlen = F_LEN(ccmd);
4172 
4173 		bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
4174 
4175 		if (dst->opcode > O_NAT)
4176 			/* O_REASS doesn't exists in 7.2 version, so
4177 			 * increment opcode if it is after O_REASS
4178 			 */
4179 			dst->opcode++;
4180 
4181 		if (ccmdlen > ll) {
4182 			printf("ipfw: opcode %d size truncated\n",
4183 			    ccmd->opcode);
4184 			return EINVAL;
4185 		}
4186 	}
4187 
4188 	rule->_pad = tmp->_pad;
4189 	rule->set = tmp->set;
4190 	rule->rulenum = tmp->rulenum;
4191 	rule->cmd_len = tmp->cmd_len;
4192 	rule->act_ofs = tmp->act_ofs;
4193 	rule->next_rule = (struct ip_fw *)tmp->next_rule;
4194 	rule->cmd_len = tmp->cmd_len;
4195 	rule->id = 0; /* XXX see if is ok = 0 */
4196 	rule->pcnt = tmp->pcnt;
4197 	rule->bcnt = tmp->bcnt;
4198 	rule->timestamp = tmp->timestamp;
4199 
4200 	free (tmp, M_TEMP);
4201 	return 0;
4202 }
4203 
4204 /*
4205  * Named object api
4206  *
4207  */
4208 
4209 void
4210 ipfw_init_srv(struct ip_fw_chain *ch)
4211 {
4212 
4213 	ch->srvmap = ipfw_objhash_create(IPFW_OBJECTS_DEFAULT);
4214 	ch->srvstate = malloc(sizeof(void *) * IPFW_OBJECTS_DEFAULT,
4215 	    M_IPFW, M_WAITOK | M_ZERO);
4216 }
4217 
4218 void
4219 ipfw_destroy_srv(struct ip_fw_chain *ch)
4220 {
4221 
4222 	free(ch->srvstate, M_IPFW);
4223 	ipfw_objhash_destroy(ch->srvmap);
4224 }
4225 
4226 /*
4227  * Allocate new bitmask which can be used to enlarge/shrink
4228  * named instance index.
4229  */
4230 void
4231 ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks)
4232 {
4233 	size_t size;
4234 	int max_blocks;
4235 	u_long *idx_mask;
4236 
4237 	KASSERT((items % BLOCK_ITEMS) == 0,
4238 	   ("bitmask size needs to power of 2 and greater or equal to %zu",
4239 	    BLOCK_ITEMS));
4240 
4241 	max_blocks = items / BLOCK_ITEMS;
4242 	size = items / 8;
4243 	idx_mask = malloc(size * IPFW_MAX_SETS, M_IPFW, M_WAITOK);
4244 	/* Mark all as free */
4245 	memset(idx_mask, 0xFF, size * IPFW_MAX_SETS);
4246 	*idx_mask &= ~(u_long)1; /* Skip index 0 */
4247 
4248 	*idx = idx_mask;
4249 	*pblocks = max_blocks;
4250 }
4251 
4252 /*
4253  * Copy current bitmask index to new one.
4254  */
4255 void
4256 ipfw_objhash_bitmap_merge(struct namedobj_instance *ni, void **idx, int *blocks)
4257 {
4258 	int old_blocks, new_blocks;
4259 	u_long *old_idx, *new_idx;
4260 	int i;
4261 
4262 	old_idx = ni->idx_mask;
4263 	old_blocks = ni->max_blocks;
4264 	new_idx = *idx;
4265 	new_blocks = *blocks;
4266 
4267 	for (i = 0; i < IPFW_MAX_SETS; i++) {
4268 		memcpy(&new_idx[new_blocks * i], &old_idx[old_blocks * i],
4269 		    old_blocks * sizeof(u_long));
4270 	}
4271 }
4272 
4273 /*
4274  * Swaps current @ni index with new one.
4275  */
4276 void
4277 ipfw_objhash_bitmap_swap(struct namedobj_instance *ni, void **idx, int *blocks)
4278 {
4279 	int old_blocks;
4280 	u_long *old_idx;
4281 
4282 	old_idx = ni->idx_mask;
4283 	old_blocks = ni->max_blocks;
4284 
4285 	ni->idx_mask = *idx;
4286 	ni->max_blocks = *blocks;
4287 
4288 	/* Save old values */
4289 	*idx = old_idx;
4290 	*blocks = old_blocks;
4291 }
4292 
4293 void
4294 ipfw_objhash_bitmap_free(void *idx, int blocks)
4295 {
4296 
4297 	free(idx, M_IPFW);
4298 }
4299 
4300 /*
4301  * Creates named hash instance.
4302  * Must be called without holding any locks.
4303  * Return pointer to new instance.
4304  */
4305 struct namedobj_instance *
4306 ipfw_objhash_create(uint32_t items)
4307 {
4308 	struct namedobj_instance *ni;
4309 	int i;
4310 	size_t size;
4311 
4312 	size = sizeof(struct namedobj_instance) +
4313 	    sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE +
4314 	    sizeof(struct namedobjects_head) * NAMEDOBJ_HASH_SIZE;
4315 
4316 	ni = malloc(size, M_IPFW, M_WAITOK | M_ZERO);
4317 	ni->nn_size = NAMEDOBJ_HASH_SIZE;
4318 	ni->nv_size = NAMEDOBJ_HASH_SIZE;
4319 
4320 	ni->names = (struct namedobjects_head *)(ni +1);
4321 	ni->values = &ni->names[ni->nn_size];
4322 
4323 	for (i = 0; i < ni->nn_size; i++)
4324 		TAILQ_INIT(&ni->names[i]);
4325 
4326 	for (i = 0; i < ni->nv_size; i++)
4327 		TAILQ_INIT(&ni->values[i]);
4328 
4329 	/* Set default hashing/comparison functions */
4330 	ni->hash_f = objhash_hash_name;
4331 	ni->cmp_f = objhash_cmp_name;
4332 
4333 	/* Allocate bitmask separately due to possible resize */
4334 	ipfw_objhash_bitmap_alloc(items, (void*)&ni->idx_mask, &ni->max_blocks);
4335 
4336 	return (ni);
4337 }
4338 
4339 void
4340 ipfw_objhash_destroy(struct namedobj_instance *ni)
4341 {
4342 
4343 	free(ni->idx_mask, M_IPFW);
4344 	free(ni, M_IPFW);
4345 }
4346 
4347 void
4348 ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f,
4349     objhash_cmp_f *cmp_f)
4350 {
4351 
4352 	ni->hash_f = hash_f;
4353 	ni->cmp_f = cmp_f;
4354 }
4355 
4356 static uint32_t
4357 objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set)
4358 {
4359 
4360 	return (fnv_32_str((const char *)name, FNV1_32_INIT));
4361 }
4362 
4363 static int
4364 objhash_cmp_name(struct named_object *no, const void *name, uint32_t set)
4365 {
4366 
4367 	if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set))
4368 		return (0);
4369 
4370 	return (1);
4371 }
4372 
4373 static uint32_t
4374 objhash_hash_idx(struct namedobj_instance *ni, uint32_t val)
4375 {
4376 	uint32_t v;
4377 
4378 	v = val % (ni->nv_size - 1);
4379 
4380 	return (v);
4381 }
4382 
4383 struct named_object *
4384 ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name)
4385 {
4386 	struct named_object *no;
4387 	uint32_t hash;
4388 
4389 	hash = ni->hash_f(ni, name, set) % ni->nn_size;
4390 
4391 	TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4392 		if (ni->cmp_f(no, name, set) == 0)
4393 			return (no);
4394 	}
4395 
4396 	return (NULL);
4397 }
4398 
4399 /*
4400  * Find named object by @uid.
4401  * Check @tlvs for valid data inside.
4402  *
4403  * Returns pointer to found TLV or NULL.
4404  */
4405 ipfw_obj_ntlv *
4406 ipfw_find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv)
4407 {
4408 	ipfw_obj_ntlv *ntlv;
4409 	uintptr_t pa, pe;
4410 	int l;
4411 
4412 	pa = (uintptr_t)tlvs;
4413 	pe = pa + len;
4414 	l = 0;
4415 	for (; pa < pe; pa += l) {
4416 		ntlv = (ipfw_obj_ntlv *)pa;
4417 		l = ntlv->head.length;
4418 
4419 		if (l != sizeof(*ntlv))
4420 			return (NULL);
4421 
4422 		if (ntlv->idx != uidx)
4423 			continue;
4424 		/*
4425 		 * When userland has specified zero TLV type, do
4426 		 * not compare it with eltv. In some cases userland
4427 		 * doesn't know what type should it have. Use only
4428 		 * uidx and name for search named_object.
4429 		 */
4430 		if (ntlv->head.type != 0 &&
4431 		    ntlv->head.type != (uint16_t)etlv)
4432 			continue;
4433 
4434 		if (ipfw_check_object_name_generic(ntlv->name) != 0)
4435 			return (NULL);
4436 
4437 		return (ntlv);
4438 	}
4439 
4440 	return (NULL);
4441 }
4442 
4443 /*
4444  * Finds object config based on either legacy index
4445  * or name in ntlv.
4446  * Note @ti structure contains unchecked data from userland.
4447  *
4448  * Returns 0 in success and fills in @pno with found config
4449  */
4450 int
4451 ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti,
4452     uint32_t etlv, struct named_object **pno)
4453 {
4454 	char *name;
4455 	ipfw_obj_ntlv *ntlv;
4456 	uint32_t set;
4457 
4458 	if (ti->tlvs == NULL)
4459 		return (EINVAL);
4460 
4461 	ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv);
4462 	if (ntlv == NULL)
4463 		return (EINVAL);
4464 	name = ntlv->name;
4465 
4466 	/*
4467 	 * Use set provided by @ti instead of @ntlv one.
4468 	 * This is needed due to different sets behavior
4469 	 * controlled by V_fw_tables_sets.
4470 	 */
4471 	set = ti->set;
4472 	*pno = ipfw_objhash_lookup_name(ni, set, name);
4473 	if (*pno == NULL)
4474 		return (ESRCH);
4475 	return (0);
4476 }
4477 
4478 /*
4479  * Find named object by name, considering also its TLV type.
4480  */
4481 struct named_object *
4482 ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set,
4483     uint32_t type, const char *name)
4484 {
4485 	struct named_object *no;
4486 	uint32_t hash;
4487 
4488 	hash = ni->hash_f(ni, name, set) % ni->nn_size;
4489 
4490 	TAILQ_FOREACH(no, &ni->names[hash], nn_next) {
4491 		if (ni->cmp_f(no, name, set) == 0 &&
4492 		    no->etlv == (uint16_t)type)
4493 			return (no);
4494 	}
4495 
4496 	return (NULL);
4497 }
4498 
4499 struct named_object *
4500 ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t kidx)
4501 {
4502 	struct named_object *no;
4503 	uint32_t hash;
4504 
4505 	hash = objhash_hash_idx(ni, kidx);
4506 
4507 	TAILQ_FOREACH(no, &ni->values[hash], nv_next) {
4508 		if (no->kidx == kidx)
4509 			return (no);
4510 	}
4511 
4512 	return (NULL);
4513 }
4514 
4515 int
4516 ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a,
4517     struct named_object *b)
4518 {
4519 
4520 	if ((strcmp(a->name, b->name) == 0) && a->set == b->set)
4521 		return (1);
4522 
4523 	return (0);
4524 }
4525 
4526 void
4527 ipfw_objhash_add(struct namedobj_instance *ni, struct named_object *no)
4528 {
4529 	uint32_t hash;
4530 
4531 	hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4532 	TAILQ_INSERT_HEAD(&ni->names[hash], no, nn_next);
4533 
4534 	hash = objhash_hash_idx(ni, no->kidx);
4535 	TAILQ_INSERT_HEAD(&ni->values[hash], no, nv_next);
4536 
4537 	ni->count++;
4538 }
4539 
4540 void
4541 ipfw_objhash_del(struct namedobj_instance *ni, struct named_object *no)
4542 {
4543 	uint32_t hash;
4544 
4545 	hash = ni->hash_f(ni, no->name, no->set) % ni->nn_size;
4546 	TAILQ_REMOVE(&ni->names[hash], no, nn_next);
4547 
4548 	hash = objhash_hash_idx(ni, no->kidx);
4549 	TAILQ_REMOVE(&ni->values[hash], no, nv_next);
4550 
4551 	ni->count--;
4552 }
4553 
4554 uint32_t
4555 ipfw_objhash_count(struct namedobj_instance *ni)
4556 {
4557 
4558 	return (ni->count);
4559 }
4560 
4561 uint32_t
4562 ipfw_objhash_count_type(struct namedobj_instance *ni, uint16_t type)
4563 {
4564 	struct named_object *no;
4565 	uint32_t count;
4566 	int i;
4567 
4568 	count = 0;
4569 	for (i = 0; i < ni->nn_size; i++) {
4570 		TAILQ_FOREACH(no, &ni->names[i], nn_next) {
4571 			if (no->etlv == type)
4572 				count++;
4573 		}
4574 	}
4575 	return (count);
4576 }
4577 
4578 /*
4579  * Runs @func for each found named object.
4580  * It is safe to delete objects from callback
4581  */
4582 int
4583 ipfw_objhash_foreach(struct namedobj_instance *ni, objhash_cb_t *f, void *arg)
4584 {
4585 	struct named_object *no, *no_tmp;
4586 	int i, ret;
4587 
4588 	for (i = 0; i < ni->nn_size; i++) {
4589 		TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4590 			ret = f(ni, no, arg);
4591 			if (ret != 0)
4592 				return (ret);
4593 		}
4594 	}
4595 	return (0);
4596 }
4597 
4598 /*
4599  * Runs @f for each found named object with type @type.
4600  * It is safe to delete objects from callback
4601  */
4602 int
4603 ipfw_objhash_foreach_type(struct namedobj_instance *ni, objhash_cb_t *f,
4604     void *arg, uint16_t type)
4605 {
4606 	struct named_object *no, *no_tmp;
4607 	int i, ret;
4608 
4609 	for (i = 0; i < ni->nn_size; i++) {
4610 		TAILQ_FOREACH_SAFE(no, &ni->names[i], nn_next, no_tmp) {
4611 			if (no->etlv != type)
4612 				continue;
4613 			ret = f(ni, no, arg);
4614 			if (ret != 0)
4615 				return (ret);
4616 		}
4617 	}
4618 	return (0);
4619 }
4620 
4621 /*
4622  * Removes index from given set.
4623  * Returns 0 on success.
4624  */
4625 int
4626 ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx)
4627 {
4628 	u_long *mask;
4629 	int i, v;
4630 
4631 	i = idx / BLOCK_ITEMS;
4632 	v = idx % BLOCK_ITEMS;
4633 
4634 	if (i >= ni->max_blocks)
4635 		return (1);
4636 
4637 	mask = &ni->idx_mask[i];
4638 
4639 	if ((*mask & ((u_long)1 << v)) != 0)
4640 		return (1);
4641 
4642 	/* Mark as free */
4643 	*mask |= (u_long)1 << v;
4644 
4645 	/* Update free offset */
4646 	if (ni->free_off[0] > i)
4647 		ni->free_off[0] = i;
4648 
4649 	return (0);
4650 }
4651 
4652 /*
4653  * Allocate new index in given instance and stores in in @pidx.
4654  * Returns 0 on success.
4655  */
4656 int
4657 ipfw_objhash_alloc_idx(void *n, uint16_t *pidx)
4658 {
4659 	struct namedobj_instance *ni;
4660 	u_long *mask;
4661 	int i, off, v;
4662 
4663 	ni = (struct namedobj_instance *)n;
4664 
4665 	off = ni->free_off[0];
4666 	mask = &ni->idx_mask[off];
4667 
4668 	for (i = off; i < ni->max_blocks; i++, mask++) {
4669 		if ((v = ffsl(*mask)) == 0)
4670 			continue;
4671 
4672 		/* Mark as busy */
4673 		*mask &= ~ ((u_long)1 << (v - 1));
4674 
4675 		ni->free_off[0] = i;
4676 
4677 		v = BLOCK_ITEMS * i + v - 1;
4678 
4679 		*pidx = v;
4680 		return (0);
4681 	}
4682 
4683 	return (1);
4684 }
4685 
4686 /* end of file */
4687