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