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