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