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