Upgrade to OpenSSH 6.2p1. The most important new features are support
[freebsd.git] / sys / netpfil / ipfw / ip_fw_sockopt.c
1 /*-
2  * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3  *
4  * Supported by: Valeria Paoli
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 /*
32  * Sockopt support for ipfw. The routines here implement
33  * the upper half of the ipfw code.
34  */
35
36 #include "opt_ipfw.h"
37 #include "opt_inet.h"
38 #ifndef INET
39 #error IPFIREWALL requires INET.
40 #endif /* INET */
41 #include "opt_inet6.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>   /* struct m_tag used by nested headers */
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/rwlock.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/syslog.h>
56 #include <net/if.h>
57 #include <net/route.h>
58 #include <net/vnet.h>
59
60 #include <netinet/in.h>
61 #include <netinet/ip_var.h> /* hooks */
62 #include <netinet/ip_fw.h>
63
64 #include <netpfil/ipfw/ip_fw_private.h>
65
66 #ifdef MAC
67 #include <security/mac/mac_framework.h>
68 #endif
69
70 MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
71
72 /*
73  * static variables followed by global ones (none in this file)
74  */
75
76 /*
77  * Find the smallest rule >= key, id.
78  * We could use bsearch but it is so simple that we code it directly
79  */
80 int
81 ipfw_find_rule(struct ip_fw_chain *chain, uint32_t key, uint32_t id)
82 {
83         int i, lo, hi;
84         struct ip_fw *r;
85
86         for (lo = 0, hi = chain->n_rules - 1; lo < hi;) {
87                 i = (lo + hi) / 2;
88                 r = chain->map[i];
89                 if (r->rulenum < key)
90                         lo = i + 1;     /* continue from the next one */
91                 else if (r->rulenum > key)
92                         hi = i;         /* this might be good */
93                 else if (r->id < id)
94                         lo = i + 1;     /* continue from the next one */
95                 else /* r->id >= id */
96                         hi = i;         /* this might be good */
97         };
98         return hi;
99 }
100
101 /*
102  * allocate a new map, returns the chain locked. extra is the number
103  * of entries to add or delete.
104  */
105 static struct ip_fw **
106 get_map(struct ip_fw_chain *chain, int extra, int locked)
107 {
108
109         for (;;) {
110                 struct ip_fw **map;
111                 int i;
112
113                 i = chain->n_rules + extra;
114                 map = malloc(i * sizeof(struct ip_fw *), M_IPFW,
115                         locked ? M_NOWAIT : M_WAITOK);
116                 if (map == NULL) {
117                         printf("%s: cannot allocate map\n", __FUNCTION__);
118                         return NULL;
119                 }
120                 if (!locked)
121                         IPFW_UH_WLOCK(chain);
122                 if (i >= chain->n_rules + extra) /* good */
123                         return map;
124                 /* otherwise we lost the race, free and retry */
125                 if (!locked)
126                         IPFW_UH_WUNLOCK(chain);
127                 free(map, M_IPFW);
128         }
129 }
130
131 /*
132  * swap the maps. It is supposed to be called with IPFW_UH_WLOCK
133  */
134 static struct ip_fw **
135 swap_map(struct ip_fw_chain *chain, struct ip_fw **new_map, int new_len)
136 {
137         struct ip_fw **old_map;
138
139         IPFW_WLOCK(chain);
140         chain->id++;
141         chain->n_rules = new_len;
142         old_map = chain->map;
143         chain->map = new_map;
144         IPFW_WUNLOCK(chain);
145         return old_map;
146 }
147
148 /*
149  * Add a new rule to the list. Copy the rule into a malloc'ed area, then
150  * possibly create a rule number and add the rule to the list.
151  * Update the rule_number in the input struct so the caller knows it as well.
152  * XXX DO NOT USE FOR THE DEFAULT RULE.
153  * Must be called without IPFW_UH held
154  */
155 int
156 ipfw_add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
157 {
158         struct ip_fw *rule;
159         int i, l, insert_before;
160         struct ip_fw **map;     /* the new array of pointers */
161
162         if (chain->rules == NULL || input_rule->rulenum > IPFW_DEFAULT_RULE-1)
163                 return (EINVAL);
164
165         l = RULESIZE(input_rule);
166         rule = malloc(l, M_IPFW, M_WAITOK | M_ZERO);
167         /* get_map returns with IPFW_UH_WLOCK if successful */
168         map = get_map(chain, 1, 0 /* not locked */);
169         if (map == NULL) {
170                 free(rule, M_IPFW);
171                 return ENOSPC;
172         }
173
174         bcopy(input_rule, rule, l);
175         /* clear fields not settable from userland */
176         rule->x_next = NULL;
177         rule->next_rule = NULL;
178         IPFW_ZERO_RULE_COUNTER(rule);
179
180         if (V_autoinc_step < 1)
181                 V_autoinc_step = 1;
182         else if (V_autoinc_step > 1000)
183                 V_autoinc_step = 1000;
184         /* find the insertion point, we will insert before */
185         insert_before = rule->rulenum ? rule->rulenum + 1 : IPFW_DEFAULT_RULE;
186         i = ipfw_find_rule(chain, insert_before, 0);
187         /* duplicate first part */
188         if (i > 0)
189                 bcopy(chain->map, map, i * sizeof(struct ip_fw *));
190         map[i] = rule;
191         /* duplicate remaining part, we always have the default rule */
192         bcopy(chain->map + i, map + i + 1,
193                 sizeof(struct ip_fw *) *(chain->n_rules - i));
194         if (rule->rulenum == 0) {
195                 /* write back the number */
196                 rule->rulenum = i > 0 ? map[i-1]->rulenum : 0;
197                 if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
198                         rule->rulenum += V_autoinc_step;
199                 input_rule->rulenum = rule->rulenum;
200         }
201
202         rule->id = chain->id + 1;
203         map = swap_map(chain, map, chain->n_rules + 1);
204         chain->static_len += l;
205         IPFW_UH_WUNLOCK(chain);
206         if (map)
207                 free(map, M_IPFW);
208         return (0);
209 }
210
211 /*
212  * Reclaim storage associated with a list of rules.  This is
213  * typically the list created using remove_rule.
214  * A NULL pointer on input is handled correctly.
215  */
216 void
217 ipfw_reap_rules(struct ip_fw *head)
218 {
219         struct ip_fw *rule;
220
221         while ((rule = head) != NULL) {
222                 head = head->x_next;
223                 free(rule, M_IPFW);
224         }
225 }
226
227 /*
228  * Used by del_entry() to check if a rule should be kept.
229  * Returns 1 if the rule must be kept, 0 otherwise.
230  *
231  * Called with cmd = {0,1,5}.
232  * cmd == 0 matches on rule numbers, excludes rules in RESVD_SET if n == 0 ;
233  * cmd == 1 matches on set numbers only, rule numbers are ignored;
234  * cmd == 5 matches on rule and set numbers.
235  *
236  * n == 0 is a wildcard for rule numbers, there is no wildcard for sets.
237  *
238  * Rules to keep are
239  *      (default || reserved || !match_set || !match_number)
240  * where
241  *   default ::= (rule->rulenum == IPFW_DEFAULT_RULE)
242  *      // the default rule is always protected
243  *
244  *   reserved ::= (cmd == 0 && n == 0 && rule->set == RESVD_SET)
245  *      // RESVD_SET is protected only if cmd == 0 and n == 0 ("ipfw flush")
246  *
247  *   match_set ::= (cmd == 0 || rule->set == set)
248  *      // set number is ignored for cmd == 0
249  *
250  *   match_number ::= (cmd == 1 || n == 0 || n == rule->rulenum)
251  *      // number is ignored for cmd == 1 or n == 0
252  *
253  */
254 static int
255 keep_rule(struct ip_fw *rule, uint8_t cmd, uint8_t set, uint32_t n)
256 {
257         return
258                  (rule->rulenum == IPFW_DEFAULT_RULE)           ||
259                  (cmd == 0 && n == 0 && rule->set == RESVD_SET) ||
260                 !(cmd == 0 || rule->set == set)                 ||
261                 !(cmd == 1 || n == 0 || n == rule->rulenum);
262 }
263
264 /**
265  * Remove all rules with given number, or do set manipulation.
266  * Assumes chain != NULL && *chain != NULL.
267  *
268  * The argument is an uint32_t. The low 16 bit are the rule or set number;
269  * the next 8 bits are the new set; the top 8 bits indicate the command:
270  *
271  *      0       delete rules numbered "rulenum"
272  *      1       delete rules in set "rulenum"
273  *      2       move rules "rulenum" to set "new_set"
274  *      3       move rules from set "rulenum" to set "new_set"
275  *      4       swap sets "rulenum" and "new_set"
276  *      5       delete rules "rulenum" and set "new_set"
277  */
278 static int
279 del_entry(struct ip_fw_chain *chain, uint32_t arg)
280 {
281         struct ip_fw *rule;
282         uint32_t num;   /* rule number or old_set */
283         uint8_t cmd, new_set;
284         int start, end, i, ofs, n;
285         struct ip_fw **map = NULL;
286         int error = 0;
287
288         num = arg & 0xffff;
289         cmd = (arg >> 24) & 0xff;
290         new_set = (arg >> 16) & 0xff;
291
292         if (cmd > 5 || new_set > RESVD_SET)
293                 return EINVAL;
294         if (cmd == 0 || cmd == 2 || cmd == 5) {
295                 if (num >= IPFW_DEFAULT_RULE)
296                         return EINVAL;
297         } else {
298                 if (num > RESVD_SET)    /* old_set */
299                         return EINVAL;
300         }
301
302         IPFW_UH_WLOCK(chain);   /* arbitrate writers */
303         chain->reap = NULL;     /* prepare for deletions */
304
305         switch (cmd) {
306         case 0: /* delete rules "num" (num == 0 matches all) */
307         case 1: /* delete all rules in set N */
308         case 5: /* delete rules with number N and set "new_set". */
309
310                 /*
311                  * Locate first rule to delete (start), the rule after
312                  * the last one to delete (end), and count how many
313                  * rules to delete (n). Always use keep_rule() to
314                  * determine which rules to keep.
315                  */
316                 n = 0;
317                 if (cmd == 1) {
318                         /* look for a specific set including RESVD_SET.
319                          * Must scan the entire range, ignore num.
320                          */
321                         new_set = num;
322                         for (start = -1, end = i = 0; i < chain->n_rules; i++) {
323                                 if (keep_rule(chain->map[i], cmd, new_set, 0))
324                                         continue;
325                                 if (start < 0)
326                                         start = i;
327                                 end = i;
328                                 n++;
329                         }
330                         end++;  /* first non-matching */
331                 } else {
332                         /* Optimized search on rule numbers */
333                         start = ipfw_find_rule(chain, num, 0);
334                         for (end = start; end < chain->n_rules; end++) {
335                                 rule = chain->map[end];
336                                 if (num > 0 && rule->rulenum != num)
337                                         break;
338                                 if (!keep_rule(rule, cmd, new_set, num))
339                                         n++;
340                         }
341                 }
342
343                 if (n == 0) {
344                         /* A flush request (arg == 0 or cmd == 1) on empty
345                          * ruleset returns with no error. On the contrary,
346                          * if there is no match on a specific request,
347                          * we return EINVAL.
348                          */
349                         if (arg != 0 && cmd != 1)
350                                 error = EINVAL;
351                         break;
352                 }
353
354                 /* We have something to delete. Allocate the new map */
355                 map = get_map(chain, -n, 1 /* locked */);
356                 if (map == NULL) {
357                         error = EINVAL;
358                         break;
359                 }
360
361                 /* 1. bcopy the initial part of the map */
362                 if (start > 0)
363                         bcopy(chain->map, map, start * sizeof(struct ip_fw *));
364                 /* 2. copy active rules between start and end */
365                 for (i = ofs = start; i < end; i++) {
366                         rule = chain->map[i];
367                         if (keep_rule(rule, cmd, new_set, num))
368                                 map[ofs++] = rule;
369                 }
370                 /* 3. copy the final part of the map */
371                 bcopy(chain->map + end, map + ofs,
372                         (chain->n_rules - end) * sizeof(struct ip_fw *));
373                 /* 4. swap the maps (under BH_LOCK) */
374                 map = swap_map(chain, map, chain->n_rules - n);
375                 /* 5. now remove the rules deleted from the old map */
376                 for (i = start; i < end; i++) {
377                         int l;
378                         rule = map[i];
379                         if (keep_rule(rule, cmd, new_set, num))
380                                 continue;
381                         l = RULESIZE(rule);
382                         chain->static_len -= l;
383                         ipfw_expire_dyn_rules(chain, rule, RESVD_SET);
384                         rule->x_next = chain->reap;
385                         chain->reap = rule;
386                 }
387                 break;
388
389         /*
390          * In the next 3 cases the loop stops at (n_rules - 1)
391          * because the default rule is never eligible..
392          */
393
394         case 2: /* move rules with given RULE number to new set */
395                 for (i = 0; i < chain->n_rules - 1; i++) {
396                         rule = chain->map[i];
397                         if (rule->rulenum == num)
398                                 rule->set = new_set;
399                 }
400                 break;
401
402         case 3: /* move rules with given SET number to new set */
403                 for (i = 0; i < chain->n_rules - 1; i++) {
404                         rule = chain->map[i];
405                         if (rule->set == num)
406                                 rule->set = new_set;
407                 }
408                 break;
409
410         case 4: /* swap two sets */
411                 for (i = 0; i < chain->n_rules - 1; i++) {
412                         rule = chain->map[i];
413                         if (rule->set == num)
414                                 rule->set = new_set;
415                         else if (rule->set == new_set)
416                                 rule->set = num;
417                 }
418                 break;
419         }
420
421         rule = chain->reap;
422         chain->reap = NULL;
423         IPFW_UH_WUNLOCK(chain);
424         ipfw_reap_rules(rule);
425         if (map)
426                 free(map, M_IPFW);
427         return error;
428 }
429
430 /*
431  * Clear counters for a specific rule.
432  * Normally run under IPFW_UH_RLOCK, but these are idempotent ops
433  * so we only care that rules do not disappear.
434  */
435 static void
436 clear_counters(struct ip_fw *rule, int log_only)
437 {
438         ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
439
440         if (log_only == 0)
441                 IPFW_ZERO_RULE_COUNTER(rule);
442         if (l->o.opcode == O_LOG)
443                 l->log_left = l->max_log;
444 }
445
446 /**
447  * Reset some or all counters on firewall rules.
448  * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
449  * the next 8 bits are the set number, the top 8 bits are the command:
450  *      0       work with rules from all set's;
451  *      1       work with rules only from specified set.
452  * Specified rule number is zero if we want to clear all entries.
453  * log_only is 1 if we only want to reset logs, zero otherwise.
454  */
455 static int
456 zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
457 {
458         struct ip_fw *rule;
459         char *msg;
460         int i;
461
462         uint16_t rulenum = arg & 0xffff;
463         uint8_t set = (arg >> 16) & 0xff;
464         uint8_t cmd = (arg >> 24) & 0xff;
465
466         if (cmd > 1)
467                 return (EINVAL);
468         if (cmd == 1 && set > RESVD_SET)
469                 return (EINVAL);
470
471         IPFW_UH_RLOCK(chain);
472         if (rulenum == 0) {
473                 V_norule_counter = 0;
474                 for (i = 0; i < chain->n_rules; i++) {
475                         rule = chain->map[i];
476                         /* Skip rules not in our set. */
477                         if (cmd == 1 && rule->set != set)
478                                 continue;
479                         clear_counters(rule, log_only);
480                 }
481                 msg = log_only ? "All logging counts reset" :
482                     "Accounting cleared";
483         } else {
484                 int cleared = 0;
485                 for (i = 0; i < chain->n_rules; i++) {
486                         rule = chain->map[i];
487                         if (rule->rulenum == rulenum) {
488                                 if (cmd == 0 || rule->set == set)
489                                         clear_counters(rule, log_only);
490                                 cleared = 1;
491                         }
492                         if (rule->rulenum > rulenum)
493                                 break;
494                 }
495                 if (!cleared) { /* we did not find any matching rules */
496                         IPFW_UH_RUNLOCK(chain);
497                         return (EINVAL);
498                 }
499                 msg = log_only ? "logging count reset" : "cleared";
500         }
501         IPFW_UH_RUNLOCK(chain);
502
503         if (V_fw_verbose) {
504                 int lev = LOG_SECURITY | LOG_NOTICE;
505
506                 if (rulenum)
507                         log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
508                 else
509                         log(lev, "ipfw: %s.\n", msg);
510         }
511         return (0);
512 }
513
514 /*
515  * Check validity of the structure before insert.
516  * Rules are simple, so this mostly need to check rule sizes.
517  */
518 static int
519 check_ipfw_struct(struct ip_fw *rule, int size)
520 {
521         int l, cmdlen = 0;
522         int have_action=0;
523         ipfw_insn *cmd;
524
525         if (size < sizeof(*rule)) {
526                 printf("ipfw: rule too short\n");
527                 return (EINVAL);
528         }
529         /* first, check for valid size */
530         l = RULESIZE(rule);
531         if (l != size) {
532                 printf("ipfw: size mismatch (have %d want %d)\n", size, l);
533                 return (EINVAL);
534         }
535         if (rule->act_ofs >= rule->cmd_len) {
536                 printf("ipfw: bogus action offset (%u > %u)\n",
537                     rule->act_ofs, rule->cmd_len - 1);
538                 return (EINVAL);
539         }
540         /*
541          * Now go for the individual checks. Very simple ones, basically only
542          * instruction sizes.
543          */
544         for (l = rule->cmd_len, cmd = rule->cmd ;
545                         l > 0 ; l -= cmdlen, cmd += cmdlen) {
546                 cmdlen = F_LEN(cmd);
547                 if (cmdlen > l) {
548                         printf("ipfw: opcode %d size truncated\n",
549                             cmd->opcode);
550                         return EINVAL;
551                 }
552                 switch (cmd->opcode) {
553                 case O_PROBE_STATE:
554                 case O_KEEP_STATE:
555                 case O_PROTO:
556                 case O_IP_SRC_ME:
557                 case O_IP_DST_ME:
558                 case O_LAYER2:
559                 case O_IN:
560                 case O_FRAG:
561                 case O_DIVERTED:
562                 case O_IPOPT:
563                 case O_IPTOS:
564                 case O_IPPRECEDENCE:
565                 case O_IPVER:
566                 case O_SOCKARG:
567                 case O_TCPFLAGS:
568                 case O_TCPOPTS:
569                 case O_ESTAB:
570                 case O_VERREVPATH:
571                 case O_VERSRCREACH:
572                 case O_ANTISPOOF:
573                 case O_IPSEC:
574 #ifdef INET6
575                 case O_IP6_SRC_ME:
576                 case O_IP6_DST_ME:
577                 case O_EXT_HDR:
578                 case O_IP6:
579 #endif
580                 case O_IP4:
581                 case O_TAG:
582                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
583                                 goto bad_size;
584                         break;
585
586                 case O_FIB:
587                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
588                                 goto bad_size;
589                         if (cmd->arg1 >= rt_numfibs) {
590                                 printf("ipfw: invalid fib number %d\n",
591                                         cmd->arg1);
592                                 return EINVAL;
593                         }
594                         break;
595
596                 case O_SETFIB:
597                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
598                                 goto bad_size;
599                         if ((cmd->arg1 != IP_FW_TABLEARG) &&
600                             (cmd->arg1 >= rt_numfibs)) {
601                                 printf("ipfw: invalid fib number %d\n",
602                                         cmd->arg1);
603                                 return EINVAL;
604                         }
605                         goto check_action;
606
607                 case O_UID:
608                 case O_GID:
609                 case O_JAIL:
610                 case O_IP_SRC:
611                 case O_IP_DST:
612                 case O_TCPSEQ:
613                 case O_TCPACK:
614                 case O_PROB:
615                 case O_ICMPTYPE:
616                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
617                                 goto bad_size;
618                         break;
619
620                 case O_LIMIT:
621                         if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
622                                 goto bad_size;
623                         break;
624
625                 case O_LOG:
626                         if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
627                                 goto bad_size;
628
629                         ((ipfw_insn_log *)cmd)->log_left =
630                             ((ipfw_insn_log *)cmd)->max_log;
631
632                         break;
633
634                 case O_IP_SRC_MASK:
635                 case O_IP_DST_MASK:
636                         /* only odd command lengths */
637                         if ( !(cmdlen & 1) || cmdlen > 31)
638                                 goto bad_size;
639                         break;
640
641                 case O_IP_SRC_SET:
642                 case O_IP_DST_SET:
643                         if (cmd->arg1 == 0 || cmd->arg1 > 256) {
644                                 printf("ipfw: invalid set size %d\n",
645                                         cmd->arg1);
646                                 return EINVAL;
647                         }
648                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
649                             (cmd->arg1+31)/32 )
650                                 goto bad_size;
651                         break;
652
653                 case O_IP_SRC_LOOKUP:
654                 case O_IP_DST_LOOKUP:
655                         if (cmd->arg1 >= IPFW_TABLES_MAX) {
656                                 printf("ipfw: invalid table number %d\n",
657                                     cmd->arg1);
658                                 return (EINVAL);
659                         }
660                         if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
661                             cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1 &&
662                             cmdlen != F_INSN_SIZE(ipfw_insn_u32))
663                                 goto bad_size;
664                         break;
665                 case O_MACADDR2:
666                         if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
667                                 goto bad_size;
668                         break;
669
670                 case O_NOP:
671                 case O_IPID:
672                 case O_IPTTL:
673                 case O_IPLEN:
674                 case O_DSCP:
675                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) + 1)
676                                 goto bad_size;
677                         break;
678                 case O_TCPDATALEN:
679                 case O_TCPWIN:
680                 case O_TAGGED:
681                         if (cmdlen < 1 || cmdlen > 31)
682                                 goto bad_size;
683                         break;
684
685                 case O_MAC_TYPE:
686                 case O_IP_SRCPORT:
687                 case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
688                         if (cmdlen < 2 || cmdlen > 31)
689                                 goto bad_size;
690                         break;
691
692                 case O_RECV:
693                 case O_XMIT:
694                 case O_VIA:
695                         if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
696                                 goto bad_size;
697                         break;
698
699                 case O_ALTQ:
700                         if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
701                                 goto bad_size;
702                         break;
703
704                 case O_PIPE:
705                 case O_QUEUE:
706                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
707                                 goto bad_size;
708                         goto check_action;
709
710                 case O_FORWARD_IP:
711                         if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
712                                 goto bad_size;
713                         goto check_action;
714 #ifdef INET6
715                 case O_FORWARD_IP6:
716                         if (cmdlen != F_INSN_SIZE(ipfw_insn_sa6))
717                                 goto bad_size;
718                         goto check_action;
719 #endif /* INET6 */
720
721                 case O_DIVERT:
722                 case O_TEE:
723                         if (ip_divert_ptr == NULL)
724                                 return EINVAL;
725                         else
726                                 goto check_size;
727                 case O_NETGRAPH:
728                 case O_NGTEE:
729                         if (ng_ipfw_input_p == NULL)
730                                 return EINVAL;
731                         else
732                                 goto check_size;
733                 case O_NAT:
734                         if (!IPFW_NAT_LOADED)
735                                 return EINVAL;
736                         if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
737                                 goto bad_size;          
738                         goto check_action;
739                 case O_FORWARD_MAC: /* XXX not implemented yet */
740                 case O_CHECK_STATE:
741                 case O_COUNT:
742                 case O_ACCEPT:
743                 case O_DENY:
744                 case O_REJECT:
745                 case O_SETDSCP:
746 #ifdef INET6
747                 case O_UNREACH6:
748 #endif
749                 case O_SKIPTO:
750                 case O_REASS:
751                 case O_CALLRETURN:
752 check_size:
753                         if (cmdlen != F_INSN_SIZE(ipfw_insn))
754                                 goto bad_size;
755 check_action:
756                         if (have_action) {
757                                 printf("ipfw: opcode %d, multiple actions"
758                                         " not allowed\n",
759                                         cmd->opcode);
760                                 return EINVAL;
761                         }
762                         have_action = 1;
763                         if (l != cmdlen) {
764                                 printf("ipfw: opcode %d, action must be"
765                                         " last opcode\n",
766                                         cmd->opcode);
767                                 return EINVAL;
768                         }
769                         break;
770 #ifdef INET6
771                 case O_IP6_SRC:
772                 case O_IP6_DST:
773                         if (cmdlen != F_INSN_SIZE(struct in6_addr) +
774                             F_INSN_SIZE(ipfw_insn))
775                                 goto bad_size;
776                         break;
777
778                 case O_FLOW6ID:
779                         if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
780                             ((ipfw_insn_u32 *)cmd)->o.arg1)
781                                 goto bad_size;
782                         break;
783
784                 case O_IP6_SRC_MASK:
785                 case O_IP6_DST_MASK:
786                         if ( !(cmdlen & 1) || cmdlen > 127)
787                                 goto bad_size;
788                         break;
789                 case O_ICMP6TYPE:
790                         if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
791                                 goto bad_size;
792                         break;
793 #endif
794
795                 default:
796                         switch (cmd->opcode) {
797 #ifndef INET6
798                         case O_IP6_SRC_ME:
799                         case O_IP6_DST_ME:
800                         case O_EXT_HDR:
801                         case O_IP6:
802                         case O_UNREACH6:
803                         case O_IP6_SRC:
804                         case O_IP6_DST:
805                         case O_FLOW6ID:
806                         case O_IP6_SRC_MASK:
807                         case O_IP6_DST_MASK:
808                         case O_ICMP6TYPE:
809                                 printf("ipfw: no IPv6 support in kernel\n");
810                                 return EPROTONOSUPPORT;
811 #endif
812                         default:
813                                 printf("ipfw: opcode %d, unknown opcode\n",
814                                         cmd->opcode);
815                                 return EINVAL;
816                         }
817                 }
818         }
819         if (have_action == 0) {
820                 printf("ipfw: missing action\n");
821                 return EINVAL;
822         }
823         return 0;
824
825 bad_size:
826         printf("ipfw: opcode %d size %d wrong\n",
827                 cmd->opcode, cmdlen);
828         return EINVAL;
829 }
830
831
832 /*
833  * Translation of requests for compatibility with FreeBSD 7.2/8.
834  * a static variable tells us if we have an old client from userland,
835  * and if necessary we translate requests and responses between the
836  * two formats.
837  */
838 static int is7 = 0;
839
840 struct ip_fw7 {
841         struct ip_fw7   *next;          /* linked list of rules     */
842         struct ip_fw7   *next_rule;     /* ptr to next [skipto] rule    */
843         /* 'next_rule' is used to pass up 'set_disable' status      */
844
845         uint16_t        act_ofs;        /* offset of action in 32-bit units */
846         uint16_t        cmd_len;        /* # of 32-bit words in cmd */
847         uint16_t        rulenum;        /* rule number          */
848         uint8_t         set;            /* rule set (0..31)     */
849         // #define RESVD_SET   31  /* set for default and persistent rules */
850         uint8_t         _pad;           /* padding          */
851         // uint32_t        id;             /* rule id, only in v.8 */
852         /* These fields are present in all rules.           */
853         uint64_t        pcnt;           /* Packet counter       */
854         uint64_t        bcnt;           /* Byte counter         */
855         uint32_t        timestamp;      /* tv_sec of last match     */
856
857         ipfw_insn       cmd[1];         /* storage for commands     */
858 };
859
860         int convert_rule_to_7(struct ip_fw *rule);
861 int convert_rule_to_8(struct ip_fw *rule);
862
863 #ifndef RULESIZE7
864 #define RULESIZE7(rule)  (sizeof(struct ip_fw7) + \
865         ((struct ip_fw7 *)(rule))->cmd_len * 4 - 4)
866 #endif
867
868
869 /*
870  * Copy the static and dynamic rules to the supplied buffer
871  * and return the amount of space actually used.
872  * Must be run under IPFW_UH_RLOCK
873  */
874 static size_t
875 ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
876 {
877         char *bp = buf;
878         char *ep = bp + space;
879         struct ip_fw *rule, *dst;
880         int l, i;
881         time_t  boot_seconds;
882
883         boot_seconds = boottime.tv_sec;
884         for (i = 0; i < chain->n_rules; i++) {
885                 rule = chain->map[i];
886
887                 if (is7) {
888                     /* Convert rule to FreeBSd 7.2 format */
889                     l = RULESIZE7(rule);
890                     if (bp + l + sizeof(uint32_t) <= ep) {
891                         int error;
892                         bcopy(rule, bp, l + sizeof(uint32_t));
893                         error = convert_rule_to_7((struct ip_fw *) bp);
894                         if (error)
895                                 return 0; /*XXX correct? */
896                         /*
897                          * XXX HACK. Store the disable mask in the "next"
898                          * pointer in a wild attempt to keep the ABI the same.
899                          * Why do we do this on EVERY rule?
900                          */
901                         bcopy(&V_set_disable,
902                                 &(((struct ip_fw7 *)bp)->next_rule),
903                                 sizeof(V_set_disable));
904                         if (((struct ip_fw7 *)bp)->timestamp)
905                             ((struct ip_fw7 *)bp)->timestamp += boot_seconds;
906                         bp += l;
907                     }
908                     continue; /* go to next rule */
909                 }
910
911                 /* normal mode, don't touch rules */
912                 l = RULESIZE(rule);
913                 if (bp + l > ep) { /* should not happen */
914                         printf("overflow dumping static rules\n");
915                         break;
916                 }
917                 dst = (struct ip_fw *)bp;
918                 bcopy(rule, dst, l);
919                 /*
920                  * XXX HACK. Store the disable mask in the "next"
921                  * pointer in a wild attempt to keep the ABI the same.
922                  * Why do we do this on EVERY rule?
923                  */
924                 bcopy(&V_set_disable, &dst->next_rule, sizeof(V_set_disable));
925                 if (dst->timestamp)
926                         dst->timestamp += boot_seconds;
927                 bp += l;
928         }
929         ipfw_get_dynamic(chain, &bp, ep); /* protected by the dynamic lock */
930         return (bp - (char *)buf);
931 }
932
933
934 #define IP_FW3_OPLENGTH(x)      ((x)->sopt_valsize - sizeof(ip_fw3_opheader))
935 /**
936  * {set|get}sockopt parser.
937  */
938 int
939 ipfw_ctl(struct sockopt *sopt)
940 {
941 #define RULE_MAXSIZE    (256*sizeof(u_int32_t))
942         int error;
943         size_t size, len, valsize;
944         struct ip_fw *buf, *rule;
945         struct ip_fw_chain *chain;
946         u_int32_t rulenum[2];
947         uint32_t opt;
948         char xbuf[128];
949         ip_fw3_opheader *op3 = NULL;
950
951         error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
952         if (error)
953                 return (error);
954
955         /*
956          * Disallow modifications in really-really secure mode, but still allow
957          * the logging counters to be reset.
958          */
959         if (sopt->sopt_name == IP_FW_ADD ||
960             (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
961                 error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
962                 if (error)
963                         return (error);
964         }
965
966         chain = &V_layer3_chain;
967         error = 0;
968
969         /* Save original valsize before it is altered via sooptcopyin() */
970         valsize = sopt->sopt_valsize;
971         if ((opt = sopt->sopt_name) == IP_FW3) {
972                 /* 
973                  * Copy not less than sizeof(ip_fw3_opheader).
974                  * We hope any IP_FW3 command will fit into 128-byte buffer.
975                  */
976                 if ((error = sooptcopyin(sopt, xbuf, sizeof(xbuf),
977                         sizeof(ip_fw3_opheader))) != 0)
978                         return (error);
979                 op3 = (ip_fw3_opheader *)xbuf;
980                 opt = op3->opcode;
981         }
982
983         switch (opt) {
984         case IP_FW_GET:
985                 /*
986                  * pass up a copy of the current rules. Static rules
987                  * come first (the last of which has number IPFW_DEFAULT_RULE),
988                  * followed by a possibly empty list of dynamic rule.
989                  * The last dynamic rule has NULL in the "next" field.
990                  *
991                  * Note that the calculated size is used to bound the
992                  * amount of data returned to the user.  The rule set may
993                  * change between calculating the size and returning the
994                  * data in which case we'll just return what fits.
995                  */
996                 for (;;) {
997                         int len = 0, want;
998
999                         size = chain->static_len;
1000                         size += ipfw_dyn_len();
1001                         if (size >= sopt->sopt_valsize)
1002                                 break;
1003                         buf = malloc(size, M_TEMP, M_WAITOK);
1004                         IPFW_UH_RLOCK(chain);
1005                         /* check again how much space we need */
1006                         want = chain->static_len + ipfw_dyn_len();
1007                         if (size >= want)
1008                                 len = ipfw_getrules(chain, buf, size);
1009                         IPFW_UH_RUNLOCK(chain);
1010                         if (size >= want)
1011                                 error = sooptcopyout(sopt, buf, len);
1012                         free(buf, M_TEMP);
1013                         if (size >= want)
1014                                 break;
1015                 }
1016                 break;
1017
1018         case IP_FW_FLUSH:
1019                 /* locking is done within del_entry() */
1020                 error = del_entry(chain, 0); /* special case, rule=0, cmd=0 means all */
1021                 break;
1022
1023         case IP_FW_ADD:
1024                 rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
1025                 error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
1026                         sizeof(struct ip_fw7) );
1027
1028                 /*
1029                  * If the size of commands equals RULESIZE7 then we assume
1030                  * a FreeBSD7.2 binary is talking to us (set is7=1).
1031                  * is7 is persistent so the next 'ipfw list' command
1032                  * will use this format.
1033                  * NOTE: If wrong version is guessed (this can happen if
1034                  *       the first ipfw command is 'ipfw [pipe] list')
1035                  *       the ipfw binary may crash or loop infinitly...
1036                  */
1037                 if (sopt->sopt_valsize == RULESIZE7(rule)) {
1038                     is7 = 1;
1039                     error = convert_rule_to_8(rule);
1040                     if (error)
1041                         return error;
1042                     if (error == 0)
1043                         error = check_ipfw_struct(rule, RULESIZE(rule));
1044                 } else {
1045                     is7 = 0;
1046                 if (error == 0)
1047                         error = check_ipfw_struct(rule, sopt->sopt_valsize);
1048                 }
1049                 if (error == 0) {
1050                         /* locking is done within ipfw_add_rule() */
1051                         error = ipfw_add_rule(chain, rule);
1052                         size = RULESIZE(rule);
1053                         if (!error && sopt->sopt_dir == SOPT_GET) {
1054                                 if (is7) {
1055                                         error = convert_rule_to_7(rule);
1056                                         size = RULESIZE7(rule);
1057                                         if (error)
1058                                                 return error;
1059                                 }
1060                                 error = sooptcopyout(sopt, rule, size);
1061                 }
1062                 }
1063                 free(rule, M_TEMP);
1064                 break;
1065
1066         case IP_FW_DEL:
1067                 /*
1068                  * IP_FW_DEL is used for deleting single rules or sets,
1069                  * and (ab)used to atomically manipulate sets. Argument size
1070                  * is used to distinguish between the two:
1071                  *    sizeof(u_int32_t)
1072                  *      delete single rule or set of rules,
1073                  *      or reassign rules (or sets) to a different set.
1074                  *    2*sizeof(u_int32_t)
1075                  *      atomic disable/enable sets.
1076                  *      first u_int32_t contains sets to be disabled,
1077                  *      second u_int32_t contains sets to be enabled.
1078                  */
1079                 error = sooptcopyin(sopt, rulenum,
1080                         2*sizeof(u_int32_t), sizeof(u_int32_t));
1081                 if (error)
1082                         break;
1083                 size = sopt->sopt_valsize;
1084                 if (size == sizeof(u_int32_t) && rulenum[0] != 0) {
1085                         /* delete or reassign, locking done in del_entry() */
1086                         error = del_entry(chain, rulenum[0]);
1087                 } else if (size == 2*sizeof(u_int32_t)) { /* set enable/disable */
1088                         IPFW_UH_WLOCK(chain);
1089                         V_set_disable =
1090                             (V_set_disable | rulenum[0]) & ~rulenum[1] &
1091                             ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
1092                         IPFW_UH_WUNLOCK(chain);
1093                 } else
1094                         error = EINVAL;
1095                 break;
1096
1097         case IP_FW_ZERO:
1098         case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
1099                 rulenum[0] = 0;
1100                 if (sopt->sopt_val != 0) {
1101                     error = sooptcopyin(sopt, rulenum,
1102                             sizeof(u_int32_t), sizeof(u_int32_t));
1103                     if (error)
1104                         break;
1105                 }
1106                 error = zero_entry(chain, rulenum[0],
1107                         sopt->sopt_name == IP_FW_RESETLOG);
1108                 break;
1109
1110         /*--- TABLE manipulations are protected by the IPFW_LOCK ---*/
1111         case IP_FW_TABLE_ADD:
1112                 {
1113                         ipfw_table_entry ent;
1114
1115                         error = sooptcopyin(sopt, &ent,
1116                             sizeof(ent), sizeof(ent));
1117                         if (error)
1118                                 break;
1119                         error = ipfw_add_table_entry(chain, ent.tbl,
1120                             &ent.addr, sizeof(ent.addr), ent.masklen, 
1121                             IPFW_TABLE_CIDR, ent.value);
1122                 }
1123                 break;
1124
1125         case IP_FW_TABLE_DEL:
1126                 {
1127                         ipfw_table_entry ent;
1128
1129                         error = sooptcopyin(sopt, &ent,
1130                             sizeof(ent), sizeof(ent));
1131                         if (error)
1132                                 break;
1133                         error = ipfw_del_table_entry(chain, ent.tbl,
1134                             &ent.addr, sizeof(ent.addr), ent.masklen, IPFW_TABLE_CIDR);
1135                 }
1136                 break;
1137
1138         case IP_FW_TABLE_XADD: /* IP_FW3 */
1139         case IP_FW_TABLE_XDEL: /* IP_FW3 */
1140                 {
1141                         ipfw_table_xentry *xent = (ipfw_table_xentry *)(op3 + 1);
1142
1143                         /* Check minimum header size */
1144                         if (IP_FW3_OPLENGTH(sopt) < offsetof(ipfw_table_xentry, k)) {
1145                                 error = EINVAL;
1146                                 break;
1147                         }
1148
1149                         /* Check if len field is valid */
1150                         if (xent->len > sizeof(ipfw_table_xentry)) {
1151                                 error = EINVAL;
1152                                 break;
1153                         }
1154                         
1155                         len = xent->len - offsetof(ipfw_table_xentry, k);
1156
1157                         error = (opt == IP_FW_TABLE_XADD) ?
1158                                 ipfw_add_table_entry(chain, xent->tbl, &xent->k, 
1159                                         len, xent->masklen, xent->type, xent->value) :
1160                                 ipfw_del_table_entry(chain, xent->tbl, &xent->k,
1161                                         len, xent->masklen, xent->type);
1162                 }
1163                 break;
1164
1165         case IP_FW_TABLE_FLUSH:
1166                 {
1167                         u_int16_t tbl;
1168
1169                         error = sooptcopyin(sopt, &tbl,
1170                             sizeof(tbl), sizeof(tbl));
1171                         if (error)
1172                                 break;
1173                         error = ipfw_flush_table(chain, tbl);
1174                 }
1175                 break;
1176
1177         case IP_FW_TABLE_GETSIZE:
1178                 {
1179                         u_int32_t tbl, cnt;
1180
1181                         if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
1182                             sizeof(tbl))))
1183                                 break;
1184                         IPFW_RLOCK(chain);
1185                         error = ipfw_count_table(chain, tbl, &cnt);
1186                         IPFW_RUNLOCK(chain);
1187                         if (error)
1188                                 break;
1189                         error = sooptcopyout(sopt, &cnt, sizeof(cnt));
1190                 }
1191                 break;
1192
1193         case IP_FW_TABLE_LIST:
1194                 {
1195                         ipfw_table *tbl;
1196
1197                         if (sopt->sopt_valsize < sizeof(*tbl)) {
1198                                 error = EINVAL;
1199                                 break;
1200                         }
1201                         size = sopt->sopt_valsize;
1202                         tbl = malloc(size, M_TEMP, M_WAITOK);
1203                         error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
1204                         if (error) {
1205                                 free(tbl, M_TEMP);
1206                                 break;
1207                         }
1208                         tbl->size = (size - sizeof(*tbl)) /
1209                             sizeof(ipfw_table_entry);
1210                         IPFW_RLOCK(chain);
1211                         error = ipfw_dump_table(chain, tbl);
1212                         IPFW_RUNLOCK(chain);
1213                         if (error) {
1214                                 free(tbl, M_TEMP);
1215                                 break;
1216                         }
1217                         error = sooptcopyout(sopt, tbl, size);
1218                         free(tbl, M_TEMP);
1219                 }
1220                 break;
1221
1222         case IP_FW_TABLE_XGETSIZE: /* IP_FW3 */
1223                 {
1224                         uint32_t *tbl;
1225
1226                         if (IP_FW3_OPLENGTH(sopt) < sizeof(uint32_t)) {
1227                                 error = EINVAL;
1228                                 break;
1229                         }
1230
1231                         tbl = (uint32_t *)(op3 + 1);
1232
1233                         IPFW_RLOCK(chain);
1234                         error = ipfw_count_xtable(chain, *tbl, tbl);
1235                         IPFW_RUNLOCK(chain);
1236                         if (error)
1237                                 break;
1238                         error = sooptcopyout(sopt, op3, sopt->sopt_valsize);
1239                 }
1240                 break;
1241
1242         case IP_FW_TABLE_XLIST: /* IP_FW3 */
1243                 {
1244                         ipfw_xtable *tbl;
1245
1246                         if ((size = valsize) < sizeof(ipfw_xtable)) {
1247                                 error = EINVAL;
1248                                 break;
1249                         }
1250
1251                         tbl = malloc(size, M_TEMP, M_ZERO | M_WAITOK);
1252                         memcpy(tbl, op3, sizeof(ipfw_xtable));
1253
1254                         /* Get maximum number of entries we can store */
1255                         tbl->size = (size - sizeof(ipfw_xtable)) /
1256                             sizeof(ipfw_table_xentry);
1257                         IPFW_RLOCK(chain);
1258                         error = ipfw_dump_xtable(chain, tbl);
1259                         IPFW_RUNLOCK(chain);
1260                         if (error) {
1261                                 free(tbl, M_TEMP);
1262                                 break;
1263                         }
1264
1265                         /* Revert size field back to bytes */
1266                         tbl->size = tbl->size * sizeof(ipfw_table_xentry) +
1267                                 sizeof(ipfw_table);
1268                         /* 
1269                          * Since we call sooptcopyin() with small buffer, sopt_valsize is
1270                          * decreased to reflect supplied buffer size. Set it back to original value
1271                          */
1272                         sopt->sopt_valsize = valsize;
1273                         error = sooptcopyout(sopt, tbl, size);
1274                         free(tbl, M_TEMP);
1275                 }
1276                 break;
1277
1278         /*--- NAT operations are protected by the IPFW_LOCK ---*/
1279         case IP_FW_NAT_CFG:
1280                 if (IPFW_NAT_LOADED)
1281                         error = ipfw_nat_cfg_ptr(sopt);
1282                 else {
1283                         printf("IP_FW_NAT_CFG: %s\n",
1284                             "ipfw_nat not present, please load it");
1285                         error = EINVAL;
1286                 }
1287                 break;
1288
1289         case IP_FW_NAT_DEL:
1290                 if (IPFW_NAT_LOADED)
1291                         error = ipfw_nat_del_ptr(sopt);
1292                 else {
1293                         printf("IP_FW_NAT_DEL: %s\n",
1294                             "ipfw_nat not present, please load it");
1295                         error = EINVAL;
1296                 }
1297                 break;
1298
1299         case IP_FW_NAT_GET_CONFIG:
1300                 if (IPFW_NAT_LOADED)
1301                         error = ipfw_nat_get_cfg_ptr(sopt);
1302                 else {
1303                         printf("IP_FW_NAT_GET_CFG: %s\n",
1304                             "ipfw_nat not present, please load it");
1305                         error = EINVAL;
1306                 }
1307                 break;
1308
1309         case IP_FW_NAT_GET_LOG:
1310                 if (IPFW_NAT_LOADED)
1311                         error = ipfw_nat_get_log_ptr(sopt);
1312                 else {
1313                         printf("IP_FW_NAT_GET_LOG: %s\n",
1314                             "ipfw_nat not present, please load it");
1315                         error = EINVAL;
1316                 }
1317                 break;
1318
1319         default:
1320                 printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
1321                 error = EINVAL;
1322         }
1323
1324         return (error);
1325 #undef RULE_MAXSIZE
1326 }
1327
1328
1329 #define RULE_MAXSIZE    (256*sizeof(u_int32_t))
1330
1331 /* Functions to convert rules 7.2 <==> 8.0 */
1332 int
1333 convert_rule_to_7(struct ip_fw *rule)
1334 {
1335         /* Used to modify original rule */
1336         struct ip_fw7 *rule7 = (struct ip_fw7 *)rule;
1337         /* copy of original rule, version 8 */
1338         struct ip_fw *tmp;
1339
1340         /* Used to copy commands */
1341         ipfw_insn *ccmd, *dst;
1342         int ll = 0, ccmdlen = 0;
1343
1344         tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
1345         if (tmp == NULL) {
1346                 return 1; //XXX error
1347         }
1348         bcopy(rule, tmp, RULE_MAXSIZE);
1349
1350         /* Copy fields */
1351         rule7->_pad = tmp->_pad;
1352         rule7->set = tmp->set;
1353         rule7->rulenum = tmp->rulenum;
1354         rule7->cmd_len = tmp->cmd_len;
1355         rule7->act_ofs = tmp->act_ofs;
1356         rule7->next_rule = (struct ip_fw7 *)tmp->next_rule;
1357         rule7->next = (struct ip_fw7 *)tmp->x_next;
1358         rule7->cmd_len = tmp->cmd_len;
1359         rule7->pcnt = tmp->pcnt;
1360         rule7->bcnt = tmp->bcnt;
1361         rule7->timestamp = tmp->timestamp;
1362
1363         /* Copy commands */
1364         for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule7->cmd ;
1365                         ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
1366                 ccmdlen = F_LEN(ccmd);
1367
1368                 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
1369
1370                 if (dst->opcode > O_NAT)
1371                         /* O_REASS doesn't exists in 7.2 version, so
1372                          * decrement opcode if it is after O_REASS
1373                          */
1374                         dst->opcode--;
1375
1376                 if (ccmdlen > ll) {
1377                         printf("ipfw: opcode %d size truncated\n",
1378                                 ccmd->opcode);
1379                         return EINVAL;
1380                 }
1381         }
1382         free(tmp, M_TEMP);
1383
1384         return 0;
1385 }
1386
1387 int
1388 convert_rule_to_8(struct ip_fw *rule)
1389 {
1390         /* Used to modify original rule */
1391         struct ip_fw7 *rule7 = (struct ip_fw7 *) rule;
1392
1393         /* Used to copy commands */
1394         ipfw_insn *ccmd, *dst;
1395         int ll = 0, ccmdlen = 0;
1396
1397         /* Copy of original rule */
1398         struct ip_fw7 *tmp = malloc(RULE_MAXSIZE, M_TEMP, M_NOWAIT | M_ZERO);
1399         if (tmp == NULL) {
1400                 return 1; //XXX error
1401         }
1402
1403         bcopy(rule7, tmp, RULE_MAXSIZE);
1404
1405         for (ll = tmp->cmd_len, ccmd = tmp->cmd, dst = rule->cmd ;
1406                         ll > 0 ; ll -= ccmdlen, ccmd += ccmdlen, dst += ccmdlen) {
1407                 ccmdlen = F_LEN(ccmd);
1408                 
1409                 bcopy(ccmd, dst, F_LEN(ccmd)*sizeof(uint32_t));
1410
1411                 if (dst->opcode > O_NAT)
1412                         /* O_REASS doesn't exists in 7.2 version, so
1413                          * increment opcode if it is after O_REASS
1414                          */
1415                         dst->opcode++;
1416
1417                 if (ccmdlen > ll) {
1418                         printf("ipfw: opcode %d size truncated\n",
1419                             ccmd->opcode);
1420                         return EINVAL;
1421                 }
1422         }
1423
1424         rule->_pad = tmp->_pad;
1425         rule->set = tmp->set;
1426         rule->rulenum = tmp->rulenum;
1427         rule->cmd_len = tmp->cmd_len;
1428         rule->act_ofs = tmp->act_ofs;
1429         rule->next_rule = (struct ip_fw *)tmp->next_rule;
1430         rule->x_next = (struct ip_fw *)tmp->next;
1431         rule->cmd_len = tmp->cmd_len;
1432         rule->id = 0; /* XXX see if is ok = 0 */
1433         rule->pcnt = tmp->pcnt;
1434         rule->bcnt = tmp->bcnt;
1435         rule->timestamp = tmp->timestamp;
1436
1437         free (tmp, M_TEMP);
1438         return 0;
1439 }
1440
1441 /* end of file */