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