ipfw: Remove context generation; the race it tries to fix no longer exists
[dragonfly.git] / sbin / ipfw / ipfw2.c
blob7eb9824ba0fd77f07ea58adb8a9ff5ce8f9aa590
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
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
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.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
20 * $FreeBSD: src/sbin/ipfw/ipfw2.c,v 1.4.2.13 2003/05/27 22:21:11 gshapiro Exp $
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>
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>
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>
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_sort, /* field to sort results (0 = no) */
67 do_dynamic, /* display dynamic rules */
68 do_expired, /* display expired dynamic rules */
69 do_compact, /* show rules in compact mode */
70 show_sets, /* display rule sets */
71 verbose;
73 #define IP_MASK_ALL 0xffffffff
76 * structure to hold flag names and associated values to be
77 * set in the appropriate masks.
78 * A NULL string terminates the array.
79 * Often, an element with 0 value contains an error string.
82 struct _s_x {
83 char *s;
84 int x;
87 static struct _s_x f_tcpflags[] = {
88 { "syn", TH_SYN },
89 { "fin", TH_FIN },
90 { "ack", TH_ACK },
91 { "psh", TH_PUSH },
92 { "rst", TH_RST },
93 { "urg", TH_URG },
94 { "tcp flag", 0 },
95 { NULL, 0 }
98 static struct _s_x f_tcpopts[] = {
99 { "mss", IP_FW_TCPOPT_MSS },
100 { "maxseg", IP_FW_TCPOPT_MSS },
101 { "window", IP_FW_TCPOPT_WINDOW },
102 { "sack", IP_FW_TCPOPT_SACK },
103 { "ts", IP_FW_TCPOPT_TS },
104 { "timestamp", IP_FW_TCPOPT_TS },
105 { "cc", IP_FW_TCPOPT_CC },
106 { "tcp option", 0 },
107 { NULL, 0 }
111 * IP options span the range 0 to 255 so we need to remap them
112 * (though in fact only the low 5 bits are significant).
114 static struct _s_x f_ipopts[] = {
115 { "ssrr", IP_FW_IPOPT_SSRR},
116 { "lsrr", IP_FW_IPOPT_LSRR},
117 { "rr", IP_FW_IPOPT_RR},
118 { "ts", IP_FW_IPOPT_TS},
119 { "ip option", 0 },
120 { NULL, 0 }
123 static struct _s_x f_iptos[] = {
124 { "lowdelay", IPTOS_LOWDELAY},
125 { "throughput", IPTOS_THROUGHPUT},
126 { "reliability", IPTOS_RELIABILITY},
127 { "mincost", IPTOS_MINCOST},
128 { "congestion", IPTOS_CE},
129 { "ecntransport", IPTOS_ECT},
130 { "ip tos option", 0},
131 { NULL, 0 }
134 static struct _s_x limit_masks[] = {
135 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
136 {"src-addr", DYN_SRC_ADDR},
137 {"src-port", DYN_SRC_PORT},
138 {"dst-addr", DYN_DST_ADDR},
139 {"dst-port", DYN_DST_PORT},
140 {NULL, 0}
144 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
145 * This is only used in this code.
147 #define IPPROTO_ETHERTYPE 0x1000
148 static struct _s_x ether_types[] = {
150 * Note, we cannot use "-:&/" in the names because they are field
151 * separators in the type specifications. Also, we use s = NULL as
152 * end-delimiter, because a type of 0 can be legal.
154 { "ip", 0x0800 },
155 { "ipv4", 0x0800 },
156 { "ipv6", 0x86dd },
157 { "arp", 0x0806 },
158 { "rarp", 0x8035 },
159 { "vlan", 0x8100 },
160 { "loop", 0x9000 },
161 { "trail", 0x1000 },
162 { "pppoe_disc", 0x8863 },
163 { "pppoe_sess", 0x8864 },
164 { "ipx_8022", 0x00E0 },
165 { "ipx_8023", 0x0000 },
166 { "ipx_ii", 0x8137 },
167 { "ipx_snap", 0x8137 },
168 { "ipx", 0x8137 },
169 { "ns", 0x0600 },
170 { NULL, 0 }
173 static void show_usage(void);
175 enum tokens {
176 TOK_NULL=0,
178 TOK_OR,
179 TOK_NOT,
180 TOK_STARTBRACE,
181 TOK_ENDBRACE,
183 TOK_ACCEPT,
184 TOK_COUNT,
185 TOK_PIPE,
186 TOK_QUEUE,
187 TOK_DIVERT,
188 TOK_TEE,
189 TOK_FORWARD,
190 TOK_SKIPTO,
191 TOK_DENY,
192 TOK_REJECT,
193 TOK_RESET,
194 TOK_UNREACH,
195 TOK_CHECKSTATE,
197 TOK_UID,
198 TOK_GID,
199 TOK_IN,
200 TOK_LIMIT,
201 TOK_KEEPSTATE,
202 TOK_LAYER2,
203 TOK_OUT,
204 TOK_XMIT,
205 TOK_RECV,
206 TOK_VIA,
207 TOK_FRAG,
208 TOK_IPOPTS,
209 TOK_IPLEN,
210 TOK_IPID,
211 TOK_IPPRECEDENCE,
212 TOK_IPTOS,
213 TOK_IPTTL,
214 TOK_IPVER,
215 TOK_ESTAB,
216 TOK_SETUP,
217 TOK_TCPFLAGS,
218 TOK_TCPOPTS,
219 TOK_TCPSEQ,
220 TOK_TCPACK,
221 TOK_TCPWIN,
222 TOK_ICMPTYPES,
223 TOK_MAC,
224 TOK_MACTYPE,
226 TOK_PLR,
227 TOK_NOERROR,
228 TOK_BUCKETS,
229 TOK_DSTIP,
230 TOK_SRCIP,
231 TOK_DSTPORT,
232 TOK_SRCPORT,
233 TOK_ALL,
234 TOK_MASK,
235 TOK_BW,
236 TOK_DELAY,
237 TOK_RED,
238 TOK_GRED,
239 TOK_DROPTAIL,
240 TOK_PROTO,
241 TOK_WEIGHT,
244 struct _s_x dummynet_params[] = {
245 { "plr", TOK_PLR },
246 { "noerror", TOK_NOERROR },
247 { "buckets", TOK_BUCKETS },
248 { "dst-ip", TOK_DSTIP },
249 { "src-ip", TOK_SRCIP },
250 { "dst-port", TOK_DSTPORT },
251 { "src-port", TOK_SRCPORT },
252 { "proto", TOK_PROTO },
253 { "weight", TOK_WEIGHT },
254 { "all", TOK_ALL },
255 { "mask", TOK_MASK },
256 { "droptail", TOK_DROPTAIL },
257 { "red", TOK_RED },
258 { "gred", TOK_GRED },
259 { "bw", TOK_BW },
260 { "bandwidth", TOK_BW },
261 { "delay", TOK_DELAY },
262 { "pipe", TOK_PIPE },
263 { "queue", TOK_QUEUE },
264 { "dummynet-params", TOK_NULL },
265 { NULL, 0 }
268 struct _s_x rule_actions[] = {
269 { "accept", TOK_ACCEPT },
270 { "pass", TOK_ACCEPT },
271 { "allow", TOK_ACCEPT },
272 { "permit", TOK_ACCEPT },
273 { "count", TOK_COUNT },
274 { "pipe", TOK_PIPE },
275 { "queue", TOK_QUEUE },
276 { "divert", TOK_DIVERT },
277 { "tee", TOK_TEE },
278 { "fwd", TOK_FORWARD },
279 { "forward", TOK_FORWARD },
280 { "skipto", TOK_SKIPTO },
281 { "deny", TOK_DENY },
282 { "drop", TOK_DENY },
283 { "reject", TOK_REJECT },
284 { "reset", TOK_RESET },
285 { "unreach", TOK_UNREACH },
286 { "check-state", TOK_CHECKSTATE },
287 { NULL, TOK_NULL },
288 { NULL, 0 }
291 struct _s_x rule_options[] = {
292 { "uid", TOK_UID },
293 { "gid", TOK_GID },
294 { "in", TOK_IN },
295 { "limit", TOK_LIMIT },
296 { "keep-state", TOK_KEEPSTATE },
297 { "layer2", TOK_LAYER2 },
298 { "out", TOK_OUT },
299 { "xmit", TOK_XMIT },
300 { "recv", TOK_RECV },
301 { "via", TOK_VIA },
302 { "fragment", TOK_FRAG },
303 { "frag", TOK_FRAG },
304 { "ipoptions", TOK_IPOPTS },
305 { "ipopts", TOK_IPOPTS },
306 { "iplen", TOK_IPLEN },
307 { "ipid", TOK_IPID },
308 { "ipprecedence", TOK_IPPRECEDENCE },
309 { "iptos", TOK_IPTOS },
310 { "ipttl", TOK_IPTTL },
311 { "ipversion", TOK_IPVER },
312 { "ipver", TOK_IPVER },
313 { "estab", TOK_ESTAB },
314 { "established", TOK_ESTAB },
315 { "setup", TOK_SETUP },
316 { "tcpflags", TOK_TCPFLAGS },
317 { "tcpflgs", TOK_TCPFLAGS },
318 { "tcpoptions", TOK_TCPOPTS },
319 { "tcpopts", TOK_TCPOPTS },
320 { "tcpseq", TOK_TCPSEQ },
321 { "tcpack", TOK_TCPACK },
322 { "tcpwin", TOK_TCPWIN },
323 { "icmptype", TOK_ICMPTYPES },
324 { "icmptypes", TOK_ICMPTYPES },
325 { "dst-ip", TOK_DSTIP },
326 { "src-ip", TOK_SRCIP },
327 { "dst-port", TOK_DSTPORT },
328 { "src-port", TOK_SRCPORT },
329 { "proto", TOK_PROTO },
330 { "MAC", TOK_MAC },
331 { "mac", TOK_MAC },
332 { "mac-type", TOK_MACTYPE },
334 { "not", TOK_NOT }, /* pseudo option */
335 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
336 { "or", TOK_OR }, /* pseudo option */
337 { "|", /* escape */ TOK_OR }, /* pseudo option */
338 { "{", TOK_STARTBRACE }, /* pseudo option */
339 { "(", TOK_STARTBRACE }, /* pseudo option */
340 { "}", TOK_ENDBRACE }, /* pseudo option */
341 { ")", TOK_ENDBRACE }, /* pseudo option */
342 { NULL, TOK_NULL },
343 { NULL, 0 }
347 * match_token takes a table and a string, returns the value associated
348 * with the string (0 meaning an error in most cases)
350 static int
351 match_token(struct _s_x *table, char *string)
353 struct _s_x *pt;
354 int i = strlen(string);
356 for (pt = table ; i && pt->s != NULL ; pt++)
357 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
358 return pt->x;
359 return -1;
362 static char *
363 match_value(struct _s_x *p, u_int32_t value)
365 for (; p->s != NULL; p++)
366 if (p->x == value)
367 return p->s;
368 return NULL;
372 * prints one port, symbolic or numeric
374 static void
375 print_port(int proto, u_int16_t port)
378 if (proto == IPPROTO_ETHERTYPE) {
379 char *s;
381 if (do_resolv && (s = match_value(ether_types, port)) )
382 printf("%s", s);
383 else
384 printf("0x%04x", port);
385 } else {
386 struct servent *se = NULL;
387 if (do_resolv) {
388 struct protoent *pe = getprotobynumber(proto);
390 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
392 if (se)
393 printf("%s", se->s_name);
394 else
395 printf("%d", port);
400 * print the values in a list of ports
401 * XXX todo: add support for mask.
403 static void
404 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
406 u_int16_t *p = cmd->ports;
407 int i;
408 char *sep= " ";
410 if (cmd->o.len & F_NOT)
411 printf(" not");
412 if (opcode != 0)
413 printf ("%s", opcode == O_MAC_TYPE ? " mac-type" :
414 (opcode == O_IP_DSTPORT ? " dst-port" : " src-port"));
415 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
416 printf("%s", sep);
417 print_port(proto, p[0]);
418 if (p[0] != p[1]) {
419 printf("-");
420 print_port(proto, p[1]);
422 sep = ",";
427 * Like strtol, but also translates service names into port numbers
428 * for some protocols.
429 * In particular:
430 * proto == -1 disables the protocol check;
431 * proto == IPPROTO_ETHERTYPE looks up an internal table
432 * proto == <some value in /etc/protocols> matches the values there.
433 * Returns *end == s in case the parameter is not found.
435 static int
436 strtoport(char *s, char **end, int base, int proto)
438 char *p, *buf;
439 char *s1;
440 int i;
442 *end = s; /* default - not found */
443 if ( *s == '\0')
444 return 0; /* not found */
446 if (isdigit(*s))
447 return strtol(s, end, base);
450 * find separator. '\\' escapes the next char.
452 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
453 if (*s1 == '\\' && s1[1] != '\0')
454 s1++;
456 buf = malloc(s1 - s + 1);
457 if (buf == NULL)
458 return 0;
461 * copy into a buffer skipping backslashes
463 for (p = s, i = 0; p != s1 ; p++)
464 if ( *p != '\\')
465 buf[i++] = *p;
466 buf[i++] = '\0';
468 if (proto == IPPROTO_ETHERTYPE) {
469 i = match_token(ether_types, buf);
470 free(buf);
471 if (i != -1) { /* found */
472 *end = s1;
473 return i;
475 } else {
476 struct protoent *pe = NULL;
477 struct servent *se;
479 if (proto != 0)
480 pe = getprotobynumber(proto);
481 setservent(1);
482 se = getservbyname(buf, pe ? pe->p_name : NULL);
483 free(buf);
484 if (se != NULL) {
485 *end = s1;
486 return ntohs(se->s_port);
489 return 0; /* not found */
493 * fill the body of the command with the list of port ranges.
494 * At the moment it only understands numeric ranges.
496 static int
497 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
499 u_int16_t *p = cmd->ports;
500 int i = 0;
501 char *s = av;
503 while (*s) {
504 u_int16_t a, b;
506 a = strtoport(av, &s, 0, proto);
507 if (s == av) /* no parameter */
508 break;
509 if (*s == '-') { /* a range */
510 av = s+1;
511 b = strtoport(av, &s, 0, proto);
512 if (s == av) /* no parameter */
513 break;
514 p[0] = a;
515 p[1] = b;
516 } else if (*s == ',' || *s == '\0' ) {
517 p[0] = p[1] = a;
518 } else { /* invalid separator */
519 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n",
520 *s, av);
522 i++;
523 p += 2;
524 av = s+1;
526 if (i > 0) {
527 if (i+1 > F_LEN_MASK)
528 errx(EX_DATAERR, "too many ports/ranges\n");
529 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
531 return i;
534 static struct _s_x icmpcodes[] = {
535 { "net", ICMP_UNREACH_NET },
536 { "host", ICMP_UNREACH_HOST },
537 { "protocol", ICMP_UNREACH_PROTOCOL },
538 { "port", ICMP_UNREACH_PORT },
539 { "needfrag", ICMP_UNREACH_NEEDFRAG },
540 { "srcfail", ICMP_UNREACH_SRCFAIL },
541 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
542 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
543 { "isolated", ICMP_UNREACH_ISOLATED },
544 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
545 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
546 { "tosnet", ICMP_UNREACH_TOSNET },
547 { "toshost", ICMP_UNREACH_TOSHOST },
548 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
549 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
550 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
551 { NULL, 0 }
554 static void
555 fill_reject_code(u_short *codep, char *str)
557 int val;
558 char *s;
560 val = strtoul(str, &s, 0);
561 if (s == str || *s != '\0' || val >= 0x100)
562 val = match_token(icmpcodes, str);
563 if (val < 0)
564 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
565 *codep = val;
566 return;
569 static void
570 print_reject_code(u_int16_t code)
572 char *s = match_value(icmpcodes, code);
574 if (s != NULL)
575 printf("unreach %s", s);
576 else
577 printf("unreach %u", code);
581 * Returns the number of bits set (from left) in a contiguous bitmask,
582 * or -1 if the mask is not contiguous.
583 * XXX this needs a proper fix.
584 * This effectively works on masks in big-endian (network) format.
585 * when compiled on little endian architectures.
587 * First bit is bit 7 of the first byte -- note, for MAC addresses,
588 * the first bit on the wire is bit 0 of the first byte.
589 * len is the max length in bits.
591 static int
592 contigmask(u_char *p, int len)
594 int i, n;
595 for (i=0; i<len ; i++)
596 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
597 break;
598 for (n=i+1; n < len; n++)
599 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
600 return -1; /* mask not contiguous */
601 return i;
605 * print flags set/clear in the two bitmasks passed as parameters.
606 * There is a specialized check for f_tcpflags.
608 static void
609 print_flags(char *name, ipfw_insn *cmd, struct _s_x *list)
611 char *comma="";
612 int i;
613 u_char set = cmd->arg1 & 0xff;
614 u_char clear = (cmd->arg1 >> 8) & 0xff;
616 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
617 printf(" setup");
618 return;
621 printf(" %s ", name);
622 for (i=0; list[i].x != 0; i++) {
623 if (set & list[i].x) {
624 set &= ~list[i].x;
625 printf("%s%s", comma, list[i].s);
626 comma = ",";
628 if (clear & list[i].x) {
629 clear &= ~list[i].x;
630 printf("%s!%s", comma, list[i].s);
631 comma = ",";
637 * Print the ip address contained in a command.
639 static void
640 print_ip(ipfw_insn_ip *cmd, char *s)
642 struct hostent *he = NULL;
643 int mb;
645 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
647 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
648 printf("me");
649 return;
651 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
652 u_int32_t x, *d;
653 int i;
654 char comma = '{';
656 x = cmd->o.arg1 - 1;
657 x = htonl( ~x );
658 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
659 printf("%s/%d", inet_ntoa(cmd->addr),
660 contigmask((u_char *)&x, 32));
661 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
662 x &= 0xff; /* base */
663 d = (u_int32_t *)&(cmd->mask);
664 for (i=0; i < cmd->o.arg1; i++)
665 if (d[ i/32] & (1<<(i & 31))) {
666 printf("%c%d", comma, i+x);
667 comma = ',';
669 printf("}");
670 return;
672 if (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST)
673 mb = 32;
674 else
675 mb = contigmask((u_char *)&(cmd->mask.s_addr), 32);
676 if (mb == 32 && do_resolv)
677 he = gethostbyaddr(&(cmd->addr.s_addr), sizeof(u_long),
678 AF_INET);
679 if (he != NULL) /* resolved to name */
680 printf("%s", he->h_name);
681 else if (mb == 0) /* any */
682 printf("any");
683 else { /* numeric IP followed by some kind of mask */
684 printf("%s", inet_ntoa(cmd->addr));
685 if (mb < 0)
686 printf(":%s", inet_ntoa(cmd->mask));
687 else if (mb < 32)
688 printf("/%d", mb);
693 * prints a MAC address/mask pair
695 static void
696 print_mac(u_char *addr, u_char *mask)
698 int l = contigmask(mask, 48);
700 if (l == 0)
701 printf(" any");
702 else {
703 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
704 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
705 if (l == -1)
706 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
707 mask[0], mask[1], mask[2],
708 mask[3], mask[4], mask[5]);
709 else if (l < 48)
710 printf("/%d", l);
714 static void
715 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
717 u_int8_t type;
719 cmd->d[0] = 0;
720 while (*av) {
721 if (*av == ',')
722 av++;
724 type = strtoul(av, &av, 0);
726 if (*av != ',' && *av != '\0')
727 errx(EX_DATAERR, "invalid ICMP type");
729 if (type > 31)
730 errx(EX_DATAERR, "ICMP type out of range");
732 cmd->d[0] |= 1 << type;
734 cmd->o.opcode = O_ICMPTYPE;
735 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
738 static void
739 print_icmptypes(ipfw_insn_u32 *cmd)
741 int i;
742 char sep= ' ';
744 printf(" icmptypes");
745 for (i = 0; i < 32; i++) {
746 if ( (cmd->d[0] & (1 << (i))) == 0)
747 continue;
748 printf("%c%d", sep, i);
749 sep = ',';
754 * show_ipfw() prints the body of an ipfw rule.
755 * Because the standard rule has at least proto src_ip dst_ip, we use
756 * a helper function to produce these entries if not provided explicitly.
757 * The first argument is the list of fields we have, the second is
758 * the list of fields we want to be printed.
760 * Special cases if we have provided a MAC header:
761 * + if the rule does not contain IP addresses/ports, do not print them;
762 * + if the rule does not contain an IP proto, print "all" instead of "ip";
764 * Once we have 'have_options', IP header fields are printed as options.
766 #define HAVE_PROTO 0x0001
767 #define HAVE_SRCIP 0x0002
768 #define HAVE_DSTIP 0x0004
769 #define HAVE_MAC 0x0008
770 #define HAVE_MACTYPE 0x0010
771 #define HAVE_OPTIONS 0x8000
773 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
774 static void
775 show_prerequisites(int *flags, int want, int cmd)
777 if ( (*flags & HAVE_IP) == HAVE_IP)
778 *flags |= HAVE_OPTIONS;
780 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC &&
781 cmd != O_MAC_TYPE) {
783 * mac-type was optimized out by the compiler,
784 * restore it
786 printf(" any");
787 *flags |= HAVE_MACTYPE | HAVE_OPTIONS;
788 return;
790 if ( !(*flags & HAVE_OPTIONS)) {
791 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
792 printf(" ip");
793 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
794 printf(" from any");
795 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
796 printf(" to any");
798 *flags |= want;
801 static void
802 show_ipfw(struct ipfw_ioc_rule *rule, int pcwidth, int bcwidth)
804 static int twidth = 0;
805 int l;
806 ipfw_insn *cmd;
807 int proto = 0; /* default */
808 int flags = 0; /* prerequisites */
809 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
810 int or_block = 0; /* we are in an or block */
812 u_int32_t set_disable = rule->set_disable;
814 if (set_disable & (1 << rule->set)) { /* disabled */
815 if (!show_sets)
816 return;
817 else
818 printf("# DISABLED ");
820 printf("%05u ", rule->rulenum);
822 if (do_acct)
823 printf("%*ju %*ju ", pcwidth, (uintmax_t)rule->pcnt, bcwidth,
824 (uintmax_t)rule->bcnt);
826 if (do_time) {
827 char timestr[30];
829 if (twidth == 0) {
830 strcpy(timestr, ctime((time_t *)&twidth));
831 *strchr(timestr, '\n') = '\0';
832 twidth = strlen(timestr);
834 if (rule->timestamp) {
835 time_t t = _long_to_time(rule->timestamp);
837 strcpy(timestr, ctime(&t));
838 *strchr(timestr, '\n') = '\0';
839 printf("%s ", timestr);
840 } else {
841 printf("%*s ", twidth, " ");
845 if (show_sets)
846 printf("set %d ", rule->set);
849 * print the optional "match probability"
851 if (rule->cmd_len > 0) {
852 cmd = rule->cmd ;
853 if (cmd->opcode == O_PROB) {
854 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
855 double d = 1.0 * p->d[0];
857 d = (d / 0x7fffffff);
858 printf("prob %f ", d);
863 * first print actions
865 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
866 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
867 switch(cmd->opcode) {
868 case O_CHECK_STATE:
869 printf("check-state");
870 flags = HAVE_IP; /* avoid printing anything else */
871 break;
873 case O_ACCEPT:
874 printf("allow");
875 break;
877 case O_COUNT:
878 printf("count");
879 break;
881 case O_DENY:
882 printf("deny");
883 break;
885 case O_REJECT:
886 if (cmd->arg1 == ICMP_REJECT_RST)
887 printf("reset");
888 else if (cmd->arg1 == ICMP_UNREACH_HOST)
889 printf("reject");
890 else
891 print_reject_code(cmd->arg1);
892 break;
894 case O_SKIPTO:
895 printf("skipto %u", cmd->arg1);
896 break;
898 case O_PIPE:
899 printf("pipe %u", cmd->arg1);
900 break;
902 case O_QUEUE:
903 printf("queue %u", cmd->arg1);
904 break;
906 case O_DIVERT:
907 printf("divert %u", cmd->arg1);
908 break;
910 case O_TEE:
911 printf("tee %u", cmd->arg1);
912 break;
914 case O_FORWARD_IP:
916 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
918 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
919 if (s->sa.sin_port)
920 printf(",%d", s->sa.sin_port);
922 break;
924 case O_LOG: /* O_LOG is printed last */
925 logptr = (ipfw_insn_log *)cmd;
926 break;
928 default:
929 printf("** unrecognized action %d len %d",
930 cmd->opcode, cmd->len);
933 if (logptr) {
934 if (logptr->max_log > 0)
935 printf(" log logamount %d", logptr->max_log);
936 else
937 printf(" log");
941 * then print the body.
943 if (rule->usr_flags & IPFW_USR_F_NORULE) {
944 /* empty rules before options */
945 if (!do_compact)
946 printf(" ip from any to any");
947 flags |= HAVE_IP | HAVE_OPTIONS;
950 for (l = rule->act_ofs, cmd = rule->cmd ;
951 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
952 /* useful alias */
953 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
955 show_prerequisites(&flags, 0, cmd->opcode);
957 switch(cmd->opcode) {
958 case O_PROB:
959 break; /* done already */
961 case O_PROBE_STATE:
962 break; /* no need to print anything here */
964 case O_MACADDR2: {
965 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
967 if ((cmd->len & F_OR) && !or_block)
968 printf(" {");
969 if (cmd->len & F_NOT)
970 printf(" not");
971 printf(" MAC");
972 flags |= HAVE_MAC;
973 print_mac( m->addr, m->mask);
974 print_mac( m->addr + 6, m->mask + 6);
976 break;
978 case O_MAC_TYPE:
979 if ((cmd->len & F_OR) && !or_block)
980 printf(" {");
981 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE,
982 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
983 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS;
984 break;
986 case O_IP_SRC:
987 case O_IP_SRC_MASK:
988 case O_IP_SRC_ME:
989 case O_IP_SRC_SET:
990 show_prerequisites(&flags, HAVE_PROTO, 0);
991 if (!(flags & HAVE_SRCIP))
992 printf(" from");
993 if ((cmd->len & F_OR) && !or_block)
994 printf(" {");
995 print_ip((ipfw_insn_ip *)cmd,
996 (flags & HAVE_OPTIONS) ? " src-ip" : "");
997 flags |= HAVE_SRCIP;
998 break;
1000 case O_IP_DST:
1001 case O_IP_DST_MASK:
1002 case O_IP_DST_ME:
1003 case O_IP_DST_SET:
1004 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1005 if (!(flags & HAVE_DSTIP))
1006 printf(" to");
1007 if ((cmd->len & F_OR) && !or_block)
1008 printf(" {");
1009 print_ip((ipfw_insn_ip *)cmd,
1010 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1011 flags |= HAVE_DSTIP;
1012 break;
1014 case O_IP_DSTPORT:
1015 show_prerequisites(&flags, HAVE_IP, 0);
1016 case O_IP_SRCPORT:
1017 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1018 if ((cmd->len & F_OR) && !or_block)
1019 printf(" {");
1020 print_newports((ipfw_insn_u16 *)cmd, proto,
1021 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1022 break;
1024 case O_PROTO: {
1025 struct protoent *pe;
1027 if ((cmd->len & F_OR) && !or_block)
1028 printf(" {");
1029 if (cmd->len & F_NOT)
1030 printf(" not");
1031 proto = cmd->arg1;
1032 pe = getprotobynumber(cmd->arg1);
1033 if (flags & HAVE_OPTIONS)
1034 printf(" proto");
1035 if (pe)
1036 printf(" %s", pe->p_name);
1037 else
1038 printf(" %u", cmd->arg1);
1040 flags |= HAVE_PROTO;
1041 break;
1043 default: /*options ... */
1044 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1045 if ((cmd->len & F_OR) && !or_block)
1046 printf(" {");
1047 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1048 printf(" not");
1049 switch(cmd->opcode) {
1050 case O_FRAG:
1051 printf(" frag");
1052 break;
1054 case O_IN:
1055 printf(cmd->len & F_NOT ? " out" : " in");
1056 break;
1058 case O_LAYER2:
1059 printf(" layer2");
1060 break;
1061 case O_XMIT:
1062 case O_RECV:
1063 case O_VIA: {
1064 char *s;
1065 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1067 if (cmd->opcode == O_XMIT)
1068 s = "xmit";
1069 else if (cmd->opcode == O_RECV)
1070 s = "recv";
1071 else if (cmd->opcode == O_VIA)
1072 s = "via";
1073 else
1074 s = "?huh?";
1075 if (cmdif->name[0] == '\0')
1076 printf(" %s %s", s,
1077 inet_ntoa(cmdif->p.ip));
1078 printf(" %s %s", s, cmdif->name);
1080 break;
1082 case O_IPID:
1083 printf(" ipid %u", cmd->arg1 );
1084 break;
1086 case O_IPTTL:
1087 printf(" ipttl %u", cmd->arg1 );
1088 break;
1090 case O_IPVER:
1091 printf(" ipver %u", cmd->arg1 );
1092 break;
1094 case O_IPPRECEDENCE:
1095 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1096 break;
1098 case O_IPLEN:
1099 printf(" iplen %u", cmd->arg1 );
1100 break;
1102 case O_IPOPT:
1103 print_flags("ipoptions", cmd, f_ipopts);
1104 break;
1106 case O_IPTOS:
1107 print_flags("iptos", cmd, f_iptos);
1108 break;
1110 case O_ICMPTYPE:
1111 print_icmptypes((ipfw_insn_u32 *)cmd);
1112 break;
1114 case O_ESTAB:
1115 printf(" established");
1116 break;
1118 case O_TCPFLAGS:
1119 print_flags("tcpflags", cmd, f_tcpflags);
1120 break;
1122 case O_TCPOPTS:
1123 print_flags("tcpoptions", cmd, f_tcpopts);
1124 break;
1126 case O_TCPWIN:
1127 printf(" tcpwin %d", ntohs(cmd->arg1));
1128 break;
1130 case O_TCPACK:
1131 printf(" tcpack %u", ntohl(cmd32->d[0]));
1132 break;
1134 case O_TCPSEQ:
1135 printf(" tcpseq %u", ntohl(cmd32->d[0]));
1136 break;
1138 case O_UID:
1140 struct passwd *pwd = getpwuid(cmd32->d[0]);
1142 if (pwd)
1143 printf(" uid %s", pwd->pw_name);
1144 else
1145 printf(" uid %u", cmd32->d[0]);
1147 break;
1149 case O_GID:
1151 struct group *grp = getgrgid(cmd32->d[0]);
1153 if (grp)
1154 printf(" gid %s", grp->gr_name);
1155 else
1156 printf(" gid %u", cmd32->d[0]);
1158 break;
1160 case O_KEEP_STATE:
1161 printf(" keep-state");
1162 break;
1164 case O_LIMIT:
1166 struct _s_x *p = limit_masks;
1167 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1168 u_int8_t x = c->limit_mask;
1169 char *comma = " ";
1171 printf(" limit");
1172 for ( ; p->x != 0 ; p++)
1173 if ((x & p->x) == p->x) {
1174 x &= ~p->x;
1175 printf("%s%s", comma, p->s);
1176 comma = ",";
1178 printf(" %d", c->conn_limit);
1180 break;
1182 default:
1183 printf(" [opcode %d len %d]",
1184 cmd->opcode, cmd->len);
1187 if (cmd->len & F_OR) {
1188 printf(" or");
1189 or_block = 1;
1190 } else if (or_block) {
1191 printf(" }");
1192 or_block = 0;
1195 show_prerequisites(&flags, HAVE_IP, 0);
1197 printf("\n");
1200 static void
1201 show_dyn_ipfw(struct ipfw_ioc_state *d, int pcwidth, int bcwidth)
1203 struct protoent *pe;
1204 struct in_addr a;
1206 if (!do_expired) {
1207 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1208 return;
1211 printf("%05u %*ju %*ju (%ds)", d->rulenum, pcwidth, (uintmax_t)d->pcnt,
1212 bcwidth, (uintmax_t)d->bcnt, d->expire);
1213 switch (d->dyn_type) {
1214 case O_LIMIT_PARENT:
1215 printf(" PARENT %d", d->count);
1216 break;
1217 case O_LIMIT:
1218 printf(" LIMIT");
1219 break;
1220 case O_KEEP_STATE: /* bidir, no mask */
1221 printf(" STATE");
1222 break;
1225 if ((pe = getprotobynumber(d->id.u.ip.proto)) != NULL)
1226 printf(" %s", pe->p_name);
1227 else
1228 printf(" proto %u", d->id.u.ip.proto);
1230 a.s_addr = htonl(d->id.u.ip.src_ip);
1231 printf(" %s %d", inet_ntoa(a), d->id.u.ip.src_port);
1233 a.s_addr = htonl(d->id.u.ip.dst_ip);
1234 printf(" <-> %s %d", inet_ntoa(a), d->id.u.ip.dst_port);
1235 printf("\n");
1239 sort_q(const void *pa, const void *pb)
1241 int rev = (do_sort < 0);
1242 int field = rev ? -do_sort : do_sort;
1243 long long res = 0;
1244 const struct dn_ioc_flowqueue *a = pa;
1245 const struct dn_ioc_flowqueue *b = pb;
1247 switch (field) {
1248 case 1: /* pkts */
1249 res = a->len - b->len;
1250 break;
1251 case 2: /* bytes */
1252 res = a->len_bytes - b->len_bytes;
1253 break;
1255 case 3: /* tot pkts */
1256 res = a->tot_pkts - b->tot_pkts;
1257 break;
1259 case 4: /* tot bytes */
1260 res = a->tot_bytes - b->tot_bytes;
1261 break;
1263 if (res < 0)
1264 res = -1;
1265 if (res > 0)
1266 res = 1;
1267 return (int)(rev ? res : -res);
1270 static void
1271 list_queues(struct dn_ioc_flowset *fs, struct dn_ioc_flowqueue *q)
1273 int l;
1275 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1276 fs->flow_mask.u.ip.proto,
1277 fs->flow_mask.u.ip.src_ip, fs->flow_mask.u.ip.src_port,
1278 fs->flow_mask.u.ip.dst_ip, fs->flow_mask.u.ip.dst_port);
1279 if (fs->rq_elements == 0)
1280 return;
1282 printf("BKT Prot ___Source IP/port____ "
1283 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1284 if (do_sort != 0)
1285 heapsort(q, fs->rq_elements, sizeof(*q), sort_q);
1286 for (l = 0; l < fs->rq_elements; l++) {
1287 struct in_addr ina;
1288 struct protoent *pe;
1290 ina.s_addr = htonl(q[l].id.u.ip.src_ip);
1291 printf("%3d ", q[l].hash_slot);
1292 pe = getprotobynumber(q[l].id.u.ip.proto);
1293 if (pe)
1294 printf("%-4s ", pe->p_name);
1295 else
1296 printf("%4u ", q[l].id.u.ip.proto);
1297 printf("%15s/%-5d ",
1298 inet_ntoa(ina), q[l].id.u.ip.src_port);
1299 ina.s_addr = htonl(q[l].id.u.ip.dst_ip);
1300 printf("%15s/%-5d ",
1301 inet_ntoa(ina), q[l].id.u.ip.dst_port);
1302 printf("%4ju %8ju %2u %4u %3u\n",
1303 (uintmax_t)q[l].tot_pkts, (uintmax_t)q[l].tot_bytes,
1304 q[l].len, q[l].len_bytes, q[l].drops);
1305 if (verbose)
1306 printf(" S %20ju F %20ju\n",
1307 (uintmax_t)q[l].S, (uintmax_t)q[l].F);
1311 static void
1312 print_flowset_parms(struct dn_ioc_flowset *fs, char *prefix)
1314 int l;
1315 char qs[30];
1316 char plr[30];
1317 char red[90]; /* Display RED parameters */
1319 l = fs->qsize;
1320 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1321 if (l >= 8192)
1322 sprintf(qs, "%d KB", l / 1024);
1323 else
1324 sprintf(qs, "%d B", l);
1325 } else
1326 sprintf(qs, "%3d sl.", l);
1327 if (fs->plr)
1328 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
1329 else
1330 plr[0] = '\0';
1331 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
1332 sprintf(red,
1333 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
1334 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
1335 1.0 * fs->w_q / (double)(1 << SCALE_RED),
1336 SCALE_VAL(fs->min_th),
1337 SCALE_VAL(fs->max_th),
1338 1.0 * fs->max_p / (double)(1 << SCALE_RED));
1339 else
1340 sprintf(red, "droptail");
1342 printf("%s %s%s %d queues (%d buckets) %s\n",
1343 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
1346 static void
1347 list_pipes(void *data, int nbytes, int ac, char *av[])
1349 u_long rulenum;
1350 void *next = data;
1351 struct dn_ioc_pipe *p = (struct dn_ioc_pipe *)data;
1352 struct dn_ioc_flowset *fs;
1353 struct dn_ioc_flowqueue *q;
1354 int l;
1356 if (ac > 0)
1357 rulenum = strtoul(*av++, NULL, 10);
1358 else
1359 rulenum = 0;
1360 for (; nbytes >= sizeof(*p); p = (struct dn_ioc_pipe *)next) {
1361 double b = p->bandwidth;
1362 char buf[30];
1363 char prefix[80];
1365 if (p->fs.fs_type != DN_IS_PIPE)
1366 break; /* done with pipes, now queues */
1369 * compute length, as pipe have variable size
1371 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
1372 next = (void *)p + l;
1373 nbytes -= l;
1375 if (rulenum != 0 && rulenum != p->pipe_nr)
1376 continue;
1379 * Print rate
1381 if (b == 0)
1382 sprintf(buf, "unlimited");
1383 else if (b >= 1000000)
1384 sprintf(buf, "%7.3f Mbit/s", b/1000000);
1385 else if (b >= 1000)
1386 sprintf(buf, "%7.3f Kbit/s", b/1000);
1387 else
1388 sprintf(buf, "%7.3f bit/s ", b);
1390 sprintf(prefix, "%05d: %s %4d ms ",
1391 p->pipe_nr, buf, p->delay);
1392 print_flowset_parms(&p->fs, prefix);
1393 if (verbose)
1394 printf(" V %20ju\n", (uintmax_t)p->V >> MY_M);
1396 q = (struct dn_ioc_flowqueue *)(p+1);
1397 list_queues(&p->fs, q);
1399 for (fs = next; nbytes >= sizeof(*fs); fs = next) {
1400 char prefix[80];
1402 if (fs->fs_type != DN_IS_QUEUE)
1403 break;
1404 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
1405 next = (void *)fs + l;
1406 nbytes -= l;
1407 q = (struct dn_ioc_flowqueue *)(fs+1);
1408 sprintf(prefix, "q%05d: weight %d pipe %d ",
1409 fs->fs_nr, fs->weight, fs->parent_nr);
1410 print_flowset_parms(fs, prefix);
1411 list_queues(fs, q);
1416 * This one handles all set-related commands
1417 * ipfw set { show | enable | disable }
1418 * ipfw set swap X Y
1419 * ipfw set move X to Y
1420 * ipfw set move rule X to Y
1422 static void
1423 sets_handler(int ac, char *av[])
1425 u_int32_t set_disable, masks[2];
1426 int i, nbytes;
1427 u_int16_t rulenum;
1428 u_int8_t cmd, new_set;
1430 ac--;
1431 av++;
1433 if (!ac)
1434 errx(EX_USAGE, "set needs command");
1435 if (!strncmp(*av, "show", strlen(*av)) ) {
1436 void *data;
1437 char *msg;
1439 nbytes = sizeof(struct ipfw_ioc_rule);
1440 if ((data = malloc(nbytes)) == NULL)
1441 err(EX_OSERR, "malloc");
1442 if (getsockopt(s, IPPROTO_IP, IP_FW_GET, data, &nbytes) < 0)
1443 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1444 set_disable = ((struct ipfw_ioc_rule *)data)->set_disable;
1446 for (i = 0, msg = "disable" ; i < 31; i++)
1447 if ( (set_disable & (1<<i))) {
1448 printf("%s %d", msg, i);
1449 msg = "";
1451 msg = (set_disable) ? " enable" : "enable";
1452 for (i = 0; i < 31; i++)
1453 if ( !(set_disable & (1<<i))) {
1454 printf("%s %d", msg, i);
1455 msg = "";
1457 printf("\n");
1458 } else if (!strncmp(*av, "swap", strlen(*av))) {
1459 ac--; av++;
1460 if (ac != 2)
1461 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1462 rulenum = atoi(av[0]);
1463 new_set = atoi(av[1]);
1464 if (!isdigit(*(av[0])) || rulenum > 30)
1465 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1466 if (!isdigit(*(av[1])) || new_set > 30)
1467 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1468 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1469 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL,
1470 masks, sizeof(u_int32_t));
1471 } else if (!strncmp(*av, "move", strlen(*av))) {
1472 ac--; av++;
1473 if (ac && !strncmp(*av, "rule", strlen(*av))) {
1474 cmd = 2;
1475 ac--; av++;
1476 } else
1477 cmd = 3;
1478 if (ac != 3 || strncmp(av[1], "to", strlen(*av)))
1479 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1480 rulenum = atoi(av[0]);
1481 new_set = atoi(av[2]);
1482 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > 30) ||
1483 (cmd == 2 && rulenum == 65535) )
1484 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1485 if (!isdigit(*(av[2])) || new_set > 30)
1486 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1487 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1488 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL,
1489 masks, sizeof(u_int32_t));
1490 } else if (!strncmp(*av, "disable", strlen(*av)) ||
1491 !strncmp(*av, "enable", strlen(*av)) ) {
1492 int which = !strncmp(*av, "enable", strlen(*av)) ? 1 : 0;
1494 ac--; av++;
1495 masks[0] = masks[1] = 0;
1497 while (ac) {
1498 if (isdigit(**av)) {
1499 i = atoi(*av);
1500 if (i < 0 || i > 30)
1501 errx(EX_DATAERR,
1502 "invalid set number %d\n", i);
1503 masks[which] |= (1<<i);
1504 } else if (!strncmp(*av, "disable", strlen(*av)))
1505 which = 0;
1506 else if (!strncmp(*av, "enable", strlen(*av)))
1507 which = 1;
1508 else
1509 errx(EX_DATAERR,
1510 "invalid set command %s\n", *av);
1511 av++; ac--;
1513 if ( (masks[0] & masks[1]) != 0 )
1514 errx(EX_DATAERR,
1515 "cannot enable and disable the same set\n");
1517 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, masks, sizeof(masks));
1518 if (i)
1519 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1520 } else
1521 errx(EX_USAGE, "invalid set command %s\n", *av);
1524 static void
1525 sysctl_handler(int ac, char *av[], int which)
1527 ac--;
1528 av++;
1530 if (*av == NULL) {
1531 warnx("missing keyword to enable/disable\n");
1532 } else if (strncmp(*av, "firewall", strlen(*av)) == 0) {
1533 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1534 &which, sizeof(which));
1535 } else if (strncmp(*av, "one_pass", strlen(*av)) == 0) {
1536 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1537 &which, sizeof(which));
1538 } else if (strncmp(*av, "debug", strlen(*av)) == 0) {
1539 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1540 &which, sizeof(which));
1541 } else if (strncmp(*av, "verbose", strlen(*av)) == 0) {
1542 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1543 &which, sizeof(which));
1544 } else if (strncmp(*av, "dyn_keepalive", strlen(*av)) == 0) {
1545 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1546 &which, sizeof(which));
1547 } else {
1548 warnx("unrecognize enable/disable keyword: %s\n", *av);
1552 static void
1553 list(int ac, char *av[])
1555 struct ipfw_ioc_rule *r;
1556 struct ipfw_ioc_state *dynrules, *d;
1558 void *data = NULL;
1559 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1560 int exitval = EX_OK;
1561 int lac;
1562 char **lav;
1563 u_long rnum;
1564 char *endptr;
1565 int seen = 0;
1567 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1568 int nalloc = 1024; /* start somewhere... */
1570 ac--;
1571 av++;
1573 /* get rules or pipes from kernel, resizing array as necessary */
1574 nbytes = nalloc;
1576 while (nbytes >= nalloc) {
1577 nalloc = nalloc * 2 + 200;
1578 nbytes = nalloc;
1579 if ((data = realloc(data, nbytes)) == NULL)
1580 err(EX_OSERR, "realloc");
1581 if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0)
1582 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1583 do_pipe ? "DUMMYNET" : "FW");
1586 if (do_pipe) {
1587 list_pipes(data, nbytes, ac, av);
1588 goto done;
1592 * Count static rules.
1594 r = data;
1595 nstat = r->static_count;
1598 * Count dynamic rules. This is easier as they have
1599 * fixed size.
1601 dynrules = (struct ipfw_ioc_state *)((void *)r + r->static_len);
1602 ndyn = (nbytes - r->static_len) / sizeof(*dynrules);
1604 /* if showing stats, figure out column widths ahead of time */
1605 bcwidth = pcwidth = 0;
1606 if (do_acct) {
1607 for (n = 0, r = data; n < nstat;
1608 n++, r = (void *)r + IOC_RULESIZE(r)) {
1609 /* packet counter */
1610 width = snprintf(NULL, 0, "%ju", (uintmax_t)r->pcnt);
1611 if (width > pcwidth)
1612 pcwidth = width;
1614 /* byte counter */
1615 width = snprintf(NULL, 0, "%ju", (uintmax_t)r->bcnt);
1616 if (width > bcwidth)
1617 bcwidth = width;
1620 if (do_dynamic && ndyn) {
1621 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1622 width = snprintf(NULL, 0, "%ju", (uintmax_t)d->pcnt);
1623 if (width > pcwidth)
1624 pcwidth = width;
1626 width = snprintf(NULL, 0, "%ju", (uintmax_t)d->bcnt);
1627 if (width > bcwidth)
1628 bcwidth = width;
1631 /* if no rule numbers were specified, list all rules */
1632 if (ac == 0) {
1633 for (n = 0, r = data; n < nstat;
1634 n++, r = (void *)r + IOC_RULESIZE(r) )
1635 show_ipfw(r, pcwidth, bcwidth);
1637 if (do_dynamic && ndyn) {
1638 printf("## Dynamic rules (%d):\n", ndyn);
1639 for (n = 0, d = dynrules; n < ndyn; n++, d++)
1640 show_dyn_ipfw(d, pcwidth, bcwidth);
1642 goto done;
1645 /* display specific rules requested on command line */
1647 for (lac = ac, lav = av; lac != 0; lac--) {
1648 /* convert command line rule # */
1649 rnum = strtoul(*lav++, &endptr, 10);
1650 if (*endptr) {
1651 exitval = EX_USAGE;
1652 warnx("invalid rule number: %s", *(lav - 1));
1653 continue;
1655 for (n = seen = 0, r = data; n < nstat;
1656 n++, r = (void *)r + IOC_RULESIZE(r) ) {
1657 if (r->rulenum > rnum)
1658 break;
1659 if (r->rulenum == rnum) {
1660 show_ipfw(r, pcwidth, bcwidth);
1661 seen = 1;
1664 if (!seen) {
1665 /* give precedence to other error(s) */
1666 if (exitval == EX_OK)
1667 exitval = EX_UNAVAILABLE;
1668 warnx("rule %lu does not exist", rnum);
1672 if (do_dynamic && ndyn) {
1673 printf("## Dynamic rules:\n");
1674 for (lac = ac, lav = av; lac != 0; lac--) {
1675 rnum = strtoul(*lav++, &endptr, 10);
1676 if (*endptr)
1677 /* already warned */
1678 continue;
1679 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1680 if (d->rulenum > rnum)
1681 break;
1682 if (d->rulenum == rnum)
1683 show_dyn_ipfw(d, pcwidth, bcwidth);
1688 ac = 0;
1690 done:
1691 free(data);
1693 if (exitval != EX_OK)
1694 exit(exitval);
1697 static void
1698 show_usage(void)
1700 fprintf(stderr, "usage: ipfw [options]\n"
1701 " add [number] rule\n"
1702 " pipe number config [pipeconfig]\n"
1703 " queue number config [queueconfig]\n"
1704 " [pipe] flush\n"
1705 " [pipe] delete number ...\n"
1706 " [pipe] {list|show} [number ...]\n"
1707 " {zero|resetlog} [number ...]\n"
1708 "do \"ipfw -h\" or see ipfw manpage for details\n"
1711 exit(EX_USAGE);
1714 static void
1715 help(void)
1718 fprintf(stderr, "ipfw syntax summary:\n"
1719 "ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1720 "ipfw {pipe|queue} N config BODY\n"
1721 "ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1722 "\n"
1723 "RULE: [1..] [PROB] BODY\n"
1724 "RULENUM: INTEGER(1..65534)\n"
1725 "PROB: prob REAL(0..1)\n"
1726 "BODY: check-state [LOG] (no body) |\n"
1727 " ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1728 "ACTION: check-state | allow | count | deny | reject | skipto N |\n"
1729 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1730 "ADDR: [ MAC dst src ether_type ] \n"
1731 " [ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1732 "IPLIST: IPADDR | ( IPADDR or ... or IPADDR )\n"
1733 "IPADDR: [not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1734 "OPTION_LIST: OPTION [,OPTION_LIST]\n"
1736 exit(0);
1740 static int
1741 lookup_host (char *host, struct in_addr *ipaddr)
1743 struct hostent *he;
1745 if (!inet_aton(host, ipaddr)) {
1746 if ((he = gethostbyname(host)) == NULL)
1747 return(-1);
1748 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1750 return(0);
1754 * fills the addr and mask fields in the instruction as appropriate from av.
1755 * Update length as appropriate.
1756 * The following formats are allowed:
1757 * any matches any IP. Actually returns an empty instruction.
1758 * me returns O_IP_*_ME
1759 * 1.2.3.4 single IP address
1760 * 1.2.3.4:5.6.7.8 address:mask
1761 * 1.2.3.4/24 address/mask
1762 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1764 static void
1765 fill_ip(ipfw_insn_ip *cmd, char *av)
1767 char *p = NULL, md = 0;
1768 u_int32_t i;
1770 cmd->o.len &= ~F_LEN_MASK; /* zero len */
1772 if (!strncmp(av, "any", strlen(av)))
1773 return;
1775 if (!strncmp(av, "me", strlen(av))) {
1776 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1777 return;
1780 p = strchr(av, '/');
1781 if (!p)
1782 p = strchr(av, ':');
1783 if (p) {
1784 md = *p;
1785 *p++ = '\0';
1788 if (lookup_host(av, &cmd->addr) != 0)
1789 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
1790 switch (md) {
1791 case ':':
1792 if (!inet_aton(p, &cmd->mask))
1793 errx(EX_DATAERR, "bad netmask ``%s''", p);
1794 break;
1795 case '/':
1796 i = atoi(p);
1797 if (i == 0)
1798 cmd->mask.s_addr = htonl(0);
1799 else if (i > 32)
1800 errx(EX_DATAERR, "bad width ``%s''", p);
1801 else
1802 cmd->mask.s_addr = htonl(~0 << (32 - i));
1803 break;
1804 default:
1805 cmd->mask.s_addr = htonl(~0);
1806 break;
1808 cmd->addr.s_addr &= cmd->mask.s_addr;
1810 * now look if we have a set of addresses. They are stored as follows:
1811 * arg1 is the set size (powers of 2, 2..256)
1812 * addr is the base address IN HOST FORMAT
1813 * mask.. is an array of u_int32_t with bits set.
1815 if (p)
1816 p = strchr(p, '{');
1817 if (p) { /* fetch addresses */
1818 u_int32_t *d;
1819 int low, high;
1820 int i = contigmask((u_char *)&(cmd->mask), 32);
1822 if (i < 24 || i > 31) {
1823 fprintf(stderr, "invalid set with mask %d\n",
1825 exit(0);
1827 cmd->o.arg1 = 1<<(32-i);
1828 cmd->addr.s_addr = ntohl(cmd->addr.s_addr);
1829 d = (u_int32_t *)&cmd->mask;
1830 cmd->o.opcode = O_IP_DST_SET; /* default */
1831 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
1832 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
1833 d[i] = 0; /* clear masks */
1835 av = p+1;
1836 low = cmd->addr.s_addr & 0xff;
1837 high = low + cmd->o.arg1 - 1;
1838 while (isdigit(*av)) {
1839 char *s;
1840 u_int16_t a = strtol(av, &s, 0);
1842 if (s == av) /* no parameter */
1843 break;
1844 if (a < low || a > high) {
1845 fprintf(stderr, "addr %d out of range [%d-%d]\n",
1846 a, low, high);
1847 exit(0);
1849 a -= low;
1850 d[ a/32] |= 1<<(a & 31);
1851 if (*s != ',')
1852 break;
1853 av = s+1;
1855 return;
1858 if (cmd->mask.s_addr == 0) { /* any */
1859 if (cmd->o.len & F_NOT)
1860 errx(EX_DATAERR, "not any never matches");
1861 else /* useless, nuke it */
1862 return;
1863 } else if (cmd->mask.s_addr == IP_MASK_ALL) /* one IP */
1864 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1865 else /* addr/mask */
1866 cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip);
1871 * helper function to process a set of flags and set bits in the
1872 * appropriate masks.
1874 static void
1875 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
1876 struct _s_x *flags, char *p)
1878 u_int8_t set=0, clear=0;
1880 while (p && *p) {
1881 char *q; /* points to the separator */
1882 int val;
1883 u_int8_t *which; /* mask we are working on */
1885 if (*p == '!') {
1886 p++;
1887 which = &clear;
1888 } else
1889 which = &set;
1890 q = strchr(p, ',');
1891 if (q)
1892 *q++ = '\0';
1893 val = match_token(flags, p);
1894 if (val <= 0)
1895 errx(EX_DATAERR, "invalid flag %s", p);
1896 *which |= (u_int8_t)val;
1897 p = q;
1899 cmd->opcode = opcode;
1900 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
1901 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
1905 static void
1906 delete(int ac, char *av[])
1908 u_int32_t rulenum;
1909 struct dn_ioc_pipe pipe;
1910 int i;
1911 int exitval = EX_OK;
1912 int do_set = 0;
1914 memset(&pipe, 0, sizeof pipe);
1916 av++; ac--;
1917 if (ac > 0 && !strncmp(*av, "set", strlen(*av))) {
1918 do_set = 1; /* delete set */
1919 ac--; av++;
1922 /* Rule number */
1923 while (ac && isdigit(**av)) {
1924 i = atoi(*av); av++; ac--;
1925 if (do_pipe) {
1926 if (do_pipe == 1)
1927 pipe.pipe_nr = i;
1928 else
1929 pipe.fs.fs_nr = i;
1930 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
1931 &pipe, sizeof pipe);
1932 if (i) {
1933 exitval = 1;
1934 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1935 do_pipe == 1 ? pipe.pipe_nr :
1936 pipe.fs.fs_nr);
1938 } else {
1939 rulenum = (i & 0xffff) | (do_set << 24);
1940 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum,
1941 sizeof rulenum);
1942 if (i) {
1943 exitval = EX_UNAVAILABLE;
1944 warn("rule %u: setsockopt(IP_FW_DEL)",
1945 rulenum);
1949 if (exitval != EX_OK)
1950 exit(exitval);
1955 * fill the interface structure. We do not check the name as we can
1956 * create interfaces dynamically, so checking them at insert time
1957 * makes relatively little sense.
1958 * Interface names containing '*', '?', or '[' are assumed to be shell
1959 * patterns which match interfaces.
1961 static void
1962 fill_iface(ipfw_insn_if *cmd, char *arg)
1964 cmd->name[0] = '\0';
1965 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
1967 /* Parse the interface or address */
1968 if (!strcmp(arg, "any"))
1969 cmd->o.len = 0; /* effectively ignore this command */
1970 else if (!isdigit(*arg)) {
1971 strlcpy(cmd->name, arg, sizeof(cmd->name));
1972 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
1973 } else if (!inet_aton(arg, &cmd->p.ip))
1974 errx(EX_DATAERR, "bad ip address ``%s''", arg);
1977 static unsigned long
1978 getbw(const char *str, u_short *flags, int kb)
1980 char *end;
1981 unsigned long val;
1982 int inbytes = 0;
1984 val = strtoul(str, &end, 0);
1985 if (*end == 'k' || *end == 'K') {
1986 ++end;
1987 val *= kb;
1988 } else if (*end == 'm' || *end == 'M') {
1989 ++end;
1990 val *= kb * kb;
1994 * Deal with bits or bytes or b(bits) or B(bytes). If there is no
1995 * trailer assume bits.
1997 if (strncasecmp(end, "bit", 3) == 0) {
1999 } else if (strncasecmp(end, "byte", 4) == 0) {
2000 inbytes = 1;
2001 } else if (*end == 'b') {
2003 } else if (*end == 'B') {
2004 inbytes = 1;
2008 * Return in bits if flags is NULL, else flag bits
2009 * or bytes in flags and return the unconverted value.
2011 if (inbytes && flags)
2012 *flags |= DN_QSIZE_IS_BYTES;
2013 else if (inbytes && flags == NULL)
2014 val *= 8;
2015 return(val);
2019 * the following macro returns an error message if we run out of
2020 * arguments.
2022 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
2024 static void
2025 config_pipe(int ac, char **av)
2027 struct dn_ioc_pipe pipe;
2028 int i;
2029 char *end;
2030 u_int32_t a;
2031 void *par = NULL;
2033 memset(&pipe, 0, sizeof pipe);
2035 av++; ac--;
2036 /* Pipe number */
2037 if (ac && isdigit(**av)) {
2038 i = atoi(*av); av++; ac--;
2039 if (do_pipe == 1)
2040 pipe.pipe_nr = i;
2041 else
2042 pipe.fs.fs_nr = i;
2044 while (ac > 0) {
2045 double d;
2046 int tok = match_token(dummynet_params, *av);
2047 ac--; av++;
2049 switch(tok) {
2050 case TOK_NOERROR:
2051 pipe.fs.flags_fs |= DN_NOERROR;
2052 break;
2054 case TOK_PLR:
2055 NEED1("plr needs argument 0..1\n");
2056 d = strtod(av[0], NULL);
2057 if (d > 1)
2058 d = 1;
2059 else if (d < 0)
2060 d = 0;
2061 pipe.fs.plr = (int)(d*0x7fffffff);
2062 ac--; av++;
2063 break;
2065 case TOK_QUEUE:
2066 NEED1("queue needs queue size\n");
2067 end = NULL;
2068 pipe.fs.qsize = getbw(av[0], &pipe.fs.flags_fs, 1024);
2069 ac--; av++;
2070 break;
2072 case TOK_BUCKETS:
2073 NEED1("buckets needs argument\n");
2074 pipe.fs.rq_size = strtoul(av[0], NULL, 0);
2075 ac--; av++;
2076 break;
2078 case TOK_MASK:
2079 NEED1("mask needs mask specifier\n");
2081 * per-flow queue, mask is dst_ip, dst_port,
2082 * src_ip, src_port, proto measured in bits
2084 par = NULL;
2086 pipe.fs.flow_mask.type = ETHERTYPE_IP;
2087 pipe.fs.flow_mask.u.ip.dst_ip = 0;
2088 pipe.fs.flow_mask.u.ip.src_ip = 0;
2089 pipe.fs.flow_mask.u.ip.dst_port = 0;
2090 pipe.fs.flow_mask.u.ip.src_port = 0;
2091 pipe.fs.flow_mask.u.ip.proto = 0;
2092 end = NULL;
2094 while (ac >= 1) {
2095 u_int32_t *p32 = NULL;
2096 u_int16_t *p16 = NULL;
2098 tok = match_token(dummynet_params, *av);
2099 ac--; av++;
2100 switch(tok) {
2101 case TOK_ALL:
2103 * special case, all bits significant
2105 pipe.fs.flow_mask.u.ip.dst_ip = ~0;
2106 pipe.fs.flow_mask.u.ip.src_ip = ~0;
2107 pipe.fs.flow_mask.u.ip.dst_port = ~0;
2108 pipe.fs.flow_mask.u.ip.src_port = ~0;
2109 pipe.fs.flow_mask.u.ip.proto = ~0;
2110 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2111 goto end_mask;
2113 case TOK_DSTIP:
2114 p32 = &pipe.fs.flow_mask.u.ip.dst_ip;
2115 break;
2117 case TOK_SRCIP:
2118 p32 = &pipe.fs.flow_mask.u.ip.src_ip;
2119 break;
2121 case TOK_DSTPORT:
2122 p16 = &pipe.fs.flow_mask.u.ip.dst_port;
2123 break;
2125 case TOK_SRCPORT:
2126 p16 = &pipe.fs.flow_mask.u.ip.src_port;
2127 break;
2129 case TOK_PROTO:
2130 break;
2132 default:
2133 ac++; av--; /* backtrack */
2134 goto end_mask;
2136 if (ac < 1)
2137 errx(EX_USAGE, "mask: value missing");
2138 if (*av[0] == '/') {
2139 a = strtoul(av[0]+1, &end, 0);
2140 a = (a == 32) ? ~0 : (1 << a) - 1;
2141 } else
2142 a = strtoul(av[0], &end, 0);
2143 if (p32 != NULL)
2144 *p32 = a;
2145 else if (p16 != NULL) {
2146 if (a > 65535)
2147 errx(EX_DATAERR,
2148 "mask: must be 16 bit");
2149 *p16 = (u_int16_t)a;
2150 } else {
2151 if (a > 255)
2152 errx(EX_DATAERR,
2153 "mask: must be 8 bit");
2154 pipe.fs.flow_mask.u.ip.proto = (uint8_t)a;
2156 if (a != 0)
2157 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2158 ac--; av++;
2159 } /* end while, config masks */
2160 end_mask:
2161 break;
2163 case TOK_RED:
2164 case TOK_GRED:
2165 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
2166 pipe.fs.flags_fs |= DN_IS_RED;
2167 if (tok == TOK_GRED)
2168 pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
2170 * the format for parameters is w_q/min_th/max_th/max_p
2172 if ((end = strsep(&av[0], "/"))) {
2173 double w_q = strtod(end, NULL);
2174 if (w_q > 1 || w_q <= 0)
2175 errx(EX_DATAERR, "0 < w_q <= 1");
2176 pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
2178 if ((end = strsep(&av[0], "/"))) {
2179 pipe.fs.min_th = strtoul(end, &end, 0);
2180 if (*end == 'K' || *end == 'k')
2181 pipe.fs.min_th *= 1024;
2183 if ((end = strsep(&av[0], "/"))) {
2184 pipe.fs.max_th = strtoul(end, &end, 0);
2185 if (*end == 'K' || *end == 'k')
2186 pipe.fs.max_th *= 1024;
2188 if ((end = strsep(&av[0], "/"))) {
2189 double max_p = strtod(end, NULL);
2190 if (max_p > 1 || max_p <= 0)
2191 errx(EX_DATAERR, "0 < max_p <= 1");
2192 pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED));
2194 ac--; av++;
2195 break;
2197 case TOK_DROPTAIL:
2198 pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
2199 break;
2201 case TOK_BW:
2202 NEED1("bw needs bandwidth\n");
2203 if (do_pipe != 1)
2204 errx(EX_DATAERR, "bandwidth only valid for pipes");
2206 * set bandwidth value
2208 pipe.bandwidth = getbw(av[0], NULL, 1000);
2209 if (pipe.bandwidth < 0)
2210 errx(EX_DATAERR, "bandwidth too large");
2211 ac--; av++;
2212 break;
2214 case TOK_DELAY:
2215 if (do_pipe != 1)
2216 errx(EX_DATAERR, "delay only valid for pipes");
2217 NEED1("delay needs argument 0..10000ms\n");
2218 pipe.delay = strtoul(av[0], NULL, 0);
2219 ac--; av++;
2220 break;
2222 case TOK_WEIGHT:
2223 if (do_pipe == 1)
2224 errx(EX_DATAERR,"weight only valid for queues");
2225 NEED1("weight needs argument 0..100\n");
2226 pipe.fs.weight = strtoul(av[0], &end, 0);
2227 ac--; av++;
2228 break;
2230 case TOK_PIPE:
2231 if (do_pipe == 1)
2232 errx(EX_DATAERR,"pipe only valid for queues");
2233 NEED1("pipe needs pipe_number\n");
2234 pipe.fs.parent_nr = strtoul(av[0], &end, 0);
2235 ac--; av++;
2236 break;
2238 default:
2239 errx(EX_DATAERR, "unrecognised option ``%s''", *av);
2242 if (do_pipe == 1) {
2243 if (pipe.pipe_nr == 0)
2244 errx(EX_DATAERR, "pipe_nr must be > 0");
2245 if (pipe.delay > 10000)
2246 errx(EX_DATAERR, "delay must be < 10000");
2247 } else { /* do_pipe == 2, queue */
2248 if (pipe.fs.parent_nr == 0)
2249 errx(EX_DATAERR, "pipe must be > 0");
2250 if (pipe.fs.weight >100)
2251 errx(EX_DATAERR, "weight must be <= 100");
2253 if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) {
2254 if (pipe.fs.qsize > 1024*1024)
2255 errx(EX_DATAERR, "queue size must be < 1MB");
2256 } else {
2257 if (pipe.fs.qsize > 100)
2258 errx(EX_DATAERR, "2 <= queue size <= 100");
2260 if (pipe.fs.flags_fs & DN_IS_RED) {
2261 size_t len;
2262 int lookup_depth, avg_pkt_size;
2263 double s, idle, weight, w_q;
2264 int clock_hz;
2265 int t;
2267 if (pipe.fs.min_th >= pipe.fs.max_th)
2268 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
2269 pipe.fs.min_th, pipe.fs.max_th);
2270 if (pipe.fs.max_th == 0)
2271 errx(EX_DATAERR, "max_th must be > 0");
2273 len = sizeof(int);
2274 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
2275 &lookup_depth, &len, NULL, 0) == -1)
2277 errx(1, "sysctlbyname(\"%s\")",
2278 "net.inet.ip.dummynet.red_lookup_depth");
2279 if (lookup_depth == 0)
2280 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
2281 " must be greater than zero");
2283 len = sizeof(int);
2284 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2285 &avg_pkt_size, &len, NULL, 0) == -1)
2287 errx(1, "sysctlbyname(\"%s\")",
2288 "net.inet.ip.dummynet.red_avg_pkt_size");
2289 if (avg_pkt_size == 0)
2290 errx(EX_DATAERR,
2291 "net.inet.ip.dummynet.red_avg_pkt_size must"
2292 " be greater than zero");
2294 len = sizeof(clock_hz);
2295 if (sysctlbyname("net.inet.ip.dummynet.hz", &clock_hz, &len,
2296 NULL, 0) == -1) {
2297 errx(1, "sysctlbyname(\"%s\")",
2298 "net.inet.ip.dummynet.hz");
2302 * Ticks needed for sending a medium-sized packet.
2303 * Unfortunately, when we are configuring a WF2Q+ queue, we
2304 * do not have bandwidth information, because that is stored
2305 * in the parent pipe, and also we have multiple queues
2306 * competing for it. So we set s=0, which is not very
2307 * correct. But on the other hand, why do we want RED with
2308 * WF2Q+ ?
2310 if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
2311 s = 0;
2312 else
2313 s = clock_hz * avg_pkt_size * 8 / pipe.bandwidth;
2316 * max idle time (in ticks) before avg queue size becomes 0.
2317 * NOTA: (3/w_q) is approx the value x so that
2318 * (1-w_q)^x < 10^-3.
2320 w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
2321 idle = s * 3. / w_q;
2322 pipe.fs.lookup_step = (int)idle / lookup_depth;
2323 if (!pipe.fs.lookup_step)
2324 pipe.fs.lookup_step = 1;
2325 weight = 1 - w_q;
2326 for (t = pipe.fs.lookup_step; t > 0; --t)
2327 weight *= weight;
2328 pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2330 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
2331 sizeof pipe);
2332 if (i)
2333 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2336 static void
2337 get_mac_addr_mask(char *p, u_char *addr, u_char *mask)
2339 int i, l;
2341 for (i=0; i<6; i++)
2342 addr[i] = mask[i] = 0;
2343 if (!strcmp(p, "any"))
2344 return;
2346 for (i=0; *p && i<6;i++, p++) {
2347 addr[i] = strtol(p, &p, 16);
2348 if (*p != ':') /* we start with the mask */
2349 break;
2351 if (*p == '/') { /* mask len */
2352 l = strtol(p+1, &p, 0);
2353 for (i=0; l>0; l -=8, i++)
2354 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2355 } else if (*p == '&') { /* mask */
2356 for (i=0, p++; *p && i<6;i++, p++) {
2357 mask[i] = strtol(p, &p, 16);
2358 if (*p != ':')
2359 break;
2361 } else if (*p == '\0') {
2362 for (i=0; i<6; i++)
2363 mask[i] = 0xff;
2365 for (i=0; i<6; i++)
2366 addr[i] &= mask[i];
2370 * helper function, updates the pointer to cmd with the length
2371 * of the current command, and also cleans up the first word of
2372 * the new command in case it has been clobbered before.
2374 static ipfw_insn *
2375 next_cmd(ipfw_insn *cmd)
2377 cmd += F_LEN(cmd);
2378 bzero(cmd, sizeof(*cmd));
2379 return cmd;
2383 * A function to fill simple commands of size 1.
2384 * Existing flags are preserved.
2386 static void
2387 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg)
2389 cmd->opcode = opcode;
2390 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2391 cmd->arg1 = arg;
2395 * Fetch and add the MAC address and type, with masks. This generates one or
2396 * two microinstructions, and returns the pointer to the last one.
2398 static ipfw_insn *
2399 add_mac(ipfw_insn *cmd, int ac, char *av[])
2401 ipfw_insn_mac *mac;
2403 if (ac < 2)
2404 errx(EX_DATAERR, "MAC dst src");
2406 cmd->opcode = O_MACADDR2;
2407 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2409 mac = (ipfw_insn_mac *)cmd;
2410 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2411 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2412 return cmd;
2415 static ipfw_insn *
2416 add_mactype(ipfw_insn *cmd, int ac, char *av)
2418 if (ac < 1)
2419 errx(EX_DATAERR, "missing MAC type");
2420 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2421 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2422 cmd->opcode = O_MAC_TYPE;
2423 return cmd;
2424 } else
2425 return NULL;
2428 static ipfw_insn *
2429 add_proto(ipfw_insn *cmd, char *av)
2431 struct protoent *pe;
2432 u_char proto = 0;
2434 if (!strncmp(av, "all", strlen(av)))
2435 ; /* same as "ip" */
2436 else if ((proto = atoi(av)) > 0)
2437 ; /* all done! */
2438 else if ((pe = getprotobyname(av)) != NULL)
2439 proto = pe->p_proto;
2440 else
2441 return NULL;
2442 if (proto != IPPROTO_IP)
2443 fill_cmd(cmd, O_PROTO, 0, proto);
2444 return cmd;
2447 static ipfw_insn *
2448 add_srcip(ipfw_insn *cmd, char *av)
2450 fill_ip((ipfw_insn_ip *)cmd, av);
2451 if (cmd->opcode == O_IP_DST_SET) /* set */
2452 cmd->opcode = O_IP_SRC_SET;
2453 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2454 cmd->opcode = O_IP_SRC_ME;
2455 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2456 cmd->opcode = O_IP_SRC;
2457 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2458 cmd->opcode = O_IP_SRC_MASK;
2459 return cmd;
2462 static ipfw_insn *
2463 add_dstip(ipfw_insn *cmd, char *av)
2465 fill_ip((ipfw_insn_ip *)cmd, av);
2466 if (cmd->opcode == O_IP_DST_SET) /* set */
2468 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2469 cmd->opcode = O_IP_DST_ME;
2470 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2471 cmd->opcode = O_IP_DST;
2472 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2473 cmd->opcode = O_IP_DST_MASK;
2474 return cmd;
2477 static ipfw_insn *
2478 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2480 if (!strncmp(av, "any", strlen(av))) {
2481 return NULL;
2482 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2483 /* XXX todo: check that we have a protocol with ports */
2484 cmd->opcode = opcode;
2485 return cmd;
2487 return NULL;
2491 * Parse arguments and assemble the microinstructions which make up a rule.
2492 * Rules are added into the 'rulebuf' and then copied in the correct order
2493 * into the actual rule.
2495 * The syntax for a rule starts with the action, followed by an
2496 * optional log action, and the various match patterns.
2497 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2498 * (generated if the rule includes a keep-state option), then the
2499 * various match patterns, the "log" action, and the actual action.
2502 static void
2503 add(int ac, char *av[])
2506 * rules are added into the 'rulebuf' and then copied in
2507 * the correct order into the actual rule.
2508 * Some things that need to go out of order (prob, action etc.)
2509 * go into actbuf[].
2511 static uint32_t rulebuf[IPFW_RULE_SIZE_MAX];
2512 static uint32_t actbuf[IPFW_RULE_SIZE_MAX];
2513 static uint32_t cmdbuf[IPFW_RULE_SIZE_MAX];
2515 ipfw_insn *src, *dst, *cmd, *action, *prev = NULL;
2516 ipfw_insn *first_cmd; /* first match pattern */
2518 struct ipfw_ioc_rule *rule;
2521 * various flags used to record that we entered some fields.
2523 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2525 int i;
2527 int open_par = 0; /* open parenthesis ( */
2529 /* proto is here because it is used to fetch ports */
2530 u_char proto = IPPROTO_IP; /* default protocol */
2532 double match_prob = 1; /* match probability, default is always match */
2534 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2535 bzero(cmdbuf, sizeof(cmdbuf));
2536 bzero(rulebuf, sizeof(rulebuf));
2538 rule = (struct ipfw_ioc_rule *)rulebuf;
2539 cmd = (ipfw_insn *)cmdbuf;
2540 action = (ipfw_insn *)actbuf;
2542 av++; ac--;
2544 /* [rule N] -- Rule number optional */
2545 if (ac && isdigit(**av)) {
2546 rule->rulenum = atoi(*av);
2547 av++;
2548 ac--;
2551 /* [set N] -- set number (0..30), optional */
2552 if (ac > 1 && !strncmp(*av, "set", strlen(*av))) {
2553 int set = strtoul(av[1], NULL, 10);
2554 if (set < 0 || set > 30)
2555 errx(EX_DATAERR, "illegal set %s", av[1]);
2556 rule->set = set;
2557 av += 2; ac -= 2;
2560 /* [prob D] -- match probability, optional */
2561 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2562 match_prob = strtod(av[1], NULL);
2564 if (match_prob <= 0 || match_prob > 1)
2565 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2566 av += 2; ac -= 2;
2569 /* action -- mandatory */
2570 NEED1("missing action");
2571 i = match_token(rule_actions, *av);
2572 ac--; av++;
2573 action->len = 1; /* default */
2574 switch(i) {
2575 case TOK_CHECKSTATE:
2576 have_state = action;
2577 action->opcode = O_CHECK_STATE;
2578 break;
2580 case TOK_ACCEPT:
2581 action->opcode = O_ACCEPT;
2582 break;
2584 case TOK_DENY:
2585 action->opcode = O_DENY;
2586 action->arg1 = 0;
2587 break;
2589 case TOK_REJECT:
2590 action->opcode = O_REJECT;
2591 action->arg1 = ICMP_UNREACH_HOST;
2592 break;
2594 case TOK_RESET:
2595 action->opcode = O_REJECT;
2596 action->arg1 = ICMP_REJECT_RST;
2597 break;
2599 case TOK_UNREACH:
2600 action->opcode = O_REJECT;
2601 NEED1("missing reject code");
2602 fill_reject_code(&action->arg1, *av);
2603 ac--; av++;
2604 break;
2606 case TOK_COUNT:
2607 action->opcode = O_COUNT;
2608 break;
2610 case TOK_QUEUE:
2611 case TOK_PIPE:
2612 action->len = F_INSN_SIZE(ipfw_insn_pipe);
2613 case TOK_SKIPTO:
2614 if (i == TOK_QUEUE)
2615 action->opcode = O_QUEUE;
2616 else if (i == TOK_PIPE)
2617 action->opcode = O_PIPE;
2618 else if (i == TOK_SKIPTO)
2619 action->opcode = O_SKIPTO;
2620 NEED1("missing skipto/pipe/queue number");
2621 action->arg1 = strtoul(*av, NULL, 10);
2622 av++; ac--;
2623 break;
2625 case TOK_DIVERT:
2626 case TOK_TEE:
2627 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2628 NEED1("missing divert/tee port");
2629 action->arg1 = strtoul(*av, NULL, 0);
2630 if (action->arg1 == 0) {
2631 struct servent *s;
2632 setservent(1);
2633 s = getservbyname(av[0], "divert");
2634 if (s != NULL)
2635 action->arg1 = ntohs(s->s_port);
2636 else
2637 errx(EX_DATAERR, "illegal divert/tee port");
2639 ac--; av++;
2640 break;
2642 case TOK_FORWARD: {
2643 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2644 char *s, *end;
2646 NEED1("missing forward address[:port]");
2648 action->opcode = O_FORWARD_IP;
2649 action->len = F_INSN_SIZE(ipfw_insn_sa);
2651 p->sa.sin_len = sizeof(struct sockaddr_in);
2652 p->sa.sin_family = AF_INET;
2653 p->sa.sin_port = 0;
2655 * locate the address-port separator (':' or ',')
2657 s = strchr(*av, ':');
2658 if (s == NULL)
2659 s = strchr(*av, ',');
2660 if (s != NULL) {
2661 *(s++) = '\0';
2662 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2663 if (s == end)
2664 errx(EX_DATAERR,
2665 "illegal forwarding port ``%s''", s);
2666 p->sa.sin_port = (u_short)i;
2668 lookup_host(*av, &(p->sa.sin_addr));
2670 ac--; av++;
2671 break;
2673 default:
2674 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2676 action = next_cmd(action);
2679 * [log [logamount N]] -- log, optional
2681 * If exists, it goes first in the cmdbuf, but then it is
2682 * skipped in the copy section to the end of the buffer.
2684 if (ac && !strncmp(*av, "log", strlen(*av))) {
2685 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2687 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2688 cmd->opcode = O_LOG;
2689 av++; ac--;
2690 if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2691 ac--; av++;
2692 NEED1("logamount requires argument");
2693 c->max_log = atoi(*av);
2694 if (c->max_log < 0)
2695 errx(EX_DATAERR, "logamount must be positive");
2696 ac--; av++;
2698 cmd = next_cmd(cmd);
2701 if (have_state) /* must be a check-state, we are done */
2702 goto done;
2704 #define OR_START(target) \
2705 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2706 if (open_par) \
2707 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2708 prev = NULL; \
2709 open_par = 1; \
2710 if ( (av[0])[1] == '\0') { \
2711 ac--; av++; \
2712 } else \
2713 (*av)++; \
2715 target: \
2718 #define CLOSE_PAR \
2719 if (open_par) { \
2720 if (ac && ( \
2721 !strncmp(*av, ")", strlen(*av)) || \
2722 !strncmp(*av, "}", strlen(*av)) )) { \
2723 prev = NULL; \
2724 open_par = 0; \
2725 ac--; av++; \
2726 } else \
2727 errx(EX_USAGE, "missing \")\"\n"); \
2730 #define NOT_BLOCK \
2731 if (ac && !strncmp(*av, "not", strlen(*av))) { \
2732 if (cmd->len & F_NOT) \
2733 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2734 cmd->len |= F_NOT; \
2735 ac--; av++; \
2738 #define OR_BLOCK(target) \
2739 if (ac && !strncmp(*av, "or", strlen(*av))) { \
2740 if (prev == NULL || open_par == 0) \
2741 errx(EX_DATAERR, "invalid OR block"); \
2742 prev->len |= F_OR; \
2743 ac--; av++; \
2744 goto target; \
2746 CLOSE_PAR;
2748 first_cmd = cmd;
2750 #if 0
2752 * MAC addresses, optional.
2753 * If we have this, we skip the part "proto from src to dst"
2754 * and jump straight to the option parsing.
2756 NOT_BLOCK;
2757 NEED1("missing protocol");
2758 if (!strncmp(*av, "MAC", strlen(*av)) ||
2759 !strncmp(*av, "mac", strlen(*av))) {
2760 ac--; av++; /* the "MAC" keyword */
2761 add_mac(cmd, ac, av); /* exits in case of errors */
2762 cmd = next_cmd(cmd);
2763 ac -= 2; av += 2; /* dst-mac and src-mac */
2764 NOT_BLOCK;
2765 NEED1("missing mac type");
2766 if (add_mactype(cmd, ac, av[0]))
2767 cmd = next_cmd(cmd);
2768 ac--; av++; /* any or mac-type */
2769 goto read_options;
2771 #endif
2774 * protocol, mandatory
2776 OR_START(get_proto);
2777 NOT_BLOCK;
2778 NEED1("missing protocol");
2779 if (add_proto(cmd, *av)) {
2780 av++; ac--;
2781 if (F_LEN(cmd) == 0) /* plain IP */
2782 proto = 0;
2783 else {
2784 proto = cmd->arg1;
2785 prev = cmd;
2786 cmd = next_cmd(cmd);
2788 } else if (first_cmd != cmd) {
2789 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
2790 } else
2791 goto read_options;
2792 OR_BLOCK(get_proto);
2795 * "from", mandatory
2797 if (!ac || strncmp(*av, "from", strlen(*av)))
2798 errx(EX_USAGE, "missing ``from''");
2799 ac--; av++;
2802 * source IP, mandatory
2804 OR_START(source_ip);
2805 NOT_BLOCK; /* optional "not" */
2806 NEED1("missing source address");
2807 if (add_srcip(cmd, *av)) {
2808 ac--; av++;
2809 if (F_LEN(cmd) != 0) { /* ! any */
2810 prev = cmd;
2811 cmd = next_cmd(cmd);
2814 OR_BLOCK(source_ip);
2817 * source ports, optional
2819 NOT_BLOCK; /* optional "not" */
2820 if (ac) {
2821 if (!strncmp(*av, "any", strlen(*av)) ||
2822 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
2823 ac--; av++;
2824 if (F_LEN(cmd) != 0)
2825 cmd = next_cmd(cmd);
2830 * "to", mandatory
2832 if (!ac || strncmp(*av, "to", strlen(*av)))
2833 errx(EX_USAGE, "missing ``to''");
2834 av++; ac--;
2837 * destination, mandatory
2839 OR_START(dest_ip);
2840 NOT_BLOCK; /* optional "not" */
2841 NEED1("missing dst address");
2842 if (add_dstip(cmd, *av)) {
2843 ac--; av++;
2844 if (F_LEN(cmd) != 0) { /* ! any */
2845 prev = cmd;
2846 cmd = next_cmd(cmd);
2849 OR_BLOCK(dest_ip);
2852 * dest. ports, optional
2854 NOT_BLOCK; /* optional "not" */
2855 if (ac) {
2856 if (!strncmp(*av, "any", strlen(*av)) ||
2857 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
2858 ac--; av++;
2859 if (F_LEN(cmd) != 0)
2860 cmd = next_cmd(cmd);
2864 read_options:
2865 if (ac && first_cmd == cmd) {
2867 * nothing specified so far, store in the rule to ease
2868 * printout later.
2870 rule->usr_flags = IPFW_USR_F_NORULE;
2872 prev = NULL;
2873 while (ac) {
2874 char *s;
2875 ipfw_insn_u32 *cmd32; /* alias for cmd */
2877 s = *av;
2878 cmd32 = (ipfw_insn_u32 *)cmd;
2880 if (*s == '!') { /* alternate syntax for NOT */
2881 if (cmd->len & F_NOT)
2882 errx(EX_USAGE, "double \"not\" not allowed\n");
2883 cmd->len = F_NOT;
2884 s++;
2886 i = match_token(rule_options, s);
2887 ac--; av++;
2888 switch(i) {
2889 case TOK_NOT:
2890 if (cmd->len & F_NOT)
2891 errx(EX_USAGE, "double \"not\" not allowed\n");
2892 cmd->len = F_NOT;
2893 break;
2895 case TOK_OR:
2896 if (open_par == 0 || prev == NULL)
2897 errx(EX_USAGE, "invalid \"or\" block\n");
2898 prev->len |= F_OR;
2899 break;
2901 case TOK_STARTBRACE:
2902 if (open_par)
2903 errx(EX_USAGE, "+nested \"(\" not allowed\n");
2904 open_par = 1;
2905 break;
2907 case TOK_ENDBRACE:
2908 if (!open_par)
2909 errx(EX_USAGE, "+missing \")\"\n");
2910 open_par = 0;
2911 prev = NULL;
2912 break;
2914 case TOK_IN:
2915 fill_cmd(cmd, O_IN, 0, 0);
2916 break;
2918 case TOK_OUT:
2919 cmd->len ^= F_NOT; /* toggle F_NOT */
2920 fill_cmd(cmd, O_IN, 0, 0);
2921 break;
2923 case TOK_FRAG:
2924 fill_cmd(cmd, O_FRAG, 0, 0);
2925 break;
2927 case TOK_LAYER2:
2928 fill_cmd(cmd, O_LAYER2, 0, 0);
2929 break;
2931 case TOK_XMIT:
2932 case TOK_RECV:
2933 case TOK_VIA:
2934 NEED1("recv, xmit, via require interface name"
2935 " or address");
2936 fill_iface((ipfw_insn_if *)cmd, av[0]);
2937 ac--; av++;
2938 if (F_LEN(cmd) == 0) /* not a valid address */
2939 break;
2940 if (i == TOK_XMIT)
2941 cmd->opcode = O_XMIT;
2942 else if (i == TOK_RECV)
2943 cmd->opcode = O_RECV;
2944 else if (i == TOK_VIA)
2945 cmd->opcode = O_VIA;
2946 break;
2948 case TOK_ICMPTYPES:
2949 NEED1("icmptypes requires list of types");
2950 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
2951 av++; ac--;
2952 break;
2954 case TOK_IPTTL:
2955 NEED1("ipttl requires TTL");
2956 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
2957 ac--; av++;
2958 break;
2960 case TOK_IPID:
2961 NEED1("ipid requires length");
2962 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
2963 ac--; av++;
2964 break;
2966 case TOK_IPLEN:
2967 NEED1("iplen requires length");
2968 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
2969 ac--; av++;
2970 break;
2972 case TOK_IPVER:
2973 NEED1("ipver requires version");
2974 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
2975 ac--; av++;
2976 break;
2978 case TOK_IPPRECEDENCE:
2979 NEED1("ipprecedence requires value");
2980 fill_cmd(cmd, O_IPPRECEDENCE, 0,
2981 (strtoul(*av, NULL, 0) & 7) << 5);
2982 ac--; av++;
2983 break;
2985 case TOK_IPOPTS:
2986 NEED1("missing argument for ipoptions");
2987 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
2988 ac--; av++;
2989 break;
2991 case TOK_IPTOS:
2992 NEED1("missing argument for iptos");
2993 fill_flags(cmd, O_IPTOS, f_iptos, *av);
2994 ac--; av++;
2995 break;
2997 case TOK_UID:
2998 NEED1("uid requires argument");
3000 char *end;
3001 uid_t uid;
3002 struct passwd *pwd;
3004 cmd->opcode = O_UID;
3005 uid = strtoul(*av, &end, 0);
3006 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3007 if (pwd == NULL)
3008 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3009 cmd32->d[0] = pwd->pw_uid;
3010 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3011 ac--; av++;
3013 break;
3015 case TOK_GID:
3016 NEED1("gid requires argument");
3018 char *end;
3019 gid_t gid;
3020 struct group *grp;
3022 cmd->opcode = O_GID;
3023 gid = strtoul(*av, &end, 0);
3024 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3025 if (grp == NULL)
3026 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3027 cmd32->d[0] = grp->gr_gid;
3028 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3029 ac--; av++;
3031 break;
3033 case TOK_ESTAB:
3034 fill_cmd(cmd, O_ESTAB, 0, 0);
3035 break;
3037 case TOK_SETUP:
3038 fill_cmd(cmd, O_TCPFLAGS, 0,
3039 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3040 break;
3042 case TOK_TCPOPTS:
3043 NEED1("missing argument for tcpoptions");
3044 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3045 ac--; av++;
3046 break;
3048 case TOK_TCPSEQ:
3049 case TOK_TCPACK:
3050 NEED1("tcpseq/tcpack requires argument");
3051 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3052 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3053 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3054 ac--; av++;
3055 break;
3057 case TOK_TCPWIN:
3058 NEED1("tcpwin requires length");
3059 fill_cmd(cmd, O_TCPWIN, 0,
3060 htons(strtoul(*av, NULL, 0)));
3061 ac--; av++;
3062 break;
3064 case TOK_TCPFLAGS:
3065 NEED1("missing argument for tcpflags");
3066 cmd->opcode = O_TCPFLAGS;
3067 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3068 ac--; av++;
3069 break;
3071 case TOK_KEEPSTATE:
3072 if (open_par)
3073 errx(EX_USAGE, "keep-state cannot be part "
3074 "of an or block");
3075 if (have_state)
3076 errx(EX_USAGE, "only one of keep-state "
3077 "and limit is allowed");
3078 have_state = cmd;
3079 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3080 break;
3082 case TOK_LIMIT:
3083 if (open_par)
3084 errx(EX_USAGE, "limit cannot be part "
3085 "of an or block");
3086 if (have_state)
3087 errx(EX_USAGE, "only one of keep-state "
3088 "and limit is allowed");
3089 NEED1("limit needs mask and # of connections");
3090 have_state = cmd;
3092 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3094 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3095 cmd->opcode = O_LIMIT;
3096 c->limit_mask = 0;
3097 c->conn_limit = 0;
3098 for (; ac >1 ;) {
3099 int val;
3101 val = match_token(limit_masks, *av);
3102 if (val <= 0)
3103 break;
3104 c->limit_mask |= val;
3105 ac--; av++;
3107 c->conn_limit = atoi(*av);
3108 if (c->conn_limit == 0)
3109 errx(EX_USAGE, "limit: limit must be >0");
3110 if (c->limit_mask == 0)
3111 errx(EX_USAGE, "missing limit mask");
3112 ac--; av++;
3114 break;
3116 case TOK_PROTO:
3117 NEED1("missing protocol");
3118 if (add_proto(cmd, *av)) {
3119 proto = cmd->arg1;
3120 ac--; av++;
3121 } else
3122 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3123 break;
3125 case TOK_SRCIP:
3126 NEED1("missing source IP");
3127 if (add_srcip(cmd, *av)) {
3128 ac--; av++;
3130 break;
3132 case TOK_DSTIP:
3133 NEED1("missing destination IP");
3134 if (add_dstip(cmd, *av)) {
3135 ac--; av++;
3137 break;
3139 case TOK_SRCPORT:
3140 NEED1("missing source port");
3141 if (!strncmp(*av, "any", strlen(*av)) ||
3142 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3143 ac--; av++;
3144 } else
3145 errx(EX_DATAERR, "invalid source port %s", *av);
3146 break;
3148 case TOK_DSTPORT:
3149 NEED1("missing destination port");
3150 if (!strncmp(*av, "any", strlen(*av)) ||
3151 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3152 ac--; av++;
3153 } else
3154 errx(EX_DATAERR, "invalid destination port %s",
3155 *av);
3156 break;
3158 case TOK_MAC:
3159 if (ac < 2)
3160 errx(EX_USAGE, "MAC dst-mac src-mac");
3161 if (add_mac(cmd, ac, av)) {
3162 ac -= 2; av += 2;
3164 break;
3166 case TOK_MACTYPE:
3167 NEED1("missing mac type");
3168 if (!add_mactype(cmd, ac, *av))
3169 errx(EX_DATAERR, "invalid mac type %s", *av);
3170 ac--; av++;
3171 break;
3173 default:
3174 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3176 if (F_LEN(cmd) > 0) { /* prepare to advance */
3177 prev = cmd;
3178 cmd = next_cmd(cmd);
3182 done:
3184 * Now copy stuff into the rule.
3185 * If we have a keep-state option, the first instruction
3186 * must be a PROBE_STATE (which is generated here).
3187 * If we have a LOG option, it was stored as the first command,
3188 * and now must be moved to the top of the action part.
3190 dst = (ipfw_insn *)rule->cmd;
3193 * First thing to write into the command stream is the match probability.
3195 if (match_prob != 1) { /* 1 means always match */
3196 dst->opcode = O_PROB;
3197 dst->len = 2;
3198 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3199 dst += dst->len;
3203 * generate O_PROBE_STATE if necessary
3205 if (have_state && have_state->opcode != O_CHECK_STATE) {
3206 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3207 dst = next_cmd(dst);
3210 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT
3212 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3213 i = F_LEN(src);
3215 switch (src->opcode) {
3216 case O_LOG:
3217 case O_KEEP_STATE:
3218 case O_LIMIT:
3219 break;
3220 default:
3221 bcopy(src, dst, i * sizeof(u_int32_t));
3222 dst += i;
3227 * put back the have_state command as last opcode
3229 if (have_state && have_state->opcode != O_CHECK_STATE) {
3230 i = F_LEN(have_state);
3231 bcopy(have_state, dst, i * sizeof(u_int32_t));
3232 dst += i;
3235 * start action section
3237 rule->act_ofs = dst - rule->cmd;
3240 * put back O_LOG if necessary
3242 src = (ipfw_insn *)cmdbuf;
3243 if ( src->opcode == O_LOG ) {
3244 i = F_LEN(src);
3245 bcopy(src, dst, i * sizeof(u_int32_t));
3246 dst += i;
3249 * copy all other actions
3251 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3252 i = F_LEN(src);
3253 bcopy(src, dst, i * sizeof(u_int32_t));
3254 dst += i;
3257 rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
3258 i = (void *)dst - (void *)rule;
3259 if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
3260 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3261 if (!do_quiet)
3262 show_ipfw(rule, 10, 10);
3265 static void
3266 zero(int ac, char *av[])
3268 int rulenum;
3269 int failed = EX_OK;
3271 av++; ac--;
3273 if (!ac) {
3274 /* clear all entries */
3275 if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
3276 err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
3277 if (!do_quiet)
3278 printf("Accounting cleared.\n");
3280 return;
3283 while (ac) {
3284 /* Rule number */
3285 if (isdigit(**av)) {
3286 rulenum = atoi(*av);
3287 av++;
3288 ac--;
3289 if (setsockopt(s, IPPROTO_IP,
3290 IP_FW_ZERO, &rulenum, sizeof rulenum)) {
3291 warn("rule %u: setsockopt(IP_FW_ZERO)",
3292 rulenum);
3293 failed = EX_UNAVAILABLE;
3294 } else if (!do_quiet)
3295 printf("Entry %d cleared\n", rulenum);
3296 } else {
3297 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3300 if (failed != EX_OK)
3301 exit(failed);
3304 static void
3305 resetlog(int ac, char *av[])
3307 int rulenum;
3308 int failed = EX_OK;
3310 av++; ac--;
3312 if (!ac) {
3313 /* clear all entries */
3314 if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
3315 err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
3316 if (!do_quiet)
3317 printf("Logging counts reset.\n");
3319 return;
3322 while (ac) {
3323 /* Rule number */
3324 if (isdigit(**av)) {
3325 rulenum = atoi(*av);
3326 av++;
3327 ac--;
3328 if (setsockopt(s, IPPROTO_IP,
3329 IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
3330 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
3331 rulenum);
3332 failed = EX_UNAVAILABLE;
3333 } else if (!do_quiet)
3334 printf("Entry %d logging count reset\n",
3335 rulenum);
3336 } else {
3337 errx(EX_DATAERR, "invalid rule number ``%s''", *av);
3340 if (failed != EX_OK)
3341 exit(failed);
3344 static void
3345 flush(void)
3347 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3349 if (!do_force && !do_quiet) { /* need to ask user */
3350 int c;
3352 printf("Are you sure? [yn] ");
3353 fflush(stdout);
3354 do {
3355 c = toupper(getc(stdin));
3356 while (c != '\n' && getc(stdin) != '\n')
3357 if (feof(stdin))
3358 return; /* and do not flush */
3359 } while (c != 'Y' && c != 'N');
3360 printf("\n");
3361 if (c == 'N') /* user said no */
3362 return;
3364 if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
3365 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3366 do_pipe ? "DUMMYNET" : "FW");
3367 if (!do_quiet)
3368 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
3371 static int
3372 ipfw_main(int ac, char **av)
3374 int ch;
3376 if (ac == 1)
3377 show_usage();
3379 /* Set the force flag for non-interactive processes */
3380 do_force = !isatty(STDIN_FILENO);
3382 optind = optreset = 1;
3383 while ((ch = getopt(ac, av, "hs:acdefNqStv")) != -1)
3384 switch (ch) {
3385 case 'h': /* help */
3386 help();
3387 break; /* NOTREACHED */
3389 case 's': /* sort */
3390 do_sort = atoi(optarg);
3391 break;
3392 case 'a':
3393 do_acct = 1;
3394 break;
3395 case 'c':
3396 do_compact = 1;
3397 break;
3398 case 'd':
3399 do_dynamic = 1;
3400 break;
3401 case 'e':
3402 do_expired = 1;
3403 break;
3404 case 'f':
3405 do_force = 1;
3406 break;
3407 case 'N':
3408 do_resolv = 1;
3409 break;
3410 case 'q':
3411 do_quiet = 1;
3412 break;
3413 case 'S':
3414 show_sets = 1;
3415 break;
3416 case 't':
3417 do_time = 1;
3418 break;
3419 case 'v': /* verbose */
3420 verbose++;
3421 break;
3422 default:
3423 show_usage();
3426 ac -= optind;
3427 av += optind;
3428 NEED1("bad arguments, for usage summary ``ipfw''");
3431 * optional: pipe or queue
3433 if (!strncmp(*av, "pipe", strlen(*av))) {
3434 do_pipe = 1;
3435 ac--;
3436 av++;
3437 } else if (!strncmp(*av, "queue", strlen(*av))) {
3438 do_pipe = 2;
3439 ac--;
3440 av++;
3442 NEED1("missing command");
3445 * for pipes and queues we normally say 'pipe NN config'
3446 * but the code is easier to parse as 'pipe config NN'
3447 * so we swap the two arguments.
3449 if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
3450 char *p = av[0];
3451 av[0] = av[1];
3452 av[1] = p;
3454 if (!strncmp(*av, "add", strlen(*av)))
3455 add(ac, av);
3456 else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
3457 config_pipe(ac, av);
3458 else if (!strncmp(*av, "delete", strlen(*av)))
3459 delete(ac, av);
3460 else if (!strncmp(*av, "flush", strlen(*av)))
3461 flush();
3462 else if (!strncmp(*av, "zero", strlen(*av)))
3463 zero(ac, av);
3464 else if (!strncmp(*av, "resetlog", strlen(*av)))
3465 resetlog(ac, av);
3466 else if (!strncmp(*av, "print", strlen(*av)) ||
3467 !strncmp(*av, "list", strlen(*av)))
3468 list(ac, av);
3469 else if (!strncmp(*av, "enable", strlen(*av)))
3470 sysctl_handler(ac, av, 1);
3471 else if (!strncmp(*av, "disable", strlen(*av)))
3472 sysctl_handler(ac, av, 0);
3473 else if (!strncmp(*av, "set", strlen(*av)))
3474 sets_handler(ac, av);
3475 else if (!strncmp(*av, "show", strlen(*av))) {
3476 do_acct++;
3477 list(ac, av);
3478 } else
3479 errx(EX_USAGE, "bad command `%s'", *av);
3480 return 0;
3484 static void
3485 ipfw_readfile(int ac, char *av[])
3487 #define MAX_ARGS 32
3488 #define WHITESP " \t\f\v\n\r"
3489 char buf[BUFSIZ];
3490 char *a, *p, *args[MAX_ARGS], *cmd = NULL;
3491 char linename[20];
3492 int i=0, lineno=0, qflag=0, pflag=0, status;
3493 FILE *f = NULL;
3494 pid_t preproc = 0;
3495 int c;
3497 while ((c = getopt(ac, av, "D:U:p:q")) != -1)
3498 switch(c) {
3499 case 'D':
3500 if (!pflag)
3501 errx(EX_USAGE, "-D requires -p");
3502 if (i > MAX_ARGS - 2)
3503 errx(EX_USAGE,
3504 "too many -D or -U options");
3505 args[i++] = "-D";
3506 args[i++] = optarg;
3507 break;
3509 case 'U':
3510 if (!pflag)
3511 errx(EX_USAGE, "-U requires -p");
3512 if (i > MAX_ARGS - 2)
3513 errx(EX_USAGE,
3514 "too many -D or -U options");
3515 args[i++] = "-U";
3516 args[i++] = optarg;
3517 break;
3519 case 'p':
3520 pflag = 1;
3521 cmd = optarg;
3522 args[0] = cmd;
3523 i = 1;
3524 break;
3526 case 'q':
3527 qflag = 1;
3528 break;
3530 default:
3531 errx(EX_USAGE, "bad arguments, for usage"
3532 " summary ``ipfw''");
3535 av += optind;
3536 ac -= optind;
3537 if (ac != 1)
3538 errx(EX_USAGE, "extraneous filename arguments");
3540 if ((f = fopen(av[0], "r")) == NULL)
3541 err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3543 if (pflag) {
3544 /* pipe through preprocessor (cpp or m4) */
3545 int pipedes[2];
3547 args[i] = NULL;
3549 if (pipe(pipedes) == -1)
3550 err(EX_OSERR, "cannot create pipe");
3552 switch((preproc = fork())) {
3553 case -1:
3554 err(EX_OSERR, "cannot fork");
3556 case 0:
3557 /* child */
3558 if (dup2(fileno(f), 0) == -1
3559 || dup2(pipedes[1], 1) == -1)
3560 err(EX_OSERR, "dup2()");
3561 fclose(f);
3562 close(pipedes[1]);
3563 close(pipedes[0]);
3564 execvp(cmd, args);
3565 err(EX_OSERR, "execvp(%s) failed", cmd);
3567 default:
3568 /* parent */
3569 fclose(f);
3570 close(pipedes[1]);
3571 if ((f = fdopen(pipedes[0], "r")) == NULL) {
3572 int savederrno = errno;
3574 kill(preproc, SIGTERM);
3575 errno = savederrno;
3576 err(EX_OSERR, "fdopen()");
3581 while (fgets(buf, BUFSIZ, f)) {
3582 lineno++;
3583 snprintf(linename, sizeof(linename), "Line %d", lineno);
3584 args[0] = linename;
3586 if (*buf == '#')
3587 continue;
3588 if ((p = strchr(buf, '#')) != NULL)
3589 *p = '\0';
3590 i = 1;
3591 if (qflag)
3592 args[i++] = "-q";
3593 for (a = strtok(buf, WHITESP);
3594 a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3595 args[i] = a;
3596 if (i == (qflag? 2: 1))
3597 continue;
3598 if (i == MAX_ARGS)
3599 errx(EX_USAGE, "%s: too many arguments",
3600 linename);
3601 args[i] = NULL;
3603 ipfw_main(i, args);
3605 fclose(f);
3606 if (pflag) {
3607 if (waitpid(preproc, &status, 0) == -1)
3608 errx(EX_OSERR, "waitpid()");
3609 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3610 errx(EX_UNAVAILABLE,
3611 "preprocessor exited with status %d",
3612 WEXITSTATUS(status));
3613 else if (WIFSIGNALED(status))
3614 errx(EX_UNAVAILABLE,
3615 "preprocessor exited with signal %d",
3616 WTERMSIG(status));
3621 main(int ac, char *av[])
3623 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3624 if (s < 0)
3625 err(EX_UNAVAILABLE, "socket");
3628 * If the last argument is an absolute pathname, interpret it
3629 * as a file to be preprocessed.
3632 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3633 ipfw_readfile(ac, av);
3634 else
3635 ipfw_main(ac, av);
3636 return EX_OK;