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