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