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>
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
51 #include <netinet/ip_icmp.h>
52 #include <netinet/ip_fw.h>
53 #include <net/route.h> /* def. of struct route */
54 #include <netinet/ip_dummynet.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
58 int s, /* main RAW socket */
59 do_resolv, /* Would try to resolve all */
60 do_acct, /* Show packet/byte count */
61 do_time, /* Show time stamps */
62 do_quiet, /* Be quiet in add and flush */
63 do_force, /* Don't ask for confirmation */
64 do_pipe, /* this cmd refers to a pipe */
65 do_sort, /* field to sort results (0 = no) */
66 do_dynamic, /* display dynamic rules */
67 do_expired, /* display expired dynamic rules */
70 #define IP_MASK_ALL 0xffffffff
73 * structure to hold flag names and associated values to be
74 * set in the appropriate masks.
75 * A NULL string terminates the array.
76 * Often, an element with 0 value contains an error string.
84 static struct _s_x f_tcpflags[] = {
95 static struct _s_x f_tcpopts[] = {
96 { "mss", IP_FW_TCPOPT_MSS },
97 { "maxseg", IP_FW_TCPOPT_MSS },
98 { "window", IP_FW_TCPOPT_WINDOW },
99 { "sack", IP_FW_TCPOPT_SACK },
100 { "ts", IP_FW_TCPOPT_TS },
101 { "timestamp", IP_FW_TCPOPT_TS },
102 { "cc", IP_FW_TCPOPT_CC },
108 * IP options span the range 0 to 255 so we need to remap them
109 * (though in fact only the low 5 bits are significant).
111 static struct _s_x f_ipopts[] = {
112 { "ssrr", IP_FW_IPOPT_SSRR},
113 { "lsrr", IP_FW_IPOPT_LSRR},
114 { "rr", IP_FW_IPOPT_RR},
115 { "ts", IP_FW_IPOPT_TS},
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},
131 static struct _s_x limit_masks[] = {
132 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
133 {"src-addr", DYN_SRC_ADDR},
134 {"src-port", DYN_SRC_PORT},
135 {"dst-addr", DYN_DST_ADDR},
136 {"dst-port", DYN_DST_PORT},
141 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
142 * This is only used in this code.
144 #define IPPROTO_ETHERTYPE 0x1000
145 static struct _s_x ether_types[] = {
147 * Note, we cannot use "-:&/" in the names because they are field
148 * separators in the type specifications. Also, we use s = NULL as
149 * end-delimiter, because a type of 0 can be legal.
162 { "pppoe_disc", 0x8863 },
163 { "pppoe_sess", 0x8864 },
164 { "ipx_8022", 0x00E0 },
165 { "ipx_8023", 0x0000 },
166 { "ipx_ii", 0x8137 },
167 { "ipx_snap", 0x8137 },
173 static void show_usage(void);
239 struct _s_x dummynet_params[] = {
241 { "buckets", TOK_BUCKETS },
242 { "dst-ip", TOK_DSTIP },
243 { "src-ip", TOK_SRCIP },
244 { "dst-port", TOK_DSTPORT },
245 { "src-port", TOK_SRCPORT },
246 { "proto", TOK_PROTO },
247 { "weight", TOK_WEIGHT },
249 { "mask", TOK_MASK },
250 { "droptail", TOK_DROPTAIL },
252 { "gred", TOK_GRED },
254 { "bandwidth", TOK_BW },
255 { "delay", TOK_DELAY },
256 { "pipe", TOK_PIPE },
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 { "unreach", TOK_UNREACH },
280 { "check-state", TOK_CHECKSTATE },
285 struct _s_x rule_options[] = {
289 { "limit", TOK_LIMIT },
290 { "keep-state", TOK_KEEPSTATE },
291 { "bridged", TOK_LAYER2 },
292 { "layer2", TOK_LAYER2 },
294 { "xmit", TOK_XMIT },
295 { "recv", TOK_RECV },
297 { "fragment", TOK_FRAG },
298 { "frag", TOK_FRAG },
299 { "ipoptions", TOK_IPOPTS },
300 { "ipopts", TOK_IPOPTS },
301 { "iplen", TOK_IPLEN },
302 { "ipid", TOK_IPID },
303 { "ipprecedence", TOK_IPPRECEDENCE },
304 { "iptos", TOK_IPTOS },
305 { "ipttl", TOK_IPTTL },
306 { "ipversion", TOK_IPVER },
307 { "ipver", TOK_IPVER },
308 { "estab", TOK_ESTAB },
309 { "established", TOK_ESTAB },
310 { "setup", TOK_SETUP },
311 { "tcpflags", TOK_TCPFLAGS },
312 { "tcpflgs", TOK_TCPFLAGS },
313 { "tcpoptions", TOK_TCPOPTS },
314 { "tcpopts", TOK_TCPOPTS },
315 { "tcpseq", TOK_TCPSEQ },
316 { "tcpack", TOK_TCPACK },
317 { "tcpwin", TOK_TCPWIN },
318 { "icmptype", TOK_ICMPTYPES },
319 { "icmptypes", TOK_ICMPTYPES },
321 { "not", TOK_NOT }, /* pseudo option */
322 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
323 { "or", TOK_OR }, /* pseudo option */
324 { "|", /* escape */ TOK_OR }, /* pseudo option */
330 * match_token takes a table and a string, returns the value associated
331 * with the string (0 meaning an error in most cases)
334 match_token(struct _s_x *table, char *string)
337 int i = strlen(string);
339 for (pt = table ; i && pt->s != NULL ; pt++)
340 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
346 match_value(struct _s_x *p, u_int32_t value)
348 for (; p->s != NULL; p++)
355 * prints one port, symbolic or numeric
358 print_port(int proto, u_int16_t port)
361 if (proto == IPPROTO_ETHERTYPE) {
364 if (do_resolv && (s = match_value(ether_types, port)) )
367 printf("0x%04x", port);
369 struct servent *se = NULL;
371 struct protoent *pe = getprotobynumber(proto);
373 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
376 printf("%s", se->s_name);
383 * print the values in a list of ports
384 * XXX todo: add support for mask.
387 print_newports(ipfw_insn_u16 *cmd, int proto)
389 u_int16_t *p = cmd->ports;
393 if (cmd->o.len & F_NOT)
395 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
397 print_port(proto, p[0]);
400 print_port(proto, p[1]);
407 * Like strtol, but also translates service names into port numbers
408 * for some protocols.
410 * proto == -1 disables the protocol check;
411 * proto == IPPROTO_ETHERTYPE looks up an internal table
412 * proto == <some value in /etc/protocols> matches the values there.
415 strtoport(char *s, char **end, int base, int proto)
424 return strtol(s, end, base);
427 * find separator and replace with a '\0'
429 for (s1 = s; *s1 && isalnum(*s1) ; s1++)
434 if (proto == IPPROTO_ETHERTYPE) {
435 i = match_token(ether_types, s);
437 if (i == -1) { /* not found */
445 struct protoent *pe = NULL;
449 pe = getprotobynumber(proto);
451 se = getservbyname(s, pe ? pe->p_name : NULL);
455 return ntohs(se->s_port);
464 * fill the body of the command with the list of port ranges.
465 * At the moment it only understands numeric ranges.
468 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
470 u_int16_t *p = cmd->ports;
473 for (; *av ; i++, p +=2 ) {
477 a = strtoport(av, &s, 0, proto);
478 if (s == av) /* no parameter */
480 if (*s == '-') { /* a range */
482 b = strtoport(av, &s, 0, proto);
483 if (s == av) /* no parameter */
487 } else if (*s == ',' || *s == '\0' ) {
489 } else /* invalid separator */
494 if (i+1 > F_LEN_MASK)
495 errx(EX_DATAERR, "too many port range\n");
496 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
501 static struct _s_x icmpcodes[] = {
502 { "net", ICMP_UNREACH_NET },
503 { "host", ICMP_UNREACH_HOST },
504 { "protocol", ICMP_UNREACH_PROTOCOL },
505 { "port", ICMP_UNREACH_PORT },
506 { "needfrag", ICMP_UNREACH_NEEDFRAG },
507 { "srcfail", ICMP_UNREACH_SRCFAIL },
508 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
509 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
510 { "isolated", ICMP_UNREACH_ISOLATED },
511 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
512 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
513 { "tosnet", ICMP_UNREACH_TOSNET },
514 { "toshost", ICMP_UNREACH_TOSHOST },
515 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
516 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
517 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
522 fill_reject_code(u_short *codep, char *str)
527 val = strtoul(str, &s, 0);
528 if (s == str || *s != '\0' || val >= 0x100)
529 val = match_token(icmpcodes, str);
531 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
537 print_reject_code(u_int16_t code)
539 char *s = match_value(icmpcodes, code);
542 printf("unreach %s", s);
544 printf("unreach %u", code);
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]);
682 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
691 type = strtoul(av, &av, 0);
693 if (*av != ',' && *av != '\0')
694 errx(EX_DATAERR, "invalid ICMP type");
697 errx(EX_DATAERR, "ICMP type out of range");
699 cmd->d[0] |= 1 << type;
701 cmd->o.opcode = O_ICMPTYPE;
702 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
706 print_icmptypes(ipfw_insn_u32 *cmd)
711 printf(" icmptypes");
712 for (i = 0; i < 32; i++) {
713 if ( (cmd->d[0] & (1 << (i))) == 0)
715 printf("%c%d", sep, i);
721 * show_ipfw() prints the body of an ipfw rule.
722 * Because the standard rule has at least proto src_ip dst_ip, we use
723 * a helper function to produce these entries if not provided explicitly.
731 show_prerequisites(int *flags, int want)
733 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
735 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
737 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
743 show_ipfw(struct ip_fw *rule)
747 int proto = 0; /* default */
748 int flags = 0; /* prerequisites */
749 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
750 int or_block = 0; /* we are in an or block */
752 printf("%05u ", rule->rulenum);
755 printf("%10qu %10qu ", rule->pcnt, rule->bcnt);
758 if (rule->timestamp) {
760 time_t t = _long_to_time(rule->timestamp);
762 strcpy(timestr, ctime(&t));
763 *strchr(timestr, '\n') = '\0';
764 printf("%s ", timestr);
771 * first print actions
773 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
774 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
775 switch(cmd->opcode) {
777 printf("check-state");
778 /* avoid printing anything else */
779 flags = HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP;
784 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
785 double d = 1.0 * p->d[0];
787 d = 1 - (d / 0x7fffffff);
788 printf("prob %f ", d);
805 if (cmd->arg1 == ICMP_REJECT_RST)
807 else if (cmd->arg1 == ICMP_UNREACH_HOST)
810 print_reject_code(cmd->arg1);
814 printf("skipto %u", cmd->arg1);
818 printf("pipe %u", cmd->arg1);
822 printf("queue %u", cmd->arg1);
826 printf("divert %u", cmd->arg1);
830 printf("tee %u", cmd->arg1);
835 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
837 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
839 printf(",%d", ntohs(s->sa.sin_port));
843 case O_LOG: /* O_LOG is printed last */
844 logptr = (ipfw_insn_log *)cmd;
848 printf("** unrecognized action %d len %d",
849 cmd->opcode, cmd->len);
853 if (logptr->max_log > 0)
854 printf(" log logamount %d", logptr->max_log);
859 * then print the body
861 for (l = rule->act_ofs, cmd = rule->cmd ;
862 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
864 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
866 switch(cmd->opcode) {
868 break; /* no need to print anything here */
871 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
872 if ( (flags & HAVE_MAC) == 0)
875 if (cmd->len & F_NOT)
877 print_mac( m->addr, m->mask);
878 print_mac( m->addr + 6, m->mask + 6);
883 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE);
890 show_prerequisites(&flags, HAVE_PROTO);
891 if (!(flags & HAVE_SRCIP))
893 if ((cmd->len & F_OR) && !or_block)
895 print_ip((ipfw_insn_ip *)cmd);
903 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP);
904 if (!(flags & HAVE_DSTIP))
906 if ((cmd->len & F_OR) && !or_block)
908 print_ip((ipfw_insn_ip *)cmd);
913 show_prerequisites(&flags,
914 HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
916 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP);
917 print_newports((ipfw_insn_u16 *)cmd, proto);
923 if ((cmd->len & F_OR) && !or_block)
925 if (cmd->len & F_NOT)
928 pe = getprotobynumber(cmd->arg1);
930 printf(" %s", pe->p_name);
932 printf(" %u", cmd->arg1);
937 default: /*options ... */
938 show_prerequisites(&flags,
939 HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
940 if ((cmd->len & F_OR) && !or_block)
942 if (cmd->len & F_NOT && cmd->opcode != O_IN)
944 switch(cmd->opcode) {
950 printf(cmd->len & F_NOT ? " out" : " in");
960 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
962 if (cmd->opcode == O_XMIT)
964 else if (cmd->opcode == O_RECV)
966 else if (cmd->opcode == O_VIA)
968 if (cmdif->name[0] == '\0')
970 inet_ntoa(cmdif->p.ip));
971 else if (cmdif->p.unit == -1)
972 printf(" %s %s*", s, cmdif->name);
974 printf(" %s %s%d", s, cmdif->name,
980 printf(" ipid %u", cmd->arg1 );
984 printf(" ipttl %u", cmd->arg1 );
988 printf(" ipver %u", cmd->arg1 );
992 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
996 printf(" iplen %u", cmd->arg1 );
1000 print_flags("ipoptions", cmd, f_ipopts);
1004 print_flags("iptos", cmd, f_iptos);
1008 print_icmptypes((ipfw_insn_u32 *)cmd);
1012 printf(" established");
1016 print_flags("tcpflags", cmd, f_tcpflags);
1020 print_flags("tcpoptions", cmd, f_tcpopts);
1024 printf(" tcpwin %d", ntohs(cmd->arg1));
1028 printf(" tcpack %d", ntohl(cmd32->d[0]));
1032 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1037 struct passwd *pwd = getpwuid(cmd32->d[0]);
1040 printf(" uid %s", pwd->pw_name);
1042 printf(" uid %u", cmd32->d[0]);
1048 struct group *grp = getgrgid(cmd32->d[0]);
1051 printf(" gid %s", grp->gr_name);
1053 printf(" gid %u", cmd32->d[0]);
1058 printf(" keep-state");
1063 struct _s_x *p = limit_masks;
1064 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1065 u_int8_t x = c->limit_mask;
1069 for ( ; p->x != 0 ; p++)
1070 if ((x & p->x) == p->x) {
1072 printf("%s%s", comma, p->s);
1075 printf(" %d", c->conn_limit);
1080 printf(" [opcode %d len %d]",
1081 cmd->opcode, cmd->len);
1084 if (cmd->len & F_OR) {
1087 } else if (or_block) {
1092 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP|HAVE_DSTIP);
1098 show_dyn_ipfw(ipfw_dyn_rule *d)
1100 struct protoent *pe;
1104 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1108 printf("%05d %10qu %10qu (%ds)",
1109 (int)(d->rule), d->pcnt, d->bcnt, d->expire);
1110 switch (d->dyn_type) {
1111 case O_LIMIT_PARENT:
1112 printf(" PARENT %d", d->count);
1117 case O_KEEP_STATE: /* bidir, no mask */
1122 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1123 printf(" %s", pe->p_name);
1125 printf(" proto %u", d->id.proto);
1127 a.s_addr = htonl(d->id.src_ip);
1128 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1130 a.s_addr = htonl(d->id.dst_ip);
1131 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1136 sort_q(const void *pa, const void *pb)
1138 int rev = (do_sort < 0);
1139 int field = rev ? -do_sort : do_sort;
1141 const struct dn_flow_queue *a = pa;
1142 const struct dn_flow_queue *b = pb;
1146 res = a->len - b->len;
1149 res = a->len_bytes - b->len_bytes;
1152 case 3: /* tot pkts */
1153 res = a->tot_pkts - b->tot_pkts;
1156 case 4: /* tot bytes */
1157 res = a->tot_bytes - b->tot_bytes;
1164 return (int)(rev ? res : -res);
1168 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
1172 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1173 fs->flow_mask.proto,
1174 fs->flow_mask.src_ip, fs->flow_mask.src_port,
1175 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
1176 if (fs->rq_elements == 0)
1179 printf("BKT Prot ___Source IP/port____ "
1180 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1182 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
1183 for (l = 0; l < fs->rq_elements; l++) {
1185 struct protoent *pe;
1187 ina.s_addr = htonl(q[l].id.src_ip);
1188 printf("%3d ", q[l].hash_slot);
1189 pe = getprotobynumber(q[l].id.proto);
1191 printf("%-4s ", pe->p_name);
1193 printf("%4u ", q[l].id.proto);
1194 printf("%15s/%-5d ",
1195 inet_ntoa(ina), q[l].id.src_port);
1196 ina.s_addr = htonl(q[l].id.dst_ip);
1197 printf("%15s/%-5d ",
1198 inet_ntoa(ina), q[l].id.dst_port);
1199 printf("%4qu %8qu %2u %4u %3u\n",
1200 q[l].tot_pkts, q[l].tot_bytes,
1201 q[l].len, q[l].len_bytes, q[l].drops);
1203 printf(" S %20qd F %20qd\n",
1209 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
1214 char red[90]; /* Display RED parameters */
1217 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1219 sprintf(qs, "%d KB", l / 1024);
1221 sprintf(qs, "%d B", l);
1223 sprintf(qs, "%3d sl.", l);
1225 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
1228 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
1230 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
1231 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
1232 1.0 * fs->w_q / (double)(1 << SCALE_RED),
1233 SCALE_VAL(fs->min_th),
1234 SCALE_VAL(fs->max_th),
1235 1.0 * fs->max_p / (double)(1 << SCALE_RED));
1237 sprintf(red, "droptail");
1239 printf("%s %s%s %d queues (%d buckets) %s\n",
1240 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
1244 list_pipes(void *data, int nbytes, int ac, char *av[])
1248 struct dn_pipe *p = (struct dn_pipe *) data;
1249 struct dn_flow_set *fs;
1250 struct dn_flow_queue *q;
1254 rulenum = strtoul(*av++, NULL, 10);
1257 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
1258 double b = p->bandwidth;
1262 if (p->next != (struct dn_pipe *)DN_IS_PIPE)
1263 break; /* done with pipes, now queues */
1266 * compute length, as pipe have variable size
1268 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
1269 next = (void *)p + l;
1272 if (rulenum != 0 && rulenum != p->pipe_nr)
1276 * Print rate (or clocking interface)
1278 if (p->if_name[0] != '\0')
1279 sprintf(buf, "%s", p->if_name);
1281 sprintf(buf, "unlimited");
1282 else if (b >= 1000000)
1283 sprintf(buf, "%7.3f Mbit/s", b/1000000);
1285 sprintf(buf, "%7.3f Kbit/s", b/1000);
1287 sprintf(buf, "%7.3f bit/s ", b);
1289 sprintf(prefix, "%05d: %s %4d ms ",
1290 p->pipe_nr, buf, p->delay);
1291 print_flowset_parms(&(p->fs), prefix);
1293 printf(" V %20qd\n", p->V >> MY_M);
1295 q = (struct dn_flow_queue *)(p+1);
1296 list_queues(&(p->fs), q);
1298 for (fs = next; nbytes >= sizeof *fs; fs = next) {
1301 if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE)
1303 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
1304 next = (void *)fs + l;
1306 q = (struct dn_flow_queue *)(fs+1);
1307 sprintf(prefix, "q%05d: weight %d pipe %d ",
1308 fs->fs_nr, fs->weight, fs->parent_nr);
1309 print_flowset_parms(fs, prefix);
1315 list(int ac, char *av[])
1318 ipfw_dyn_rule *dynrules, *d;
1320 void *lim, *data = NULL;
1321 int n, nbytes, nstat, ndyn;
1322 int exitval = EX_OK;
1329 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1330 int nalloc = 1024; /* start somewhere... */
1335 /* get rules or pipes from kernel, resizing array as necessary */
1338 while (nbytes >= nalloc) {
1339 nalloc = nalloc * 2 + 200;
1341 if ((data = realloc(data, nbytes)) == NULL)
1342 err(EX_OSERR, "realloc");
1343 if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0)
1344 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1345 do_pipe ? "DUMMYNET" : "FW");
1349 list_pipes(data, nbytes, ac, av);
1354 * Count static rules. They have variable size so we
1355 * need to scan the list to count them.
1357 for (nstat = 1, r = data, lim = data + nbytes;
1358 r->rulenum < 65535 && (void *)r < lim;
1359 ++nstat, r = (void *)r + RULESIZE(r) )
1363 * Count dynamic rules. This is easier as they have
1366 r = (void *)r + RULESIZE(r);
1367 dynrules = (ipfw_dyn_rule *)r ;
1368 n = (void *)r - data;
1369 ndyn = (nbytes - n) / sizeof *dynrules;
1371 /* if no rule numbers were specified, list all rules */
1373 for (n = 0, r = data; n < nstat;
1374 n++, r = (void *)r + RULESIZE(r) )
1377 if (do_dynamic && ndyn) {
1378 printf("## Dynamic rules (%d):\n", ndyn);
1379 for (n = 0, d = dynrules; n < ndyn; n++, d++)
1385 /* display specific rules requested on command line */
1387 for (lac = ac, lav = av; lac != 0; lac--) {
1388 /* convert command line rule # */
1389 rnum = strtoul(*lav++, &endptr, 10);
1392 warnx("invalid rule number: %s", *(lav - 1));
1395 for (n = seen = 0, r = data; n < nstat;
1396 n++, r = (void *)r + RULESIZE(r) ) {
1397 if (r->rulenum > rnum)
1399 if (r->rulenum == rnum) {
1405 /* give precedence to other error(s) */
1406 if (exitval == EX_OK)
1407 exitval = EX_UNAVAILABLE;
1408 warnx("rule %lu does not exist", rnum);
1412 if (do_dynamic && ndyn) {
1413 printf("## Dynamic rules:\n");
1414 for (lac = ac, lav = av; lac != 0; lac--) {
1415 rnum = strtoul(*lav++, &endptr, 10);
1417 /* already warned */
1419 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1420 if ((int)(d->rule) > rnum)
1422 if ((int)(d->rule) == rnum)
1433 if (exitval != EX_OK)
1440 fprintf(stderr, "usage: ipfw [options]\n"
1441 " add [number] rule\n"
1442 " pipe number config [pipeconfig]\n"
1443 " queue number config [queueconfig]\n"
1445 " [pipe] delete number ...\n"
1446 " [pipe] {list|show} [number ...]\n"
1447 " {zero|resetlog} [number ...]\n"
1448 "do \"ipfw -h\" or see ipfw manpage for details\n"
1458 fprintf(stderr, "ipfw syntax summary:\n"
1459 "ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1460 "ipfw {pipe|queue} N config BODY\n"
1461 "ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1463 "RULE: [1..] [PROB] BODY\n"
1464 "RULENUM: INTEGER(1..65534)\n"
1465 "PROB: prob REAL(0..1)\n"
1466 "BODY: check-state [LOG] (no body) |\n"
1467 " ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1468 "ACTION: check-state | allow | count | deny | reject | skipto N |\n"
1469 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1470 "ADDR: [ MAC dst src ether_type ] \n"
1471 " [ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1472 "IPLIST: IPADDR | ( IPADDR or ... or IPADDR )\n"
1473 "IPADDR: [not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1474 "OPTION_LIST: OPTION [,OPTION_LIST]\n"
1481 lookup_host (char *host, struct in_addr *ipaddr)
1485 if (!inet_aton(host, ipaddr)) {
1486 if ((he = gethostbyname(host)) == NULL)
1488 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1494 * fills the addr and mask fields in the instruction as appropriate from av.
1495 * Update length as appropriate.
1496 * The following formats are allowed:
1497 * any matches any IP. Actually returns an empty instruction.
1498 * me returns O_IP_*_ME
1499 * 1.2.3.4 single IP address
1500 * 1.2.3.4:5.6.7.8 address:mask
1501 * 1.2.3.4/24 address/mask
1502 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1505 fill_ip(ipfw_insn_ip *cmd, char *av)
1507 char *p = 0, md = 0;
1510 cmd->o.len &= ~F_LEN_MASK; /* zero len */
1512 if (!strncmp(av, "any", strlen(av)))
1515 if (!strncmp(av, "me", strlen(av))) {
1516 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1520 p = strchr(av, '/');
1522 p = strchr(av, ':');
1528 if (lookup_host(av, &cmd->addr) != 0)
1529 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
1532 if (!inet_aton(p, &cmd->mask))
1533 errx(EX_DATAERR, "bad netmask ``%s''", p);
1538 cmd->mask.s_addr = htonl(0);
1540 errx(EX_DATAERR, "bad width ``%s''", p);
1542 cmd->mask.s_addr = htonl(~0 << (32 - i));
1545 cmd->mask.s_addr = htonl(~0);
1548 cmd->addr.s_addr &= cmd->mask.s_addr;
1550 * now look if we have a set of addresses. They are stored as follows:
1551 * arg1 is the set size (powers of 2, 2..256)
1552 * addr is the base address IN HOST FORMAT
1553 * mask.. is an array of u_int32_t with bits set.
1557 if (p) { /* fetch addresses */
1560 int i = contigmask((u_char *)&(cmd->mask), 32);
1562 if (i < 24 || i > 31) {
1563 fprintf(stderr, "invalid set with mask %d\n",
1567 cmd->o.arg1 = 1<<(32-i);
1568 cmd->addr.s_addr = ntohl(cmd->addr.s_addr);
1569 d = (u_int32_t *)&cmd->mask;
1570 cmd->o.opcode = O_IP_DST_SET; /* default */
1571 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
1572 fprintf(stderr,"-- set size %d cmdlen %d\n",
1573 cmd->o.arg1, cmd->o.len );
1574 for (i = 0; i < cmd->o.arg1/32 ; i++)
1575 d[i] = 0; /* clear masks */
1578 low = cmd->addr.s_addr & 0xff;
1579 high = low + cmd->o.arg1 - 1;
1580 while (isdigit(*av)) {
1582 u_int16_t a = strtol(av, &s, 0);
1584 if (s == av) /* no parameter */
1586 if (a < low || a > high) {
1587 fprintf(stderr, "addr %d out of range [%d-%d]\n",
1592 d[ a/32] |= 1<<(a & 31);
1600 if (cmd->mask.s_addr == 0) { /* any */
1601 if (cmd->o.len & F_NOT)
1602 errx(EX_DATAERR, "not any never matches");
1603 else /* useless, nuke it */
1605 } else if (cmd->mask.s_addr == IP_MASK_ALL) /* one IP */
1606 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1607 else /* addr/mask */
1608 cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip);
1613 * helper function to process a set of flags and set bits in the
1614 * appropriate masks.
1617 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
1618 struct _s_x *flags, char *p)
1620 u_int8_t set=0, clear=0;
1623 char *q; /* points to the separator */
1625 u_int8_t *which; /* mask we are working on */
1635 val = match_token(flags, p);
1637 errx(EX_DATAERR, "invalid flag %s", p);
1638 *which |= (u_int8_t)val;
1641 cmd->opcode = opcode;
1642 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
1643 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
1648 delete(int ac, char *av[])
1651 struct dn_pipe pipe;
1653 int exitval = EX_OK;
1655 memset(&pipe, 0, sizeof pipe);
1660 while (ac && isdigit(**av)) {
1661 i = atoi(*av); av++; ac--;
1667 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
1668 &pipe, sizeof pipe);
1671 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1672 do_pipe == 1 ? pipe.pipe_nr :
1677 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum,
1680 exitval = EX_UNAVAILABLE;
1681 warn("rule %u: setsockopt(IP_FW_DEL)",
1686 if (exitval != EX_OK)
1692 * fill the interface structure. We do not check the name as we can
1693 * create interfaces dynamically, so checking them at insert time
1694 * makes relatively little sense.
1695 * A '*' following the name means any unit.
1698 fill_iface(ipfw_insn_if *cmd, char *arg)
1700 cmd->name[0] = '\0';
1701 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
1703 /* Parse the interface or address */
1704 if (!strcmp(arg, "any"))
1705 cmd->o.len = 0; /* effectively ignore this command */
1706 else if (!isdigit(*arg)) {
1709 strncpy(cmd->name, arg, sizeof(cmd->name));
1710 cmd->name[sizeof(cmd->name) - 1] = '\0';
1711 /* find first digit or wildcard */
1712 for (q = cmd->name; *q && !isdigit(*q) && *q != '*'; q++)
1714 cmd->p.unit = (*q == '*') ? -1 : atoi(q);
1716 } else if (!inet_aton(arg, &cmd->p.ip))
1717 errx(EX_DATAERR, "bad ip address ``%s''", arg);
1721 * the following macro returns an error message if we run out of
1724 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
1727 config_pipe(int ac, char **av)
1729 struct dn_pipe pipe;
1735 memset(&pipe, 0, sizeof pipe);
1739 if (ac && isdigit(**av)) {
1740 i = atoi(*av); av++; ac--;
1748 int tok = match_token(dummynet_params, *av);
1753 NEED1("plr needs argument 0..1\n");
1754 d = strtod(av[0], NULL);
1759 pipe.fs.plr = (int)(d*0x7fffffff);
1764 NEED1("queue needs queue size\n");
1766 pipe.fs.qsize = strtoul(av[0], &end, 0);
1767 if (*end == 'K' || *end == 'k') {
1768 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1769 pipe.fs.qsize *= 1024;
1770 } else if (*end == 'B' || !strncmp(end, "by", 2)) {
1771 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1777 NEED1("buckets needs argument\n");
1778 pipe.fs.rq_size = strtoul(av[0], NULL, 0);
1783 NEED1("mask needs mask specifier\n");
1785 * per-flow queue, mask is dst_ip, dst_port,
1786 * src_ip, src_port, proto measured in bits
1790 pipe.fs.flow_mask.dst_ip = 0;
1791 pipe.fs.flow_mask.src_ip = 0;
1792 pipe.fs.flow_mask.dst_port = 0;
1793 pipe.fs.flow_mask.src_port = 0;
1794 pipe.fs.flow_mask.proto = 0;
1798 u_int32_t *p32 = NULL;
1799 u_int16_t *p16 = NULL;
1801 tok = match_token(dummynet_params, *av);
1806 * special case, all bits significant
1808 pipe.fs.flow_mask.dst_ip = ~0;
1809 pipe.fs.flow_mask.src_ip = ~0;
1810 pipe.fs.flow_mask.dst_port = ~0;
1811 pipe.fs.flow_mask.src_port = ~0;
1812 pipe.fs.flow_mask.proto = ~0;
1813 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1817 p32 = &pipe.fs.flow_mask.dst_ip;
1821 p32 = &pipe.fs.flow_mask.src_ip;
1825 p16 = &pipe.fs.flow_mask.dst_port;
1829 p16 = &pipe.fs.flow_mask.src_port;
1836 ac++; av--; /* backtrack */
1840 errx(EX_USAGE, "mask: value missing");
1841 if (*av[0] == '/') {
1842 a = strtoul(av[0]+1, &end, 0);
1843 a = (a == 32) ? ~0 : (1 << a) - 1;
1845 a = strtoul(av[0], &end, 0);
1848 else if (p16 != NULL) {
1851 "mask: must be 16 bit");
1852 *p16 = (u_int16_t)a;
1856 "mask: must be 8 bit");
1857 pipe.fs.flow_mask.proto = (u_int8_t)a;
1860 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1862 } /* end while, config masks */
1868 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
1869 pipe.fs.flags_fs |= DN_IS_RED;
1870 if (tok == TOK_GRED)
1871 pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
1873 * the format for parameters is w_q/min_th/max_th/max_p
1875 if ((end = strsep(&av[0], "/"))) {
1876 double w_q = strtod(end, NULL);
1877 if (w_q > 1 || w_q <= 0)
1878 errx(EX_DATAERR, "0 < w_q <= 1");
1879 pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
1881 if ((end = strsep(&av[0], "/"))) {
1882 pipe.fs.min_th = strtoul(end, &end, 0);
1883 if (*end == 'K' || *end == 'k')
1884 pipe.fs.min_th *= 1024;
1886 if ((end = strsep(&av[0], "/"))) {
1887 pipe.fs.max_th = strtoul(end, &end, 0);
1888 if (*end == 'K' || *end == 'k')
1889 pipe.fs.max_th *= 1024;
1891 if ((end = strsep(&av[0], "/"))) {
1892 double max_p = strtod(end, NULL);
1893 if (max_p > 1 || max_p <= 0)
1894 errx(EX_DATAERR, "0 < max_p <= 1");
1895 pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED));
1901 pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1905 NEED1("bw needs bandwidth or interface\n");
1907 errx(EX_DATAERR, "bandwidth only valid for pipes");
1909 * set clocking interface or bandwidth value
1911 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
1912 int l = sizeof(pipe.if_name)-1;
1913 /* interface name */
1914 strncpy(pipe.if_name, av[0], l);
1915 pipe.if_name[l] = '\0';
1918 pipe.if_name[0] = '\0';
1919 pipe.bandwidth = strtoul(av[0], &end, 0);
1920 if (*end == 'K' || *end == 'k') {
1922 pipe.bandwidth *= 1000;
1923 } else if (*end == 'M') {
1925 pipe.bandwidth *= 1000000;
1927 if (*end == 'B' || !strncmp(end, "by", 2))
1928 pipe.bandwidth *= 8;
1929 if (pipe.bandwidth < 0)
1930 errx(EX_DATAERR, "bandwidth too large");
1937 errx(EX_DATAERR, "delay only valid for pipes");
1938 NEED1("delay needs argument 0..10000ms\n");
1939 pipe.delay = strtoul(av[0], NULL, 0);
1945 errx(EX_DATAERR,"weight only valid for queues");
1946 NEED1("weight needs argument 0..100\n");
1947 pipe.fs.weight = strtoul(av[0], &end, 0);
1953 errx(EX_DATAERR,"pipe only valid for queues");
1954 NEED1("pipe needs pipe_number\n");
1955 pipe.fs.parent_nr = strtoul(av[0], &end, 0);
1960 errx(EX_DATAERR, "unrecognised option ``%s''", *av);
1964 if (pipe.pipe_nr == 0)
1965 errx(EX_DATAERR, "pipe_nr must be > 0");
1966 if (pipe.delay > 10000)
1967 errx(EX_DATAERR, "delay must be < 10000");
1968 } else { /* do_pipe == 2, queue */
1969 if (pipe.fs.parent_nr == 0)
1970 errx(EX_DATAERR, "pipe must be > 0");
1971 if (pipe.fs.weight >100)
1972 errx(EX_DATAERR, "weight must be <= 100");
1974 if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) {
1975 if (pipe.fs.qsize > 1024*1024)
1976 errx(EX_DATAERR, "queue size must be < 1MB");
1978 if (pipe.fs.qsize > 100)
1979 errx(EX_DATAERR, "2 <= queue size <= 100");
1981 if (pipe.fs.flags_fs & DN_IS_RED) {
1983 int lookup_depth, avg_pkt_size;
1984 double s, idle, weight, w_q;
1985 struct clockinfo clock;
1988 if (pipe.fs.min_th >= pipe.fs.max_th)
1989 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1990 pipe.fs.min_th, pipe.fs.max_th);
1991 if (pipe.fs.max_th == 0)
1992 errx(EX_DATAERR, "max_th must be > 0");
1995 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1996 &lookup_depth, &len, NULL, 0) == -1)
1998 errx(1, "sysctlbyname(\"%s\")",
1999 "net.inet.ip.dummynet.red_lookup_depth");
2000 if (lookup_depth == 0)
2001 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
2002 " must be greater than zero");
2005 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2006 &avg_pkt_size, &len, NULL, 0) == -1)
2008 errx(1, "sysctlbyname(\"%s\")",
2009 "net.inet.ip.dummynet.red_avg_pkt_size");
2010 if (avg_pkt_size == 0)
2012 "net.inet.ip.dummynet.red_avg_pkt_size must"
2013 " be greater than zero");
2015 len = sizeof(struct clockinfo);
2016 if (sysctlbyname("kern.clockrate", &clock, &len, NULL, 0) == -1)
2017 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
2020 * Ticks needed for sending a medium-sized packet.
2021 * Unfortunately, when we are configuring a WF2Q+ queue, we
2022 * do not have bandwidth information, because that is stored
2023 * in the parent pipe, and also we have multiple queues
2024 * competing for it. So we set s=0, which is not very
2025 * correct. But on the other hand, why do we want RED with
2028 if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
2031 s = clock.hz * avg_pkt_size * 8 / pipe.bandwidth;
2034 * max idle time (in ticks) before avg queue size becomes 0.
2035 * NOTA: (3/w_q) is approx the value x so that
2036 * (1-w_q)^x < 10^-3.
2038 w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
2039 idle = s * 3. / w_q;
2040 pipe.fs.lookup_step = (int)idle / lookup_depth;
2041 if (!pipe.fs.lookup_step)
2042 pipe.fs.lookup_step = 1;
2044 for (t = pipe.fs.lookup_step; t > 0; --t)
2046 pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2048 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
2051 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2055 get_mac_addr_mask(char *p, u_char *addr, u_char *mask)
2060 addr[i] = mask[i] = 0;
2061 if (!strcmp(p, "any"))
2064 for (i=0; *p && i<6;i++, p++) {
2065 addr[i] = strtol(p, &p, 16);
2066 if (*p != ':') /* we start with the mask */
2069 if (*p == '/') { /* mask len */
2070 l = strtol(p+1, &p, 0);
2071 for (i=0; l>0; l -=8, i++)
2072 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2073 } else if (*p == '&') { /* mask */
2074 for (i=0, p++; *p && i<6;i++, p++) {
2075 mask[i] = strtol(p, &p, 16);
2079 } else if (*p == '\0') {
2088 * helper function, updates the pointer to cmd with the length
2089 * of the current command, and also cleans up the first word of
2090 * the new command in case it has been clobbered before.
2093 next_cmd(ipfw_insn *cmd)
2096 bzero(cmd, sizeof(*cmd));
2101 * A function to fill simple commands of size 1.
2102 * Existing flags are preserved.
2105 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg)
2107 cmd->opcode = opcode;
2108 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2113 * Fetch and add the MAC address and type, with masks. This generates one or
2114 * two microinstructions, and returns the pointer to the last one.
2117 add_mac(ipfw_insn *cmd, int ac, char *av[])
2119 ipfw_insn_mac *mac; /* also *src */
2122 errx(EX_DATAERR, "MAC dst src type");
2124 cmd->opcode = O_MACADDR2;
2125 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2127 mac = (ipfw_insn_mac *)cmd;
2128 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2129 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2132 if (strcmp(av[0], "any") != 0) { /* we have a non-null port */
2135 fill_newports((ipfw_insn_u16 *)cmd, av[0], IPPROTO_ETHERTYPE);
2136 cmd->opcode = O_MAC_TYPE;
2143 * Parse arguments and assemble the microinstructions which make up a rule.
2144 * Rules are added into the 'rulebuf' and then copied in the correct order
2145 * into the actual rule.
2147 * The syntax for a rule starts with the action, followed by an
2148 * optional log action, and the various match patterns.
2149 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2150 * (generated if the rule includes a keep-state option), then the
2151 * various match patterns, the "log" action, and the actual action.
2155 add(int ac, char *av[])
2158 * rules are added into the 'rulebuf' and then copied in
2159 * the correct order into the actual rule.
2160 * Some things that need to go out of order (prob, action etc.)
2163 static u_int32_t rulebuf[255], actbuf[255], cmdbuf[255];
2165 ipfw_insn *src, *dst, *cmd, *action, *prev;
2170 * various flags used to record that we entered some fields.
2172 int have_mac = 0; /* set if we have a MAC address */
2173 int have_state = 0; /* check-state or keep-state */
2177 int open_par = 0; /* open parenthesis ( */
2179 /* proto is here because it is used to fetch ports */
2180 u_char proto = IPPROTO_IP; /* default protocol */
2182 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2183 bzero(cmdbuf, sizeof(cmdbuf));
2184 bzero(rulebuf, sizeof(rulebuf));
2186 rule = (struct ip_fw *)rulebuf;
2187 cmd = (ipfw_insn *)cmdbuf;
2188 action = (ipfw_insn *)actbuf;
2192 /* [rule N] -- Rule number optional */
2193 if (ac && isdigit(**av)) {
2194 rule->rulenum = atoi(*av);
2199 /* [prob D] -- match probability, optional */
2200 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2201 double d = strtod(av[1], NULL);
2203 if (d <= 0 || d > 1)
2204 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2205 if (d != 1) { /* 1 means always match */
2206 action->opcode = O_PROB;
2208 *((int32_t *)(action+1)) =
2209 (int32_t)((1 - d) * 0x7fffffff);
2210 action += action->len;
2215 /* action -- mandatory */
2216 NEED1("missing action");
2217 i = match_token(rule_actions, *av);
2219 action->len = 1; /* default */
2221 case TOK_CHECKSTATE:
2223 action->opcode = O_CHECK_STATE;
2227 action->opcode = O_ACCEPT;
2231 action->opcode = O_DENY;
2236 action->opcode = O_REJECT;
2237 action->arg1 = ICMP_UNREACH_HOST;
2241 action->opcode = O_REJECT;
2242 action->arg1 = ICMP_REJECT_RST;
2246 action->opcode = O_REJECT;
2247 NEED1("missing reject code");
2248 fill_reject_code(&action->arg1, *av);
2253 action->opcode = O_COUNT;
2258 action->len = F_INSN_SIZE(ipfw_insn_pipe);
2261 action->opcode = O_QUEUE;
2262 else if (i == TOK_PIPE)
2263 action->opcode = O_PIPE;
2264 else if (i == TOK_SKIPTO)
2265 action->opcode = O_SKIPTO;
2266 NEED1("missing skipto/pipe/queue number");
2267 action->arg1 = strtoul(*av, NULL, 10);
2273 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2274 NEED1("missing divert/tee port");
2275 action->arg1 = strtoul(*av, NULL, 0);
2276 if (action->arg1 == 0) {
2279 s = getservbyname(av[0], "divert");
2281 action->arg1 = ntohs(s->s_port);
2283 errx(EX_DATAERR, "illegal divert/tee port");
2289 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2292 NEED1("missing forward address[:port]");
2294 action->opcode = O_FORWARD_IP;
2295 action->len = F_INSN_SIZE(ipfw_insn_sa);
2297 p->sa.sin_len = sizeof(struct sockaddr_in);
2298 p->sa.sin_family = AF_INET;
2301 * locate the address-port separator (':' or ',')
2303 s = strchr(*av, ':');
2305 s = strchr(*av, ',');
2308 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2311 "illegal forwarding port ``%s''", s);
2312 p->sa.sin_port = htons( (u_short)i );
2314 lookup_host(*av, &(p->sa.sin_addr));
2320 errx(EX_DATAERR, "invalid action %s\n", *av);
2322 action = next_cmd(action);
2325 * [log [logamount N]] -- log, optional
2327 * If exists, it goes first in the cmdbuf, but then it is
2328 * skipped in the copy section to the end of the buffer.
2330 if (ac && !strncmp(*av, "log", strlen(*av))) {
2331 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2333 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2334 cmd->opcode = O_LOG;
2336 if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2338 NEED1("logamount requires argument");
2339 c->max_log = atoi(*av);
2341 errx(EX_DATAERR, "logamount must be positive");
2344 cmd = next_cmd(cmd);
2352 #define OR_START(target) \
2353 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2355 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2357 if ( (av[0])[1] == '\0') { \
2368 !strncmp(*av, ")", strlen(*av)) || \
2369 !strncmp(*av, "}", strlen(*av)) )) { \
2373 errx(EX_USAGE, "missing \")\"\n"); \
2377 if (ac && !strncmp(*av, "not", strlen(*av))) { \
2378 if (cmd->len & F_NOT) \
2379 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2380 cmd->len |= F_NOT; \
2384 #define OR_BLOCK(target) \
2385 if (ac && !strncmp(*av, "or", strlen(*av))) { \
2386 if (prev == NULL || open_par == 0) \
2387 errx(EX_DATAERR, "invalid OR block"); \
2388 prev->len |= F_OR; \
2395 * protocol, mandatory
2397 OR_START(get_proto);
2399 NEED1("missing protocol");
2401 struct protoent *pe;
2403 if (!strncmp(*av, "all", strlen(*av)))
2404 ; /* same as "ip" */
2405 else if (!strncmp(*av, "MAC", strlen(*av))) {
2406 /* need exactly 3 fields */
2407 cmd = add_mac(cmd, ac-1, av+1); /* exits in case of errors */
2411 } else if ((proto = atoi(*av)) > 0)
2413 else if ((pe = getprotobyname(*av)) != NULL)
2414 proto = pe->p_proto;
2416 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
2418 if (proto != IPPROTO_IP)
2419 fill_cmd(cmd, O_PROTO, 0, proto);
2421 cmd = next_cmd(cmd);
2422 OR_BLOCK(get_proto);
2425 * "from", mandatory (unless we have a MAC address)
2427 if (!ac || strncmp(*av, "from", strlen(*av))) {
2428 if (have_mac) /* we do not need a "to" address */
2430 errx(EX_USAGE, "missing ``from''");
2435 * source IP, mandatory
2437 OR_START(source_ip);
2438 NOT_BLOCK; /* optional "not" */
2439 NEED1("missing source address");
2441 /* source -- mandatory */
2442 fill_ip((ipfw_insn_ip *)cmd, *av);
2443 if (cmd->opcode == O_IP_DST_SET) /* set */
2444 cmd->opcode = O_IP_SRC_SET;
2445 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2446 cmd->opcode = O_IP_SRC_ME;
2447 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2448 cmd->opcode = O_IP_SRC;
2449 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2450 cmd->opcode = O_IP_SRC_MASK;
2451 /* otherwise len will be zero and the command skipped */
2453 prev = cmd; /* in case we need to backtrack */
2454 cmd = next_cmd(cmd);
2455 OR_BLOCK(source_ip);
2458 * source ports, optional
2460 NOT_BLOCK; /* optional "not" */
2461 if (ac && fill_newports((ipfw_insn_u16 *)cmd, *av, proto)) {
2462 /* XXX todo: check that we have a protocol with ports */
2463 cmd->opcode = O_IP_SRCPORT;
2466 cmd = next_cmd(cmd);
2471 * "to", mandatory (unless we have a MAC address
2473 if (!ac || strncmp(*av, "to", strlen(*av))) {
2476 errx(EX_USAGE, "missing ``to''");
2481 * destination, mandatory
2484 NOT_BLOCK; /* optional "not" */
2485 NEED1("missing dst address");
2486 fill_ip((ipfw_insn_ip *)cmd, *av);
2487 if (cmd->opcode == O_IP_DST_SET) /* set */
2489 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2490 cmd->opcode = O_IP_DST_ME;
2491 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2492 cmd->opcode = O_IP_DST;
2493 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2494 cmd->opcode = O_IP_DST_MASK;
2498 cmd = next_cmd(cmd);
2502 * dest. ports, optional
2504 NOT_BLOCK; /* optional "not" */
2505 if (ac && fill_newports((ipfw_insn_u16 *)cmd, *av, proto)) {
2506 /* XXX todo: check that we have a protocol with ports */
2507 cmd->opcode = O_IP_DSTPORT;
2517 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; /* alias */
2519 if (*s == '!') { /* alternate syntax for NOT */
2520 if (cmd->len & F_NOT)
2521 errx(EX_USAGE, "double \"not\" not allowed\n");
2525 i = match_token(rule_options, s);
2529 if (cmd->len & F_NOT)
2530 errx(EX_USAGE, "double \"not\" not allowed\n");
2536 errx(EX_USAGE, "invalid \"or\" block\n");
2541 fill_cmd(cmd, O_IN, 0, 0);
2545 cmd->len ^= F_NOT; /* toggle F_NOT */
2546 fill_cmd(cmd, O_IN, 0, 0);
2550 fill_cmd(cmd, O_FRAG, 0, 0);
2554 fill_cmd(cmd, O_LAYER2, 0, 0);
2560 NEED1("recv, xmit, via require interface name"
2562 fill_iface((ipfw_insn_if *)cmd, av[0]);
2564 if (F_LEN(cmd) == 0) /* not a valid address */
2567 cmd->opcode = O_XMIT;
2568 else if (i == TOK_RECV)
2569 cmd->opcode = O_RECV;
2570 else if (i == TOK_VIA)
2571 cmd->opcode = O_VIA;
2575 NEED1("icmptypes requires list of types");
2576 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
2581 NEED1("ipttl requires TTL");
2582 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
2587 NEED1("ipid requires length");
2588 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
2593 NEED1("iplen requires length");
2594 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
2599 NEED1("ipver requires version");
2600 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
2604 case TOK_IPPRECEDENCE:
2605 NEED1("ipprecedence requires value");
2606 fill_cmd(cmd, O_IPPRECEDENCE, 0,
2607 (strtoul(*av, NULL, 0) & 7) << 5);
2612 NEED1("missing argument for ipoptions");
2613 fill_flags(cmd, O_IPOPTS, f_ipopts, *av);
2618 NEED1("missing argument for iptos");
2619 fill_flags(cmd, O_IPOPTS, f_iptos, *av);
2624 NEED1("uid requires argument");
2630 cmd->opcode = O_UID;
2631 uid = strtoul(*av, &end, 0);
2632 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
2634 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
2636 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2642 NEED1("gid requires argument");
2648 cmd->opcode = O_GID;
2649 gid = strtoul(*av, &end, 0);
2650 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
2652 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
2655 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2661 fill_cmd(cmd, O_ESTAB, 0, 0);
2665 fill_cmd(cmd, O_TCPFLAGS, 0,
2666 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
2670 NEED1("missing argument for tcpoptions");
2671 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
2677 NEED1("tcpseq/tcpack requires argument");
2678 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2679 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
2680 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
2685 NEED1("tcpwin requires length");
2686 fill_cmd(cmd, O_TCPWIN, 0,
2687 htons(strtoul(*av, NULL, 0)));
2692 NEED1("missing argument for tcpflags");
2693 cmd->opcode = O_TCPFLAGS;
2694 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
2700 errx(EX_USAGE, "only one of check-state "
2701 "and limit is allowed");
2703 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
2707 NEED1("limit needs mask and # of connections");
2709 errx(EX_USAGE, "only one of check-state "
2710 "and limit is allowed");
2712 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2714 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
2715 cmd->opcode = O_LIMIT;
2721 val = match_token(limit_masks, *av);
2724 c->limit_mask |= val;
2727 c->conn_limit = atoi(*av);
2728 if (c->conn_limit == 0)
2729 errx(EX_USAGE, "limit: limit must be >0");
2730 if (c->limit_mask == 0)
2731 errx(EX_USAGE, "missing limit mask");
2738 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
2740 if (F_LEN(cmd) > 0) { /* prepare to advance */
2742 cmd = next_cmd(cmd);
2748 * Now copy stuff into the rule.
2749 * If we have a keep-state option, the first instruction
2750 * must be a PROBE_STATE (which is generated here).
2751 * If we have a LOG option, it was stored as the first command,
2752 * and now must be moved to the top of the action part.
2754 dst = (ipfw_insn *)rule->cmd;
2757 * generate O_PROBE_STATE if necessary
2760 fill_cmd(dst, O_PROBE_STATE, 0, 0);
2761 dst = next_cmd(dst);
2764 * copy all commands but O_LOG
2766 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
2769 if (src->opcode != O_LOG) {
2770 bcopy(src, dst, i * sizeof(u_int32_t));
2776 * start action section
2778 rule->act_ofs = dst - rule->cmd;
2781 * put back O_LOG if necessary
2783 src = (ipfw_insn *)cmdbuf;
2784 if ( src->opcode == O_LOG ) {
2786 bcopy(src, dst, i * sizeof(u_int32_t));
2790 * copy all other actions
2792 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
2794 bcopy(src, dst, i * sizeof(u_int32_t));
2798 rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
2799 i = (void *)dst - (void *)rule;
2800 if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
2801 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
2807 zero (int ac, char *av[])
2815 /* clear all entries */
2816 if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
2817 err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
2819 printf("Accounting cleared.\n");
2826 if (isdigit(**av)) {
2827 rulenum = atoi(*av);
2830 if (setsockopt(s, IPPROTO_IP,
2831 IP_FW_ZERO, &rulenum, sizeof rulenum)) {
2832 warn("rule %u: setsockopt(IP_FW_ZERO)",
2834 failed = EX_UNAVAILABLE;
2835 } else if (!do_quiet)
2836 printf("Entry %d cleared\n", rulenum);
2838 errx(EX_USAGE, "invalid rule number ``%s''", *av);
2841 if (failed != EX_OK)
2846 resetlog (int ac, char *av[])
2854 /* clear all entries */
2855 if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
2856 err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
2858 printf("Logging counts reset.\n");
2865 if (isdigit(**av)) {
2866 rulenum = atoi(*av);
2869 if (setsockopt(s, IPPROTO_IP,
2870 IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
2871 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
2873 failed = EX_UNAVAILABLE;
2874 } else if (!do_quiet)
2875 printf("Entry %d logging count reset\n",
2878 errx(EX_DATAERR, "invalid rule number ``%s''", *av);
2881 if (failed != EX_OK)
2888 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
2890 if (!do_force && !do_quiet) { /* need to ask user */
2893 printf("Are you sure? [yn] ");
2896 c = toupper(getc(stdin));
2897 while (c != '\n' && getc(stdin) != '\n')
2899 return; /* and do not flush */
2900 } while (c != 'Y' && c != 'N');
2902 if (c == 'N') /* user said no */
2905 if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
2906 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
2907 do_pipe ? "DUMMYNET" : "FW");
2909 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
2913 ipfw_main(int ac, char **av)
2920 /* Set the force flag for non-interactive processes */
2921 do_force = !isatty(STDIN_FILENO);
2923 optind = optreset = 1;
2924 while ((ch = getopt(ac, av, "hs:adefNqtv")) != -1)
2926 case 'h': /* help */
2928 break; /* NOTREACHED */
2930 case 's': /* sort */
2931 do_sort = atoi(optarg);
2954 case 'v': /* verbose */
2963 NEED1("bad arguments, for usage summary ``ipfw''");
2966 * optional: pipe or queue
2968 if (!strncmp(*av, "pipe", strlen(*av))) {
2972 } else if (!strncmp(*av, "queue", strlen(*av))) {
2977 NEED1("missing command");
2980 * for pipes and queues we normally say 'pipe NN config'
2981 * but the code is easier to parse as 'pipe config NN'
2982 * so we swap the two arguments.
2984 if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
2989 if (!strncmp(*av, "add", strlen(*av)))
2991 else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
2992 config_pipe(ac, av);
2993 else if (!strncmp(*av, "delete", strlen(*av)))
2995 else if (!strncmp(*av, "flush", strlen(*av)))
2997 else if (!strncmp(*av, "zero", strlen(*av)))
2999 else if (!strncmp(*av, "resetlog", strlen(*av)))
3001 else if (!strncmp(*av, "print", strlen(*av)) ||
3002 !strncmp(*av, "list", strlen(*av)))
3004 else if (!strncmp(*av, "show", strlen(*av))) {
3008 errx(EX_USAGE, "bad command `%s'", *av);
3014 ipfw_readfile(int ac, char *av[])
3017 #define WHITESP " \t\f\v\n\r"
3019 char *a, *p, *args[MAX_ARGS], *cmd = NULL;
3021 int i=0, lineno=0, qflag=0, pflag=0, status;
3026 while ((c = getopt(ac, av, "D:U:p:q")) != -1)
3030 errx(EX_USAGE, "-D requires -p");
3031 if (i > MAX_ARGS - 2)
3033 "too many -D or -U options");
3040 errx(EX_USAGE, "-U requires -p");
3041 if (i > MAX_ARGS - 2)
3043 "too many -D or -U options");
3060 errx(EX_USAGE, "bad arguments, for usage"
3061 " summary ``ipfw''");
3067 errx(EX_USAGE, "extraneous filename arguments");
3069 if ((f = fopen(av[0], "r")) == NULL)
3070 err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3073 /* pipe through preprocessor (cpp or m4) */
3078 if (pipe(pipedes) == -1)
3079 err(EX_OSERR, "cannot create pipe");
3081 switch((preproc = fork())) {
3083 err(EX_OSERR, "cannot fork");
3087 if (dup2(fileno(f), 0) == -1
3088 || dup2(pipedes[1], 1) == -1)
3089 err(EX_OSERR, "dup2()");
3094 err(EX_OSERR, "execvp(%s) failed", cmd);
3100 if ((f = fdopen(pipedes[0], "r")) == NULL) {
3101 int savederrno = errno;
3103 (void)kill(preproc, SIGTERM);
3105 err(EX_OSERR, "fdopen()");
3110 while (fgets(buf, BUFSIZ, f)) {
3112 sprintf(linename, "Line %d", lineno);
3117 if ((p = strchr(buf, '#')) != NULL)
3122 for (a = strtok(buf, WHITESP);
3123 a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3125 if (i == (qflag? 2: 1))
3128 errx(EX_USAGE, "%s: too many arguments",
3136 if (waitpid(preproc, &status, 0) == -1)
3137 errx(EX_OSERR, "waitpid()");
3138 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3139 errx(EX_UNAVAILABLE,
3140 "preprocessor exited with status %d",
3141 WEXITSTATUS(status));
3142 else if (WIFSIGNALED(status))
3143 errx(EX_UNAVAILABLE,
3144 "preprocessor exited with signal %d",
3150 main(int ac, char *av[])
3152 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3154 err(EX_UNAVAILABLE, "socket");
3157 * If the last argument is an absolute pathname, interpret it
3158 * as a file to be preprocessed.
3161 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3162 ipfw_readfile(ac, av);