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