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