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