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