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