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