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