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