]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/ipfw/ipfw2.c
Replace "cidr" table type with "addr" type.
[FreeBSD/FreeBSD.git] / sbin / ipfw / ipfw2.c
1 /*
2  * Copyright (c) 2002-2003 Luigi Rizzo
3  * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4  * Copyright (c) 1994 Ugen J.S.Antsilevich
5  *
6  * Idea and grammar partially left from:
7  * Copyright (c) 1993 Daniel Boulet
8  *
9  * Redistribution and use in source forms, with and without modification,
10  * are permitted provided that this entire comment appears intact.
11  *
12  * Redistribution in binary form may occur without any restrictions.
13  * Obviously, it would be nice if you gave credit where credit is due
14  * but requiring it would be too onerous.
15  *
16  * This software is provided ``AS IS'' without any warranties of any kind.
17  *
18  * NEW command line interface for IP firewall facility
19  *
20  * $FreeBSD$
21  */
22
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
28
29 #include "ipfw2.h"
30
31 #include <ctype.h>
32 #include <err.h>
33 #include <errno.h>
34 #include <grp.h>
35 #include <netdb.h>
36 #include <pwd.h>
37 #include <stdio.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sysexits.h>
42 #include <time.h>       /* ctime */
43 #include <timeconv.h>   /* _long_to_time */
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <stddef.h>     /* offsetof */
47
48 #include <net/ethernet.h>
49 #include <net/if.h>             /* only IFNAMSIZ */
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>   /* only n_short, n_long */
52 #include <netinet/ip.h>
53 #include <netinet/ip_icmp.h>
54 #include <netinet/ip_fw.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
57
58 struct cmdline_opts co; /* global options */
59
60 struct format_opts {
61         int bcwidth;
62         int pcwidth;
63         int show_counters;
64         uint32_t set_mask;      /* enabled sets mask */
65         uint32_t flags;         /* request flags */
66         uint32_t first;         /* first rule to request */
67         uint32_t last;          /* last rule to request */
68         uint32_t dcnt;          /* number of dynamic states */
69         ipfw_obj_ctlv *tstate;  /* table state data */
70 };
71
72 int resvd_set_number = RESVD_SET;
73
74 int ipfw_socket = -1;
75
76 #define CHECK_LENGTH(v, len) do {                               \
77         if ((v) < (len))                                        \
78                 errx(EX_DATAERR, "Rule too long");              \
79         } while (0)
80 /*
81  * Check if we have enough space in cmd buffer. Note that since
82  * first 8? u32 words are reserved by reserved header, full cmd
83  * buffer can't be used, so we need to protect from buffer overrun
84  * only. At the beginnig, cblen is less than actual buffer size by
85  * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
86  * for checking small instructions fitting in given range.
87  * We also (ab)use the fact that ipfw_insn is always the first field
88  * for any custom instruction.
89  */
90 #define CHECK_CMDLEN    CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
91
92 #define GET_UINT_ARG(arg, min, max, tok, s_x) do {                      \
93         if (!av[0])                                                     \
94                 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
95         if (_substrcmp(*av, "tablearg") == 0) {                         \
96                 arg = IP_FW_TARG;                                       \
97                 break;                                                  \
98         }                                                               \
99                                                                         \
100         {                                                               \
101         long _xval;                                                     \
102         char *end;                                                      \
103                                                                         \
104         _xval = strtol(*av, &end, 10);                                  \
105                                                                         \
106         if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
107                 errx(EX_DATAERR, "%s: invalid argument: %s",            \
108                     match_value(s_x, tok), *av);                        \
109                                                                         \
110         if (errno == ERANGE || _xval < min || _xval > max)              \
111                 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
112                     match_value(s_x, tok), min, max, *av);              \
113                                                                         \
114         if (_xval == IP_FW_TARG)                                        \
115                 errx(EX_DATAERR, "%s: illegal argument value: %s",      \
116                     match_value(s_x, tok), *av);                        \
117         arg = _xval;                                                    \
118         }                                                               \
119 } while (0)
120
121 static struct _s_x f_tcpflags[] = {
122         { "syn", TH_SYN },
123         { "fin", TH_FIN },
124         { "ack", TH_ACK },
125         { "psh", TH_PUSH },
126         { "rst", TH_RST },
127         { "urg", TH_URG },
128         { "tcp flag", 0 },
129         { NULL, 0 }
130 };
131
132 static struct _s_x f_tcpopts[] = {
133         { "mss",        IP_FW_TCPOPT_MSS },
134         { "maxseg",     IP_FW_TCPOPT_MSS },
135         { "window",     IP_FW_TCPOPT_WINDOW },
136         { "sack",       IP_FW_TCPOPT_SACK },
137         { "ts",         IP_FW_TCPOPT_TS },
138         { "timestamp",  IP_FW_TCPOPT_TS },
139         { "cc",         IP_FW_TCPOPT_CC },
140         { "tcp option", 0 },
141         { NULL, 0 }
142 };
143
144 /*
145  * IP options span the range 0 to 255 so we need to remap them
146  * (though in fact only the low 5 bits are significant).
147  */
148 static struct _s_x f_ipopts[] = {
149         { "ssrr",       IP_FW_IPOPT_SSRR},
150         { "lsrr",       IP_FW_IPOPT_LSRR},
151         { "rr",         IP_FW_IPOPT_RR},
152         { "ts",         IP_FW_IPOPT_TS},
153         { "ip option",  0 },
154         { NULL, 0 }
155 };
156
157 static struct _s_x f_iptos[] = {
158         { "lowdelay",   IPTOS_LOWDELAY},
159         { "throughput", IPTOS_THROUGHPUT},
160         { "reliability", IPTOS_RELIABILITY},
161         { "mincost",    IPTOS_MINCOST},
162         { "congestion", IPTOS_ECN_CE},
163         { "ecntransport", IPTOS_ECN_ECT0},
164         { "ip tos option", 0},
165         { NULL, 0 }
166 };
167
168 struct _s_x f_ipdscp[] = {
169         { "af11", IPTOS_DSCP_AF11 >> 2 },       /* 001010 */
170         { "af12", IPTOS_DSCP_AF12 >> 2 },       /* 001100 */
171         { "af13", IPTOS_DSCP_AF13 >> 2 },       /* 001110 */
172         { "af21", IPTOS_DSCP_AF21 >> 2 },       /* 010010 */
173         { "af22", IPTOS_DSCP_AF22 >> 2 },       /* 010100 */
174         { "af23", IPTOS_DSCP_AF23 >> 2 },       /* 010110 */
175         { "af31", IPTOS_DSCP_AF31 >> 2 },       /* 011010 */
176         { "af32", IPTOS_DSCP_AF32 >> 2 },       /* 011100 */
177         { "af33", IPTOS_DSCP_AF33 >> 2 },       /* 011110 */
178         { "af41", IPTOS_DSCP_AF41 >> 2 },       /* 100010 */
179         { "af42", IPTOS_DSCP_AF42 >> 2 },       /* 100100 */
180         { "af43", IPTOS_DSCP_AF43 >> 2 },       /* 100110 */
181         { "be", IPTOS_DSCP_CS0 >> 2 },  /* 000000 */
182         { "ef", IPTOS_DSCP_EF >> 2 },   /* 101110 */
183         { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
184         { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
185         { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
186         { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
187         { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
188         { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
189         { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
190         { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
191         { NULL, 0 }
192 };
193
194 static struct _s_x limit_masks[] = {
195         {"all",         DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
196         {"src-addr",    DYN_SRC_ADDR},
197         {"src-port",    DYN_SRC_PORT},
198         {"dst-addr",    DYN_DST_ADDR},
199         {"dst-port",    DYN_DST_PORT},
200         {NULL,          0}
201 };
202
203 /*
204  * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
205  * This is only used in this code.
206  */
207 #define IPPROTO_ETHERTYPE       0x1000
208 static struct _s_x ether_types[] = {
209     /*
210      * Note, we cannot use "-:&/" in the names because they are field
211      * separators in the type specifications. Also, we use s = NULL as
212      * end-delimiter, because a type of 0 can be legal.
213      */
214         { "ip",         0x0800 },
215         { "ipv4",       0x0800 },
216         { "ipv6",       0x86dd },
217         { "arp",        0x0806 },
218         { "rarp",       0x8035 },
219         { "vlan",       0x8100 },
220         { "loop",       0x9000 },
221         { "trail",      0x1000 },
222         { "at",         0x809b },
223         { "atalk",      0x809b },
224         { "aarp",       0x80f3 },
225         { "pppoe_disc", 0x8863 },
226         { "pppoe_sess", 0x8864 },
227         { "ipx_8022",   0x00E0 },
228         { "ipx_8023",   0x0000 },
229         { "ipx_ii",     0x8137 },
230         { "ipx_snap",   0x8137 },
231         { "ipx",        0x8137 },
232         { "ns",         0x0600 },
233         { NULL,         0 }
234 };
235
236
237 static struct _s_x rule_actions[] = {
238         { "accept",             TOK_ACCEPT },
239         { "pass",               TOK_ACCEPT },
240         { "allow",              TOK_ACCEPT },
241         { "permit",             TOK_ACCEPT },
242         { "count",              TOK_COUNT },
243         { "pipe",               TOK_PIPE },
244         { "queue",              TOK_QUEUE },
245         { "divert",             TOK_DIVERT },
246         { "tee",                TOK_TEE },
247         { "netgraph",           TOK_NETGRAPH },
248         { "ngtee",              TOK_NGTEE },
249         { "fwd",                TOK_FORWARD },
250         { "forward",            TOK_FORWARD },
251         { "skipto",             TOK_SKIPTO },
252         { "deny",               TOK_DENY },
253         { "drop",               TOK_DENY },
254         { "reject",             TOK_REJECT },
255         { "reset6",             TOK_RESET6 },
256         { "reset",              TOK_RESET },
257         { "unreach6",           TOK_UNREACH6 },
258         { "unreach",            TOK_UNREACH },
259         { "check-state",        TOK_CHECKSTATE },
260         { "//",                 TOK_COMMENT },
261         { "nat",                TOK_NAT },
262         { "reass",              TOK_REASS },
263         { "setfib",             TOK_SETFIB },
264         { "setdscp",            TOK_SETDSCP },
265         { "call",               TOK_CALL },
266         { "return",             TOK_RETURN },
267         { NULL, 0 }     /* terminator */
268 };
269
270 static struct _s_x rule_action_params[] = {
271         { "altq",               TOK_ALTQ },
272         { "log",                TOK_LOG },
273         { "tag",                TOK_TAG },
274         { "untag",              TOK_UNTAG },
275         { NULL, 0 }     /* terminator */
276 };
277
278 /*
279  * The 'lookup' instruction accepts one of the following arguments.
280  * -1 is a terminator for the list.
281  * Arguments are passed as v[1] in O_DST_LOOKUP options.
282  */
283 static int lookup_key[] = {
284         TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
285         TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
286
287 static struct _s_x rule_options[] = {
288         { "tagged",             TOK_TAGGED },
289         { "uid",                TOK_UID },
290         { "gid",                TOK_GID },
291         { "jail",               TOK_JAIL },
292         { "in",                 TOK_IN },
293         { "limit",              TOK_LIMIT },
294         { "keep-state",         TOK_KEEPSTATE },
295         { "bridged",            TOK_LAYER2 },
296         { "layer2",             TOK_LAYER2 },
297         { "out",                TOK_OUT },
298         { "diverted",           TOK_DIVERTED },
299         { "diverted-loopback",  TOK_DIVERTEDLOOPBACK },
300         { "diverted-output",    TOK_DIVERTEDOUTPUT },
301         { "xmit",               TOK_XMIT },
302         { "recv",               TOK_RECV },
303         { "via",                TOK_VIA },
304         { "fragment",           TOK_FRAG },
305         { "frag",               TOK_FRAG },
306         { "fib",                TOK_FIB },
307         { "ipoptions",          TOK_IPOPTS },
308         { "ipopts",             TOK_IPOPTS },
309         { "iplen",              TOK_IPLEN },
310         { "ipid",               TOK_IPID },
311         { "ipprecedence",       TOK_IPPRECEDENCE },
312         { "dscp",               TOK_DSCP },
313         { "iptos",              TOK_IPTOS },
314         { "ipttl",              TOK_IPTTL },
315         { "ipversion",          TOK_IPVER },
316         { "ipver",              TOK_IPVER },
317         { "estab",              TOK_ESTAB },
318         { "established",        TOK_ESTAB },
319         { "setup",              TOK_SETUP },
320         { "sockarg",            TOK_SOCKARG },
321         { "tcpdatalen",         TOK_TCPDATALEN },
322         { "tcpflags",           TOK_TCPFLAGS },
323         { "tcpflgs",            TOK_TCPFLAGS },
324         { "tcpoptions",         TOK_TCPOPTS },
325         { "tcpopts",            TOK_TCPOPTS },
326         { "tcpseq",             TOK_TCPSEQ },
327         { "tcpack",             TOK_TCPACK },
328         { "tcpwin",             TOK_TCPWIN },
329         { "icmptype",           TOK_ICMPTYPES },
330         { "icmptypes",          TOK_ICMPTYPES },
331         { "dst-ip",             TOK_DSTIP },
332         { "src-ip",             TOK_SRCIP },
333         { "dst-port",           TOK_DSTPORT },
334         { "src-port",           TOK_SRCPORT },
335         { "proto",              TOK_PROTO },
336         { "MAC",                TOK_MAC },
337         { "mac",                TOK_MAC },
338         { "mac-type",           TOK_MACTYPE },
339         { "verrevpath",         TOK_VERREVPATH },
340         { "versrcreach",        TOK_VERSRCREACH },
341         { "antispoof",          TOK_ANTISPOOF },
342         { "ipsec",              TOK_IPSEC },
343         { "icmp6type",          TOK_ICMP6TYPES },
344         { "icmp6types",         TOK_ICMP6TYPES },
345         { "ext6hdr",            TOK_EXT6HDR},
346         { "flow-id",            TOK_FLOWID},
347         { "ipv6",               TOK_IPV6},
348         { "ip6",                TOK_IPV6},
349         { "ipv4",               TOK_IPV4},
350         { "ip4",                TOK_IPV4},
351         { "dst-ipv6",           TOK_DSTIP6},
352         { "dst-ip6",            TOK_DSTIP6},
353         { "src-ipv6",           TOK_SRCIP6},
354         { "src-ip6",            TOK_SRCIP6},
355         { "lookup",             TOK_LOOKUP},
356         { "flow",               TOK_FLOW},
357         { "//",                 TOK_COMMENT },
358
359         { "not",                TOK_NOT },              /* pseudo option */
360         { "!", /* escape ? */   TOK_NOT },              /* pseudo option */
361         { "or",                 TOK_OR },               /* pseudo option */
362         { "|", /* escape */     TOK_OR },               /* pseudo option */
363         { "{",                  TOK_STARTBRACE },       /* pseudo option */
364         { "(",                  TOK_STARTBRACE },       /* pseudo option */
365         { "}",                  TOK_ENDBRACE },         /* pseudo option */
366         { ")",                  TOK_ENDBRACE },         /* pseudo option */
367         { NULL, 0 }     /* terminator */
368 };
369
370 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
371 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
372     ipfw_cfg_lheader **pcfg, size_t *psize);
373 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
374     ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
375 static void ipfw_list_tifaces(void);
376
377 /*
378  * Simple string buffer API.
379  * Used to simplify buffer passing between function and for
380  * transparent overrun handling.
381  */
382
383 /*
384  * Allocates new buffer of given size @sz.
385  *
386  * Returns 0 on success.
387  */
388 int
389 bp_alloc(struct buf_pr *b, size_t size)
390 {
391         memset(b, 0, sizeof(struct buf_pr));
392
393         if ((b->buf = calloc(1, size)) == NULL)
394                 return (ENOMEM);
395
396         b->ptr = b->buf;
397         b->size = size;
398         b->avail = b->size;
399
400         return (0);
401 }
402
403 void
404 bp_free(struct buf_pr *b)
405 {
406
407         free(b->buf);
408 }
409
410 /*
411  * Flushes buffer so new writer start from beginning.
412  */
413 void
414 bp_flush(struct buf_pr *b)
415 {
416
417         b->ptr = b->buf;
418         b->avail = b->size;
419 }
420
421 /*
422  * Print message specified by @format and args.
423  * Automatically manage buffer space and transparently handle
424  * buffer overruns.
425  *
426  * Returns number of bytes that should have been printed.
427  */
428 int
429 bprintf(struct buf_pr *b, char *format, ...)
430 {
431         va_list args;
432         int i;
433
434         va_start(args, format);
435
436         i = vsnprintf(b->ptr, b->avail, format, args);
437         va_end(args);
438
439         if (i > b->avail || i < 0) {
440                 /* Overflow or print error */
441                 b->avail = 0;
442         } else {
443                 b->ptr += i;
444                 b->avail -= i;
445         } 
446
447         b->needed += i;
448
449         return (i);
450 }
451
452 /*
453  * Special values printer for tablearg-aware opcodes.
454  */
455 void
456 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
457 {
458
459         if (str != NULL)
460                 bprintf(bp, "%s", str);
461         if (arg == IP_FW_TARG)
462                 bprintf(bp, "tablearg");
463         else
464                 bprintf(bp, "%u", arg);
465 }
466
467 /*
468  * Helper routine to print a possibly unaligned uint64_t on
469  * various platform. If width > 0, print the value with
470  * the desired width, followed by a space;
471  * otherwise, return the required width.
472  */
473 int
474 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
475 {
476 #ifdef TCC
477 #define U64_FMT "I64"
478 #else
479 #define U64_FMT "llu"
480 #endif
481         uint64_t u;
482         unsigned long long d;
483
484         bcopy (pd, &u, sizeof(u));
485         d = u;
486         return (width > 0) ?
487                 bprintf(b, "%*" U64_FMT " ", width, d) :
488                 snprintf(NULL, 0, "%" U64_FMT, d) ;
489 #undef U64_FMT
490 }
491
492
493 void *
494 safe_calloc(size_t number, size_t size)
495 {
496         void *ret = calloc(number, size);
497
498         if (ret == NULL)
499                 err(EX_OSERR, "calloc");
500         return ret;
501 }
502
503 void *
504 safe_realloc(void *ptr, size_t size)
505 {
506         void *ret = realloc(ptr, size);
507
508         if (ret == NULL)
509                 err(EX_OSERR, "realloc");
510         return ret;
511 }
512
513 /*
514  * Compare things like interface or table names.
515  */
516 int
517 stringnum_cmp(const char *a, const char *b)
518 {
519         int la, lb;
520
521         la = strlen(a);
522         lb = strlen(b);
523
524         if (la > lb)
525                 return (1);
526         else if (la < lb)
527                 return (-01);
528
529         return (strcmp(a, b));
530 }
531
532
533 /*
534  * conditionally runs the command.
535  * Selected options or negative -> getsockopt
536  */
537 int
538 do_cmd(int optname, void *optval, uintptr_t optlen)
539 {
540         int i;
541
542         if (co.test_only)
543                 return 0;
544
545         if (ipfw_socket == -1)
546                 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
547         if (ipfw_socket < 0)
548                 err(EX_UNAVAILABLE, "socket");
549
550         if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
551             optname == IP_FW_ADD || optname == IP_FW3 ||
552             optname == IP_FW_NAT_GET_CONFIG ||
553             optname < 0 ||
554             optname == IP_FW_NAT_GET_LOG) {
555                 if (optname < 0)
556                         optname = -optname;
557                 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
558                         (socklen_t *)optlen);
559         } else {
560                 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
561         }
562         return i;
563 }
564
565 /*
566  * do_set3 - pass ipfw control cmd to kernel
567  * @optname: option name
568  * @optval: pointer to option data
569  * @optlen: option length
570  *
571  * Assumes op3 header is already embedded.
572  * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
573  * Returns 0 on success or errno otherwise.
574  */
575 int
576 do_set3(int optname, ip_fw3_opheader *op3, uintptr_t optlen)
577 {
578         int errno;
579
580         if (co.test_only)
581                 return (0);
582
583         if (ipfw_socket == -1)
584                 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
585         if (ipfw_socket < 0)
586                 err(EX_UNAVAILABLE, "socket");
587
588         op3->opcode = optname;
589
590         if (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen) != 0)
591                 return (errno);
592
593         return (0);
594 }
595
596 /*
597  * do_get3 - pass ipfw control cmd to kernel
598  * @optname: option name
599  * @optval: pointer to option data
600  * @optlen: pointer to option length
601  *
602  * Assumes op3 header is already embedded.
603  * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
604  * Returns 0 on success or errno otherwise.
605  */
606 int
607 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
608 {
609         int error;
610
611         if (co.test_only)
612                 return (0);
613
614         if (ipfw_socket == -1)
615                 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
616         if (ipfw_socket < 0)
617                 err(EX_UNAVAILABLE, "socket");
618
619         op3->opcode = optname;
620
621         error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3,
622             (socklen_t *)optlen);
623
624         if (error == -1) {
625                 if (errno != 0)
626                         error = errno;
627         }
628
629         return (error);
630 }
631
632 /**
633  * match_token takes a table and a string, returns the value associated
634  * with the string (-1 in case of failure).
635  */
636 int
637 match_token(struct _s_x *table, char *string)
638 {
639         struct _s_x *pt;
640         uint i = strlen(string);
641
642         for (pt = table ; i && pt->s != NULL ; pt++)
643                 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
644                         return pt->x;
645         return (-1);
646 }
647
648 /**
649  * match_token takes a table and a string, returns the value associated
650  * with the string for the best match.
651  *
652  * Returns:
653  * value from @table for matched records
654  * -1 for non-matched records
655  * -2 if more than one records match @string.
656  */
657 int
658 match_token_relaxed(struct _s_x *table, char *string)
659 {
660         struct _s_x *pt, *m;
661         int i, c;
662
663         i = strlen(string);
664         c = 0;
665
666         for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
667                 if (strncmp(pt->s, string, i) != 0)
668                         continue;
669                 m = pt;
670                 c++;
671         }
672
673         if (c == 1)
674                 return (m->x);
675
676         return (c > 0 ? -2: -1);
677 }
678
679 /**
680  * match_value takes a table and a value, returns the string associated
681  * with the value (NULL in case of failure).
682  */
683 char const *
684 match_value(struct _s_x *p, int value)
685 {
686         for (; p->s != NULL; p++)
687                 if (p->x == value)
688                         return p->s;
689         return NULL;
690 }
691
692 size_t
693 concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
694 {
695         struct _s_x *pt;
696         int l;
697         size_t sz;
698
699         for (sz = 0, pt = table ; pt->s != NULL; pt++) {
700                 l = snprintf(buf + sz, bufsize - sz, "%s%s",
701                     (sz == 0) ? "" : delimiter, pt->s);
702                 sz += l;
703                 bufsize += l;
704                 if (sz > bufsize)
705                         return (bufsize);
706         }
707
708         return (sz);
709 }
710
711 /*
712  * helper function to process a set of flags and set bits in the
713  * appropriate masks.
714  */
715 void
716 fill_flags(struct _s_x *flags, char *p, uint8_t *set, uint8_t *clear)
717 {
718         char *q;        /* points to the separator */
719         int val;
720         uint8_t *which; /* mask we are working on */
721
722         while (p && *p) {
723                 if (*p == '!') {
724                         p++;
725                         which = clear;
726                 } else
727                         which = set;
728                 q = strchr(p, ',');
729                 if (q)
730                         *q++ = '\0';
731                 val = match_token(flags, p);
732                 if (val <= 0)
733                         errx(EX_DATAERR, "invalid flag %s", p);
734                 *which |= (uint8_t)val;
735                 p = q;
736         }
737 }
738
739 void
740 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint8_t set)
741 {
742         char const *comma = "";
743         int i, l;
744
745         for (i = 0; list[i].x != 0; i++) {
746                 if ((set & list[i].x) == 0)
747                         continue;
748                 
749                 set &= ~list[i].x;
750                 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
751                 if (l >= sz)
752                         return;
753                 comma = ",";
754                 buf += l;
755                 sz -=l;
756         }
757 }
758
759 /*
760  * _substrcmp takes two strings and returns 1 if they do not match,
761  * and 0 if they match exactly or the first string is a sub-string
762  * of the second.  A warning is printed to stderr in the case that the
763  * first string is a sub-string of the second.
764  *
765  * This function will be removed in the future through the usual
766  * deprecation process.
767  */
768 int
769 _substrcmp(const char *str1, const char* str2)
770 {
771
772         if (strncmp(str1, str2, strlen(str1)) != 0)
773                 return 1;
774
775         if (strlen(str1) != strlen(str2))
776                 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
777                     str1, str2);
778         return 0;
779 }
780
781 /*
782  * _substrcmp2 takes three strings and returns 1 if the first two do not match,
783  * and 0 if they match exactly or the second string is a sub-string
784  * of the first.  A warning is printed to stderr in the case that the
785  * first string does not match the third.
786  *
787  * This function exists to warn about the bizarre construction
788  * strncmp(str, "by", 2) which is used to allow people to use a shortcut
789  * for "bytes".  The problem is that in addition to accepting "by",
790  * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
791  * other string beginning with "by".
792  *
793  * This function will be removed in the future through the usual
794  * deprecation process.
795  */
796 int
797 _substrcmp2(const char *str1, const char* str2, const char* str3)
798 {
799
800         if (strncmp(str1, str2, strlen(str2)) != 0)
801                 return 1;
802
803         if (strcmp(str1, str3) != 0)
804                 warnx("DEPRECATED: '%s' matched '%s'",
805                     str1, str3);
806         return 0;
807 }
808
809 /*
810  * prints one port, symbolic or numeric
811  */
812 static void
813 print_port(struct buf_pr *bp, int proto, uint16_t port)
814 {
815
816         if (proto == IPPROTO_ETHERTYPE) {
817                 char const *s;
818
819                 if (co.do_resolv && (s = match_value(ether_types, port)) )
820                         bprintf(bp, "%s", s);
821                 else
822                         bprintf(bp, "0x%04x", port);
823         } else {
824                 struct servent *se = NULL;
825                 if (co.do_resolv) {
826                         struct protoent *pe = getprotobynumber(proto);
827
828                         se = getservbyport(htons(port), pe ? pe->p_name : NULL);
829                 }
830                 if (se)
831                         bprintf(bp, "%s", se->s_name);
832                 else
833                         bprintf(bp, "%d", port);
834         }
835 }
836
837 static struct _s_x _port_name[] = {
838         {"dst-port",    O_IP_DSTPORT},
839         {"src-port",    O_IP_SRCPORT},
840         {"ipid",        O_IPID},
841         {"iplen",       O_IPLEN},
842         {"ipttl",       O_IPTTL},
843         {"mac-type",    O_MAC_TYPE},
844         {"tcpdatalen",  O_TCPDATALEN},
845         {"tcpwin",      O_TCPWIN},
846         {"tagged",      O_TAGGED},
847         {NULL,          0}
848 };
849
850 /*
851  * Print the values in a list 16-bit items of the types above.
852  * XXX todo: add support for mask.
853  */
854 static void
855 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
856 {
857         uint16_t *p = cmd->ports;
858         int i;
859         char const *sep;
860
861         if (opcode != 0) {
862                 sep = match_value(_port_name, opcode);
863                 if (sep == NULL)
864                         sep = "???";
865                 bprintf(bp, " %s", sep);
866         }
867         sep = " ";
868         for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
869                 bprintf(bp, "%s", sep);
870                 print_port(bp, proto, p[0]);
871                 if (p[0] != p[1]) {
872                         bprintf(bp, "-");
873                         print_port(bp, proto, p[1]);
874                 }
875                 sep = ",";
876         }
877 }
878
879 /*
880  * Like strtol, but also translates service names into port numbers
881  * for some protocols.
882  * In particular:
883  *      proto == -1 disables the protocol check;
884  *      proto == IPPROTO_ETHERTYPE looks up an internal table
885  *      proto == <some value in /etc/protocols> matches the values there.
886  * Returns *end == s in case the parameter is not found.
887  */
888 static int
889 strtoport(char *s, char **end, int base, int proto)
890 {
891         char *p, *buf;
892         char *s1;
893         int i;
894
895         *end = s;               /* default - not found */
896         if (*s == '\0')
897                 return 0;       /* not found */
898
899         if (isdigit(*s))
900                 return strtol(s, end, base);
901
902         /*
903          * find separator. '\\' escapes the next char.
904          */
905         for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
906                 if (*s1 == '\\' && s1[1] != '\0')
907                         s1++;
908
909         buf = safe_calloc(s1 - s + 1, 1);
910
911         /*
912          * copy into a buffer skipping backslashes
913          */
914         for (p = s, i = 0; p != s1 ; p++)
915                 if (*p != '\\')
916                         buf[i++] = *p;
917         buf[i++] = '\0';
918
919         if (proto == IPPROTO_ETHERTYPE) {
920                 i = match_token(ether_types, buf);
921                 free(buf);
922                 if (i != -1) {  /* found */
923                         *end = s1;
924                         return i;
925                 }
926         } else {
927                 struct protoent *pe = NULL;
928                 struct servent *se;
929
930                 if (proto != 0)
931                         pe = getprotobynumber(proto);
932                 setservent(1);
933                 se = getservbyname(buf, pe ? pe->p_name : NULL);
934                 free(buf);
935                 if (se != NULL) {
936                         *end = s1;
937                         return ntohs(se->s_port);
938                 }
939         }
940         return 0;       /* not found */
941 }
942
943 /*
944  * Fill the body of the command with the list of port ranges.
945  */
946 static int
947 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
948 {
949         uint16_t a, b, *p = cmd->ports;
950         int i = 0;
951         char *s = av;
952
953         while (*s) {
954                 a = strtoport(av, &s, 0, proto);
955                 if (s == av)                    /* empty or invalid argument */
956                         return (0);
957
958                 CHECK_LENGTH(cblen, i + 2);
959
960                 switch (*s) {
961                 case '-':                       /* a range */
962                         av = s + 1;
963                         b = strtoport(av, &s, 0, proto);
964                         /* Reject expressions like '1-abc' or '1-2-3'. */
965                         if (s == av || (*s != ',' && *s != '\0'))
966                                 return (0);
967                         p[0] = a;
968                         p[1] = b;
969                         break;
970                 case ',':                       /* comma separated list */
971                 case '\0':
972                         p[0] = p[1] = a;
973                         break;
974                 default:
975                         warnx("port list: invalid separator <%c> in <%s>",
976                                 *s, av);
977                         return (0);
978                 }
979
980                 i++;
981                 p += 2;
982                 av = s + 1;
983         }
984         if (i > 0) {
985                 if (i + 1 > F_LEN_MASK)
986                         errx(EX_DATAERR, "too many ports/ranges\n");
987                 cmd->o.len |= i + 1;    /* leave F_NOT and F_OR untouched */
988         }
989         return (i);
990 }
991
992 /*
993  * Fill the body of the command with the list of DiffServ codepoints.
994  */
995 static void
996 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
997 {
998         uint32_t *low, *high;
999         char *s = av, *a;
1000         int code;
1001
1002         cmd->opcode = O_DSCP;
1003         cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1004
1005         CHECK_CMDLEN;
1006
1007         low = (uint32_t *)(cmd + 1);
1008         high = low + 1;
1009
1010         *low = 0;
1011         *high = 0;
1012
1013         while (s != NULL) {
1014                 a = strchr(s, ',');
1015
1016                 if (a != NULL)
1017                         *a++ = '\0';
1018
1019                 if (isalpha(*s)) {
1020                         if ((code = match_token(f_ipdscp, s)) == -1)
1021                                 errx(EX_DATAERR, "Unknown DSCP code");
1022                 } else {
1023                         code = strtoul(s, NULL, 10);
1024                         if (code < 0 || code > 63)
1025                                 errx(EX_DATAERR, "Invalid DSCP value");
1026                 }
1027
1028                 if (code > 32)
1029                         *high |= 1 << (code - 32);
1030                 else
1031                         *low |= 1 << code;
1032
1033                 s = a;
1034         }
1035 }
1036
1037 static struct _s_x icmpcodes[] = {
1038       { "net",                  ICMP_UNREACH_NET },
1039       { "host",                 ICMP_UNREACH_HOST },
1040       { "protocol",             ICMP_UNREACH_PROTOCOL },
1041       { "port",                 ICMP_UNREACH_PORT },
1042       { "needfrag",             ICMP_UNREACH_NEEDFRAG },
1043       { "srcfail",              ICMP_UNREACH_SRCFAIL },
1044       { "net-unknown",          ICMP_UNREACH_NET_UNKNOWN },
1045       { "host-unknown",         ICMP_UNREACH_HOST_UNKNOWN },
1046       { "isolated",             ICMP_UNREACH_ISOLATED },
1047       { "net-prohib",           ICMP_UNREACH_NET_PROHIB },
1048       { "host-prohib",          ICMP_UNREACH_HOST_PROHIB },
1049       { "tosnet",               ICMP_UNREACH_TOSNET },
1050       { "toshost",              ICMP_UNREACH_TOSHOST },
1051       { "filter-prohib",        ICMP_UNREACH_FILTER_PROHIB },
1052       { "host-precedence",      ICMP_UNREACH_HOST_PRECEDENCE },
1053       { "precedence-cutoff",    ICMP_UNREACH_PRECEDENCE_CUTOFF },
1054       { NULL, 0 }
1055 };
1056
1057 static void
1058 fill_reject_code(u_short *codep, char *str)
1059 {
1060         int val;
1061         char *s;
1062
1063         val = strtoul(str, &s, 0);
1064         if (s == str || *s != '\0' || val >= 0x100)
1065                 val = match_token(icmpcodes, str);
1066         if (val < 0)
1067                 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1068         *codep = val;
1069         return;
1070 }
1071
1072 static void
1073 print_reject_code(struct buf_pr *bp, uint16_t code)
1074 {
1075         char const *s;
1076
1077         if ((s = match_value(icmpcodes, code)) != NULL)
1078                 bprintf(bp, "unreach %s", s);
1079         else
1080                 bprintf(bp, "unreach %u", code);
1081 }
1082
1083 /*
1084  * Returns the number of bits set (from left) in a contiguous bitmask,
1085  * or -1 if the mask is not contiguous.
1086  * XXX this needs a proper fix.
1087  * This effectively works on masks in big-endian (network) format.
1088  * when compiled on little endian architectures.
1089  *
1090  * First bit is bit 7 of the first byte -- note, for MAC addresses,
1091  * the first bit on the wire is bit 0 of the first byte.
1092  * len is the max length in bits.
1093  */
1094 int
1095 contigmask(uint8_t *p, int len)
1096 {
1097         int i, n;
1098
1099         for (i=0; i<len ; i++)
1100                 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1101                         break;
1102         for (n=i+1; n < len; n++)
1103                 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1104                         return -1; /* mask not contiguous */
1105         return i;
1106 }
1107
1108 /*
1109  * print flags set/clear in the two bitmasks passed as parameters.
1110  * There is a specialized check for f_tcpflags.
1111  */
1112 static void
1113 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1114     struct _s_x *list)
1115 {
1116         char const *comma = "";
1117         int i;
1118         uint8_t set = cmd->arg1 & 0xff;
1119         uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1120
1121         if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1122                 bprintf(bp, " setup");
1123                 return;
1124         }
1125
1126         bprintf(bp, " %s ", name);
1127         for (i=0; list[i].x != 0; i++) {
1128                 if (set & list[i].x) {
1129                         set &= ~list[i].x;
1130                         bprintf(bp, "%s%s", comma, list[i].s);
1131                         comma = ",";
1132                 }
1133                 if (clear & list[i].x) {
1134                         clear &= ~list[i].x;
1135                         bprintf(bp, "%s!%s", comma, list[i].s);
1136                         comma = ",";
1137                 }
1138         }
1139 }
1140
1141
1142 /*
1143  * Print the ip address contained in a command.
1144  */
1145 static void
1146 print_ip(struct buf_pr *bp, struct format_opts *fo, ipfw_insn_ip *cmd,
1147     char const *s)
1148 {
1149         struct hostent *he = NULL;
1150         struct in_addr *ia;
1151         uint32_t len = F_LEN((ipfw_insn *)cmd);
1152         uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1153         char *t;
1154
1155         if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1156                 uint32_t d = a[1];
1157                 const char *arg = "<invalid>";
1158
1159                 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1160                         arg = match_value(rule_options, lookup_key[d]);
1161                 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1162                 bprintf(bp, "%s lookup %s %s", cmd->o.len & F_NOT ? " not": "",
1163                         arg, t);
1164                 return;
1165         }
1166         bprintf(bp, "%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1167
1168         if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1169                 bprintf(bp, "me");
1170                 return;
1171         }
1172         if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1173             cmd->o.opcode == O_IP_DST_LOOKUP) {
1174                 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1175                 bprintf(bp, "table(%s", t);
1176                 if (len == F_INSN_SIZE(ipfw_insn_u32))
1177                         bprintf(bp, ",%u", *a);
1178                 bprintf(bp, ")");
1179                 return;
1180         }
1181         if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1182                 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1183                 int i, j;
1184                 char comma = '{';
1185
1186                 x = cmd->o.arg1 - 1;
1187                 x = htonl( ~x );
1188                 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1189                 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1190                         contigmask((uint8_t *)&x, 32));
1191                 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1192                 x &= 0xff; /* base */
1193                 /*
1194                  * Print bits and ranges.
1195                  * Locate first bit set (i), then locate first bit unset (j).
1196                  * If we have 3+ consecutive bits set, then print them as a
1197                  * range, otherwise only print the initial bit and rescan.
1198                  */
1199                 for (i=0; i < cmd->o.arg1; i++)
1200                         if (map[i/32] & (1<<(i & 31))) {
1201                                 for (j=i+1; j < cmd->o.arg1; j++)
1202                                         if (!(map[ j/32] & (1<<(j & 31))))
1203                                                 break;
1204                                 bprintf(bp, "%c%d", comma, i+x);
1205                                 if (j>i+2) { /* range has at least 3 elements */
1206                                         bprintf(bp, "-%d", j-1+x);
1207                                         i = j-1;
1208                                 }
1209                                 comma = ',';
1210                         }
1211                 bprintf(bp, "}");
1212                 return;
1213         }
1214         /*
1215          * len == 2 indicates a single IP, whereas lists of 1 or more
1216          * addr/mask pairs have len = (2n+1). We convert len to n so we
1217          * use that to count the number of entries.
1218          */
1219     for (len = len / 2; len > 0; len--, a += 2) {
1220         int mb =        /* mask length */
1221             (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1222                 32 : contigmask((uint8_t *)&(a[1]), 32);
1223         if (mb == 32 && co.do_resolv)
1224                 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1225         if (he != NULL)         /* resolved to name */
1226                 bprintf(bp, "%s", he->h_name);
1227         else if (mb == 0)       /* any */
1228                 bprintf(bp, "any");
1229         else {          /* numeric IP followed by some kind of mask */
1230                 ia = (struct in_addr *)&a[0];
1231                 bprintf(bp, "%s", inet_ntoa(*ia));
1232                 if (mb < 0)
1233                         bprintf(bp, ":%s", inet_ntoa(*ia ) );
1234                 else if (mb < 32)
1235                         bprintf(bp, "/%d", mb);
1236         }
1237         if (len > 1)
1238                 bprintf(bp, ",");
1239     }
1240 }
1241
1242 /*
1243  * prints a MAC address/mask pair
1244  */
1245 static void
1246 print_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1247 {
1248         int l = contigmask(mask, 48);
1249
1250         if (l == 0)
1251                 bprintf(bp, " any");
1252         else {
1253                 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1254                     addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1255                 if (l == -1)
1256                         bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1257                             mask[0], mask[1], mask[2],
1258                             mask[3], mask[4], mask[5]);
1259                 else if (l < 48)
1260                         bprintf(bp, "/%d", l);
1261         }
1262 }
1263
1264 static void
1265 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1266 {
1267         uint8_t type;
1268
1269         cmd->d[0] = 0;
1270         while (*av) {
1271                 if (*av == ',')
1272                         av++;
1273
1274                 type = strtoul(av, &av, 0);
1275
1276                 if (*av != ',' && *av != '\0')
1277                         errx(EX_DATAERR, "invalid ICMP type");
1278
1279                 if (type > 31)
1280                         errx(EX_DATAERR, "ICMP type out of range");
1281
1282                 cmd->d[0] |= 1 << type;
1283         }
1284         cmd->o.opcode = O_ICMPTYPE;
1285         cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1286 }
1287
1288 static void
1289 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1290 {
1291         int i;
1292         char sep= ' ';
1293
1294         bprintf(bp, " icmptypes");
1295         for (i = 0; i < 32; i++) {
1296                 if ( (cmd->d[0] & (1 << (i))) == 0)
1297                         continue;
1298                 bprintf(bp, "%c%d", sep, i);
1299                 sep = ',';
1300         }
1301 }
1302
1303 static void
1304 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1305 {
1306         int i, c;
1307         uint32_t *v;
1308         char sep= ' ';
1309         const char *code;
1310
1311         bprintf(bp, " dscp");
1312         i = 0;
1313         c = 0;
1314         v = cmd->d;
1315         while (i < 64) {
1316                 if (*v & (1 << i)) {
1317                         if ((code = match_value(f_ipdscp, i)) != NULL)
1318                                 bprintf(bp, "%c%s", sep, code);
1319                         else
1320                                 bprintf(bp, "%c%d", sep, i);
1321                         sep = ',';
1322                 }
1323
1324                 if ((++i % 32) == 0)
1325                         v++;
1326         }
1327 }
1328
1329 /*
1330  * show_ipfw() prints the body of an ipfw rule.
1331  * Because the standard rule has at least proto src_ip dst_ip, we use
1332  * a helper function to produce these entries if not provided explicitly.
1333  * The first argument is the list of fields we have, the second is
1334  * the list of fields we want to be printed.
1335  *
1336  * Special cases if we have provided a MAC header:
1337  *   + if the rule does not contain IP addresses/ports, do not print them;
1338  *   + if the rule does not contain an IP proto, print "all" instead of "ip";
1339  *
1340  * Once we have 'have_options', IP header fields are printed as options.
1341  */
1342 #define HAVE_PROTO      0x0001
1343 #define HAVE_SRCIP      0x0002
1344 #define HAVE_DSTIP      0x0004
1345 #define HAVE_PROTO4     0x0008
1346 #define HAVE_PROTO6     0x0010
1347 #define HAVE_IP         0x0100
1348 #define HAVE_OPTIONS    0x8000
1349
1350 static void
1351 show_prerequisites(struct buf_pr *bp, int *flags, int want, int cmd)
1352 {
1353         (void)cmd;      /* UNUSED */
1354         if (co.comment_only)
1355                 return;
1356         if ( (*flags & HAVE_IP) == HAVE_IP)
1357                 *flags |= HAVE_OPTIONS;
1358
1359         if ( !(*flags & HAVE_OPTIONS)) {
1360                 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1361                         if ( (*flags & HAVE_PROTO4))
1362                                 bprintf(bp, " ip4");
1363                         else if ( (*flags & HAVE_PROTO6))
1364                                 bprintf(bp, " ip6");
1365                         else
1366                                 bprintf(bp, " ip");
1367                 }
1368                 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1369                         bprintf(bp, " from any");
1370                 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1371                         bprintf(bp, " to any");
1372         }
1373         *flags |= want;
1374 }
1375
1376 static void
1377 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
1378     struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
1379 {
1380         static int twidth = 0;
1381         int l;
1382         ipfw_insn *cmd, *tagptr = NULL;
1383         const char *comment = NULL;     /* ptr to comment if we have one */
1384         int proto = 0;          /* default */
1385         int flags = 0;  /* prerequisites */
1386         ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1387         ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1388         int or_block = 0;       /* we are in an or block */
1389         uint32_t uval;
1390
1391         if ((fo->set_mask & (1 << rule->set)) == 0) {
1392                 /* disabled mask */
1393                 if (!co->show_sets)
1394                         return;
1395                 else
1396                         bprintf(bp, "# DISABLED ");
1397         }
1398         bprintf(bp, "%05u ", rule->rulenum);
1399
1400         /* Print counters if enabled */
1401         if (fo->pcwidth > 0 || fo->bcwidth > 0) {
1402                 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
1403                 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
1404         }
1405
1406         if (co->do_time == 2)
1407                 bprintf(bp, "%10u ", cntr->timestamp);
1408         else if (co->do_time == 1) {
1409                 char timestr[30];
1410                 time_t t = (time_t)0;
1411
1412                 if (twidth == 0) {
1413                         strcpy(timestr, ctime(&t));
1414                         *strchr(timestr, '\n') = '\0';
1415                         twidth = strlen(timestr);
1416                 }
1417                 if (cntr->timestamp > 0) {
1418                         t = _long_to_time(cntr->timestamp);
1419
1420                         strcpy(timestr, ctime(&t));
1421                         *strchr(timestr, '\n') = '\0';
1422                         bprintf(bp, "%s ", timestr);
1423                 } else {
1424                         bprintf(bp, "%*s", twidth, " ");
1425                 }
1426         }
1427
1428         if (co->show_sets)
1429                 bprintf(bp, "set %d ", rule->set);
1430
1431         /*
1432          * print the optional "match probability"
1433          */
1434         if (rule->cmd_len > 0) {
1435                 cmd = rule->cmd ;
1436                 if (cmd->opcode == O_PROB) {
1437                         ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1438                         double d = 1.0 * p->d[0];
1439
1440                         d = (d / 0x7fffffff);
1441                         bprintf(bp, "prob %f ", d);
1442                 }
1443         }
1444
1445         /*
1446          * first print actions
1447          */
1448         for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1449                         l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1450                 switch(cmd->opcode) {
1451                 case O_CHECK_STATE:
1452                         bprintf(bp, "check-state");
1453                         /* avoid printing anything else */
1454                         flags = HAVE_PROTO | HAVE_SRCIP |
1455                                 HAVE_DSTIP | HAVE_IP;
1456                         break;
1457
1458                 case O_ACCEPT:
1459                         bprintf(bp, "allow");
1460                         break;
1461
1462                 case O_COUNT:
1463                         bprintf(bp, "count");
1464                         break;
1465
1466                 case O_DENY:
1467                         bprintf(bp, "deny");
1468                         break;
1469
1470                 case O_REJECT:
1471                         if (cmd->arg1 == ICMP_REJECT_RST)
1472                                 bprintf(bp, "reset");
1473                         else if (cmd->arg1 == ICMP_UNREACH_HOST)
1474                                 bprintf(bp, "reject");
1475                         else
1476                                 print_reject_code(bp, cmd->arg1);
1477                         break;
1478
1479                 case O_UNREACH6:
1480                         if (cmd->arg1 == ICMP6_UNREACH_RST)
1481                                 bprintf(bp, "reset6");
1482                         else
1483                                 print_unreach6_code(cmd->arg1);
1484                         break;
1485
1486                 case O_SKIPTO:
1487                         bprint_uint_arg(bp, "skipto ", cmd->arg1);
1488                         break;
1489
1490                 case O_PIPE:
1491                         bprint_uint_arg(bp, "pipe ", cmd->arg1);
1492                         break;
1493
1494                 case O_QUEUE:
1495                         bprint_uint_arg(bp, "queue ", cmd->arg1);
1496                         break;
1497
1498                 case O_DIVERT:
1499                         bprint_uint_arg(bp, "divert ", cmd->arg1);
1500                         break;
1501
1502                 case O_TEE:
1503                         bprint_uint_arg(bp, "tee ", cmd->arg1);
1504                         break;
1505
1506                 case O_NETGRAPH:
1507                         bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1508                         break;
1509
1510                 case O_NGTEE:
1511                         bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1512                         break;
1513
1514                 case O_FORWARD_IP:
1515                     {
1516                         ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1517
1518                         if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1519                                 bprintf(bp, "fwd tablearg");
1520                         } else {
1521                                 bprintf(bp, "fwd %s",inet_ntoa(s->sa.sin_addr));
1522                         }
1523                         if (s->sa.sin_port)
1524                                 bprintf(bp, ",%d", s->sa.sin_port);
1525                     }
1526                         break;
1527
1528                 case O_FORWARD_IP6:
1529                     {
1530                         char buf[4 + INET6_ADDRSTRLEN + 1];
1531                         ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1532
1533                         bprintf(bp, "fwd %s", inet_ntop(AF_INET6,
1534                             &s->sa.sin6_addr, buf, sizeof(buf)));
1535                         if (s->sa.sin6_port)
1536                                 bprintf(bp, ",%d", s->sa.sin6_port);
1537                     }
1538                         break;
1539
1540                 case O_LOG: /* O_LOG is printed last */
1541                         logptr = (ipfw_insn_log *)cmd;
1542                         break;
1543
1544                 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1545                         altqptr = (ipfw_insn_altq *)cmd;
1546                         break;
1547
1548                 case O_TAG:
1549                         tagptr = cmd;
1550                         break;
1551
1552                 case O_NAT:
1553                         if (cmd->arg1 != 0)
1554                                 bprint_uint_arg(bp, "nat ", cmd->arg1);
1555                         else
1556                                 bprintf(bp, "nat global");
1557                         break;
1558
1559                 case O_SETFIB:
1560                         bprint_uint_arg(bp, "setfib ", cmd->arg1 & 0x7FFF);
1561                         break;
1562
1563                 case O_SETDSCP:
1564                     {
1565                         const char *code;
1566
1567                         if (cmd->arg1 == IP_FW_TARG) {
1568                                 bprint_uint_arg(bp, "setdscp ", cmd->arg1);
1569                                 break;
1570                         }
1571                         uval = cmd->arg1 & 0x3F;
1572                         if ((code = match_value(f_ipdscp, uval)) != NULL)
1573                                 bprintf(bp, "setdscp %s", code);
1574                         else
1575                                 bprint_uint_arg(bp, "setdscp ", uval);
1576                     }
1577                         break;
1578
1579                 case O_REASS:
1580                         bprintf(bp, "reass");
1581                         break;
1582
1583                 case O_CALLRETURN:
1584                         if (cmd->len & F_NOT)
1585                                 bprintf(bp, "return");
1586                         else
1587                                 bprint_uint_arg(bp, "call ", cmd->arg1);
1588                         break;
1589
1590                 default:
1591                         bprintf(bp, "** unrecognized action %d len %d ",
1592                                 cmd->opcode, cmd->len);
1593                 }
1594         }
1595         if (logptr) {
1596                 if (logptr->max_log > 0)
1597                         bprintf(bp, " log logamount %d", logptr->max_log);
1598                 else
1599                         bprintf(bp, " log");
1600         }
1601 #ifndef NO_ALTQ
1602         if (altqptr) {
1603                 print_altq_cmd(bp, altqptr);
1604         }
1605 #endif
1606         if (tagptr) {
1607                 if (tagptr->len & F_NOT)
1608                         bprint_uint_arg(bp, " untag ", tagptr->arg1);
1609                 else
1610                         bprint_uint_arg(bp, " tag ", tagptr->arg1);
1611         }
1612
1613         /*
1614          * then print the body.
1615          */
1616         for (l = rule->act_ofs, cmd = rule->cmd;
1617                         l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1618                 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1619                         continue;
1620                 if (cmd->opcode == O_IP4) {
1621                         flags |= HAVE_PROTO4;
1622                         break;
1623                 } else if (cmd->opcode == O_IP6) {
1624                         flags |= HAVE_PROTO6;
1625                         break;
1626                 }
1627         }
1628         if (rule->flags & IPFW_RULE_NOOPT) {    /* empty rules before options */
1629                 if (!co->do_compact) {
1630                         show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1631                         bprintf(bp, " from any to any");
1632                 }
1633                 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1634                          HAVE_SRCIP | HAVE_DSTIP;
1635         }
1636
1637         if (co->comment_only)
1638                 comment = "...";
1639
1640         for (l = rule->act_ofs, cmd = rule->cmd;
1641                         l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1642                 /* useful alias */
1643                 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1644
1645                 if (co->comment_only) {
1646                         if (cmd->opcode != O_NOP)
1647                                 continue;
1648                         bprintf(bp, " // %s\n", (char *)(cmd + 1));
1649                         return;
1650                 }
1651
1652                 show_prerequisites(bp, &flags, 0, cmd->opcode);
1653
1654                 switch(cmd->opcode) {
1655                 case O_PROB:
1656                         break;  /* done already */
1657
1658                 case O_PROBE_STATE:
1659                         break; /* no need to print anything here */
1660
1661                 case O_IP_SRC:
1662                 case O_IP_SRC_LOOKUP:
1663                 case O_IP_SRC_MASK:
1664                 case O_IP_SRC_ME:
1665                 case O_IP_SRC_SET:
1666                         show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1667                         if (!(flags & HAVE_SRCIP))
1668                                 bprintf(bp, " from");
1669                         if ((cmd->len & F_OR) && !or_block)
1670                                 bprintf(bp, " {");
1671                         print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1672                                 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1673                         flags |= HAVE_SRCIP;
1674                         break;
1675
1676                 case O_IP_DST:
1677                 case O_IP_DST_LOOKUP:
1678                 case O_IP_DST_MASK:
1679                 case O_IP_DST_ME:
1680                 case O_IP_DST_SET:
1681                         show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1682                         if (!(flags & HAVE_DSTIP))
1683                                 bprintf(bp, " to");
1684                         if ((cmd->len & F_OR) && !or_block)
1685                                 bprintf(bp, " {");
1686                         print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1687                                 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1688                         flags |= HAVE_DSTIP;
1689                         break;
1690
1691                 case O_IP6_SRC:
1692                 case O_IP6_SRC_MASK:
1693                 case O_IP6_SRC_ME:
1694                         show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1695                         if (!(flags & HAVE_SRCIP))
1696                                 bprintf(bp, " from");
1697                         if ((cmd->len & F_OR) && !or_block)
1698                                 bprintf(bp, " {");
1699                         print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1700                             (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1701                         flags |= HAVE_SRCIP | HAVE_PROTO;
1702                         break;
1703
1704                 case O_IP6_DST:
1705                 case O_IP6_DST_MASK:
1706                 case O_IP6_DST_ME:
1707                         show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1708                         if (!(flags & HAVE_DSTIP))
1709                                 bprintf(bp, " to");
1710                         if ((cmd->len & F_OR) && !or_block)
1711                                 bprintf(bp, " {");
1712                         print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1713                             (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1714                         flags |= HAVE_DSTIP;
1715                         break;
1716
1717                 case O_FLOW6ID:
1718                         print_flow6id(bp, (ipfw_insn_u32 *) cmd );
1719                         flags |= HAVE_OPTIONS;
1720                         break;
1721
1722                 case O_IP_DSTPORT:
1723                         show_prerequisites(bp, &flags,
1724                                 HAVE_PROTO | HAVE_SRCIP |
1725                                 HAVE_DSTIP | HAVE_IP, 0);
1726                 case O_IP_SRCPORT:
1727                         if (flags & HAVE_DSTIP)
1728                                 flags |= HAVE_IP;
1729                         show_prerequisites(bp, &flags,
1730                                 HAVE_PROTO | HAVE_SRCIP, 0);
1731                         if ((cmd->len & F_OR) && !or_block)
1732                                 bprintf(bp, " {");
1733                         if (cmd->len & F_NOT)
1734                                 bprintf(bp, " not");
1735                         print_newports(bp, (ipfw_insn_u16 *)cmd, proto,
1736                                 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1737                         break;
1738
1739                 case O_PROTO: {
1740                         struct protoent *pe = NULL;
1741
1742                         if ((cmd->len & F_OR) && !or_block)
1743                                 bprintf(bp, " {");
1744                         if (cmd->len & F_NOT)
1745                                 bprintf(bp, " not");
1746                         proto = cmd->arg1;
1747                         pe = getprotobynumber(cmd->arg1);
1748                         if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1749                             !(flags & HAVE_PROTO))
1750                                 show_prerequisites(bp, &flags,
1751                                     HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1752                                     HAVE_DSTIP | HAVE_OPTIONS, 0);
1753                         if (flags & HAVE_OPTIONS)
1754                                 bprintf(bp, " proto");
1755                         if (pe)
1756                                 bprintf(bp, " %s", pe->p_name);
1757                         else
1758                                 bprintf(bp, " %u", cmd->arg1);
1759                         }
1760                         flags |= HAVE_PROTO;
1761                         break;
1762
1763                 default: /*options ... */
1764                         if (!(cmd->len & (F_OR|F_NOT)))
1765                                 if (((cmd->opcode == O_IP6) &&
1766                                     (flags & HAVE_PROTO6)) ||
1767                                     ((cmd->opcode == O_IP4) &&
1768                                     (flags & HAVE_PROTO4)))
1769                                         break;
1770                         show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP |
1771                                     HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1772                         if ((cmd->len & F_OR) && !or_block)
1773                                 bprintf(bp, " {");
1774                         if (cmd->len & F_NOT && cmd->opcode != O_IN)
1775                                 bprintf(bp, " not");
1776                         switch(cmd->opcode) {
1777                         case O_MACADDR2: {
1778                                 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1779
1780                                 bprintf(bp, " MAC");
1781                                 print_mac(bp, m->addr, m->mask);
1782                                 print_mac(bp, m->addr + 6, m->mask + 6);
1783                                 }
1784                                 break;
1785
1786                         case O_MAC_TYPE:
1787                                 print_newports(bp, (ipfw_insn_u16 *)cmd,
1788                                                 IPPROTO_ETHERTYPE, cmd->opcode);
1789                                 break;
1790
1791
1792                         case O_FRAG:
1793                                 bprintf(bp, " frag");
1794                                 break;
1795
1796                         case O_FIB:
1797                                 bprintf(bp, " fib %u", cmd->arg1 );
1798                                 break;
1799                         case O_SOCKARG:
1800                                 bprintf(bp, " sockarg");
1801                                 break;
1802
1803                         case O_IN:
1804                                 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1805                                 break;
1806
1807                         case O_DIVERTED:
1808                                 switch (cmd->arg1) {
1809                                 case 3:
1810                                         bprintf(bp, " diverted");
1811                                         break;
1812                                 case 1:
1813                                         bprintf(bp, " diverted-loopback");
1814                                         break;
1815                                 case 2:
1816                                         bprintf(bp, " diverted-output");
1817                                         break;
1818                                 default:
1819                                         bprintf(bp, " diverted-?<%u>", cmd->arg1);
1820                                         break;
1821                                 }
1822                                 break;
1823
1824                         case O_LAYER2:
1825                                 bprintf(bp, " layer2");
1826                                 break;
1827                         case O_XMIT:
1828                         case O_RECV:
1829                         case O_VIA:
1830                             {
1831                                 char const *s, *t;
1832                                 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1833
1834                                 if (cmd->opcode == O_XMIT)
1835                                         s = "xmit";
1836                                 else if (cmd->opcode == O_RECV)
1837                                         s = "recv";
1838                                 else /* if (cmd->opcode == O_VIA) */
1839                                         s = "via";
1840                                 if (cmdif->name[0] == '\0')
1841                                         bprintf(bp, " %s %s", s,
1842                                             inet_ntoa(cmdif->p.ip));
1843                                 else if (cmdif->name[0] == '\1') {
1844                                         /* interface table */
1845                                         t = table_search_ctlv(fo->tstate,
1846                                             cmdif->p.kidx);
1847                                         bprintf(bp, " %s table(%s)", s, t);
1848                                 } else
1849                                         bprintf(bp, " %s %s", s, cmdif->name);
1850
1851                                 break;
1852                             }
1853                         case O_IP_FLOW_LOOKUP:
1854                             {
1855                                 char *t;
1856
1857                                 t = table_search_ctlv(fo->tstate, cmd->arg1);
1858                                 bprintf(bp, " flow table(%s", t);
1859                                 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1860                                         bprintf(bp, ",%u",
1861                                             ((ipfw_insn_u32 *)cmd)->d[0]);
1862                                 bprintf(bp, ")");
1863                                 break;
1864                             }
1865                         case O_IPID:
1866                                 if (F_LEN(cmd) == 1)
1867                                     bprintf(bp, " ipid %u", cmd->arg1 );
1868                                 else
1869                                     print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1870                                         O_IPID);
1871                                 break;
1872
1873                         case O_IPTTL:
1874                                 if (F_LEN(cmd) == 1)
1875                                     bprintf(bp, " ipttl %u", cmd->arg1 );
1876                                 else
1877                                     print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1878                                         O_IPTTL);
1879                                 break;
1880
1881                         case O_IPVER:
1882                                 bprintf(bp, " ipver %u", cmd->arg1 );
1883                                 break;
1884
1885                         case O_IPPRECEDENCE:
1886                                 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1887                                 break;
1888
1889                         case O_DSCP:
1890                                 print_dscp(bp, (ipfw_insn_u32 *)cmd);
1891                                 break;
1892
1893                         case O_IPLEN:
1894                                 if (F_LEN(cmd) == 1)
1895                                     bprintf(bp, " iplen %u", cmd->arg1 );
1896                                 else
1897                                     print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1898                                         O_IPLEN);
1899                                 break;
1900
1901                         case O_IPOPT:
1902                                 print_flags(bp, "ipoptions", cmd, f_ipopts);
1903                                 break;
1904
1905                         case O_IPTOS:
1906                                 print_flags(bp, "iptos", cmd, f_iptos);
1907                                 break;
1908
1909                         case O_ICMPTYPE:
1910                                 print_icmptypes(bp, (ipfw_insn_u32 *)cmd);
1911                                 break;
1912
1913                         case O_ESTAB:
1914                                 bprintf(bp, " established");
1915                                 break;
1916
1917                         case O_TCPDATALEN:
1918                                 if (F_LEN(cmd) == 1)
1919                                     bprintf(bp, " tcpdatalen %u", cmd->arg1 );
1920                                 else
1921                                     print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1922                                         O_TCPDATALEN);
1923                                 break;
1924
1925                         case O_TCPFLAGS:
1926                                 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1927                                 break;
1928
1929                         case O_TCPOPTS:
1930                                 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1931                                 break;
1932
1933                         case O_TCPWIN:
1934                                 if (F_LEN(cmd) == 1)
1935                                     bprintf(bp, " tcpwin %u", cmd->arg1);
1936                                 else
1937                                     print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1938                                         O_TCPWIN);
1939                                 break;
1940
1941                         case O_TCPACK:
1942                                 bprintf(bp, " tcpack %d", ntohl(cmd32->d[0]));
1943                                 break;
1944
1945                         case O_TCPSEQ:
1946                                 bprintf(bp, " tcpseq %d", ntohl(cmd32->d[0]));
1947                                 break;
1948
1949                         case O_UID:
1950                             {
1951                                 struct passwd *pwd = getpwuid(cmd32->d[0]);
1952
1953                                 if (pwd)
1954                                         bprintf(bp, " uid %s", pwd->pw_name);
1955                                 else
1956                                         bprintf(bp, " uid %u", cmd32->d[0]);
1957                             }
1958                                 break;
1959
1960                         case O_GID:
1961                             {
1962                                 struct group *grp = getgrgid(cmd32->d[0]);
1963
1964                                 if (grp)
1965                                         bprintf(bp, " gid %s", grp->gr_name);
1966                                 else
1967                                         bprintf(bp, " gid %u", cmd32->d[0]);
1968                             }
1969                                 break;
1970
1971                         case O_JAIL:
1972                                 bprintf(bp, " jail %d", cmd32->d[0]);
1973                                 break;
1974
1975                         case O_VERREVPATH:
1976                                 bprintf(bp, " verrevpath");
1977                                 break;
1978
1979                         case O_VERSRCREACH:
1980                                 bprintf(bp, " versrcreach");
1981                                 break;
1982
1983                         case O_ANTISPOOF:
1984                                 bprintf(bp, " antispoof");
1985                                 break;
1986
1987                         case O_IPSEC:
1988                                 bprintf(bp, " ipsec");
1989                                 break;
1990
1991                         case O_NOP:
1992                                 comment = (char *)(cmd + 1);
1993                                 break;
1994
1995                         case O_KEEP_STATE:
1996                                 bprintf(bp, " keep-state");
1997                                 break;
1998
1999                         case O_LIMIT: {
2000                                 struct _s_x *p = limit_masks;
2001                                 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2002                                 uint8_t x = c->limit_mask;
2003                                 char const *comma = " ";
2004
2005                                 bprintf(bp, " limit");
2006                                 for (; p->x != 0 ; p++)
2007                                         if ((x & p->x) == p->x) {
2008                                                 x &= ~p->x;
2009                                                 bprintf(bp, "%s%s", comma,p->s);
2010                                                 comma = ",";
2011                                         }
2012                                 bprint_uint_arg(bp, " ", c->conn_limit);
2013                                 break;
2014                         }
2015
2016                         case O_IP6:
2017                                 bprintf(bp, " ip6");
2018                                 break;
2019
2020                         case O_IP4:
2021                                 bprintf(bp, " ip4");
2022                                 break;
2023
2024                         case O_ICMP6TYPE:
2025                                 print_icmp6types(bp, (ipfw_insn_u32 *)cmd);
2026                                 break;
2027
2028                         case O_EXT_HDR:
2029                                 print_ext6hdr(bp, (ipfw_insn *)cmd);
2030                                 break;
2031
2032                         case O_TAGGED:
2033                                 if (F_LEN(cmd) == 1)
2034                                         bprint_uint_arg(bp, " tagged ",
2035                                             cmd->arg1);
2036                                 else
2037                                         print_newports(bp, (ipfw_insn_u16 *)cmd,
2038                                             0, O_TAGGED);
2039                                 break;
2040
2041                         default:
2042                                 bprintf(bp, " [opcode %d len %d]",
2043                                     cmd->opcode, cmd->len);
2044                         }
2045                 }
2046                 if (cmd->len & F_OR) {
2047                         bprintf(bp, " or");
2048                         or_block = 1;
2049                 } else if (or_block) {
2050                         bprintf(bp, " }");
2051                         or_block = 0;
2052                 }
2053         }
2054         show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
2055                                               | HAVE_IP, 0);
2056         if (comment)
2057                 bprintf(bp, " // %s", comment);
2058         bprintf(bp, "\n");
2059 }
2060
2061 static void
2062 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2063     struct buf_pr *bp, ipfw_dyn_rule *d)
2064 {
2065         struct protoent *pe;
2066         struct in_addr a;
2067         uint16_t rulenum;
2068         char buf[INET6_ADDRSTRLEN];
2069
2070         if (!co->do_expired) {
2071                 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2072                         return;
2073         }
2074         bcopy(&d->rule, &rulenum, sizeof(rulenum));
2075         bprintf(bp, "%05d", rulenum);
2076         if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2077                 bprintf(bp, " ");
2078                 pr_u64(bp, &d->pcnt, fo->pcwidth);
2079                 pr_u64(bp, &d->bcnt, fo->bcwidth);
2080                 bprintf(bp, "(%ds)", d->expire);
2081         }
2082         switch (d->dyn_type) {
2083         case O_LIMIT_PARENT:
2084                 bprintf(bp, " PARENT %d", d->count);
2085                 break;
2086         case O_LIMIT:
2087                 bprintf(bp, " LIMIT");
2088                 break;
2089         case O_KEEP_STATE: /* bidir, no mask */
2090                 bprintf(bp, " STATE");
2091                 break;
2092         }
2093
2094         if ((pe = getprotobynumber(d->id.proto)) != NULL)
2095                 bprintf(bp, " %s", pe->p_name);
2096         else
2097                 bprintf(bp, " proto %u", d->id.proto);
2098
2099         if (d->id.addr_type == 4) {
2100                 a.s_addr = htonl(d->id.src_ip);
2101                 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2102
2103                 a.s_addr = htonl(d->id.dst_ip);
2104                 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2105         } else if (d->id.addr_type == 6) {
2106                 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2107                     sizeof(buf)), d->id.src_port);
2108                 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2109                     buf, sizeof(buf)), d->id.dst_port);
2110         } else
2111                 bprintf(bp, " UNKNOWN <-> UNKNOWN\n");
2112 }
2113
2114 static int
2115 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2116 {
2117         ipfw_range_header rh;
2118
2119         memset(&rh, 0, sizeof(rh));
2120         memcpy(&rh.range, rt, sizeof(*rt));
2121         rh.range.head.length = sizeof(*rt);
2122         rh.range.head.type = IPFW_TLV_RANGE;
2123
2124         return (do_set3(cmd, &rh.opheader, sizeof(rh)));
2125 }
2126
2127 /*
2128  * This one handles all set-related commands
2129  *      ipfw set { show | enable | disable }
2130  *      ipfw set swap X Y
2131  *      ipfw set move X to Y
2132  *      ipfw set move rule X to Y
2133  */
2134 void
2135 ipfw_sets_handler(char *av[])
2136 {
2137         uint32_t masks[2];
2138         int i;
2139         uint8_t cmd, new_set, rulenum;
2140         ipfw_range_tlv rt;
2141         char *msg;
2142         size_t size;
2143
2144         av++;
2145         memset(&rt, 0, sizeof(rt));
2146
2147         if (av[0] == NULL)
2148                 errx(EX_USAGE, "set needs command");
2149         if (_substrcmp(*av, "show") == 0) {
2150                 struct format_opts fo;
2151                 ipfw_cfg_lheader *cfg;
2152
2153                 memset(&fo, 0, sizeof(fo));
2154                 if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2155                         err(EX_OSERR, "requesting config failed");
2156
2157                 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2158                         if ((cfg->set_mask & (1<<i)) == 0) {
2159                                 printf("%s %d", msg, i);
2160                                 msg = "";
2161                         }
2162                 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2163                 for (i = 0; i < RESVD_SET; i++)
2164                         if ((cfg->set_mask & (1<<i)) != 0) {
2165                                 printf("%s %d", msg, i);
2166                                 msg = "";
2167                         }
2168                 printf("\n");
2169                 free(cfg);
2170         } else if (_substrcmp(*av, "swap") == 0) {
2171                 av++;
2172                 if ( av[0] == NULL || av[1] == NULL )
2173                         errx(EX_USAGE, "set swap needs 2 set numbers\n");
2174                 rt.set = atoi(av[0]);
2175                 rt.new_set = atoi(av[1]);
2176                 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2177                         errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2178                 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2179                         errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2180                 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2181         } else if (_substrcmp(*av, "move") == 0) {
2182                 av++;
2183                 if (av[0] && _substrcmp(*av, "rule") == 0) {
2184                         rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2185                         cmd = IP_FW_XMOVE;
2186                         av++;
2187                 } else
2188                         cmd = IP_FW_SET_MOVE; /* Move set to new one */
2189                 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2190                                 av[3] != NULL ||  _substrcmp(av[1], "to") != 0)
2191                         errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2192                 rulenum = atoi(av[0]);
2193                 rt.new_set = atoi(av[2]);
2194                 if (cmd == IP_FW_XMOVE) {
2195                         rt.start_rule = rulenum;
2196                         rt.end_rule = rulenum;
2197                 } else
2198                         rt.set = rulenum;
2199                 rt.new_set = atoi(av[2]);
2200                 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2201                         (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2202                         errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2203                 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2204                         errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2205                 i = do_range_cmd(cmd, &rt);
2206         } else if (_substrcmp(*av, "disable") == 0 ||
2207                    _substrcmp(*av, "enable") == 0 ) {
2208                 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2209
2210                 av++;
2211                 masks[0] = masks[1] = 0;
2212
2213                 while (av[0]) {
2214                         if (isdigit(**av)) {
2215                                 i = atoi(*av);
2216                                 if (i < 0 || i > RESVD_SET)
2217                                         errx(EX_DATAERR,
2218                                             "invalid set number %d\n", i);
2219                                 masks[which] |= (1<<i);
2220                         } else if (_substrcmp(*av, "disable") == 0)
2221                                 which = 0;
2222                         else if (_substrcmp(*av, "enable") == 0)
2223                                 which = 1;
2224                         else
2225                                 errx(EX_DATAERR,
2226                                         "invalid set command %s\n", *av);
2227                         av++;
2228                 }
2229                 if ( (masks[0] & masks[1]) != 0 )
2230                         errx(EX_DATAERR,
2231                             "cannot enable and disable the same set\n");
2232
2233                 rt.set = masks[0];
2234                 rt.new_set = masks[1];
2235                 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2236                 if (i)
2237                         warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2238         } else
2239                 errx(EX_USAGE, "invalid set command %s\n", *av);
2240 }
2241
2242 void
2243 ipfw_sysctl_handler(char *av[], int which)
2244 {
2245         av++;
2246
2247         if (av[0] == NULL) {
2248                 warnx("missing keyword to enable/disable\n");
2249         } else if (_substrcmp(*av, "firewall") == 0) {
2250                 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2251                     &which, sizeof(which));
2252                 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2253                     &which, sizeof(which));
2254         } else if (_substrcmp(*av, "one_pass") == 0) {
2255                 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2256                     &which, sizeof(which));
2257         } else if (_substrcmp(*av, "debug") == 0) {
2258                 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2259                     &which, sizeof(which));
2260         } else if (_substrcmp(*av, "verbose") == 0) {
2261                 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2262                     &which, sizeof(which));
2263         } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2264                 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2265                     &which, sizeof(which));
2266 #ifndef NO_ALTQ
2267         } else if (_substrcmp(*av, "altq") == 0) {
2268                 altq_set_enabled(which);
2269 #endif
2270         } else {
2271                 warnx("unrecognize enable/disable keyword: %s\n", *av);
2272         }
2273 }
2274
2275 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2276     void *arg, void *state);
2277
2278 static void
2279 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2280     void *arg, void *_state)
2281 {
2282         ipfw_dyn_rule *d;
2283         int width;
2284         uint8_t set;
2285
2286         d = (ipfw_dyn_rule *)_state;
2287         /* Count _ALL_ states */
2288         fo->dcnt++;
2289
2290         if (fo->show_counters == 0)
2291                 return;
2292
2293         if (co->use_set) {
2294                 /* skip states from another set */
2295                 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2296                     sizeof(uint8_t));
2297                 if (set != co->use_set - 1)
2298                         return;
2299         }
2300
2301         width = pr_u64(NULL, &d->pcnt, 0);
2302         if (width > fo->pcwidth)
2303                 fo->pcwidth = width;
2304
2305         width = pr_u64(NULL, &d->bcnt, 0);
2306         if (width > fo->bcwidth)
2307                 fo->bcwidth = width;
2308 }
2309
2310 static int
2311 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2312     caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2313 {
2314         int ttype;
2315         state_cb *fptr;
2316         void *farg;
2317         ipfw_obj_tlv *tlv;
2318         ipfw_obj_ctlv *ctlv;
2319
2320         fptr = NULL;
2321         ttype = 0;
2322
2323         while (sz > 0) {
2324                 ctlv = (ipfw_obj_ctlv *)base;
2325                 switch (ctlv->head.type) {
2326                 case IPFW_TLV_DYNSTATE_LIST:
2327                         base += sizeof(*ctlv);
2328                         sz -= sizeof(*ctlv);
2329                         ttype = IPFW_TLV_DYN_ENT;
2330                         fptr = dyn_bc;
2331                         farg = dyn_arg;
2332                         break;
2333                 default:
2334                         return (sz);
2335                 }
2336
2337                 while (sz > 0) {
2338                         tlv = (ipfw_obj_tlv *)base;
2339                         if (tlv->type != ttype)
2340                                 break;
2341
2342                         fptr(co, fo, farg, tlv + 1);
2343                         sz -= tlv->length;
2344                         base += tlv->length;
2345                 }
2346         }
2347
2348         return (sz);
2349 }
2350
2351 static void
2352 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2353     ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2354 {
2355         int bcwidth, pcwidth, width;
2356         int n;
2357         struct ip_fw_bcounter *cntr;
2358         struct ip_fw_rule *r;
2359
2360         bcwidth = 0;
2361         pcwidth = 0;
2362         if (fo->show_counters != 0) {
2363                 for (n = 0; n < rcnt; n++,
2364                     rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2365                         cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2366                         r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2367                         /* skip rules from another set */
2368                         if (co->use_set && r->set != co->use_set - 1)
2369                                 continue;
2370
2371                         /* packet counter */
2372                         width = pr_u64(NULL, &cntr->pcnt, 0);
2373                         if (width > pcwidth)
2374                                 pcwidth = width;
2375
2376                         /* byte counter */
2377                         width = pr_u64(NULL, &cntr->bcnt, 0);
2378                         if (width > bcwidth)
2379                                 bcwidth = width;
2380                 }
2381         }
2382         fo->bcwidth = bcwidth;
2383         fo->pcwidth = pcwidth;
2384
2385         fo->dcnt = 0;
2386         if (co->do_dynamic && dynsz > 0)
2387                 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2388 }
2389
2390 static int
2391 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2392     struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2393 {
2394         int n, seen;
2395         struct ip_fw_rule *r;
2396         struct ip_fw_bcounter *cntr;
2397         int c = 0;
2398
2399         for (n = seen = 0; n < rcnt; n++,
2400             rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2401
2402                 if (fo->show_counters != 0) {
2403                         cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2404                         r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2405                 } else {
2406                         cntr = NULL;
2407                         r = (struct ip_fw_rule *)(rtlv + 1);
2408                 }
2409                 if (r->rulenum > fo->last)
2410                         break;
2411                 if (co->use_set && r->set != co->use_set - 1)
2412                         continue;
2413                 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2414                         show_static_rule(co, fo, bp, r, cntr);
2415                         printf("%s", bp->buf);
2416                         c += rtlv->length;
2417                         bp_flush(bp);
2418                         seen++;
2419                 }
2420         }
2421
2422         return (seen);
2423 }
2424
2425 static void
2426 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2427     void *_arg, void *_state)
2428 {
2429         uint16_t rulenum;
2430         uint8_t set;
2431         ipfw_dyn_rule *d;
2432         struct buf_pr *bp;
2433
2434         d = (ipfw_dyn_rule *)_state;
2435         bp = (struct buf_pr *)_arg;
2436
2437         bcopy(&d->rule, &rulenum, sizeof(rulenum));
2438         if (rulenum > fo->last)
2439                 return;
2440         if (co->use_set) {
2441                 bcopy((char *)&d->rule + sizeof(uint16_t),
2442                       &set, sizeof(uint8_t));
2443                 if (set != co->use_set - 1)
2444                         return;
2445         }
2446         if (rulenum >= fo->first) {
2447                 show_dyn_state(co, fo, bp, d);
2448                 printf("%s\n", bp->buf);
2449                 bp_flush(bp);
2450         }
2451 }
2452
2453 static int
2454 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2455     struct buf_pr *bp, caddr_t base, size_t sz)
2456 {
2457
2458         sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2459         return (sz);
2460 }
2461
2462 void
2463 ipfw_list(int ac, char *av[], int show_counters)
2464 {
2465         ipfw_cfg_lheader *cfg;
2466         struct format_opts sfo;
2467         size_t sz;
2468         int error;
2469         int lac;
2470         char **lav;
2471         uint32_t rnum;
2472         char *endptr;
2473
2474         if (co.test_only) {
2475                 fprintf(stderr, "Testing only, list disabled\n");
2476                 return;
2477         }
2478         if (co.do_pipe) {
2479                 dummynet_list(ac, av, show_counters);
2480                 return;
2481         }
2482
2483         ac--;
2484         av++;
2485         memset(&sfo, 0, sizeof(sfo));
2486
2487         /* Determine rule range to request */
2488         if (ac > 0) {
2489                 for (lac = ac, lav = av; lac != 0; lac--) {
2490                         rnum = strtoul(*lav++, &endptr, 10);
2491                         if (sfo.first == 0 || rnum < sfo.first)
2492                                 sfo.first = rnum;
2493
2494                         if (*endptr == '-')
2495                                 rnum = strtoul(endptr + 1, &endptr, 10);
2496                         if (sfo.last == 0 || rnum > sfo.last)
2497                                 sfo.last = rnum;
2498                 }
2499         }
2500
2501         /* get configuraion from kernel */
2502         cfg = NULL;
2503         sfo.show_counters = show_counters;
2504         sfo.flags = IPFW_CFG_GET_STATIC;
2505         if (co.do_dynamic != 0)
2506                 sfo.flags |= IPFW_CFG_GET_STATES;
2507         if (sfo.show_counters != 0)
2508                 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2509         if ((error = ipfw_get_config(&co, &sfo, &cfg, &sz)) != 0)
2510                 err(EX_OSERR, "retrieving config failed");
2511
2512         error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2513
2514         free(cfg);
2515
2516         if (error != EX_OK)
2517                 exit(error);
2518 }
2519
2520 static int
2521 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2522     ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2523 {
2524         caddr_t dynbase;
2525         size_t dynsz;
2526         int rcnt;
2527         int exitval = EX_OK;
2528         int lac;
2529         char **lav;
2530         char *endptr;
2531         size_t read;
2532         struct buf_pr bp;
2533         ipfw_obj_ctlv *ctlv, *tstate;
2534         ipfw_obj_tlv *rbase;
2535
2536         /*
2537          * Handle tablenames TLV first, if any
2538          */
2539         tstate = NULL;
2540         rbase = NULL;
2541         dynbase = NULL;
2542         dynsz = 0;
2543         read = sizeof(*cfg);
2544
2545         fo->set_mask = cfg->set_mask;
2546
2547         ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2548
2549         if (cfg->flags & IPFW_CFG_GET_STATIC) {
2550                 /* We've requested static rules */
2551                 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2552                         fo->tstate = ctlv;
2553                         read += ctlv->head.length;
2554                         ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2555                             ctlv->head.length);
2556                 }
2557
2558                 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2559                         rbase = (ipfw_obj_tlv *)(ctlv + 1);
2560                         rcnt = ctlv->count;
2561                         read += ctlv->head.length;
2562                         ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2563                             ctlv->head.length);
2564                 }
2565         }
2566
2567         if ((cfg->flags & IPFW_CFG_GET_STATES) && (read != sz))  {
2568                 /* We may have some dynamic states */
2569                 dynsz = sz - read;
2570                 /* Skip empty header */
2571                 if (dynsz != sizeof(ipfw_obj_ctlv))
2572                         dynbase = (caddr_t)ctlv;
2573                 else
2574                         dynsz = 0;
2575         }
2576
2577         prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2578         bp_alloc(&bp, 4096);
2579
2580         /* if no rule numbers were specified, list all rules */
2581         if (ac == 0) {
2582                 fo->first = 0;
2583                 fo->last = IPFW_DEFAULT_RULE;
2584                 list_static_range(co, fo, &bp, rbase, rcnt);
2585
2586                 if (co->do_dynamic && dynsz > 0) {
2587                         printf("## Dynamic rules (%d %lu):\n", fo->dcnt, dynsz);
2588                         list_dyn_range(co, fo, &bp, dynbase, dynsz);
2589                 }
2590
2591                 bp_free(&bp);
2592                 return (EX_OK);
2593         }
2594
2595         /* display specific rules requested on command line */
2596         for (lac = ac, lav = av; lac != 0; lac--) {
2597                 /* convert command line rule # */
2598                 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2599                 if (*endptr == '-')
2600                         fo->last = strtoul(endptr + 1, &endptr, 10);
2601                 if (*endptr) {
2602                         exitval = EX_USAGE;
2603                         warnx("invalid rule number: %s", *(lav - 1));
2604                         continue;
2605                 }
2606
2607                 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2608                         /* give precedence to other error(s) */
2609                         if (exitval == EX_OK)
2610                                 exitval = EX_UNAVAILABLE;
2611                         if (fo->first == fo->last)
2612                                 warnx("rule %u does not exist", fo->first);
2613                         else
2614                                 warnx("no rules in range %u-%u",
2615                                     fo->first, fo->last);
2616                 }
2617         }
2618
2619         if (co->do_dynamic && dynsz > 0) {
2620                 printf("## Dynamic rules:\n");
2621                 for (lac = ac, lav = av; lac != 0; lac--) {
2622                         fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2623                         if (*endptr == '-')
2624                                 fo->last = strtoul(endptr+1, &endptr, 10);
2625                         if (*endptr)
2626                                 /* already warned */
2627                                 continue;
2628                         list_dyn_range(co, fo, &bp, dynbase, dynsz);
2629                 }
2630         }
2631
2632         bp_free(&bp);
2633         return (exitval);
2634 }
2635
2636
2637 /*
2638  * Retrieves current ipfw configuration of given type
2639  * and stores its pointer to @pcfg.
2640  *
2641  * Caller is responsible for freeing @pcfg.
2642  *
2643  * Returns 0 on success.
2644  */
2645
2646 static int
2647 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2648     ipfw_cfg_lheader **pcfg, size_t *psize)
2649 {
2650         ipfw_cfg_lheader *cfg;
2651         size_t sz;
2652         int error, i;
2653
2654
2655         if (co->test_only != 0) {
2656                 fprintf(stderr, "Testing only, list disabled\n");
2657                 return (0);
2658         }
2659
2660         /* Start with some data size */
2661         sz = 4096;
2662         cfg = NULL;
2663
2664         for (i = 0; i < 16; i++) {
2665                 if (cfg != NULL)
2666                         free(cfg);
2667                 if ((cfg = calloc(1, sz)) == NULL)
2668                         return (ENOMEM);
2669
2670                 cfg->flags = fo->flags;
2671                 cfg->start_rule = fo->first;
2672                 cfg->end_rule = fo->last;
2673
2674                 if ((error = do_get3(IP_FW_XGET, &cfg->opheader, &sz)) != 0) {
2675                         if (error != ENOMEM) {
2676                                 free(cfg);
2677                                 return (error);
2678                         }
2679
2680                         /* Buffer size is not enough. Try to increase */
2681                         sz = sz * 2;
2682                         if (sz < cfg->size)
2683                                 sz = cfg->size;
2684                         continue;
2685                 }
2686
2687                 *pcfg = cfg;
2688                 *psize = sz;
2689                 return (0);
2690         }
2691
2692         free(cfg);
2693         return (ENOMEM);
2694 }
2695
2696 static int
2697 lookup_host (char *host, struct in_addr *ipaddr)
2698 {
2699         struct hostent *he;
2700
2701         if (!inet_aton(host, ipaddr)) {
2702                 if ((he = gethostbyname(host)) == NULL)
2703                         return(-1);
2704                 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2705         }
2706         return(0);
2707 }
2708
2709 struct tidx {
2710         ipfw_obj_ntlv *idx;
2711         uint32_t count;
2712         uint32_t size;
2713         uint16_t counter;
2714         uint8_t set;
2715 };
2716
2717 static uint16_t
2718 pack_table(struct tidx *tstate, char *name)
2719 {
2720         int i;
2721         ipfw_obj_ntlv *ntlv;
2722
2723         if (table_check_name(name) != 0)
2724                 return (0);
2725
2726         for (i = 0; i < tstate->count; i++) {
2727                 if (strcmp(tstate->idx[i].name, name) != 0)
2728                         continue;
2729                 if (tstate->idx[i].set != tstate->set)
2730                         continue;
2731
2732                 return (tstate->idx[i].idx);
2733         }
2734
2735         if (tstate->count + 1 > tstate->size) {
2736                 tstate->size += 4;
2737                 tstate->idx = realloc(tstate->idx, tstate->size *
2738                     sizeof(ipfw_obj_ntlv));
2739                 if (tstate->idx == NULL)
2740                         return (0);
2741         }
2742
2743         ntlv = &tstate->idx[i];
2744         memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
2745         strlcpy(ntlv->name, name, sizeof(ntlv->name));
2746         ntlv->head.type = IPFW_TLV_TBL_NAME;
2747         ntlv->head.length = sizeof(ipfw_obj_ntlv);
2748         ntlv->set = tstate->set;
2749         ntlv->idx = ++tstate->counter;
2750         tstate->count++;
2751
2752         return (ntlv->idx);
2753 }
2754
2755 static void
2756 fill_table(ipfw_insn *cmd, char *av, uint8_t opcode, struct tidx *tstate)
2757 {
2758         uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2759         uint16_t uidx;
2760         char *p;
2761
2762         if ((p = strchr(av + 6, ')')) == NULL)
2763                 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
2764         *p = '\0';
2765         p = strchr(av + 6, ',');
2766         if (p)
2767                 *p++ = '\0';
2768
2769         if ((uidx = pack_table(tstate, av + 6)) == 0)
2770                 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
2771
2772         cmd->opcode = opcode;
2773         cmd->arg1 = uidx;
2774         if (p) {
2775                 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
2776                 d[0] = strtoul(p, NULL, 0);
2777         } else
2778                 cmd->len |= F_INSN_SIZE(ipfw_insn);
2779 }
2780
2781
2782 /*
2783  * fills the addr and mask fields in the instruction as appropriate from av.
2784  * Update length as appropriate.
2785  * The following formats are allowed:
2786  *      me      returns O_IP_*_ME
2787  *      1.2.3.4         single IP address
2788  *      1.2.3.4:5.6.7.8 address:mask
2789  *      1.2.3.4/24      address/mask
2790  *      1.2.3.4/26{1,6,5,4,23}  set of addresses in a subnet
2791  * We can have multiple comma-separated address/mask entries.
2792  */
2793 static void
2794 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
2795 {
2796         int len = 0;
2797         uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2798
2799         cmd->o.len &= ~F_LEN_MASK;      /* zero len */
2800
2801         if (_substrcmp(av, "any") == 0)
2802                 return;
2803
2804         if (_substrcmp(av, "me") == 0) {
2805                 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2806                 return;
2807         }
2808
2809         if (strncmp(av, "table(", 6) == 0) {
2810                 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
2811                 return;
2812         }
2813
2814     while (av) {
2815         /*
2816          * After the address we can have '/' or ':' indicating a mask,
2817          * ',' indicating another address follows, '{' indicating a
2818          * set of addresses of unspecified size.
2819          */
2820         char *t = NULL, *p = strpbrk(av, "/:,{");
2821         int masklen;
2822         char md, nd = '\0';
2823
2824         CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2825
2826         if (p) {
2827                 md = *p;
2828                 *p++ = '\0';
2829                 if ((t = strpbrk(p, ",{")) != NULL) {
2830                         nd = *t;
2831                         *t = '\0';
2832                 }
2833         } else
2834                 md = '\0';
2835
2836         if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2837                 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2838         switch (md) {
2839         case ':':
2840                 if (!inet_aton(p, (struct in_addr *)&d[1]))
2841                         errx(EX_DATAERR, "bad netmask ``%s''", p);
2842                 break;
2843         case '/':
2844                 masklen = atoi(p);
2845                 if (masklen == 0)
2846                         d[1] = htonl(0);        /* mask */
2847                 else if (masklen > 32)
2848                         errx(EX_DATAERR, "bad width ``%s''", p);
2849                 else
2850                         d[1] = htonl(~0 << (32 - masklen));
2851                 break;
2852         case '{':       /* no mask, assume /24 and put back the '{' */
2853                 d[1] = htonl(~0 << (32 - 24));
2854                 *(--p) = md;
2855                 break;
2856
2857         case ',':       /* single address plus continuation */
2858                 *(--p) = md;
2859                 /* FALLTHROUGH */
2860         case 0:         /* initialization value */
2861         default:
2862                 d[1] = htonl(~0);       /* force /32 */
2863                 break;
2864         }
2865         d[0] &= d[1];           /* mask base address with mask */
2866         if (t)
2867                 *t = nd;
2868         /* find next separator */
2869         if (p)
2870                 p = strpbrk(p, ",{");
2871         if (p && *p == '{') {
2872                 /*
2873                  * We have a set of addresses. They are stored as follows:
2874                  *   arg1       is the set size (powers of 2, 2..256)
2875                  *   addr       is the base address IN HOST FORMAT
2876                  *   mask..     is an array of arg1 bits (rounded up to
2877                  *              the next multiple of 32) with bits set
2878                  *              for each host in the map.
2879                  */
2880                 uint32_t *map = (uint32_t *)&cmd->mask;
2881                 int low, high;
2882                 int i = contigmask((uint8_t *)&(d[1]), 32);
2883
2884                 if (len > 0)
2885                         errx(EX_DATAERR, "address set cannot be in a list");
2886                 if (i < 24 || i > 31)
2887                         errx(EX_DATAERR, "invalid set with mask %d\n", i);
2888                 cmd->o.arg1 = 1<<(32-i);        /* map length           */
2889                 d[0] = ntohl(d[0]);             /* base addr in host format */
2890                 cmd->o.opcode = O_IP_DST_SET;   /* default */
2891                 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2892                 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2893                         map[i] = 0;     /* clear map */
2894
2895                 av = p + 1;
2896                 low = d[0] & 0xff;
2897                 high = low + cmd->o.arg1 - 1;
2898                 /*
2899                  * Here, i stores the previous value when we specify a range
2900                  * of addresses within a mask, e.g. 45-63. i = -1 means we
2901                  * have no previous value.
2902                  */
2903                 i = -1; /* previous value in a range */
2904                 while (isdigit(*av)) {
2905                         char *s;
2906                         int a = strtol(av, &s, 0);
2907
2908                         if (s == av) { /* no parameter */
2909                             if (*av != '}')
2910                                 errx(EX_DATAERR, "set not closed\n");
2911                             if (i != -1)
2912                                 errx(EX_DATAERR, "incomplete range %d-", i);
2913                             break;
2914                         }
2915                         if (a < low || a > high)
2916                             errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2917                                 a, low, high);
2918                         a -= low;
2919                         if (i == -1)    /* no previous in range */
2920                             i = a;
2921                         else {          /* check that range is valid */
2922                             if (i > a)
2923                                 errx(EX_DATAERR, "invalid range %d-%d",
2924                                         i+low, a+low);
2925                             if (*s == '-')
2926                                 errx(EX_DATAERR, "double '-' in range");
2927                         }
2928                         for (; i <= a; i++)
2929                             map[i/32] |= 1<<(i & 31);
2930                         i = -1;
2931                         if (*s == '-')
2932                             i = a;
2933                         else if (*s == '}')
2934                             break;
2935                         av = s+1;
2936                 }
2937                 return;
2938         }
2939         av = p;
2940         if (av)                 /* then *av must be a ',' */
2941                 av++;
2942
2943         /* Check this entry */
2944         if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2945                 /*
2946                  * 'any' turns the entire list into a NOP.
2947                  * 'not any' never matches, so it is removed from the
2948                  * list unless it is the only item, in which case we
2949                  * report an error.
2950                  */
2951                 if (cmd->o.len & F_NOT) {       /* "not any" never matches */
2952                         if (av == NULL && len == 0) /* only this entry */
2953                                 errx(EX_DATAERR, "not any never matches");
2954                 }
2955                 /* else do nothing and skip this entry */
2956                 return;
2957         }
2958         /* A single IP can be stored in an optimized format */
2959         if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2960                 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2961                 return;
2962         }
2963         len += 2;       /* two words... */
2964         d += 2;
2965     } /* end while */
2966     if (len + 1 > F_LEN_MASK)
2967         errx(EX_DATAERR, "address list too long");
2968     cmd->o.len |= len+1;
2969 }
2970
2971
2972 /* n2mask sets n bits of the mask */
2973 void
2974 n2mask(struct in6_addr *mask, int n)
2975 {
2976         static int      minimask[9] =
2977             { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2978         u_char          *p;
2979
2980         memset(mask, 0, sizeof(struct in6_addr));
2981         p = (u_char *) mask;
2982         for (; n > 0; p++, n -= 8) {
2983                 if (n >= 8)
2984                         *p = 0xff;
2985                 else
2986                         *p = minimask[n];
2987         }
2988         return;
2989 }
2990
2991 static void
2992 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2993         struct _s_x *flags, char *p)
2994 {
2995         uint8_t set = 0, clear = 0;
2996
2997         fill_flags(flags, p, &set, &clear);
2998
2999         cmd->opcode = opcode;
3000         cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
3001         cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3002 }
3003
3004
3005 void
3006 ipfw_delete(char *av[])
3007 {
3008         uint32_t rulenum;
3009         int i;
3010         int exitval = EX_OK;
3011         int do_set = 0;
3012         ipfw_range_tlv rt;
3013
3014         av++;
3015         NEED1("missing rule specification");
3016         memset(&rt, 0, sizeof(rt));
3017         if ( *av && _substrcmp(*av, "set") == 0) {
3018                 /* Do not allow using the following syntax:
3019                  *      ipfw set N delete set M
3020                  */
3021                 if (co.use_set)
3022                         errx(EX_DATAERR, "invalid syntax");
3023                 do_set = 1;     /* delete set */
3024                 av++;
3025         }
3026
3027         /* Rule number */
3028         while (*av && isdigit(**av)) {
3029                 i = atoi(*av); av++;
3030                 if (co.do_nat) {
3031                         exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3032                         if (exitval) {
3033                                 exitval = EX_UNAVAILABLE;
3034                                 warn("rule %u not available", i);
3035                         }
3036                 } else if (co.do_pipe) {
3037                         exitval = ipfw_delete_pipe(co.do_pipe, i);
3038                 } else {
3039                         if (do_set != 0) {
3040                                 rt.set = i & 31;
3041                                 rt.flags = IPFW_RCFLAG_SET;
3042                         } else {
3043                                 rt.start_rule = i & 0xffff;
3044                                 rt.end_rule = i & 0xffff;
3045                                 if (rt.start_rule == 0 && rt.end_rule == 0)
3046                                         rt.flags |= IPFW_RCFLAG_ALL;
3047                                 else
3048                                         rt.flags |= IPFW_RCFLAG_RANGE;
3049                                 if (co.use_set != 0) {
3050                                         rt.set = co.use_set - 1;
3051                                         rt.flags |= IPFW_RCFLAG_SET;
3052                                 }
3053                         }
3054                         i = do_range_cmd(IP_FW_XDEL, &rt);
3055                         if (i != 0) {
3056                                 exitval = EX_UNAVAILABLE;
3057                                 warn("rule %u: setsockopt(IP_FW_XDEL)",
3058                                     rulenum);
3059                         }
3060                 }
3061         }
3062         if (exitval != EX_OK)
3063                 exit(exitval);
3064 }
3065
3066
3067 /*
3068  * fill the interface structure. We do not check the name as we can
3069  * create interfaces dynamically, so checking them at insert time
3070  * makes relatively little sense.
3071  * Interface names containing '*', '?', or '[' are assumed to be shell
3072  * patterns which match interfaces.
3073  */
3074 static void
3075 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3076 {
3077         char *p;
3078         uint16_t uidx;
3079
3080         cmd->name[0] = '\0';
3081         cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3082
3083         CHECK_CMDLEN;
3084
3085         /* Parse the interface or address */
3086         if (strcmp(arg, "any") == 0)
3087                 cmd->o.len = 0;         /* effectively ignore this command */
3088         else if (strncmp(arg, "table(", 6) == 0) {
3089                 if ((p = strchr(arg + 6, ')')) == NULL)
3090                         errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3091                 *p = '\0';
3092                 p = strchr(arg + 6, ',');
3093                 if (p)
3094                         *p++ = '\0';
3095                 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3096                         errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3097
3098                 cmd->name[0] = '\1'; /* Special value indicating table */
3099                 cmd->p.kidx = uidx;
3100         } else if (!isdigit(*arg)) {
3101                 strlcpy(cmd->name, arg, sizeof(cmd->name));
3102                 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3103         } else if (!inet_aton(arg, &cmd->p.ip))
3104                 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3105 }
3106
3107 static void
3108 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3109 {
3110         int i;
3111         size_t l;
3112         char *ap, *ptr, *optr;
3113         struct ether_addr *mac;
3114         const char *macset = "0123456789abcdefABCDEF:";
3115
3116         if (strcmp(p, "any") == 0) {
3117                 for (i = 0; i < ETHER_ADDR_LEN; i++)
3118                         addr[i] = mask[i] = 0;
3119                 return;
3120         }
3121
3122         optr = ptr = strdup(p);
3123         if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3124                 l = strlen(ap);
3125                 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3126                         errx(EX_DATAERR, "Incorrect MAC address");
3127                 bcopy(mac, addr, ETHER_ADDR_LEN);
3128         } else
3129                 errx(EX_DATAERR, "Incorrect MAC address");
3130
3131         if (ptr != NULL) { /* we have mask? */
3132                 if (p[ptr - optr - 1] == '/') { /* mask len */
3133                         long ml = strtol(ptr, &ap, 10);
3134                         if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3135                                 errx(EX_DATAERR, "Incorrect mask length");
3136                         for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3137                                 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3138                 } else { /* mask */
3139                         l = strlen(ptr);
3140                         if (strspn(ptr, macset) != l ||
3141                             (mac = ether_aton(ptr)) == NULL)
3142                                 errx(EX_DATAERR, "Incorrect mask");
3143                         bcopy(mac, mask, ETHER_ADDR_LEN);
3144                 }
3145         } else { /* default mask: ff:ff:ff:ff:ff:ff */
3146                 for (i = 0; i < ETHER_ADDR_LEN; i++)
3147                         mask[i] = 0xff;
3148         }
3149         for (i = 0; i < ETHER_ADDR_LEN; i++)
3150                 addr[i] &= mask[i];
3151
3152         free(optr);
3153 }
3154
3155 /*
3156  * helper function, updates the pointer to cmd with the length
3157  * of the current command, and also cleans up the first word of
3158  * the new command in case it has been clobbered before.
3159  */
3160 static ipfw_insn *
3161 next_cmd(ipfw_insn *cmd, int *len)
3162 {
3163         *len -= F_LEN(cmd);
3164         CHECK_LENGTH(*len, 0);
3165         cmd += F_LEN(cmd);
3166         bzero(cmd, sizeof(*cmd));
3167         return cmd;
3168 }
3169
3170 /*
3171  * Takes arguments and copies them into a comment
3172  */
3173 static void
3174 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3175 {
3176         int i, l;
3177         char *p = (char *)(cmd + 1);
3178
3179         cmd->opcode = O_NOP;
3180         cmd->len =  (cmd->len & (F_NOT | F_OR));
3181
3182         /* Compute length of comment string. */
3183         for (i = 0, l = 0; av[i] != NULL; i++)
3184                 l += strlen(av[i]) + 1;
3185         if (l == 0)
3186                 return;
3187         if (l > 84)
3188                 errx(EX_DATAERR,
3189                     "comment too long (max 80 chars)");
3190         l = 1 + (l+3)/4;
3191         cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
3192         CHECK_CMDLEN;
3193
3194         for (i = 0; av[i] != NULL; i++) {
3195                 strcpy(p, av[i]);
3196                 p += strlen(av[i]);
3197                 *p++ = ' ';
3198         }
3199         *(--p) = '\0';
3200 }
3201
3202 /*
3203  * A function to fill simple commands of size 1.
3204  * Existing flags are preserved.
3205  */
3206 static void
3207 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3208 {
3209         cmd->opcode = opcode;
3210         cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3211         cmd->arg1 = arg;
3212 }
3213
3214 /*
3215  * Fetch and add the MAC address and type, with masks. This generates one or
3216  * two microinstructions, and returns the pointer to the last one.
3217  */
3218 static ipfw_insn *
3219 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3220 {
3221         ipfw_insn_mac *mac;
3222
3223         if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3224                 errx(EX_DATAERR, "MAC dst src");
3225
3226         cmd->opcode = O_MACADDR2;
3227         cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3228         CHECK_CMDLEN;
3229
3230         mac = (ipfw_insn_mac *)cmd;
3231         get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3232         get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3233             &(mac->mask[ETHER_ADDR_LEN])); /* src */
3234         return cmd;
3235 }
3236
3237 static ipfw_insn *
3238 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3239 {
3240         if (!av)
3241                 errx(EX_DATAERR, "missing MAC type");
3242         if (strcmp(av, "any") != 0) { /* we have a non-null type */
3243                 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3244                     cblen);
3245                 cmd->opcode = O_MAC_TYPE;
3246                 return cmd;
3247         } else
3248                 return NULL;
3249 }
3250
3251 static ipfw_insn *
3252 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3253 {
3254         struct protoent *pe;
3255         char *ep;
3256         int proto;
3257
3258         proto = strtol(av, &ep, 10);
3259         if (*ep != '\0' || proto <= 0) {
3260                 if ((pe = getprotobyname(av)) == NULL)
3261                         return NULL;
3262                 proto = pe->p_proto;
3263         }
3264
3265         fill_cmd(cmd, O_PROTO, 0, proto);
3266         *protop = proto;
3267         return cmd;
3268 }
3269
3270 static ipfw_insn *
3271 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3272 {
3273         u_char proto = IPPROTO_IP;
3274
3275         if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3276                 ; /* do not set O_IP4 nor O_IP6 */
3277         else if (strcmp(av, "ip4") == 0)
3278                 /* explicit "just IPv4" rule */
3279                 fill_cmd(cmd, O_IP4, 0, 0);
3280         else if (strcmp(av, "ip6") == 0) {
3281                 /* explicit "just IPv6" rule */
3282                 proto = IPPROTO_IPV6;
3283                 fill_cmd(cmd, O_IP6, 0, 0);
3284         } else
3285                 return add_proto0(cmd, av, protop);
3286
3287         *protop = proto;
3288         return cmd;
3289 }
3290
3291 static ipfw_insn *
3292 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3293 {
3294         u_char proto = IPPROTO_IP;
3295
3296         if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3297                 ; /* do not set O_IP4 nor O_IP6 */
3298         else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3299                 /* explicit "just IPv4" rule */
3300                 fill_cmd(cmd, O_IP4, 0, 0);
3301         else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3302                 /* explicit "just IPv6" rule */
3303                 proto = IPPROTO_IPV6;
3304                 fill_cmd(cmd, O_IP6, 0, 0);
3305         } else
3306                 return add_proto0(cmd, av, protop);
3307
3308         *protop = proto;
3309         return cmd;
3310 }
3311
3312 static ipfw_insn *
3313 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3314 {
3315         fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3316         if (cmd->opcode == O_IP_DST_SET)                        /* set */
3317                 cmd->opcode = O_IP_SRC_SET;
3318         else if (cmd->opcode == O_IP_DST_LOOKUP)                /* table */
3319                 cmd->opcode = O_IP_SRC_LOOKUP;
3320         else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))          /* me */
3321                 cmd->opcode = O_IP_SRC_ME;
3322         else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))      /* one IP */
3323                 cmd->opcode = O_IP_SRC;
3324         else                                                    /* addr/mask */
3325                 cmd->opcode = O_IP_SRC_MASK;
3326         return cmd;
3327 }
3328
3329 static ipfw_insn *
3330 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3331 {
3332         fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3333         if (cmd->opcode == O_IP_DST_SET)                        /* set */
3334                 ;
3335         else if (cmd->opcode == O_IP_DST_LOOKUP)                /* table */
3336                 ;
3337         else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))          /* me */
3338                 cmd->opcode = O_IP_DST_ME;
3339         else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))      /* one IP */
3340                 cmd->opcode = O_IP_DST;
3341         else                                                    /* addr/mask */
3342                 cmd->opcode = O_IP_DST_MASK;
3343         return cmd;
3344 }
3345
3346 static ipfw_insn *
3347 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3348 {
3349         /* XXX "any" is trapped before. Perhaps "to" */
3350         if (_substrcmp(av, "any") == 0) {
3351                 return NULL;
3352         } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3353                 /* XXX todo: check that we have a protocol with ports */
3354                 cmd->opcode = opcode;
3355                 return cmd;
3356         }
3357         return NULL;
3358 }
3359
3360 static ipfw_insn *
3361 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3362 {
3363         struct in6_addr a;
3364         char *host, *ch, buf[INET6_ADDRSTRLEN];
3365         ipfw_insn *ret = NULL;
3366         int len;
3367
3368         /* Copy first address in set if needed */
3369         if ((ch = strpbrk(av, "/,")) != NULL) {
3370                 len = ch - av;
3371                 strlcpy(buf, av, sizeof(buf));
3372                 if (len < sizeof(buf))
3373                         buf[len] = '\0';
3374                 host = buf;
3375         } else
3376                 host = av;
3377
3378         if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3379             inet_pton(AF_INET6, host, &a) == 1)
3380                 ret = add_srcip6(cmd, av, cblen);
3381         /* XXX: should check for IPv4, not !IPv6 */
3382         if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3383             inet_pton(AF_INET6, host, &a) != 1))
3384                 ret = add_srcip(cmd, av, cblen, tstate);
3385         if (ret == NULL && strcmp(av, "any") != 0)
3386                 ret = cmd;
3387
3388         return ret;
3389 }
3390
3391 static ipfw_insn *
3392 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3393 {
3394         struct in6_addr a;
3395         char *host, *ch, buf[INET6_ADDRSTRLEN];
3396         ipfw_insn *ret = NULL;
3397         int len;
3398
3399         /* Copy first address in set if needed */
3400         if ((ch = strpbrk(av, "/,")) != NULL) {
3401                 len = ch - av;
3402                 strlcpy(buf, av, sizeof(buf));
3403                 if (len < sizeof(buf))
3404                         buf[len] = '\0';
3405                 host = buf;
3406         } else
3407                 host = av;
3408
3409         if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
3410             inet_pton(AF_INET6, host, &a) == 1)
3411                 ret = add_dstip6(cmd, av, cblen);
3412         /* XXX: should check for IPv4, not !IPv6 */
3413         if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3414             inet_pton(AF_INET6, host, &a) != 1))
3415                 ret = add_dstip(cmd, av, cblen, tstate);
3416         if (ret == NULL && strcmp(av, "any") != 0)
3417                 ret = cmd;
3418
3419         return ret;
3420 }
3421
3422 /*
3423  * Parse arguments and assemble the microinstructions which make up a rule.
3424  * Rules are added into the 'rulebuf' and then copied in the correct order
3425  * into the actual rule.
3426  *
3427  * The syntax for a rule starts with the action, followed by
3428  * optional action parameters, and the various match patterns.
3429  * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3430  * (generated if the rule includes a keep-state option), then the
3431  * various match patterns, log/altq actions, and the actual action.
3432  *
3433  */
3434 void
3435 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3436 {
3437         /*
3438          * rules are added into the 'rulebuf' and then copied in
3439          * the correct order into the actual rule.
3440          * Some things that need to go out of order (prob, action etc.)
3441          * go into actbuf[].
3442          */
3443         static uint32_t actbuf[255], cmdbuf[255];
3444         int rblen, ablen, cblen;
3445
3446         ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3447         ipfw_insn *first_cmd;   /* first match pattern */
3448
3449         struct ip_fw_rule *rule;
3450
3451         /*
3452          * various flags used to record that we entered some fields.
3453          */
3454         ipfw_insn *have_state = NULL;   /* check-state or keep-state */
3455         ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3456         size_t len;
3457
3458         int i;
3459
3460         int open_par = 0;       /* open parenthesis ( */
3461
3462         /* proto is here because it is used to fetch ports */
3463         u_char proto = IPPROTO_IP;      /* default protocol */
3464
3465         double match_prob = 1; /* match probability, default is always match */
3466
3467         bzero(actbuf, sizeof(actbuf));          /* actions go here */
3468         bzero(cmdbuf, sizeof(cmdbuf));
3469         bzero(rbuf, *rbufsize);
3470
3471         rule = (struct ip_fw_rule *)rbuf;
3472         cmd = (ipfw_insn *)cmdbuf;
3473         action = (ipfw_insn *)actbuf;
3474
3475         rblen = *rbufsize / sizeof(uint32_t);
3476         rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3477         ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3478         cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3479         cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3480
3481 #define CHECK_RBUFLEN(len)      { CHECK_LENGTH(rblen, len); rblen -= len; }
3482 #define CHECK_ACTLEN            CHECK_LENGTH(ablen, action->len)
3483
3484         av++;
3485
3486         /* [rule N]     -- Rule number optional */
3487         if (av[0] && isdigit(**av)) {
3488                 rule->rulenum = atoi(*av);
3489                 av++;
3490         }
3491
3492         /* [set N]      -- set number (0..RESVD_SET), optional */
3493         if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3494                 int set = strtoul(av[1], NULL, 10);
3495                 if (set < 0 || set > RESVD_SET)
3496                         errx(EX_DATAERR, "illegal set %s", av[1]);
3497                 rule->set = set;
3498                 tstate->set = set;
3499                 av += 2;
3500         }
3501
3502         /* [prob D]     -- match probability, optional */
3503         if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3504                 match_prob = strtod(av[1], NULL);
3505
3506                 if (match_prob <= 0 || match_prob > 1)
3507                         errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3508                 av += 2;
3509         }
3510
3511         /* action       -- mandatory */
3512         NEED1("missing action");
3513         i = match_token(rule_actions, *av);
3514         av++;
3515         action->len = 1;        /* default */
3516         CHECK_ACTLEN;
3517         switch(i) {
3518         case TOK_CHECKSTATE:
3519                 have_state = action;
3520                 action->opcode = O_CHECK_STATE;
3521                 break;
3522
3523         case TOK_ACCEPT:
3524                 action->opcode = O_ACCEPT;
3525                 break;
3526
3527         case TOK_DENY:
3528                 action->opcode = O_DENY;
3529                 action->arg1 = 0;
3530                 break;
3531
3532         case TOK_REJECT:
3533                 action->opcode = O_REJECT;
3534                 action->arg1 = ICMP_UNREACH_HOST;
3535                 break;
3536
3537         case TOK_RESET:
3538                 action->opcode = O_REJECT;
3539                 action->arg1 = ICMP_REJECT_RST;
3540                 break;
3541
3542         case TOK_RESET6:
3543                 action->opcode = O_UNREACH6;
3544                 action->arg1 = ICMP6_UNREACH_RST;
3545                 break;
3546
3547         case TOK_UNREACH:
3548                 action->opcode = O_REJECT;
3549                 NEED1("missing reject code");
3550                 fill_reject_code(&action->arg1, *av);
3551                 av++;
3552                 break;
3553
3554         case TOK_UNREACH6:
3555                 action->opcode = O_UNREACH6;
3556                 NEED1("missing unreach code");
3557                 fill_unreach6_code(&action->arg1, *av);
3558                 av++;
3559                 break;
3560
3561         case TOK_COUNT:
3562                 action->opcode = O_COUNT;
3563                 break;
3564
3565         case TOK_NAT:
3566                 action->opcode = O_NAT;
3567                 action->len = F_INSN_SIZE(ipfw_insn_nat);
3568                 CHECK_ACTLEN;
3569                 if (_substrcmp(*av, "global") == 0) {
3570                         action->arg1 = 0;
3571                         av++;
3572                         break;
3573                 } else
3574                         goto chkarg;
3575
3576         case TOK_QUEUE:
3577                 action->opcode = O_QUEUE;
3578                 goto chkarg;
3579         case TOK_PIPE:
3580                 action->opcode = O_PIPE;
3581                 goto chkarg;
3582         case TOK_SKIPTO:
3583                 action->opcode = O_SKIPTO;
3584                 goto chkarg;
3585         case TOK_NETGRAPH:
3586                 action->opcode = O_NETGRAPH;
3587                 goto chkarg;
3588         case TOK_NGTEE:
3589                 action->opcode = O_NGTEE;
3590                 goto chkarg;
3591         case TOK_DIVERT:
3592                 action->opcode = O_DIVERT;
3593                 goto chkarg;
3594         case TOK_TEE:
3595                 action->opcode = O_TEE;
3596                 goto chkarg;
3597         case TOK_CALL:
3598                 action->opcode = O_CALLRETURN;
3599 chkarg:
3600                 if (!av[0])
3601                         errx(EX_USAGE, "missing argument for %s", *(av - 1));
3602                 if (isdigit(**av)) {
3603                         action->arg1 = strtoul(*av, NULL, 10);
3604                         if (action->arg1 <= 0 || action->arg1 >= IP_FW_TARG)
3605                                 errx(EX_DATAERR, "illegal argument for %s",
3606                                     *(av - 1));
3607                 } else if (_substrcmp(*av, "tablearg") == 0) {
3608                         action->arg1 = IP_FW_TARG;
3609                 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3610                         struct servent *s;
3611                         setservent(1);
3612                         s = getservbyname(av[0], "divert");
3613                         if (s != NULL)
3614                                 action->arg1 = ntohs(s->s_port);
3615                         else
3616                                 errx(EX_DATAERR, "illegal divert/tee port");
3617                 } else
3618                         errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3619                 av++;
3620                 break;
3621
3622         case TOK_FORWARD: {
3623                 /*
3624                  * Locate the address-port separator (':' or ',').
3625                  * Could be one of the following:
3626                  *      hostname:port
3627                  *      IPv4 a.b.c.d,port
3628                  *      IPv4 a.b.c.d:port
3629                  *      IPv6 w:x:y::z,port
3630                  * The ':' can only be used with hostname and IPv4 address.
3631                  * XXX-BZ Should we also support [w:x:y::z]:port?
3632                  */
3633                 struct sockaddr_storage result;
3634                 struct addrinfo *res;
3635                 char *s, *end;
3636                 int family;
3637                 u_short port_number;
3638
3639                 NEED1("missing forward address[:port]");
3640
3641                 /*
3642                  * locate the address-port separator (':' or ',')
3643                  */
3644                 s = strchr(*av, ',');
3645                 if (s == NULL) {
3646                         /* Distinguish between IPv4:port and IPv6 cases. */
3647                         s = strchr(*av, ':');
3648                         if (s && strchr(s+1, ':'))
3649                                 s = NULL; /* no port */
3650                 }
3651
3652                 port_number = 0;
3653                 if (s != NULL) {
3654                         /* Terminate host portion and set s to start of port. */
3655                         *(s++) = '\0';
3656                         i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3657                         if (s == end)
3658                                 errx(EX_DATAERR,
3659                                     "illegal forwarding port ``%s''", s);
3660                         port_number = (u_short)i;
3661                 }
3662
3663                 if (_substrcmp(*av, "tablearg") == 0) {
3664                         family = PF_INET;
3665                         ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3666                             INADDR_ANY;
3667                 } else {
3668                         /*
3669                          * Resolve the host name or address to a family and a
3670                          * network representation of the address.
3671                          */
3672                         if (getaddrinfo(*av, NULL, NULL, &res))
3673                                 errx(EX_DATAERR, NULL);
3674                         /* Just use the first host in the answer. */
3675                         family = res->ai_family;
3676                         memcpy(&result, res->ai_addr, res->ai_addrlen);
3677                         freeaddrinfo(res);
3678                 }
3679
3680                 if (family == PF_INET) {
3681                         ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3682
3683                         action->opcode = O_FORWARD_IP;
3684                         action->len = F_INSN_SIZE(ipfw_insn_sa);
3685                         CHECK_ACTLEN;
3686
3687                         /*
3688                          * In the kernel we assume AF_INET and use only
3689                          * sin_port and sin_addr. Remember to set sin_len as
3690                          * the routing code seems to use it too.
3691                          */
3692                         p->sa.sin_len = sizeof(struct sockaddr_in);
3693                         p->sa.sin_family = AF_INET;
3694                         p->sa.sin_port = port_number;
3695                         p->sa.sin_addr.s_addr =
3696                              ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3697                 } else if (family == PF_INET6) {
3698                         ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3699
3700                         action->opcode = O_FORWARD_IP6;
3701                         action->len = F_INSN_SIZE(ipfw_insn_sa6);
3702                         CHECK_ACTLEN;
3703
3704                         p->sa.sin6_len = sizeof(struct sockaddr_in6);
3705                         p->sa.sin6_family = AF_INET6;
3706                         p->sa.sin6_port = port_number;
3707                         p->sa.sin6_flowinfo = 0;
3708                         p->sa.sin6_scope_id = 0;
3709                         /* No table support for v6 yet. */
3710                         bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3711                             &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3712                 } else {
3713                         errx(EX_DATAERR, "Invalid address family in forward action");
3714                 }
3715                 av++;
3716                 break;
3717             }
3718         case TOK_COMMENT:
3719                 /* pretend it is a 'count' rule followed by the comment */
3720                 action->opcode = O_COUNT;
3721                 av--;           /* go back... */
3722                 break;
3723
3724         case TOK_SETFIB:
3725             {
3726                 int numfibs;
3727                 size_t intsize = sizeof(int);
3728
3729                 action->opcode = O_SETFIB;
3730                 NEED1("missing fib number");
3731                 if (_substrcmp(*av, "tablearg") == 0) {
3732                         action->arg1 = IP_FW_TARG;
3733                 } else {
3734                         action->arg1 = strtoul(*av, NULL, 10);
3735                         if (sysctlbyname("net.fibs", &numfibs, &intsize,
3736                             NULL, 0) == -1)
3737                                 errx(EX_DATAERR, "fibs not suported.\n");
3738                         if (action->arg1 >= numfibs)  /* Temporary */
3739                                 errx(EX_DATAERR, "fib too large.\n");
3740                         /* Add high-order bit to fib to make room for tablearg*/
3741                         action->arg1 |= 0x8000;
3742                 }
3743                 av++;
3744                 break;
3745             }
3746
3747         case TOK_SETDSCP:
3748             {
3749                 int code;
3750
3751                 action->opcode = O_SETDSCP;
3752                 NEED1("missing DSCP code");
3753                 if (_substrcmp(*av, "tablearg") == 0) {
3754                         action->arg1 = IP_FW_TARG;
3755                 } else if (isalpha(*av[0])) {
3756                         if ((code = match_token(f_ipdscp, *av)) == -1)
3757                                 errx(EX_DATAERR, "Unknown DSCP code");
3758                         action->arg1 = code;
3759                 } else
3760                         action->arg1 = strtoul(*av, NULL, 10);
3761                 /* Add high-order bit to DSCP to make room for tablearg */
3762                 if (action->arg1 != IP_FW_TARG)
3763                         action->arg1 |= 0x8000;
3764                 av++;
3765                 break;
3766             }
3767
3768         case TOK_REASS:
3769                 action->opcode = O_REASS;
3770                 break;
3771
3772         case TOK_RETURN:
3773                 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3774                 break;
3775
3776         default:
3777                 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3778         }
3779         action = next_cmd(action, &ablen);
3780
3781         /*
3782          * [altq queuename] -- altq tag, optional
3783          * [log [logamount N]]  -- log, optional
3784          *
3785          * If they exist, it go first in the cmdbuf, but then it is
3786          * skipped in the copy section to the end of the buffer.
3787          */
3788         while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
3789                 av++;
3790                 switch (i) {
3791                 case TOK_LOG:
3792                     {
3793                         ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3794                         int l;
3795
3796                         if (have_log)
3797                                 errx(EX_DATAERR,
3798                                     "log cannot be specified more than once");
3799                         have_log = (ipfw_insn *)c;
3800                         cmd->len = F_INSN_SIZE(ipfw_insn_log);
3801                         CHECK_CMDLEN;
3802                         cmd->opcode = O_LOG;
3803                         if (av[0] && _substrcmp(*av, "logamount") == 0) {
3804                                 av++;
3805                                 NEED1("logamount requires argument");
3806                                 l = atoi(*av);
3807                                 if (l < 0)
3808                                         errx(EX_DATAERR,
3809                                             "logamount must be positive");
3810                                 c->max_log = l;
3811                                 av++;
3812                         } else {
3813                                 len = sizeof(c->max_log);
3814                                 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3815                                     &c->max_log, &len, NULL, 0) == -1) {
3816                                         if (co.test_only) {
3817                                                 c->max_log = 0;
3818                                                 break;
3819                                         }
3820                                         errx(1, "sysctlbyname(\"%s\")",
3821                                             "net.inet.ip.fw.verbose_limit");
3822                                 }
3823                         }
3824                     }
3825                         break;
3826
3827 #ifndef NO_ALTQ
3828                 case TOK_ALTQ:
3829                     {
3830                         ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3831
3832                         NEED1("missing altq queue name");
3833                         if (have_altq)
3834                                 errx(EX_DATAERR,
3835                                     "altq cannot be specified more than once");
3836                         have_altq = (ipfw_insn *)a;
3837                         cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3838                         CHECK_CMDLEN;
3839                         cmd->opcode = O_ALTQ;
3840                         a->qid = altq_name_to_qid(*av);
3841                         av++;
3842                     }
3843                         break;
3844 #endif
3845
3846                 case TOK_TAG:
3847                 case TOK_UNTAG: {
3848                         uint16_t tag;
3849
3850                         if (have_tag)
3851                                 errx(EX_USAGE, "tag and untag cannot be "
3852                                     "specified more than once");
3853                         GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3854                            rule_action_params);
3855                         have_tag = cmd;
3856                         fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3857                         av++;
3858                         break;
3859                 }
3860
3861                 default:
3862                         abort();
3863                 }
3864                 cmd = next_cmd(cmd, &cblen);
3865         }
3866
3867         if (have_state) /* must be a check-state, we are done */
3868                 goto done;
3869
3870 #define OR_START(target)                                        \
3871         if (av[0] && (*av[0] == '(' || *av[0] == '{')) {        \
3872                 if (open_par)                                   \
3873                         errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3874                 prev = NULL;                                    \
3875                 open_par = 1;                                   \
3876                 if ( (av[0])[1] == '\0') {                      \
3877                         av++;                                   \
3878                 } else                                          \
3879                         (*av)++;                                \
3880         }                                                       \
3881         target:                                                 \
3882
3883
3884 #define CLOSE_PAR                                               \
3885         if (open_par) {                                         \
3886                 if (av[0] && (                                  \
3887                     strcmp(*av, ")") == 0 ||                    \
3888                     strcmp(*av, "}") == 0)) {                   \
3889                         prev = NULL;                            \
3890                         open_par = 0;                           \
3891                         av++;                                   \
3892                 } else                                          \
3893                         errx(EX_USAGE, "missing \")\"\n");      \
3894         }
3895
3896 #define NOT_BLOCK                                               \
3897         if (av[0] && _substrcmp(*av, "not") == 0) {             \
3898                 if (cmd->len & F_NOT)                           \
3899                         errx(EX_USAGE, "double \"not\" not allowed\n"); \
3900                 cmd->len |= F_NOT;                              \
3901                 av++;                                           \
3902         }
3903
3904 #define OR_BLOCK(target)                                        \
3905         if (av[0] && _substrcmp(*av, "or") == 0) {              \
3906                 if (prev == NULL || open_par == 0)              \
3907                         errx(EX_DATAERR, "invalid OR block");   \
3908                 prev->len |= F_OR;                              \
3909                 av++;                                   \
3910                 goto target;                                    \
3911         }                                                       \
3912         CLOSE_PAR;
3913
3914         first_cmd = cmd;
3915
3916 #if 0
3917         /*
3918          * MAC addresses, optional.
3919          * If we have this, we skip the part "proto from src to dst"
3920          * and jump straight to the option parsing.
3921          */
3922         NOT_BLOCK;
3923         NEED1("missing protocol");
3924         if (_substrcmp(*av, "MAC") == 0 ||
3925             _substrcmp(*av, "mac") == 0) {
3926                 av++;                   /* the "MAC" keyword */
3927                 add_mac(cmd, av);       /* exits in case of errors */
3928                 cmd = next_cmd(cmd);
3929                 av += 2;                /* dst-mac and src-mac */
3930                 NOT_BLOCK;
3931                 NEED1("missing mac type");
3932                 if (add_mactype(cmd, av[0]))
3933                         cmd = next_cmd(cmd);
3934                 av++;                   /* any or mac-type */
3935                 goto read_options;
3936         }
3937 #endif
3938
3939         /*
3940          * protocol, mandatory
3941          */
3942     OR_START(get_proto);
3943         NOT_BLOCK;
3944         NEED1("missing protocol");
3945         if (add_proto_compat(cmd, *av, &proto)) {
3946                 av++;
3947                 if (F_LEN(cmd) != 0) {
3948                         prev = cmd;
3949                         cmd = next_cmd(cmd, &cblen);
3950                 }
3951         } else if (first_cmd != cmd) {
3952                 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3953         } else
3954                 goto read_options;
3955     OR_BLOCK(get_proto);
3956
3957         /*
3958          * "from", mandatory
3959          */
3960         if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3961                 errx(EX_USAGE, "missing ``from''");
3962         av++;
3963
3964         /*
3965          * source IP, mandatory
3966          */
3967     OR_START(source_ip);
3968         NOT_BLOCK;      /* optional "not" */
3969         NEED1("missing source address");
3970         if (add_src(cmd, *av, proto, cblen, tstate)) {
3971                 av++;
3972                 if (F_LEN(cmd) != 0) {  /* ! any */
3973                         prev = cmd;
3974                         cmd = next_cmd(cmd, &cblen);
3975                 }
3976         } else
3977                 errx(EX_USAGE, "bad source address %s", *av);
3978     OR_BLOCK(source_ip);
3979
3980         /*
3981          * source ports, optional
3982          */
3983         NOT_BLOCK;      /* optional "not" */
3984         if ( av[0] != NULL ) {
3985                 if (_substrcmp(*av, "any") == 0 ||
3986                     add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3987                         av++;
3988                         if (F_LEN(cmd) != 0)
3989                                 cmd = next_cmd(cmd, &cblen);
3990                 }
3991         }
3992
3993         /*
3994          * "to", mandatory
3995          */
3996         if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3997                 errx(EX_USAGE, "missing ``to''");
3998         av++;
3999
4000         /*
4001          * destination, mandatory
4002          */
4003     OR_START(dest_ip);
4004         NOT_BLOCK;      /* optional "not" */
4005         NEED1("missing dst address");
4006         if (add_dst(cmd, *av, proto, cblen, tstate)) {
4007                 av++;
4008                 if (F_LEN(cmd) != 0) {  /* ! any */
4009                         prev = cmd;
4010                         cmd = next_cmd(cmd, &cblen);
4011                 }
4012         } else
4013                 errx( EX_USAGE, "bad destination address %s", *av);
4014     OR_BLOCK(dest_ip);
4015
4016         /*
4017          * dest. ports, optional
4018          */
4019         NOT_BLOCK;      /* optional "not" */
4020         if (av[0]) {
4021                 if (_substrcmp(*av, "any") == 0 ||
4022                     add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4023                         av++;
4024                         if (F_LEN(cmd) != 0)
4025                                 cmd = next_cmd(cmd, &cblen);
4026                 }
4027         }
4028
4029 read_options:
4030         if (av[0] && first_cmd == cmd) {
4031                 /*
4032                  * nothing specified so far, store in the rule to ease
4033                  * printout later.
4034                  */
4035                  rule->flags |= IPFW_RULE_NOOPT;
4036         }
4037         prev = NULL;
4038         while ( av[0] != NULL ) {
4039                 char *s;
4040                 ipfw_insn_u32 *cmd32;   /* alias for cmd */
4041
4042                 s = *av;
4043                 cmd32 = (ipfw_insn_u32 *)cmd;
4044
4045                 if (*s == '!') {        /* alternate syntax for NOT */
4046                         if (cmd->len & F_NOT)
4047                                 errx(EX_USAGE, "double \"not\" not allowed\n");
4048                         cmd->len = F_NOT;
4049                         s++;
4050                 }
4051                 i = match_token(rule_options, s);
4052                 av++;
4053                 switch(i) {
4054                 case TOK_NOT:
4055                         if (cmd->len & F_NOT)
4056                                 errx(EX_USAGE, "double \"not\" not allowed\n");
4057                         cmd->len = F_NOT;
4058                         break;
4059
4060                 case TOK_OR:
4061                         if (open_par == 0 || prev == NULL)
4062                                 errx(EX_USAGE, "invalid \"or\" block\n");
4063                         prev->len |= F_OR;
4064                         break;
4065
4066                 case TOK_STARTBRACE:
4067                         if (open_par)
4068                                 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4069                         open_par = 1;
4070                         break;
4071
4072                 case TOK_ENDBRACE:
4073                         if (!open_par)
4074                                 errx(EX_USAGE, "+missing \")\"\n");
4075                         open_par = 0;
4076                         prev = NULL;
4077                         break;
4078
4079                 case TOK_IN:
4080                         fill_cmd(cmd, O_IN, 0, 0);
4081                         break;
4082
4083                 case TOK_OUT:
4084                         cmd->len ^= F_NOT; /* toggle F_NOT */
4085                         fill_cmd(cmd, O_IN, 0, 0);
4086                         break;
4087
4088                 case TOK_DIVERTED:
4089                         fill_cmd(cmd, O_DIVERTED, 0, 3);
4090                         break;
4091
4092                 case TOK_DIVERTEDLOOPBACK:
4093                         fill_cmd(cmd, O_DIVERTED, 0, 1);
4094                         break;
4095
4096                 case TOK_DIVERTEDOUTPUT:
4097                         fill_cmd(cmd, O_DIVERTED, 0, 2);
4098                         break;
4099
4100                 case TOK_FRAG:
4101                         fill_cmd(cmd, O_FRAG, 0, 0);
4102                         break;
4103
4104                 case TOK_LAYER2:
4105                         fill_cmd(cmd, O_LAYER2, 0, 0);
4106                         break;
4107
4108                 case TOK_XMIT:
4109                 case TOK_RECV:
4110                 case TOK_VIA:
4111                         NEED1("recv, xmit, via require interface name"
4112                                 " or address");
4113                         fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4114                         av++;
4115                         if (F_LEN(cmd) == 0)    /* not a valid address */
4116                                 break;
4117                         if (i == TOK_XMIT)
4118                                 cmd->opcode = O_XMIT;
4119                         else if (i == TOK_RECV)
4120                                 cmd->opcode = O_RECV;
4121                         else if (i == TOK_VIA)
4122                                 cmd->opcode = O_VIA;
4123                         break;
4124
4125                 case TOK_ICMPTYPES:
4126                         NEED1("icmptypes requires list of types");
4127                         fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4128                         av++;
4129                         break;
4130
4131                 case TOK_ICMP6TYPES:
4132                         NEED1("icmptypes requires list of types");
4133                         fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4134                         av++;
4135                         break;
4136
4137                 case TOK_IPTTL:
4138                         NEED1("ipttl requires TTL");
4139                         if (strpbrk(*av, "-,")) {
4140                             if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4141                                 errx(EX_DATAERR, "invalid ipttl %s", *av);
4142                         } else
4143                             fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4144                         av++;
4145                         break;
4146
4147                 case TOK_IPID:
4148                         NEED1("ipid requires id");
4149                         if (strpbrk(*av, "-,")) {
4150                             if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4151                                 errx(EX_DATAERR, "invalid ipid %s", *av);
4152                         } else
4153                             fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4154                         av++;
4155                         break;
4156
4157                 case TOK_IPLEN:
4158                         NEED1("iplen requires length");
4159                         if (strpbrk(*av, "-,")) {
4160                             if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4161                                 errx(EX_DATAERR, "invalid ip len %s", *av);
4162                         } else
4163                             fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4164                         av++;
4165                         break;
4166
4167                 case TOK_IPVER:
4168                         NEED1("ipver requires version");
4169                         fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4170                         av++;
4171                         break;
4172
4173                 case TOK_IPPRECEDENCE:
4174                         NEED1("ipprecedence requires value");
4175                         fill_cmd(cmd, O_IPPRECEDENCE, 0,
4176                             (strtoul(*av, NULL, 0) & 7) << 5);
4177                         av++;
4178                         break;
4179
4180                 case TOK_DSCP:
4181                         NEED1("missing DSCP code");
4182                         fill_dscp(cmd, *av, cblen);
4183                         av++;
4184                         break;
4185
4186                 case TOK_IPOPTS:
4187                         NEED1("missing argument for ipoptions");
4188                         fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4189                         av++;
4190                         break;
4191
4192                 case TOK_IPTOS:
4193                         NEED1("missing argument for iptos");
4194                         fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4195                         av++;
4196                         break;
4197
4198                 case TOK_UID:
4199                         NEED1("uid requires argument");
4200                     {
4201                         char *end;
4202                         uid_t uid;
4203                         struct passwd *pwd;
4204
4205                         cmd->opcode = O_UID;
4206                         uid = strtoul(*av, &end, 0);
4207                         pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4208                         if (pwd == NULL)
4209                                 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4210                         cmd32->d[0] = pwd->pw_uid;
4211                         cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4212                         av++;
4213                     }
4214                         break;
4215
4216                 case TOK_GID:
4217                         NEED1("gid requires argument");
4218                     {
4219                         char *end;
4220                         gid_t gid;
4221                         struct group *grp;
4222
4223                         cmd->opcode = O_GID;
4224                         gid = strtoul(*av, &end, 0);
4225                         grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4226                         if (grp == NULL)
4227                                 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4228                         cmd32->d[0] = grp->gr_gid;
4229                         cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4230                         av++;
4231                     }
4232                         break;
4233
4234                 case TOK_JAIL:
4235                         NEED1("jail requires argument");
4236                     {
4237                         char *end;
4238                         int jid;
4239
4240                         cmd->opcode = O_JAIL;
4241                         jid = (int)strtol(*av, &end, 0);
4242                         if (jid < 0 || *end != '\0')
4243                                 errx(EX_DATAERR, "jail requires prison ID");
4244                         cmd32->d[0] = (uint32_t)jid;
4245                         cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4246                         av++;
4247                     }
4248                         break;
4249
4250                 case TOK_ESTAB:
4251                         fill_cmd(cmd, O_ESTAB, 0, 0);
4252                         break;
4253
4254                 case TOK_SETUP:
4255                         fill_cmd(cmd, O_TCPFLAGS, 0,
4256                                 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4257                         break;
4258
4259                 case TOK_TCPDATALEN:
4260                         NEED1("tcpdatalen requires length");
4261                         if (strpbrk(*av, "-,")) {
4262                             if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4263                                 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4264                         } else
4265                             fill_cmd(cmd, O_TCPDATALEN, 0,
4266                                     strtoul(*av, NULL, 0));
4267                         av++;
4268                         break;
4269
4270                 case TOK_TCPOPTS:
4271                         NEED1("missing argument for tcpoptions");
4272                         fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4273                         av++;
4274                         break;
4275
4276                 case TOK_TCPSEQ:
4277                 case TOK_TCPACK:
4278                         NEED1("tcpseq/tcpack requires argument");
4279                         cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4280                         cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4281                         cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4282                         av++;
4283                         break;
4284
4285                 case TOK_TCPWIN:
4286                         NEED1("tcpwin requires length");
4287                         if (strpbrk(*av, "-,")) {
4288                             if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4289                                 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4290                         } else
4291                             fill_cmd(cmd, O_TCPWIN, 0,
4292                                     strtoul(*av, NULL, 0));
4293                         av++;
4294                         break;
4295
4296                 case TOK_TCPFLAGS:
4297                         NEED1("missing argument for tcpflags");
4298                         cmd->opcode = O_TCPFLAGS;
4299                         fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4300                         av++;
4301                         break;
4302
4303                 case TOK_KEEPSTATE:
4304                         if (open_par)
4305                                 errx(EX_USAGE, "keep-state cannot be part "
4306                                     "of an or block");
4307                         if (have_state)
4308                                 errx(EX_USAGE, "only one of keep-state "
4309                                         "and limit is allowed");
4310                         have_state = cmd;
4311                         fill_cmd(cmd, O_KEEP_STATE, 0, 0);
4312                         break;
4313
4314                 case TOK_LIMIT: {
4315                         ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4316                         int val;
4317
4318                         if (open_par)
4319                                 errx(EX_USAGE,
4320                                     "limit cannot be part of an or block");
4321                         if (have_state)
4322                                 errx(EX_USAGE, "only one of keep-state and "
4323                                     "limit is allowed");
4324                         have_state = cmd;
4325
4326                         cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4327                         CHECK_CMDLEN;
4328                         cmd->opcode = O_LIMIT;
4329                         c->limit_mask = c->conn_limit = 0;
4330
4331                         while ( av[0] != NULL ) {
4332                                 if ((val = match_token(limit_masks, *av)) <= 0)
4333                                         break;
4334                                 c->limit_mask |= val;
4335                                 av++;
4336                         }
4337
4338                         if (c->limit_mask == 0)
4339                                 errx(EX_USAGE, "limit: missing limit mask");
4340
4341                         GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4342                             TOK_LIMIT, rule_options);
4343
4344                         av++;
4345                         break;
4346                 }
4347
4348                 case TOK_PROTO:
4349                         NEED1("missing protocol");
4350                         if (add_proto(cmd, *av, &proto)) {
4351                                 av++;
4352                         } else
4353                                 errx(EX_DATAERR, "invalid protocol ``%s''",
4354                                     *av);
4355                         break;
4356
4357                 case TOK_SRCIP:
4358                         NEED1("missing source IP");
4359                         if (add_srcip(cmd, *av, cblen, tstate)) {
4360                                 av++;
4361                         }
4362                         break;
4363
4364                 case TOK_DSTIP:
4365                         NEED1("missing destination IP");
4366                         if (add_dstip(cmd, *av, cblen, tstate)) {
4367                                 av++;
4368                         }
4369                         break;
4370
4371                 case TOK_SRCIP6:
4372                         NEED1("missing source IP6");
4373                         if (add_srcip6(cmd, *av, cblen)) {
4374                                 av++;
4375                         }
4376                         break;
4377
4378                 case TOK_DSTIP6:
4379                         NEED1("missing destination IP6");
4380                         if (add_dstip6(cmd, *av, cblen)) {
4381                                 av++;
4382                         }
4383                         break;
4384
4385                 case TOK_SRCPORT:
4386                         NEED1("missing source port");
4387                         if (_substrcmp(*av, "any") == 0 ||
4388                             add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4389                                 av++;
4390                         } else
4391                                 errx(EX_DATAERR, "invalid source port %s", *av);
4392                         break;
4393
4394                 case TOK_DSTPORT:
4395                         NEED1("missing destination port");
4396                         if (_substrcmp(*av, "any") == 0 ||
4397                             add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4398                                 av++;
4399                         } else
4400                                 errx(EX_DATAERR, "invalid destination port %s",
4401                                     *av);
4402                         break;
4403
4404                 case TOK_MAC:
4405                         if (add_mac(cmd, av, cblen))
4406                                 av += 2;
4407                         break;
4408
4409                 case TOK_MACTYPE:
4410                         NEED1("missing mac type");
4411                         if (!add_mactype(cmd, *av, cblen))
4412                                 errx(EX_DATAERR, "invalid mac type %s", *av);
4413                         av++;
4414                         break;
4415
4416                 case TOK_VERREVPATH:
4417                         fill_cmd(cmd, O_VERREVPATH, 0, 0);
4418                         break;
4419
4420                 case TOK_VERSRCREACH:
4421                         fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4422                         break;
4423
4424                 case TOK_ANTISPOOF:
4425                         fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4426                         break;
4427
4428                 case TOK_IPSEC:
4429                         fill_cmd(cmd, O_IPSEC, 0, 0);
4430                         break;
4431
4432                 case TOK_IPV6:
4433                         fill_cmd(cmd, O_IP6, 0, 0);
4434                         break;
4435
4436                 case TOK_IPV4:
4437                         fill_cmd(cmd, O_IP4, 0, 0);
4438                         break;
4439
4440                 case TOK_EXT6HDR:
4441                         fill_ext6hdr( cmd, *av );
4442                         av++;
4443                         break;
4444
4445                 case TOK_FLOWID:
4446                         if (proto != IPPROTO_IPV6 )
4447                                 errx( EX_USAGE, "flow-id filter is active "
4448                                     "only for ipv6 protocol\n");
4449                         fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4450                         av++;
4451                         break;
4452
4453                 case TOK_COMMENT:
4454                         fill_comment(cmd, av, cblen);
4455                         av[0]=NULL;
4456                         break;
4457
4458                 case TOK_TAGGED:
4459                         if (av[0] && strpbrk(*av, "-,")) {
4460                                 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4461                                         errx(EX_DATAERR, "tagged: invalid tag"
4462                                             " list: %s", *av);
4463                         }
4464                         else {
4465                                 uint16_t tag;
4466
4467                                 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4468                                     TOK_TAGGED, rule_options);
4469                                 fill_cmd(cmd, O_TAGGED, 0, tag);
4470                         }
4471                         av++;
4472                         break;
4473
4474                 case TOK_FIB:
4475                         NEED1("fib requires fib number");
4476                         fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4477                         av++;
4478                         break;
4479                 case TOK_SOCKARG:
4480                         fill_cmd(cmd, O_SOCKARG, 0, 0);
4481                         break;
4482
4483                 case TOK_LOOKUP: {
4484                         ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4485                         int j;
4486
4487                         if (!av[0] || !av[1])
4488                                 errx(EX_USAGE, "format: lookup argument tablenum");
4489                         cmd->opcode = O_IP_DST_LOOKUP;
4490                         cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4491                         i = match_token(rule_options, *av);
4492                         for (j = 0; lookup_key[j] >= 0 ; j++) {
4493                                 if (i == lookup_key[j])
4494                                         break;
4495                         }
4496                         if (lookup_key[j] <= 0)
4497                                 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4498                         __PAST_END(c->d, 1) = j; // i converted to option
4499                         av++;
4500
4501                         if ((j = pack_table(tstate, *av)) == 0)
4502                                 errx(EX_DATAERR, "Invalid table name: %s", *av);
4503
4504                         cmd->arg1 = j;
4505                         av++;
4506                     }
4507                         break;
4508                 case TOK_FLOW:
4509                         NEED1("missing table name");
4510                         if (strncmp(*av, "table(", 6) != 0)
4511                                 errx(EX_DATAERR,
4512                                     "enclose table name into \"table()\"");
4513                         fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4514                         av++;
4515                         break;
4516
4517                 default:
4518                         errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4519                 }
4520                 if (F_LEN(cmd) > 0) {   /* prepare to advance */
4521                         prev = cmd;
4522                         cmd = next_cmd(cmd, &cblen);
4523                 }
4524         }
4525
4526 done:
4527         /*
4528          * Now copy stuff into the rule.
4529          * If we have a keep-state option, the first instruction
4530          * must be a PROBE_STATE (which is generated here).
4531          * If we have a LOG option, it was stored as the first command,
4532          * and now must be moved to the top of the action part.
4533          */
4534         dst = (ipfw_insn *)rule->cmd;
4535
4536         /*
4537          * First thing to write into the command stream is the match probability.
4538          */
4539         if (match_prob != 1) { /* 1 means always match */
4540                 dst->opcode = O_PROB;
4541                 dst->len = 2;
4542                 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4543                 dst += dst->len;
4544         }
4545
4546         /*
4547          * generate O_PROBE_STATE if necessary
4548          */
4549         if (have_state && have_state->opcode != O_CHECK_STATE) {
4550                 fill_cmd(dst, O_PROBE_STATE, 0, 0);
4551                 dst = next_cmd(dst, &rblen);
4552         }
4553
4554         /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4555         for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4556                 i = F_LEN(src);
4557                 CHECK_RBUFLEN(i);
4558
4559                 switch (src->opcode) {
4560                 case O_LOG:
4561                 case O_KEEP_STATE:
4562                 case O_LIMIT:
4563                 case O_ALTQ:
4564                 case O_TAG:
4565                         break;
4566                 default:
4567                         bcopy(src, dst, i * sizeof(uint32_t));
4568                         dst += i;
4569                 }
4570         }
4571
4572         /*
4573          * put back the have_state command as last opcode
4574          */
4575         if (have_state && have_state->opcode != O_CHECK_STATE) {
4576                 i = F_LEN(have_state);
4577                 CHECK_RBUFLEN(i);
4578                 bcopy(have_state, dst, i * sizeof(uint32_t));
4579                 dst += i;
4580         }
4581         /*
4582          * start action section
4583          */
4584         rule->act_ofs = dst - rule->cmd;
4585
4586         /* put back O_LOG, O_ALTQ, O_TAG if necessary */
4587         if (have_log) {
4588                 i = F_LEN(have_log);
4589                 CHECK_RBUFLEN(i);
4590                 bcopy(have_log, dst, i * sizeof(uint32_t));
4591                 dst += i;
4592         }
4593         if (have_altq) {
4594                 i = F_LEN(have_altq);
4595                 CHECK_RBUFLEN(i);
4596                 bcopy(have_altq, dst, i * sizeof(uint32_t));
4597                 dst += i;
4598         }
4599         if (have_tag) {
4600                 i = F_LEN(have_tag);
4601                 CHECK_RBUFLEN(i);
4602                 bcopy(have_tag, dst, i * sizeof(uint32_t));
4603                 dst += i;
4604         }
4605
4606         /*
4607          * copy all other actions
4608          */
4609         for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4610                 i = F_LEN(src);
4611                 CHECK_RBUFLEN(i);
4612                 bcopy(src, dst, i * sizeof(uint32_t));
4613                 dst += i;
4614         }
4615
4616         rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4617         *rbufsize = (char *)dst - (char *)rule;
4618 }
4619
4620 /*
4621  * Adds one or more rules to ipfw chain.
4622  * Data layout:
4623  * Request:
4624  * [
4625  *   ip_fw3_opheader
4626  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
4627  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
4628  * ]
4629  * Reply:
4630  * [
4631  *   ip_fw3_opheader
4632  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
4633  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
4634  * ]
4635  *
4636  * Rules in reply are modified to store their actual ruleset number.
4637  *
4638  * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
4639  * accoring to their idx field and there has to be no duplicates.
4640  * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
4641  * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
4642  */
4643 void
4644 ipfw_add(char *av[])
4645 {
4646         uint32_t rulebuf[1024];
4647         int rbufsize, default_off, tlen, rlen;
4648         size_t sz;
4649         struct tidx ts;
4650         struct ip_fw_rule *rule;
4651         caddr_t tbuf;
4652         ip_fw3_opheader *op3;
4653         ipfw_obj_ctlv *ctlv, *tstate;
4654
4655         rbufsize = sizeof(rulebuf);
4656         memset(&ts, 0, sizeof(ts));
4657
4658         /* Optimize case with no tables */
4659         default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
4660         op3 = (ip_fw3_opheader *)rulebuf;
4661         ctlv = (ipfw_obj_ctlv *)(op3 + 1);
4662         rule = (struct ip_fw_rule *)(ctlv + 1);
4663         rbufsize -= default_off;
4664
4665         compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
4666         /* Align rule size to u64 boundary */
4667         rlen = roundup2(rbufsize, sizeof(uint64_t));
4668
4669         tbuf = NULL;
4670         sz = 0;
4671         tstate = NULL;
4672         if (ts.count != 0) {
4673                 /* Some tables. We have to alloc more data */
4674                 tlen = ts.count * sizeof(ipfw_obj_ntlv);
4675                 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
4676
4677                 if ((tbuf = calloc(1, sz)) == NULL)
4678                         err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
4679                 op3 = (ip_fw3_opheader *)tbuf;
4680                 /* Tables first */
4681                 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
4682                 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
4683                 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
4684                 ctlv->count = ts.count;
4685                 ctlv->objsize = sizeof(ipfw_obj_ntlv);
4686                 memcpy(ctlv + 1, ts.idx, tlen);
4687                 table_sort_ctlv(ctlv);
4688                 tstate = ctlv;
4689                 /* Rule next */
4690                 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
4691                 ctlv->head.type = IPFW_TLV_RULE_LIST;
4692                 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
4693                 ctlv->count = 1;
4694                 memcpy(ctlv + 1, rule, rbufsize);
4695         } else {
4696                 /* Simply add header */
4697                 sz = rlen + default_off;
4698                 memset(ctlv, 0, sizeof(*ctlv));
4699                 ctlv->head.type = IPFW_TLV_RULE_LIST;
4700                 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
4701                 ctlv->count = 1;
4702         }
4703
4704         if (do_get3(IP_FW_XADD, op3, &sz) != 0)
4705                 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
4706
4707         if (!co.do_quiet) {
4708                 struct format_opts sfo;
4709                 struct buf_pr bp;
4710                 memset(&sfo, 0, sizeof(sfo));
4711                 sfo.tstate = tstate;
4712                 sfo.set_mask = (uint32_t)(-1);
4713                 bp_alloc(&bp, 4096);
4714                 show_static_rule(&co, &sfo, &bp, rule, NULL);
4715                 printf("%s", bp.buf);
4716                 bp_free(&bp);
4717         }
4718
4719         if (tbuf != NULL)
4720                 free(tbuf);
4721
4722         if (ts.idx != NULL)
4723                 free(ts.idx);
4724 }
4725
4726 /*
4727  * clear the counters or the log counters.
4728  * optname has the following values:
4729  *  0 (zero both counters and logging)
4730  *  1 (zero logging only)
4731  */
4732 void
4733 ipfw_zero(int ac, char *av[], int optname)
4734 {
4735         ipfw_range_tlv rt;
4736         uint32_t arg;
4737         int failed = EX_OK;
4738         char const *errstr;
4739         char const *name = optname ? "RESETLOG" : "ZERO";
4740
4741         optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
4742         memset(&rt, 0, sizeof(rt));
4743
4744         av++; ac--;
4745
4746         if (ac == 0) {
4747                 /* clear all entries */
4748                 rt.flags = IPFW_RCFLAG_ALL;
4749                 if (do_range_cmd(optname, &rt) < 0)
4750                         err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
4751                 if (!co.do_quiet)
4752                         printf("%s.\n", optname == IP_FW_XZERO ?
4753                             "Accounting cleared":"Logging counts reset");
4754
4755                 return;
4756         }
4757
4758         while (ac) {
4759                 /* Rule number */
4760                 if (isdigit(**av)) {
4761                         arg = strtonum(*av, 0, 0xffff, &errstr);
4762                         if (errstr)
4763                                 errx(EX_DATAERR,
4764                                     "invalid rule number %s\n", *av);
4765                         rt.start_rule = arg;
4766                         rt.end_rule = arg;
4767                         rt.flags |= IPFW_RCFLAG_RANGE;
4768                         if (co.use_set != 0) {
4769                                 rt.set = co.use_set - 1;
4770                                 rt.flags |= IPFW_RCFLAG_SET;
4771                         }
4772                         if (do_range_cmd(optname, &rt) != 0) {
4773                                 warn("rule %u: setsockopt(IP_FW_X%s)",
4774                                     arg, name);
4775                                 failed = EX_UNAVAILABLE;
4776                         } else if (!co.do_quiet)
4777                                 printf("Entry %d %s.\n", arg,
4778                                     optname == IP_FW_XZERO ?
4779                                         "cleared" : "logging count reset");
4780                 } else {
4781                         errx(EX_USAGE, "invalid rule number ``%s''", *av);
4782                 }
4783         }
4784         if (failed != EX_OK)
4785                 exit(failed);
4786 }
4787
4788 void
4789 ipfw_flush(int force)
4790 {
4791         ipfw_range_tlv rt;
4792
4793         if (!force && !co.do_quiet) { /* need to ask user */
4794                 int c;
4795
4796                 printf("Are you sure? [yn] ");
4797                 fflush(stdout);
4798                 do {
4799                         c = toupper(getc(stdin));
4800                         while (c != '\n' && getc(stdin) != '\n')
4801                                 if (feof(stdin))
4802                                         return; /* and do not flush */
4803                 } while (c != 'Y' && c != 'N');
4804                 printf("\n");
4805                 if (c == 'N')   /* user said no */
4806                         return;
4807         }
4808         if (co.do_pipe) {
4809                 dummynet_flush();
4810                 return;
4811         }
4812         /* `ipfw set N flush` - is the same that `ipfw delete set N` */
4813         memset(&rt, 0, sizeof(rt));
4814         if (co.use_set != 0) {
4815                 rt.set = co.use_set - 1;
4816                 rt.flags = IPFW_RCFLAG_SET;
4817         } else
4818                 rt.flags = IPFW_RCFLAG_ALL;
4819         if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
4820                         err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
4821         if (!co.do_quiet)
4822                 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
4823 }
4824
4825 static struct _s_x intcmds[] = {
4826       { "talist",       TOK_TALIST },
4827       { "iflist",       TOK_IFLIST },
4828       { NULL, 0 }
4829 };
4830
4831 void
4832 ipfw_internal_handler(int ac, char *av[])
4833 {
4834         int tcmd;
4835
4836         ac--; av++;
4837         NEED1("internal cmd required");
4838
4839         if ((tcmd = match_token(intcmds, *av)) == -1)
4840                 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
4841
4842         switch (tcmd) {
4843         case TOK_IFLIST:
4844                 ipfw_list_tifaces();
4845                 break;
4846         case TOK_TALIST:
4847                 ipfw_list_ta(ac, av);
4848                 break;
4849         }
4850 }
4851
4852 static int
4853 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
4854 {
4855         ipfw_obj_lheader req, *olh;
4856         size_t sz;
4857         int error;
4858
4859         memset(&req, 0, sizeof(req));
4860         sz = sizeof(req);
4861
4862         error = do_get3(IP_FW_XIFLIST, &req.opheader, &sz);
4863         if (error != 0 && error != ENOMEM)
4864                 return (error);
4865
4866         sz = req.size;
4867         if ((olh = calloc(1, sz)) == NULL)
4868                 return (ENOMEM);
4869
4870         olh->size = sz;
4871         if ((error = do_get3(IP_FW_XIFLIST, &olh->opheader, &sz)) != 0) {
4872                 free(olh);
4873                 return (error);
4874         }
4875
4876         *polh = olh;
4877         return (0);
4878 }
4879
4880 static int
4881 ifinfo_cmp(const void *a, const void *b)
4882 {
4883         ipfw_iface_info *ia, *ib;
4884
4885         ia = (ipfw_iface_info *)a;
4886         ib = (ipfw_iface_info *)b;
4887
4888         return (stringnum_cmp(ia->ifname, ib->ifname));
4889 }
4890
4891 /*
4892  * Retrieves table list from kernel,
4893  * optionally sorts it and calls requested function for each table.
4894  * Returns 0 on success.
4895  */
4896 static void
4897 ipfw_list_tifaces()
4898 {
4899         ipfw_obj_lheader *olh;
4900         ipfw_iface_info *info;
4901         int i, error;
4902
4903         if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
4904                 err(EX_OSERR, "Unable to request ipfw tracked interface list");
4905
4906
4907         qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
4908
4909         info = (ipfw_iface_info *)(olh + 1);
4910         for (i = 0; i < olh->count; i++) {
4911                 if (info->flags & IPFW_IFFLAG_RESOLVED)
4912                         printf("%s ifindex: %d refcount: %u changes: %u\n",
4913                             info->ifname, info->ifindex, info->refcnt,
4914                             info->gencnt);
4915                 else
4916                         printf("%s ifindex: unresolved refcount: %u changes: %u\n",
4917                             info->ifname, info->refcnt, info->gencnt);
4918                 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);
4919         }
4920
4921         free(olh);
4922 }
4923
4924
4925
4926