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