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