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