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