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