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