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