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
23 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
47 #include <netinet/in.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
50 #include <netinet/ip_icmp.h>
51 #include <netinet/ip_fw.h>
52 #include <net/route.h> /* def. of struct route */
53 #include <netinet/ip_dummynet.h>
54 #include <netinet/tcp.h>
55 #include <arpa/inet.h>
57 int s, /* main RAW socket */
58 do_resolv, /* Would try to resolve all */
59 do_acct, /* Show packet/byte count */
60 do_time, /* Show time stamps */
61 do_quiet, /* Be quiet in add and flush */
62 do_force, /* Don't ask for confirmation */
63 do_pipe, /* this cmd refers to a pipe */
64 do_sort, /* field to sort results (0 = no) */
65 do_dynamic, /* display dynamic rules */
66 do_expired, /* display expired dynamic rules */
69 #define IP_MASK_ALL 0xffffffff
72 * structure to hold flag names and associated values to be
73 * set in the appropriate masks.
74 * A NULL string terminates the array.
75 * Often, an element with 0 value contains an error string.
83 static struct _s_x f_tcpflags[] = {
94 static struct _s_x f_tcpopts[] = {
95 { "mss", IP_FW_TCPOPT_MSS },
96 { "maxseg", IP_FW_TCPOPT_MSS },
97 { "window", IP_FW_TCPOPT_WINDOW },
98 { "sack", IP_FW_TCPOPT_SACK },
99 { "ts", IP_FW_TCPOPT_TS },
100 { "timestamp", IP_FW_TCPOPT_TS },
101 { "cc", IP_FW_TCPOPT_CC },
107 * IP options span the range 0 to 255 so we need to remap them
108 * (though in fact only the low 5 bits are significant).
110 static struct _s_x f_ipopts[] = {
111 { "ssrr", IP_FW_IPOPT_SSRR},
112 { "lsrr", IP_FW_IPOPT_LSRR},
113 { "rr", IP_FW_IPOPT_RR},
114 { "ts", IP_FW_IPOPT_TS},
119 #if 0 /* XXX not used yet */
120 static struct _s_x f_iptos[] = {
121 { "lowdelay", IPTOS_LOWDELAY},
122 { "throughput", IPTOS_THROUGHPUT},
123 { "reliability", IPTOS_RELIABILITY},
124 { "mincost", IPTOS_MINCOST},
125 { "congestion", IPTOS_CE},
126 { "ecntransport", IPTOS_ECT},
127 { "ip tos option", 0},
132 static struct _s_x limit_masks[] = {
133 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
134 {"src-addr", DYN_SRC_ADDR},
135 {"src-port", DYN_SRC_PORT},
136 {"dst-addr", DYN_DST_ADDR},
137 {"dst-port", DYN_DST_PORT},
142 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
143 * This is only used in this code.
145 #define IPPROTO_ETHERTYPE 0x1000
146 static struct _s_x ether_types[] = {
148 * Note, we cannot use "-:&/" in the names because they are field
149 * separators in the type specifications. Also, we use s = NULL as
150 * end-delimiter, because a type of 0 can be legal.
163 { "pppoe_disc", 0x8863 },
164 { "pppoe_sess", 0x8864 },
165 { "ipx_8022", 0x00E0 },
166 { "ipx_8023", 0x0000 },
167 { "ipx_ii", 0x8137 },
168 { "ipx_snap", 0x8137 },
174 static void show_usage(void);
240 struct _s_x dummynet_params[] = {
242 { "buckets", TOK_BUCKETS },
243 { "dst-ip", TOK_DSTIP },
244 { "src-ip", TOK_SRCIP },
245 { "dst-port", TOK_DSTPORT },
246 { "src-port", TOK_SRCPORT },
247 { "proto", TOK_PROTO },
248 { "weight", TOK_WEIGHT },
250 { "mask", TOK_MASK },
251 { "droptail", TOK_DROPTAIL },
253 { "gred", TOK_GRED },
255 { "bandwidth", TOK_BW },
256 { "delay", TOK_DELAY },
257 { "queue", TOK_QUEUE },
258 { "dummynet-params", TOK_NULL },
262 struct _s_x rule_actions[] = {
263 { "accept", TOK_ACCEPT },
264 { "pass", TOK_ACCEPT },
265 { "allow", TOK_ACCEPT },
266 { "permit", TOK_ACCEPT },
267 { "count", TOK_COUNT },
268 { "pipe", TOK_PIPE },
269 { "queue", TOK_QUEUE },
270 { "divert", TOK_DIVERT },
272 { "fwd", TOK_FORWARD },
273 { "forward", TOK_FORWARD },
274 { "skipto", TOK_SKIPTO },
275 { "deny", TOK_DENY },
276 { "drop", TOK_DENY },
277 { "reject", TOK_REJECT },
278 { "reset", TOK_RESET },
279 { "check-state", TOK_CHECKSTATE },
284 struct _s_x rule_options[] = {
288 { "limit", TOK_LIMIT },
289 { "keep-state", TOK_KEEPSTATE },
290 { "bridged", TOK_LAYER2 },
291 { "layer2", TOK_LAYER2 },
293 { "xmit", TOK_XMIT },
294 { "recv", TOK_RECV },
296 { "fragment", TOK_FRAG },
297 { "frag", TOK_FRAG },
298 { "ipoptions", TOK_IPOPTS },
299 { "ipopts", TOK_IPOPTS },
300 { "iplen", TOK_IPLEN },
301 { "ipid", TOK_IPID },
302 { "ipprecedence", TOK_IPPRECEDENCE },
303 { "iptos", TOK_IPTOS },
304 { "ipttl", TOK_IPTTL },
305 { "ipversion", TOK_IPVER },
306 { "ipver", TOK_IPVER },
307 { "estab", TOK_ESTAB },
308 { "established", TOK_ESTAB },
309 { "setup", TOK_SETUP },
310 { "tcpflags", TOK_TCPFLAGS },
311 { "tcpflgs", TOK_TCPFLAGS },
312 { "tcpoptions", TOK_TCPOPTS },
313 { "tcpopts", TOK_TCPOPTS },
314 { "tcpseq", TOK_TCPSEQ },
315 { "tcpack", TOK_TCPACK },
316 { "tcpwin", TOK_TCPWIN },
317 { "icmptypes", TOK_ICMPTYPES },
319 { "not", TOK_NOT }, /* pseudo option */
320 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
321 { "or", TOK_OR }, /* pseudo option */
322 { "|", /* escape */ TOK_OR }, /* pseudo option */
328 * match_token takes a table and a string, returns the value associated
329 * with the string (0 meaning an error in most cases)
332 match_token(struct _s_x *table, char *string)
335 int i = strlen(string);
337 for (pt = table ; i && pt->s != NULL ; pt++)
338 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
344 match_value(struct _s_x *p, u_int32_t value)
346 for (; p->s != NULL; p++)
353 * prints one port, symbolic or numeric
356 print_port(int proto, u_int16_t port)
359 if (proto == IPPROTO_ETHERTYPE) {
362 if (do_resolv && (s = match_value(ether_types, port)) )
365 printf("0x%04x", port);
367 struct servent *se = NULL;
369 struct protoent *pe = getprotobynumber(proto);
371 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
374 printf("%s", se->s_name);
381 * print the values in a list of ports
382 * XXX todo: add support for mask.
385 print_newports(ipfw_insn_u16 *cmd, int proto)
387 u_int16_t *p = cmd->ports;
391 if (cmd->o.len & F_NOT)
393 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
395 print_port(proto, p[0]);
398 print_port(proto, p[1]);
405 * Like strtol, but also translates service names into port numbers
406 * for some protocols.
408 * proto == -1 disables the protocol check;
409 * proto == IPPROTO_ETHERTYPE looks up an internal table
410 * proto == <some value in /etc/protocols> matches the values there.
413 strtoport(char *s, char **end, int base, int proto)
422 return strtol(s, end, base);
425 * find separator and replace with a '\0'
427 for (s1 = s; *s1 && isalnum(*s1) ; s1++)
432 if (proto == IPPROTO_ETHERTYPE) {
433 i = match_token(ether_types, s);
435 if (i == -1) { /* not found */
443 struct protoent *pe = NULL;
447 pe = getprotobynumber(proto);
449 se = getservbyname(s, pe ? pe->p_name : NULL);
453 return ntohs(se->s_port);
462 * fill the body of the command with the list of port ranges.
463 * At the moment it only understands numeric ranges.
466 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
468 u_int16_t *p = cmd->ports;
471 for (; *av ; i++, p +=2 ) {
475 a = strtoport(av, &s, 0, proto);
476 if (s == av) /* no parameter */
478 if (*s == '-') { /* a range */
480 b = strtoport(av, &s, 0, proto);
481 if (s == av) /* no parameter */
485 } else if (*s == ',' || *s == '\0' ) {
487 } else /* invalid separator */
492 if (i+1 > F_LEN_MASK)
493 errx(EX_DATAERR, "too many port range\n");
494 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
499 #if 0 /* XXX not used yet */
500 static struct _s_x icmpcodes[] = {
501 { "net", ICMP_UNREACH_NET },
502 { "host", ICMP_UNREACH_HOST },
503 { "protocol", ICMP_UNREACH_PROTOCOL },
504 { "port", ICMP_UNREACH_PORT },
505 { "needfrag", ICMP_UNREACH_NEEDFRAG },
506 { "srcfail", ICMP_UNREACH_SRCFAIL },
507 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
508 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
509 { "isolated", ICMP_UNREACH_ISOLATED },
510 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
511 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
512 { "tosnet", ICMP_UNREACH_TOSNET },
513 { "toshost", ICMP_UNREACH_TOSHOST },
514 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
515 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
516 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
521 fill_reject_code(u_short *codep, char *str)
526 val = strtoul(str, &s, 0);
527 if (s == str || *s != '\0' || val >= 0x100)
528 val = match_token(icmpcodes, str);
530 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
536 print_reject_code(u_int32_t code)
538 char *s = match_value(icmpcodes, code);
545 #endif /* XXX not used yet */
548 * Returns the number of bits set (from left) in a contiguous bitmask,
549 * or -1 if the mask is not contiguous.
550 * XXX this needs a proper fix.
551 * This effectively works on masks in big-endian (network) format.
552 * when compiled on little endian architectures.
554 * First bit is bit 7 of the first byte -- note, for MAC addresses,
555 * the first bit on the wire is bit 0 of the first byte.
556 * len is the max length in bits.
559 contigmask(u_char *p, int len)
562 for (i=0; i<len ; i++)
563 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
565 for (n=i+1; n < len; n++)
566 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
567 return -1; /* mask not contiguous */
572 * print flags set/clear in the two bitmasks passed as parameters.
573 * There is a specialized check for f_tcpflags.
576 print_flags(char *name, ipfw_insn *cmd, struct _s_x *list)
580 u_char set = cmd->arg1 & 0xff;
581 u_char clear = (cmd->arg1 >> 8) & 0xff;
583 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
588 printf(" %s ", name);
589 for (i=0; list[i].x != 0; i++) {
590 if (set & list[i].x) {
592 printf("%s%s", comma, list[i].s);
595 if (clear & list[i].x) {
597 printf("%s!%s", comma, list[i].s);
604 * Print the ip address contained in a command.
607 print_ip(ipfw_insn_ip *cmd)
609 struct hostent *he = NULL;
612 printf("%s ", cmd->o.len & F_NOT ? " not": "");
614 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
618 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
625 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
626 printf("%s/%d", inet_ntoa(cmd->addr),
627 contigmask((u_char *)&x, 32));
628 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
629 x &= 0xff; /* base */
630 d = (u_int32_t *)&(cmd->mask);
631 for (i=0; i < cmd->o.arg1; i++)
632 if (d[ i/32] & (1<<(i & 31))) {
633 printf("%c%d", comma, i+x);
639 if (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST)
642 mb = contigmask((u_char *)&(cmd->mask.s_addr), 32);
643 if (mb == 32 && do_resolv)
644 he = gethostbyaddr((char *)&(cmd->addr.s_addr),
645 sizeof(u_long), AF_INET);
646 if (he != NULL) /* resolved to name */
647 printf("%s", he->h_name);
648 else if (mb == 0) /* any */
650 else { /* numeric IP followed by some kind of mask */
651 printf("%s", inet_ntoa(cmd->addr));
653 printf(":%s", inet_ntoa(cmd->mask));
660 * prints a MAC address/mask pair
663 print_mac(u_char *addr, u_char *mask)
665 int l = contigmask(mask, 48);
670 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
671 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
673 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
674 mask[0], mask[1], mask[2],
675 mask[3], mask[4], mask[5]);
683 * show_ipfw() prints the body of an ipfw rule.
684 * Because the standard rule has at least proto src_ip dst_ip, we use
685 * a helper function to produce these entries if not provided explicitly.
693 show_prerequisites(int *flags, int want)
695 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
697 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
699 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
705 show_ipfw(struct ip_fw *rule)
709 int proto = 0; /* default */
710 int flags = 0; /* prerequisites */
711 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
712 int or_block = 0; /* we are in an or block */
714 printf("%05u ", rule->rulenum);
717 printf("%10qu %10qu ", rule->pcnt, rule->bcnt);
720 if (rule->timestamp) {
722 time_t t = _long_to_time(rule->timestamp);
724 strcpy(timestr, ctime(&t));
725 *strchr(timestr, '\n') = '\0';
726 printf("%s ", timestr);
733 * first print actions
735 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
736 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
737 switch(cmd->opcode) {
739 printf("check-state");
740 /* avoid printing anything else */
741 flags = HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP;
746 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
747 double d = 1.0 * p->d[0];
749 d = 1 - (d / 0x7fffffff);
750 printf("prob %f ", d);
767 printf("skipto %u", cmd->arg1);
771 printf("pipe %u", cmd->arg1);
775 printf("queue %u", cmd->arg1);
779 printf("divert %u", cmd->arg1);
783 printf("tee %u", cmd->arg1);
788 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
790 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
792 printf(",%d", ntohs(s->sa.sin_port));
796 case O_LOG: /* O_LOG is printed last */
797 logptr = (ipfw_insn_log *)cmd;
801 printf("** unrecognized action %d len %d",
802 cmd->opcode, cmd->len);
806 if (logptr->max_log > 0)
807 printf(" log logamount %d ", logptr->max_log);
812 * then print the body
814 for (l = rule->act_ofs, cmd = rule->cmd ;
815 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
816 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; /* useful alias */
818 switch(cmd->opcode) {
820 break; /* no need to print anything here */
823 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
824 if ( (flags & HAVE_MAC) == 0)
827 if (cmd->len & F_NOT)
829 print_mac( m->addr, m->mask);
830 print_mac( m->addr + 6, m->mask + 6);
835 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE);
842 show_prerequisites(&flags, HAVE_PROTO);
843 if (!(flags & HAVE_SRCIP))
845 if ((cmd->len & F_OR) && !or_block)
847 print_ip((ipfw_insn_ip *)cmd);
855 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP);
856 if (!(flags & HAVE_DSTIP))
858 if ((cmd->len & F_OR) && !or_block)
860 print_ip((ipfw_insn_ip *)cmd);
865 show_prerequisites(&flags,
866 HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
868 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP);
869 print_newports((ipfw_insn_u16 *)cmd, proto);
875 if ((cmd->len & F_OR) && !or_block)
877 if (cmd->len & F_NOT)
880 pe = getprotobynumber(cmd->arg1);
882 printf(" %s", pe->p_name);
884 printf(" %u", cmd->arg1);
889 default: /*options ... */
890 show_prerequisites(&flags,
891 HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
892 if ((cmd->len & F_OR) && !or_block)
894 if (cmd->len & F_NOT && cmd->opcode != O_IN)
896 switch(cmd->opcode) {
902 printf(cmd->len & F_NOT ? " out" : " in");
912 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
914 if (cmd->opcode == O_XMIT)
916 else if (cmd->opcode == O_RECV)
918 else if (cmd->opcode == O_VIA)
920 if (cmdif->name[0] == '\0')
921 printf(" %s %s", s, inet_ntoa(cmdif->p.ip));
922 else if (cmdif->p.unit == -1)
923 printf(" %s %s*", s, cmdif->name);
925 printf(" %s %s%d", s, cmdif->name, cmdif->p.unit);
930 printf(" ipid %u", cmd->arg1 );
934 printf(" ipttl %u", cmd->arg1 );
938 printf(" ipver %u", cmd->arg1 );
942 printf(" iplen %u", cmd->arg1 );
946 print_flags("ipoptions", cmd, f_ipopts);
950 printf(" established");
954 print_flags("tcpflags", cmd, f_tcpflags);
958 print_flags("tcpoptions", cmd, f_tcpopts);
962 printf(" tcpwin %d", ntohs(cmd->arg1));
966 printf(" tcpack %d", ntohl(cmd32->d[0]));
970 printf(" tcpseq %d", ntohl(cmd32->d[0]));
975 struct passwd *pwd = getpwuid(cmd32->d[0]);
978 printf(" uid %s", pwd->pw_name);
980 printf(" uid %u", cmd32->d[0]);
986 struct group *grp = getgrgid(cmd32->d[0]);
989 printf(" gid %s", grp->gr_name);
991 printf(" gid %u", cmd32->d[0]);
996 printf(" keep-state");
1001 struct _s_x *p = limit_masks;
1002 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1003 u_int8_t x = c->limit_mask;
1007 for ( ; p->x != 0 ; p++)
1010 printf("%s%s", comma, p->s);
1013 printf(" %d", c->conn_limit);
1018 printf(" [opcode %d len %d]",
1019 cmd->opcode, cmd->len);
1022 if (cmd->len & F_OR) {
1025 } else if (or_block) {
1030 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
1032 #if 0 /* old stuff */
1033 switch (chain->fw_flg & IP_FW_F_COMMAND) {
1034 case IP_FW_F_REJECT:
1035 if (chain->fw_reject_code == IP_FW_REJECT_RST)
1039 print_reject_code(chain->fw_reject_code);
1045 if (chain->fw_ipflg & IP_FW_IF_IPOPT)
1046 print_flags("ipopt", chain->fw_ipopt, chain->fw_ipnopt,
1049 if (chain->fw_ipflg & IP_FW_IF_IPPRE)
1050 printf(" ipprecedence %u", (chain->fw_iptos & 0xe0) >> 5);
1052 if (chain->fw_ipflg & IP_FW_IF_IPTOS)
1053 print_flags("iptos", chain->fw_iptos, chain->fw_ipntos,
1056 if (chain->fw_flg & IP_FW_F_ICMPBIT) {
1060 printf(" icmptype");
1062 for (i = 0; i < IP_FW_ICMPTYPES_DIM; ++i)
1063 for (j = 0; j < sizeof(unsigned) * 8; ++j)
1064 if (chain->fw_uar.fw_icmptypes[i] & (1 << j)) {
1065 printf("%c%d", first ? ' ' : ',',
1066 i * sizeof(unsigned) * 8 + j);
1070 #endif /* XXX old stuff */
1075 show_dyn_ipfw(ipfw_dyn_rule *d)
1077 struct protoent *pe;
1081 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1085 printf("%05d %10qu %10qu (%ds)",
1086 (int)(d->rule), d->pcnt, d->bcnt, d->expire);
1087 switch (d->dyn_type) {
1088 case O_LIMIT_PARENT:
1089 printf(" PARENT %d", d->count);
1094 case O_KEEP_STATE: /* bidir, no mask */
1099 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1100 printf(" %s", pe->p_name);
1102 printf(" proto %u", d->id.proto);
1104 a.s_addr = htonl(d->id.src_ip);
1105 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1107 a.s_addr = htonl(d->id.dst_ip);
1108 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1113 sort_q(const void *pa, const void *pb)
1115 int rev = (do_sort < 0);
1116 int field = rev ? -do_sort : do_sort;
1118 const struct dn_flow_queue *a = pa;
1119 const struct dn_flow_queue *b = pb;
1123 res = a->len - b->len;
1126 res = a->len_bytes - b->len_bytes;
1129 case 3: /* tot pkts */
1130 res = a->tot_pkts - b->tot_pkts;
1133 case 4: /* tot bytes */
1134 res = a->tot_bytes - b->tot_bytes;
1141 return (int)(rev ? res : -res);
1145 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
1149 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1150 fs->flow_mask.proto,
1151 fs->flow_mask.src_ip, fs->flow_mask.src_port,
1152 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
1153 if (fs->rq_elements == 0)
1156 printf("BKT Prot ___Source IP/port____ "
1157 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1159 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
1160 for (l = 0; l < fs->rq_elements; l++) {
1162 struct protoent *pe;
1164 ina.s_addr = htonl(q[l].id.src_ip);
1165 printf("%3d ", q[l].hash_slot);
1166 pe = getprotobynumber(q[l].id.proto);
1168 printf("%-4s ", pe->p_name);
1170 printf("%4u ", q[l].id.proto);
1171 printf("%15s/%-5d ",
1172 inet_ntoa(ina), q[l].id.src_port);
1173 ina.s_addr = htonl(q[l].id.dst_ip);
1174 printf("%15s/%-5d ",
1175 inet_ntoa(ina), q[l].id.dst_port);
1176 printf("%4qu %8qu %2u %4u %3u\n",
1177 q[l].tot_pkts, q[l].tot_bytes,
1178 q[l].len, q[l].len_bytes, q[l].drops);
1180 printf(" S %20qd F %20qd\n",
1186 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
1191 char red[90]; /* Display RED parameters */
1194 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1196 sprintf(qs, "%d KB", l / 1024);
1198 sprintf(qs, "%d B", l);
1200 sprintf(qs, "%3d sl.", l);
1202 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
1205 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
1207 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
1208 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
1209 1.0 * fs->w_q / (double)(1 << SCALE_RED),
1210 SCALE_VAL(fs->min_th),
1211 SCALE_VAL(fs->max_th),
1212 1.0 * fs->max_p / (double)(1 << SCALE_RED));
1214 sprintf(red, "droptail");
1216 printf("%s %s%s %d queues (%d buckets) %s\n",
1217 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
1221 list_pipes(void *data, int nbytes, int ac, char *av[])
1225 struct dn_pipe *p = (struct dn_pipe *) data;
1226 struct dn_flow_set *fs;
1227 struct dn_flow_queue *q;
1231 rulenum = strtoul(*av++, NULL, 10);
1234 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
1235 double b = p->bandwidth;
1239 if (p->next != (struct dn_pipe *)DN_IS_PIPE)
1240 break; /* done with pipes, now queues */
1243 * compute length, as pipe have variable size
1245 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
1246 next = (void *)p + l;
1249 if (rulenum != 0 && rulenum != p->pipe_nr)
1253 * Print rate (or clocking interface)
1255 if (p->if_name[0] != '\0')
1256 sprintf(buf, "%s", p->if_name);
1258 sprintf(buf, "unlimited");
1259 else if (b >= 1000000)
1260 sprintf(buf, "%7.3f Mbit/s", b/1000000);
1262 sprintf(buf, "%7.3f Kbit/s", b/1000);
1264 sprintf(buf, "%7.3f bit/s ", b);
1266 sprintf(prefix, "%05d: %s %4d ms ",
1267 p->pipe_nr, buf, p->delay);
1268 print_flowset_parms(&(p->fs), prefix);
1270 printf(" V %20qd\n", p->V >> MY_M);
1272 q = (struct dn_flow_queue *)(p+1);
1273 list_queues(&(p->fs), q);
1275 for (fs = next; nbytes >= sizeof *fs; fs = next) {
1278 if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE)
1280 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
1281 next = (void *)fs + l;
1283 q = (struct dn_flow_queue *)(fs+1);
1284 sprintf(prefix, "q%05d: weight %d pipe %d ",
1285 fs->fs_nr, fs->weight, fs->parent_nr);
1286 print_flowset_parms(fs, prefix);
1292 list(int ac, char *av[])
1295 ipfw_dyn_rule *dynrules, *d;
1297 void *lim, *data = NULL;
1298 int n, nbytes, nstat, ndyn;
1299 int exitval = EX_OK;
1306 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1307 int nalloc = 1024; /* start somewhere... */
1312 /* get rules or pipes from kernel, resizing array as necessary */
1315 while (nbytes >= nalloc) {
1316 nalloc = nalloc * 2 + 200;
1318 if ((data = realloc(data, nbytes)) == NULL)
1319 err(EX_OSERR, "realloc");
1320 if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0)
1321 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1322 do_pipe ? "DUMMYNET" : "FW");
1326 list_pipes(data, nbytes, ac, av);
1331 * Count static rules. They have variable size so we
1332 * need to scan the list to count them.
1334 for (nstat = 1, r = data, lim = data + nbytes;
1335 r->rulenum < 65535 && (void *)r < lim;
1336 ++nstat, r = (void *)r + RULESIZE(r) )
1340 * Count dynamic rules. This is easier as they have
1343 r = (void *)r + RULESIZE(r);
1344 dynrules = (ipfw_dyn_rule *)r ;
1345 n = (void *)r - data;
1346 ndyn = (nbytes - n) / sizeof *dynrules;
1348 /* if no rule numbers were specified, list all rules */
1350 for (n = 0, r = data; n < nstat;
1351 n++, r = (void *)r + RULESIZE(r) )
1354 if (do_dynamic && ndyn) {
1355 printf("## Dynamic rules (%d):\n", ndyn);
1356 for (n = 0, d = dynrules; n < ndyn; n++, d++)
1362 /* display specific rules requested on command line */
1364 for (lac = ac, lav = av; lac != 0; lac--) {
1365 /* convert command line rule # */
1366 rnum = strtoul(*lav++, &endptr, 10);
1369 warnx("invalid rule number: %s", *(lav - 1));
1372 for (n = seen = 0, r = data; n < nstat;
1373 n++, r = (void *)r + RULESIZE(r) ) {
1374 if (r->rulenum > rnum)
1376 if (r->rulenum == rnum) {
1382 /* give precedence to other error(s) */
1383 if (exitval == EX_OK)
1384 exitval = EX_UNAVAILABLE;
1385 warnx("rule %lu does not exist", rnum);
1389 if (do_dynamic && ndyn) {
1390 printf("## Dynamic rules:\n");
1391 for (lac = ac, lav = av; lac != 0; lac--) {
1392 rnum = strtoul(*lav++, &endptr, 10);
1394 /* already warned */
1396 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1397 if ((int)(d->rule) > rnum)
1399 if ((int)(d->rule) == rnum)
1410 if (exitval != EX_OK)
1417 fprintf(stderr, "usage: ipfw [options]\n"
1418 " add [number] rule\n"
1419 " pipe number config [pipeconfig]\n"
1420 " queue number config [queueconfig]\n"
1422 " [pipe] delete number ...\n"
1423 " [pipe] {list|show} [number ...]\n"
1424 " {zero|resetlog} [number ...]\n"
1425 "do \"ipfw -h\" or see ipfw manpage for details\n"
1435 fprintf(stderr, "ipfw syntax summary:\n"
1436 "ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1437 "ipfw {pipe|queue} N config BODY\n"
1438 "ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1440 "RULE: [1..] [PROB] BODY\n"
1441 "RULENUM: INTEGER(1..65534)\n"
1442 "PROB: prob REAL(0..1)\n"
1443 "BODY: check-state [LOG] (no body) |\n"
1444 " ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1445 "ACTION: check-state | allow | count | deny | reject | skipto N |\n"
1446 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1447 "ADDR: [ MAC dst src ether_type ] \n"
1448 " [ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1449 "IPLIST: IPADDR | ( IPADDR or ... or IPADDR )\n"
1450 "IPADDR: [not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1451 "OPTION_LIST: OPTION [,OPTION_LIST]\n"
1458 lookup_host (char *host, struct in_addr *ipaddr)
1462 if (!inet_aton(host, ipaddr)) {
1463 if ((he = gethostbyname(host)) == NULL)
1465 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1471 * fills the addr and mask fields in the instruction as appropriate from av.
1472 * Update length as appropriate.
1473 * The following formats are allowed:
1474 * any matches any IP. Actually returns an empty instruction.
1475 * me returns O_IP_*_ME
1476 * 1.2.3.4 single IP address
1477 * 1.2.3.4:5.6.7.8 address:mask
1478 * 1.2.3.4/24 address/mask
1479 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1482 fill_ip(ipfw_insn_ip *cmd, char *av)
1484 char *p = 0, md = 0;
1487 cmd->o.len &= ~F_LEN_MASK; /* zero len */
1489 if (!strncmp(av, "any", strlen(av)))
1492 if (!strncmp(av, "me", strlen(av))) {
1493 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1497 p = strchr(av, '/');
1499 p = strchr(av, ':');
1505 if (lookup_host(av, &cmd->addr) != 0)
1506 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
1509 if (!inet_aton(p, &cmd->mask))
1510 errx(EX_DATAERR, "bad netmask ``%s''", p);
1515 cmd->mask.s_addr = htonl(0);
1517 errx(EX_DATAERR, "bad width ``%s''", p);
1519 cmd->mask.s_addr = htonl(~0 << (32 - i));
1522 cmd->mask.s_addr = htonl(~0);
1525 cmd->addr.s_addr &= cmd->mask.s_addr;
1527 * now look if we have a set of addresses. They are stored as follows:
1528 * arg1 is the set size (powers of 2, 2..256)
1529 * addr is the base address IN HOST FORMAT
1530 * mask.. is an array of u_int32_t with bits set.
1534 if (p) { /* fetch addresses */
1537 int i = contigmask((u_char *)&(cmd->mask), 32);
1539 if (i < 24 || i > 31) {
1540 fprintf(stderr, "invalid set with mask %d\n",
1544 cmd->o.arg1 = 1<<(32-i);
1545 cmd->addr.s_addr = ntohl(cmd->addr.s_addr);
1546 d = (u_int32_t *)&cmd->mask;
1547 cmd->o.opcode = O_IP_DST_SET; /* default */
1548 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
1549 fprintf(stderr,"-- set size %d cmdlen %d\n",
1550 cmd->o.arg1, cmd->o.len );
1551 for (i = 0; i < cmd->o.arg1/32 ; i++)
1552 d[i] = 0; /* clear masks */
1555 low = cmd->addr.s_addr & 0xff;
1556 high = low + cmd->o.arg1 - 1;
1557 while (isdigit(*av)) {
1559 u_int16_t a = strtol(av, &s, 0);
1561 if (s == av) /* no parameter */
1563 if (a < low || a > high) {
1564 fprintf(stderr, "addr %d out of range [%d-%d]\n",
1569 d[ a/32] |= 1<<(a & 31);
1577 if (cmd->mask.s_addr == 0) { /* any */
1578 if (cmd->o.len & F_NOT)
1579 errx(EX_DATAERR, "not any never matches");
1580 else /* useless, nuke it */
1582 } else if (cmd->mask.s_addr == IP_MASK_ALL) /* one IP */
1583 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1584 else /* addr/mask */
1585 cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip);
1590 * helper function to process a set of flags and set bits in the
1591 * appropriate masks.
1594 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
1595 struct _s_x *flags, char *p)
1597 u_int8_t set=0, clear=0;
1600 char *q; /* points to the separator */
1602 u_int8_t *which; /* mask we are working on */
1612 val = match_token(flags, p);
1614 errx(EX_DATAERR, "invalid flag %s", p);
1615 *which |= (u_int8_t)val;
1618 cmd->opcode = opcode;
1619 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
1620 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
1623 #if 0 /* XXX todo */
1625 fill_icmptypes(unsigned *types, char **vp, u_int *fw_flg)
1627 unsigned long icmptype;
1634 icmptype = strtoul(c, &c, 0);
1636 if (*c != ',' && *c != '\0')
1637 errx(EX_DATAERR, "invalid ICMP type");
1639 if (icmptype >= IP_FW_ICMPTYPES_DIM * sizeof(unsigned) * 8)
1640 errx(EX_DATAERR, "ICMP type out of range");
1642 types[icmptype / (sizeof(unsigned) * 8)] |=
1643 1 << (icmptype % (sizeof(unsigned) * 8));
1644 *fw_flg |= IP_FW_F_ICMPBIT;
1647 #endif /* XXX todo */
1650 delete(int ac, char *av[])
1653 struct dn_pipe pipe;
1655 int exitval = EX_OK;
1657 memset(&pipe, 0, sizeof pipe);
1662 while (ac && isdigit(**av)) {
1663 i = atoi(*av); av++; ac--;
1669 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
1670 &pipe, sizeof pipe);
1673 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1674 do_pipe == 1 ? pipe.pipe_nr :
1679 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum,
1682 exitval = EX_UNAVAILABLE;
1683 warn("rule %u: setsockopt(IP_FW_DEL)",
1688 if (exitval != EX_OK)
1694 * fill the interface structure. We do not check the name as we can
1695 * create interfaces dynamically, so checking them at insert time
1696 * makes relatively little sense.
1697 * A '*' following the name means any unit.
1700 fill_iface(ipfw_insn_if *cmd, char *arg)
1702 cmd->name[0] = '\0';
1703 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
1705 /* Parse the interface or address */
1706 if (!strcmp(arg, "any"))
1707 cmd->o.len = 0; /* effectively ignore this command */
1708 else if (!isdigit(*arg)) {
1711 strncpy(cmd->name, arg, sizeof(cmd->name));
1712 cmd->name[sizeof(cmd->name) - 1] = '\0';
1713 /* find first digit or wildcard */
1714 for (q = cmd->name; *q && !isdigit(*q) && *q != '*'; q++)
1716 cmd->p.unit = (*q == '*') ? -1 : atoi(q);
1718 } else if (!inet_aton(arg, &cmd->p.ip))
1719 errx(EX_DATAERR, "bad ip address ``%s''", arg);
1723 * the following macro returns an error message if we run out of
1726 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
1729 config_pipe(int ac, char **av)
1731 struct dn_pipe pipe;
1737 memset(&pipe, 0, sizeof pipe);
1741 if (ac && isdigit(**av)) {
1742 i = atoi(*av); av++; ac--;
1750 int tok = match_token(dummynet_params, *av);
1755 NEED1("plr needs argument 0..1\n");
1756 d = strtod(av[0], NULL);
1761 pipe.fs.plr = (int)(d*0x7fffffff);
1766 NEED1("queue needs queue size\n");
1768 pipe.fs.qsize = strtoul(av[0], &end, 0);
1769 if (*end == 'K' || *end == 'k') {
1770 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1771 pipe.fs.qsize *= 1024;
1772 } else if (*end == 'B' || !strncmp(end, "by", 2)) {
1773 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1779 NEED1("buckets needs argument\n");
1780 pipe.fs.rq_size = strtoul(av[0], NULL, 0);
1785 NEED1("mask needs mask specifier\n");
1787 * per-flow queue, mask is dst_ip, dst_port,
1788 * src_ip, src_port, proto measured in bits
1792 pipe.fs.flow_mask.dst_ip = 0;
1793 pipe.fs.flow_mask.src_ip = 0;
1794 pipe.fs.flow_mask.dst_port = 0;
1795 pipe.fs.flow_mask.src_port = 0;
1796 pipe.fs.flow_mask.proto = 0;
1800 u_int32_t *p32 = NULL;
1801 u_int16_t *p16 = NULL;
1803 tok = match_token(dummynet_params, *av);
1808 * special case, all bits significant
1810 pipe.fs.flow_mask.dst_ip = ~0;
1811 pipe.fs.flow_mask.src_ip = ~0;
1812 pipe.fs.flow_mask.dst_port = ~0;
1813 pipe.fs.flow_mask.src_port = ~0;
1814 pipe.fs.flow_mask.proto = ~0;
1815 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1819 p32 = &pipe.fs.flow_mask.dst_ip;
1823 p32 = &pipe.fs.flow_mask.src_ip;
1827 p16 = &pipe.fs.flow_mask.dst_port;
1831 p16 = &pipe.fs.flow_mask.src_port;
1838 ac++; av--; /* backtrack */
1842 errx(EX_USAGE, "mask: value missing");
1843 if (*av[0] == '/') {
1844 a = strtoul(av[0]+1, &end, 0);
1845 a = (a == 32) ? ~0 : (1 << a) - 1;
1847 a = strtoul(av[1], &end, 0);
1850 else if (p16 != NULL) {
1853 "mask: must be 16 bit");
1854 *p16 = (u_int16_t)a;
1858 "mask: must be 8 bit");
1859 pipe.fs.flow_mask.proto = (u_int8_t)a;
1862 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1864 } /* end while, config masks */
1870 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
1871 pipe.fs.flags_fs |= DN_IS_RED;
1872 if (tok == TOK_GRED)
1873 pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
1875 * the format for parameters is w_q/min_th/max_th/max_p
1877 if ((end = strsep(&av[0], "/"))) {
1878 double w_q = strtod(end, NULL);
1879 if (w_q > 1 || w_q <= 0)
1880 errx(EX_DATAERR, "0 < w_q <= 1");
1881 pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
1883 if ((end = strsep(&av[0], "/"))) {
1884 pipe.fs.min_th = strtoul(end, &end, 0);
1885 if (*end == 'K' || *end == 'k')
1886 pipe.fs.min_th *= 1024;
1888 if ((end = strsep(&av[0], "/"))) {
1889 pipe.fs.max_th = strtoul(end, &end, 0);
1890 if (*end == 'K' || *end == 'k')
1891 pipe.fs.max_th *= 1024;
1893 if ((end = strsep(&av[0], "/"))) {
1894 double max_p = strtod(end, NULL);
1895 if (max_p > 1 || max_p <= 0)
1896 errx(EX_DATAERR, "0 < max_p <= 1");
1897 pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED));
1903 pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1907 NEED1("bw needs bandwidth or interface\n");
1909 errx(EX_DATAERR, "bandwidth only valid for pipes");
1911 * set clocking interface or bandwidth value
1913 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
1914 int l = sizeof(pipe.if_name)-1;
1915 /* interface name */
1916 strncpy(pipe.if_name, av[0], l);
1917 pipe.if_name[l] = '\0';
1920 pipe.if_name[0] = '\0';
1921 pipe.bandwidth = strtoul(av[0], &end, 0);
1922 if (*end == 'K' || *end == 'k') {
1924 pipe.bandwidth *= 1000;
1925 } else if (*end == 'M') {
1927 pipe.bandwidth *= 1000000;
1929 if (*end == 'B' || !strncmp(end, "by", 2))
1930 pipe.bandwidth *= 8;
1931 if (pipe.bandwidth < 0)
1932 errx(EX_DATAERR, "bandwidth too large");
1939 errx(EX_DATAERR, "delay only valid for pipes");
1940 NEED1("delay needs argument 0..10000ms\n");
1941 pipe.delay = strtoul(av[0], NULL, 0);
1947 errx(EX_DATAERR,"weight only valid for queues");
1948 NEED1("weight needs argument 0..100\n");
1949 pipe.fs.weight = strtoul(av[0], &end, 0);
1955 errx(EX_DATAERR,"pipe only valid for queues");
1956 NEED1("pipe needs pipe_number\n");
1957 pipe.fs.parent_nr = strtoul(av[0], &end, 0);
1962 errx(EX_DATAERR, "unrecognised option ``%s''", *av);
1966 if (pipe.pipe_nr == 0)
1967 errx(EX_DATAERR, "pipe_nr must be > 0");
1968 if (pipe.delay > 10000)
1969 errx(EX_DATAERR, "delay must be < 10000");
1970 } else { /* do_pipe == 2, queue */
1971 if (pipe.fs.parent_nr == 0)
1972 errx(EX_DATAERR, "pipe must be > 0");
1973 if (pipe.fs.weight >100)
1974 errx(EX_DATAERR, "weight must be <= 100");
1976 if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) {
1977 if (pipe.fs.qsize > 1024*1024)
1978 errx(EX_DATAERR, "queue size must be < 1MB");
1980 if (pipe.fs.qsize > 100)
1981 errx(EX_DATAERR, "2 <= queue size <= 100");
1983 if (pipe.fs.flags_fs & DN_IS_RED) {
1985 int lookup_depth, avg_pkt_size;
1986 double s, idle, weight, w_q;
1987 struct clockinfo clock;
1990 if (pipe.fs.min_th >= pipe.fs.max_th)
1991 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1992 pipe.fs.min_th, pipe.fs.max_th);
1993 if (pipe.fs.max_th == 0)
1994 errx(EX_DATAERR, "max_th must be > 0");
1997 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1998 &lookup_depth, &len, NULL, 0) == -1)
2000 errx(1, "sysctlbyname(\"%s\")",
2001 "net.inet.ip.dummynet.red_lookup_depth");
2002 if (lookup_depth == 0)
2003 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
2004 " must be greater than zero");
2007 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2008 &avg_pkt_size, &len, NULL, 0) == -1)
2010 errx(1, "sysctlbyname(\"%s\")",
2011 "net.inet.ip.dummynet.red_avg_pkt_size");
2012 if (avg_pkt_size == 0)
2014 "net.inet.ip.dummynet.red_avg_pkt_size must"
2015 " be greater than zero");
2017 len = sizeof(struct clockinfo);
2018 if (sysctlbyname("kern.clockrate", &clock, &len, NULL, 0) == -1)
2019 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
2022 * Ticks needed for sending a medium-sized packet.
2023 * Unfortunately, when we are configuring a WF2Q+ queue, we
2024 * do not have bandwidth information, because that is stored
2025 * in the parent pipe, and also we have multiple queues
2026 * competing for it. So we set s=0, which is not very
2027 * correct. But on the other hand, why do we want RED with
2030 if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
2033 s = clock.hz * avg_pkt_size * 8 / pipe.bandwidth;
2036 * max idle time (in ticks) before avg queue size becomes 0.
2037 * NOTA: (3/w_q) is approx the value x so that
2038 * (1-w_q)^x < 10^-3.
2040 w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
2041 idle = s * 3. / w_q;
2042 pipe.fs.lookup_step = (int)idle / lookup_depth;
2043 if (!pipe.fs.lookup_step)
2044 pipe.fs.lookup_step = 1;
2046 for (t = pipe.fs.lookup_step; t > 0; --t)
2048 pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2050 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
2053 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2057 get_mac_addr_mask(char *p, u_char *addr, u_char *mask)
2062 addr[i] = mask[i] = 0;
2063 if (!strcmp(p, "any"))
2066 for (i=0; *p && i<6;i++, p++) {
2067 addr[i] = strtol(p, &p, 16);
2068 if (*p != ':') /* we start with the mask */
2071 if (*p == '/') { /* mask len */
2072 l = strtol(p+1, &p, 0);
2073 for (i=0; l>0; l -=8, i++)
2074 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2075 } else if (*p == '&') { /* mask */
2076 for (i=0, p++; *p && i<6;i++, p++) {
2077 mask[i] = strtol(p, &p, 16);
2081 } else if (*p == '\0') {
2090 * helper function, updates the pointer to cmd with the length
2091 * of the current command, and also cleans up the first word of
2092 * the new command in case it has been clobbered before.
2095 next_cmd(ipfw_insn *cmd)
2098 bzero(cmd, sizeof(*cmd));
2103 * A function to fill simple commands of size 1.
2104 * Existing flags are preserved.
2107 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg)
2109 cmd->opcode = opcode;
2110 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2115 * Fetch and add the MAC address and type, with masks. This generates one or
2116 * two microinstructions, and returns the pointer to the last one.
2119 add_mac(ipfw_insn *cmd, int ac, char *av[])
2121 ipfw_insn_mac *mac; /* also *src */
2124 errx(EX_DATAERR, "MAC dst src type");
2126 cmd->opcode = O_MACADDR2;
2127 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2129 mac = (ipfw_insn_mac *)cmd;
2130 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2131 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2134 if (strcmp(av[0], "any") != 0) { /* we have a non-null port */
2137 fill_newports((ipfw_insn_u16 *)cmd, av[0], IPPROTO_ETHERTYPE);
2138 cmd->opcode = O_MAC_TYPE;
2145 * Parse arguments and assemble the microinstructions which make up a rule.
2146 * Rules are added into the 'rulebuf' and then copied in the correct order
2147 * into the actual rule.
2149 * The syntax for a rule starts with the action, followed by an
2150 * optional log action, and the various match patterns.
2151 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2152 * (generated if the rule includes a keep-state option), then the
2153 * various match patterns, the "log" action, and the actual action.
2157 add(int ac, char *av[])
2160 * rules are added into the 'rulebuf' and then copied in
2161 * the correct order into the actual rule.
2162 * Some things that need to go out of order (prob, action etc.)
2165 static u_int32_t rulebuf[255], actbuf[255], cmdbuf[255];
2167 ipfw_insn *src, *dst, *cmd, *action, *prev;
2172 * various flags used to record that we entered some fields.
2174 int have_mac = 0; /* set if we have a MAC address */
2175 int have_state = 0; /* check-state or keep-state */
2179 int open_par = 0; /* open parenthesis ( */
2181 /* proto is here because it is used to fetch ports */
2182 u_char proto = IPPROTO_IP; /* default protocol */
2184 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2185 bzero(cmdbuf, sizeof(cmdbuf));
2186 bzero(rulebuf, sizeof(rulebuf));
2188 rule = (struct ip_fw *)rulebuf;
2189 cmd = (ipfw_insn *)cmdbuf;
2190 action = (ipfw_insn *)actbuf;
2194 /* [rule N] -- Rule number optional */
2195 if (ac && isdigit(**av)) {
2196 rule->rulenum = atoi(*av);
2201 /* [prob D] -- match probability, optional */
2202 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2203 double d = strtod(av[1], NULL);
2205 if (d <= 0 || d > 1)
2206 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2207 if (d != 1) { /* 1 means always match */
2208 action->opcode = O_PROB;
2210 *((int32_t *)(action+1)) =
2211 (int32_t)((1 - d) * 0x7fffffff);
2212 action += action->len;
2217 /* action -- mandatory */
2218 NEED1("missing action");
2219 i = match_token(rule_actions, *av);
2221 action->len = 1; /* default */
2223 case TOK_CHECKSTATE:
2225 action->opcode = O_CHECK_STATE;
2229 action->opcode = O_ACCEPT;
2233 action->opcode = O_DENY;
2237 action->opcode = O_COUNT;
2242 action->len = F_INSN_SIZE(ipfw_insn_pipe);
2245 action->opcode = O_QUEUE;
2246 else if (i == TOK_PIPE)
2247 action->opcode = O_PIPE;
2248 else if (i == TOK_SKIPTO)
2249 action->opcode = O_SKIPTO;
2250 NEED1("missing skipto/pipe/queue number");
2251 action->arg1 = strtoul(*av, NULL, 10);
2257 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2258 NEED1("missing divert/tee port");
2259 action->arg1 = strtoul(*av, NULL, 0);
2260 if (action->arg1 == 0) {
2263 s = getservbyname(av[0], "divert");
2265 action->arg1 = ntohs(s->s_port);
2267 errx(EX_DATAERR, "illegal divert/tee port");
2273 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2276 NEED1("missing forward address[:port]");
2278 action->opcode = O_FORWARD_IP;
2279 action->len = F_INSN_SIZE(ipfw_insn_sa);
2281 p->sa.sin_len = sizeof(struct sockaddr_in);
2282 p->sa.sin_family = AF_INET;
2285 * locate the address-port separator (':' or ',')
2287 s = strchr(*av, ':');
2289 s = strchr(*av, ',');
2292 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2295 "illegal forwarding port ``%s''", s);
2296 p->sa.sin_port = htons( (u_short)i );
2298 lookup_host(*av, &(p->sa.sin_addr));
2304 errx(EX_DATAERR, "invalid action %s\n", *av);
2306 action = next_cmd(action);
2309 } else if (!strncmp(*av, "reject", strlen(*av))) {
2310 rule.fw_flg |= IP_FW_F_REJECT; av++; ac--;
2311 rule.fw_reject_code = ICMP_UNREACH_HOST;
2312 } else if (!strncmp(*av, "reset", strlen(*av))) {
2313 rule.fw_flg |= IP_FW_F_REJECT; av++; ac--;
2314 rule.fw_reject_code = ICMP_REJECT_RST; /* check TCP later */
2315 } else if (!strncmp(*av, "unreach", strlen(*av))) {
2316 rule.fw_flg |= IP_FW_F_REJECT; av++; ac--;
2317 fill_reject_code(&rule.fw_reject_code, *av); av++; ac--;
2319 #endif /* XXX other actions */
2322 * [log [logamount N]] -- log, optional
2324 * If exists, it goes first in the cmdbuf, but then it is
2325 * skipped in the copy section to the end of the buffer.
2327 if (ac && !strncmp(*av, "log", strlen(*av))) {
2328 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2330 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2331 cmd->opcode = O_LOG;
2333 if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2335 NEED1("logamount requires argument");
2336 c->max_log = atoi(*av);
2338 errx(EX_DATAERR, "logamount must be positive");
2341 cmd = next_cmd(cmd);
2349 #define OR_START(target) \
2350 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2352 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2354 if ( (av[0])[1] == '\0') { \
2365 !strncmp(*av, ")", strlen(*av)) || \
2366 !strncmp(*av, "}", strlen(*av)) )) { \
2370 errx(EX_USAGE, "missing \")\"\n"); \
2374 if (ac && !strncmp(*av, "not", strlen(*av))) { \
2375 if (cmd->len & F_NOT) \
2376 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2377 cmd->len |= F_NOT; \
2381 #define OR_BLOCK(target) \
2382 if (ac && !strncmp(*av, "or", strlen(*av))) { \
2383 if (prev == NULL || open_par == 0) \
2384 errx(EX_DATAERR, "invalid OR block"); \
2385 prev->len |= F_OR; \
2392 * protocol, mandatory
2394 OR_START(get_proto);
2396 NEED1("missing protocol");
2398 struct protoent *pe;
2400 if (!strncmp(*av, "all", strlen(*av)))
2401 ; /* same as "ip" */
2402 else if (!strncmp(*av, "MAC", strlen(*av))) {
2403 /* need exactly 3 fields */
2404 cmd = add_mac(cmd, ac-1, av+1); /* exits in case of errors */
2408 } else if ((proto = atoi(*av)) > 0)
2410 else if ((pe = getprotobyname(*av)) != NULL)
2411 proto = pe->p_proto;
2413 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
2415 if (proto != IPPROTO_IP)
2416 fill_cmd(cmd, O_PROTO, 0, proto);
2418 cmd = next_cmd(cmd);
2419 OR_BLOCK(get_proto);
2422 * "from", mandatory (unless we have a MAC address)
2424 if (!ac || strncmp(*av, "from", strlen(*av))) {
2425 if (have_mac) /* we do not need a "to" address */
2427 errx(EX_USAGE, "missing ``from''");
2432 * source IP, mandatory
2434 OR_START(source_ip);
2435 NOT_BLOCK; /* optional "not" */
2436 NEED1("missing source address");
2438 /* source -- mandatory */
2439 fill_ip((ipfw_insn_ip *)cmd, *av);
2440 if (cmd->opcode == O_IP_DST_SET) /* set */
2441 cmd->opcode = O_IP_SRC_SET;
2442 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2443 cmd->opcode = O_IP_SRC_ME;
2444 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2445 cmd->opcode = O_IP_SRC;
2446 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2447 cmd->opcode = O_IP_SRC_MASK;
2448 /* otherwise len will be zero and the command skipped */
2450 prev = cmd; /* in case we need to backtrack */
2451 cmd = next_cmd(cmd);
2452 OR_BLOCK(source_ip);
2455 * source ports, optional
2457 NOT_BLOCK; /* optional "not" */
2458 if (ac && fill_newports((ipfw_insn_u16 *)cmd, *av, proto)) {
2459 /* XXX todo: check that we have a protocol with ports */
2460 cmd->opcode = O_IP_SRCPORT;
2463 cmd = next_cmd(cmd);
2468 * "to", mandatory (unless we have a MAC address
2470 if (!ac || strncmp(*av, "to", strlen(*av))) {
2473 errx(EX_USAGE, "missing ``to''");
2478 * destination, mandatory
2481 NOT_BLOCK; /* optional "not" */
2482 NEED1("missing dst address");
2483 fill_ip((ipfw_insn_ip *)cmd, *av);
2484 if (cmd->opcode == O_IP_DST_SET) /* set */
2486 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2487 cmd->opcode = O_IP_DST_ME;
2488 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2489 cmd->opcode = O_IP_DST;
2490 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2491 cmd->opcode = O_IP_DST_MASK;
2495 cmd = next_cmd(cmd);
2499 * dest. ports, optional
2501 NOT_BLOCK; /* optional "not" */
2502 if (ac && fill_newports((ipfw_insn_u16 *)cmd, *av, proto)) {
2503 /* XXX todo: check that we have a protocol with ports */
2504 cmd->opcode = O_IP_DSTPORT;
2514 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; /* alias */
2516 if (*s == '!') { /* alternate syntax for NOT */
2517 if (cmd->len & F_NOT)
2518 errx(EX_USAGE, "double \"not\" not allowed\n");
2522 i = match_token(rule_options, s);
2526 if (cmd->len & F_NOT)
2527 errx(EX_USAGE, "double \"not\" not allowed\n");
2533 errx(EX_USAGE, "invalid \"or\" block\n");
2538 fill_cmd(cmd, O_IN, 0, 0);
2542 cmd->len ^= F_NOT; /* toggle F_NOT */
2543 fill_cmd(cmd, O_IN, 0, 0);
2547 fill_cmd(cmd, O_FRAG, 0, 0);
2551 fill_cmd(cmd, O_LAYER2, 0, 0);
2557 NEED1("recv, xmit, via require interface name"
2559 fill_iface((ipfw_insn_if *)cmd, av[0]);
2561 if (F_LEN(cmd) == 0) /* not a valid address */
2564 cmd->opcode = O_XMIT;
2565 else if (i == TOK_RECV)
2566 cmd->opcode = O_RECV;
2567 else if (i == TOK_VIA)
2568 cmd->opcode = O_VIA;
2572 NEED1("ipttl requires TTL");
2573 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
2578 NEED1("ipid requires length");
2579 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
2584 NEED1("iplen requires length");
2585 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
2590 NEED1("ipver requires version");
2591 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
2596 NEED1("missing argument for ipoptions");
2597 fill_flags(cmd, O_IPOPTS, f_ipopts, *av);
2602 NEED1("uid requires argument");
2608 cmd->opcode = O_UID;
2609 uid = strtoul(*av, &end, 0);
2610 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
2612 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
2614 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2620 NEED1("gid requires argument");
2626 cmd->opcode = O_GID;
2627 gid = strtoul(*av, &end, 0);
2628 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
2630 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
2633 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2639 fill_cmd(cmd, O_ESTAB, 0, 0);
2643 fill_cmd(cmd, O_TCPFLAGS, 0,
2644 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
2648 NEED1("missing argument for tcpoptions");
2649 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
2655 NEED1("tcpseq/tcpack requires argument");
2656 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2657 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
2658 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
2663 NEED1("tcpwin requires length");
2664 fill_cmd(cmd, O_TCPWIN, 0,
2665 htons(strtoul(*av, NULL, 0)));
2670 NEED1("missing argument for tcpflags");
2671 cmd->opcode = O_TCPFLAGS;
2672 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
2678 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
2682 NEED1("limit needs mask and # of connections");
2684 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2686 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
2687 cmd->opcode = O_LIMIT;
2693 val = match_token(limit_masks, *av);
2696 c->limit_mask |= val;
2699 c->conn_limit = atoi(*av);
2700 if (c->conn_limit == 0)
2701 errx(EX_USAGE, "limit: limit must be >0");
2702 if (c->limit_mask == 0)
2703 errx(EX_USAGE, "missing limit mask");
2710 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
2712 if (F_LEN(cmd) > 0) { /* prepare to advance */
2714 cmd = next_cmd(cmd);
2717 #if 0 /* XXX todo */
2720 } else if (!strncmp(*av, "ipprecedence", strlen(*av))) {
2725 NEED1("missing argument for ``ipprecedence''");
2726 ippre = strtoul(*av, &c, 0);
2728 errx(EX_DATAERR, "argument to ipprecedence"
2729 " must be numeric");
2731 errx(EX_DATAERR, "argument to ipprecedence"
2733 rule.fw_ipflg |= IP_FW_IF_IPPRE;
2734 rule.fw_iptos |= (u_short)(ippre << 5);
2736 } else if (!strncmp(*av, "iptos", strlen(*av))) {
2738 NEED1("missing argument for ``iptos''");
2739 rule.fw_ipflg |= IP_FW_IF_IPTOS;
2740 fill_flags(&rule.fw_iptos, &rule.fw_ipntos,
2743 } else if (rule.fw_prot == IPPROTO_ICMP) {
2744 if (!strncmp(*av, "icmptypes", strlen(*av))) {
2746 NEED1("missing argument for ``icmptypes''");
2747 fill_icmptypes(rule.fw_uar.fw_icmptypes,
2753 #endif /* XXX todo */
2756 * Now copy stuff into the rule.
2757 * If we have a keep-state option, the first instruction
2758 * must be a PROBE_STATE (which is generated here).
2759 * If we have a LOG option, it was stored as the first command,
2760 * and now must be moved to the top of the action part.
2762 dst = (ipfw_insn *)rule->cmd;
2765 * generate O_PROBE_STATE if necessary
2768 fill_cmd(dst, O_PROBE_STATE, 0, 0);
2769 dst = next_cmd(dst);
2772 * copy all commands but O_LOG
2774 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
2777 if (src->opcode != O_LOG) {
2778 bcopy(src, dst, i * sizeof(u_int32_t));
2784 * start action section
2786 rule->act_ofs = dst - rule->cmd;
2789 * put back O_LOG if necessary
2791 src = (ipfw_insn *)cmdbuf;
2792 if ( src->opcode == O_LOG ) {
2794 bcopy(src, dst, i * sizeof(u_int32_t));
2798 * copy all other actions
2800 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
2802 bcopy(src, dst, i * sizeof(u_int32_t));
2806 rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
2807 i = (void *)dst - (void *)rule;
2810 if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
2811 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
2817 zero (int ac, char *av[])
2825 /* clear all entries */
2826 if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
2827 err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
2829 printf("Accounting cleared.\n");
2836 if (isdigit(**av)) {
2837 rulenum = atoi(*av);
2840 if (setsockopt(s, IPPROTO_IP,
2841 IP_FW_ZERO, &rulenum, sizeof rulenum)) {
2842 warn("rule %u: setsockopt(IP_FW_ZERO)",
2844 failed = EX_UNAVAILABLE;
2845 } else if (!do_quiet)
2846 printf("Entry %d cleared\n", rulenum);
2848 errx(EX_USAGE, "invalid rule number ``%s''", *av);
2851 if (failed != EX_OK)
2856 resetlog (int ac, char *av[])
2864 /* clear all entries */
2865 if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
2866 err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
2868 printf("Logging counts reset.\n");
2875 if (isdigit(**av)) {
2876 rulenum = atoi(*av);
2879 if (setsockopt(s, IPPROTO_IP,
2880 IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
2881 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
2883 failed = EX_UNAVAILABLE;
2884 } else if (!do_quiet)
2885 printf("Entry %d logging count reset\n",
2888 errx(EX_DATAERR, "invalid rule number ``%s''", *av);
2891 if (failed != EX_OK)
2898 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
2900 if (!do_force && !do_quiet) { /* need to ask user */
2903 printf("Are you sure? [yn] ");
2906 c = toupper(getc(stdin));
2907 while (c != '\n' && getc(stdin) != '\n')
2909 return; /* and do not flush */
2910 } while (c != 'Y' && c != 'N');
2912 if (c == 'N') /* user said no */
2915 if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
2916 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
2917 do_pipe ? "DUMMYNET" : "FW");
2919 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
2923 ipfw_main(int ac, char **av)
2930 /* Set the force flag for non-interactive processes */
2931 do_force = !isatty(STDIN_FILENO);
2933 optind = optreset = 1;
2934 while ((ch = getopt(ac, av, "hs:adefNqtv")) != -1)
2936 case 'h': /* help */
2938 break; /* NOTREACHED */
2940 case 's': /* sort */
2941 do_sort = atoi(optarg);
2964 case 'v': /* verbose */
2973 NEED1("bad arguments, for usage summary ``ipfw''");
2976 * optional: pipe or queue
2978 if (!strncmp(*av, "pipe", strlen(*av))) {
2982 } else if (!strncmp(*av, "queue", strlen(*av))) {
2987 NEED1("missing command");
2990 * for pipes and queues we normally say 'pipe NN config'
2991 * but the code is easier to parse as 'pipe config NN'
2992 * so we swap the two arguments.
2994 if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
2999 if (!strncmp(*av, "add", strlen(*av)))
3001 else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
3002 config_pipe(ac, av);
3003 else if (!strncmp(*av, "delete", strlen(*av)))
3005 else if (!strncmp(*av, "flush", strlen(*av)))
3007 else if (!strncmp(*av, "zero", strlen(*av)))
3009 else if (!strncmp(*av, "resetlog", strlen(*av)))
3011 else if (!strncmp(*av, "print", strlen(*av)) ||
3012 !strncmp(*av, "list", strlen(*av)))
3014 else if (!strncmp(*av, "show", strlen(*av))) {
3018 errx(EX_USAGE, "bad command `%s'", *av);
3024 ipfw_readfile(int ac, char *av[])
3027 #define WHITESP " \t\f\v\n\r"
3029 char *a, *p, *args[MAX_ARGS], *cmd = NULL;
3031 int i=0, lineno=0, qflag=0, pflag=0, status;
3036 while ((c = getopt(ac, av, "D:U:p:q")) != -1)
3040 errx(EX_USAGE, "-D requires -p");
3041 if (i > MAX_ARGS - 2)
3043 "too many -D or -U options");
3050 errx(EX_USAGE, "-U requires -p");
3051 if (i > MAX_ARGS - 2)
3053 "too many -D or -U options");
3070 errx(EX_USAGE, "bad arguments, for usage"
3071 " summary ``ipfw''");
3077 errx(EX_USAGE, "extraneous filename arguments");
3079 if ((f = fopen(av[0], "r")) == NULL)
3080 err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3083 /* pipe through preprocessor (cpp or m4) */
3088 if (pipe(pipedes) == -1)
3089 err(EX_OSERR, "cannot create pipe");
3091 switch((preproc = fork())) {
3093 err(EX_OSERR, "cannot fork");
3097 if (dup2(fileno(f), 0) == -1
3098 || dup2(pipedes[1], 1) == -1)
3099 err(EX_OSERR, "dup2()");
3104 err(EX_OSERR, "execvp(%s) failed", cmd);
3110 if ((f = fdopen(pipedes[0], "r")) == NULL) {
3111 int savederrno = errno;
3113 (void)kill(preproc, SIGTERM);
3115 err(EX_OSERR, "fdopen()");
3120 while (fgets(buf, BUFSIZ, f)) {
3122 sprintf(linename, "Line %d", lineno);
3127 if ((p = strchr(buf, '#')) != NULL)
3132 for (a = strtok(buf, WHITESP);
3133 a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3135 if (i == (qflag? 2: 1))
3138 errx(EX_USAGE, "%s: too many arguments",
3146 if (waitpid(preproc, &status, 0) == -1)
3147 errx(EX_OSERR, "waitpid()");
3148 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3149 errx(EX_UNAVAILABLE,
3150 "preprocessor exited with status %d",
3151 WEXITSTATUS(status));
3152 else if (WIFSIGNALED(status))
3153 errx(EX_UNAVAILABLE,
3154 "preprocessor exited with signal %d",
3160 main(int ac, char *av[])
3162 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3164 err(EX_UNAVAILABLE, "socket");
3169 * If the last argument is an absolute pathname, interpret it
3170 * as a file to be preprocessed.
3173 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3174 ipfw_readfile(ac, av);