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