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