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