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