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 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
1573 d[i] = 0; /* clear masks */
1576 low = cmd->addr.s_addr & 0xff;
1577 high = low + cmd->o.arg1 - 1;
1578 while (isdigit(*av)) {
1580 u_int16_t a = strtol(av, &s, 0);
1582 if (s == av) /* no parameter */
1584 if (a < low || a > high) {
1585 fprintf(stderr, "addr %d out of range [%d-%d]\n",
1590 d[ a/32] |= 1<<(a & 31);
1598 if (cmd->mask.s_addr == 0) { /* any */
1599 if (cmd->o.len & F_NOT)
1600 errx(EX_DATAERR, "not any never matches");
1601 else /* useless, nuke it */
1603 } else if (cmd->mask.s_addr == IP_MASK_ALL) /* one IP */
1604 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1605 else /* addr/mask */
1606 cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip);
1611 * helper function to process a set of flags and set bits in the
1612 * appropriate masks.
1615 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
1616 struct _s_x *flags, char *p)
1618 u_int8_t set=0, clear=0;
1621 char *q; /* points to the separator */
1623 u_int8_t *which; /* mask we are working on */
1633 val = match_token(flags, p);
1635 errx(EX_DATAERR, "invalid flag %s", p);
1636 *which |= (u_int8_t)val;
1639 cmd->opcode = opcode;
1640 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
1641 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
1646 delete(int ac, char *av[])
1649 struct dn_pipe pipe;
1651 int exitval = EX_OK;
1653 memset(&pipe, 0, sizeof pipe);
1658 while (ac && isdigit(**av)) {
1659 i = atoi(*av); av++; ac--;
1665 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
1666 &pipe, sizeof pipe);
1669 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1670 do_pipe == 1 ? pipe.pipe_nr :
1675 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum,
1678 exitval = EX_UNAVAILABLE;
1679 warn("rule %u: setsockopt(IP_FW_DEL)",
1684 if (exitval != EX_OK)
1690 * fill the interface structure. We do not check the name as we can
1691 * create interfaces dynamically, so checking them at insert time
1692 * makes relatively little sense.
1693 * A '*' following the name means any unit.
1696 fill_iface(ipfw_insn_if *cmd, char *arg)
1698 cmd->name[0] = '\0';
1699 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
1701 /* Parse the interface or address */
1702 if (!strcmp(arg, "any"))
1703 cmd->o.len = 0; /* effectively ignore this command */
1704 else if (!isdigit(*arg)) {
1707 strncpy(cmd->name, arg, sizeof(cmd->name));
1708 cmd->name[sizeof(cmd->name) - 1] = '\0';
1709 /* find first digit or wildcard */
1710 for (q = cmd->name; *q && !isdigit(*q) && *q != '*'; q++)
1712 cmd->p.unit = (*q == '*') ? -1 : atoi(q);
1714 } else if (!inet_aton(arg, &cmd->p.ip))
1715 errx(EX_DATAERR, "bad ip address ``%s''", arg);
1719 * the following macro returns an error message if we run out of
1722 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
1725 config_pipe(int ac, char **av)
1727 struct dn_pipe pipe;
1733 memset(&pipe, 0, sizeof pipe);
1737 if (ac && isdigit(**av)) {
1738 i = atoi(*av); av++; ac--;
1746 int tok = match_token(dummynet_params, *av);
1751 NEED1("plr needs argument 0..1\n");
1752 d = strtod(av[0], NULL);
1757 pipe.fs.plr = (int)(d*0x7fffffff);
1762 NEED1("queue needs queue size\n");
1764 pipe.fs.qsize = strtoul(av[0], &end, 0);
1765 if (*end == 'K' || *end == 'k') {
1766 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1767 pipe.fs.qsize *= 1024;
1768 } else if (*end == 'B' || !strncmp(end, "by", 2)) {
1769 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
1775 NEED1("buckets needs argument\n");
1776 pipe.fs.rq_size = strtoul(av[0], NULL, 0);
1781 NEED1("mask needs mask specifier\n");
1783 * per-flow queue, mask is dst_ip, dst_port,
1784 * src_ip, src_port, proto measured in bits
1788 pipe.fs.flow_mask.dst_ip = 0;
1789 pipe.fs.flow_mask.src_ip = 0;
1790 pipe.fs.flow_mask.dst_port = 0;
1791 pipe.fs.flow_mask.src_port = 0;
1792 pipe.fs.flow_mask.proto = 0;
1796 u_int32_t *p32 = NULL;
1797 u_int16_t *p16 = NULL;
1799 tok = match_token(dummynet_params, *av);
1804 * special case, all bits significant
1806 pipe.fs.flow_mask.dst_ip = ~0;
1807 pipe.fs.flow_mask.src_ip = ~0;
1808 pipe.fs.flow_mask.dst_port = ~0;
1809 pipe.fs.flow_mask.src_port = ~0;
1810 pipe.fs.flow_mask.proto = ~0;
1811 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1815 p32 = &pipe.fs.flow_mask.dst_ip;
1819 p32 = &pipe.fs.flow_mask.src_ip;
1823 p16 = &pipe.fs.flow_mask.dst_port;
1827 p16 = &pipe.fs.flow_mask.src_port;
1834 ac++; av--; /* backtrack */
1838 errx(EX_USAGE, "mask: value missing");
1839 if (*av[0] == '/') {
1840 a = strtoul(av[0]+1, &end, 0);
1841 a = (a == 32) ? ~0 : (1 << a) - 1;
1843 a = strtoul(av[0], &end, 0);
1846 else if (p16 != NULL) {
1849 "mask: must be 16 bit");
1850 *p16 = (u_int16_t)a;
1854 "mask: must be 8 bit");
1855 pipe.fs.flow_mask.proto = (u_int8_t)a;
1858 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
1860 } /* end while, config masks */
1866 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
1867 pipe.fs.flags_fs |= DN_IS_RED;
1868 if (tok == TOK_GRED)
1869 pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
1871 * the format for parameters is w_q/min_th/max_th/max_p
1873 if ((end = strsep(&av[0], "/"))) {
1874 double w_q = strtod(end, NULL);
1875 if (w_q > 1 || w_q <= 0)
1876 errx(EX_DATAERR, "0 < w_q <= 1");
1877 pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
1879 if ((end = strsep(&av[0], "/"))) {
1880 pipe.fs.min_th = strtoul(end, &end, 0);
1881 if (*end == 'K' || *end == 'k')
1882 pipe.fs.min_th *= 1024;
1884 if ((end = strsep(&av[0], "/"))) {
1885 pipe.fs.max_th = strtoul(end, &end, 0);
1886 if (*end == 'K' || *end == 'k')
1887 pipe.fs.max_th *= 1024;
1889 if ((end = strsep(&av[0], "/"))) {
1890 double max_p = strtod(end, NULL);
1891 if (max_p > 1 || max_p <= 0)
1892 errx(EX_DATAERR, "0 < max_p <= 1");
1893 pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED));
1899 pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1903 NEED1("bw needs bandwidth or interface\n");
1905 errx(EX_DATAERR, "bandwidth only valid for pipes");
1907 * set clocking interface or bandwidth value
1909 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
1910 int l = sizeof(pipe.if_name)-1;
1911 /* interface name */
1912 strncpy(pipe.if_name, av[0], l);
1913 pipe.if_name[l] = '\0';
1916 pipe.if_name[0] = '\0';
1917 pipe.bandwidth = strtoul(av[0], &end, 0);
1918 if (*end == 'K' || *end == 'k') {
1920 pipe.bandwidth *= 1000;
1921 } else if (*end == 'M') {
1923 pipe.bandwidth *= 1000000;
1925 if (*end == 'B' || !strncmp(end, "by", 2))
1926 pipe.bandwidth *= 8;
1927 if (pipe.bandwidth < 0)
1928 errx(EX_DATAERR, "bandwidth too large");
1935 errx(EX_DATAERR, "delay only valid for pipes");
1936 NEED1("delay needs argument 0..10000ms\n");
1937 pipe.delay = strtoul(av[0], NULL, 0);
1943 errx(EX_DATAERR,"weight only valid for queues");
1944 NEED1("weight needs argument 0..100\n");
1945 pipe.fs.weight = strtoul(av[0], &end, 0);
1951 errx(EX_DATAERR,"pipe only valid for queues");
1952 NEED1("pipe needs pipe_number\n");
1953 pipe.fs.parent_nr = strtoul(av[0], &end, 0);
1958 errx(EX_DATAERR, "unrecognised option ``%s''", *av);
1962 if (pipe.pipe_nr == 0)
1963 errx(EX_DATAERR, "pipe_nr must be > 0");
1964 if (pipe.delay > 10000)
1965 errx(EX_DATAERR, "delay must be < 10000");
1966 } else { /* do_pipe == 2, queue */
1967 if (pipe.fs.parent_nr == 0)
1968 errx(EX_DATAERR, "pipe must be > 0");
1969 if (pipe.fs.weight >100)
1970 errx(EX_DATAERR, "weight must be <= 100");
1972 if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) {
1973 if (pipe.fs.qsize > 1024*1024)
1974 errx(EX_DATAERR, "queue size must be < 1MB");
1976 if (pipe.fs.qsize > 100)
1977 errx(EX_DATAERR, "2 <= queue size <= 100");
1979 if (pipe.fs.flags_fs & DN_IS_RED) {
1981 int lookup_depth, avg_pkt_size;
1982 double s, idle, weight, w_q;
1983 struct clockinfo clock;
1986 if (pipe.fs.min_th >= pipe.fs.max_th)
1987 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1988 pipe.fs.min_th, pipe.fs.max_th);
1989 if (pipe.fs.max_th == 0)
1990 errx(EX_DATAERR, "max_th must be > 0");
1993 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1994 &lookup_depth, &len, NULL, 0) == -1)
1996 errx(1, "sysctlbyname(\"%s\")",
1997 "net.inet.ip.dummynet.red_lookup_depth");
1998 if (lookup_depth == 0)
1999 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
2000 " must be greater than zero");
2003 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2004 &avg_pkt_size, &len, NULL, 0) == -1)
2006 errx(1, "sysctlbyname(\"%s\")",
2007 "net.inet.ip.dummynet.red_avg_pkt_size");
2008 if (avg_pkt_size == 0)
2010 "net.inet.ip.dummynet.red_avg_pkt_size must"
2011 " be greater than zero");
2013 len = sizeof(struct clockinfo);
2014 if (sysctlbyname("kern.clockrate", &clock, &len, NULL, 0) == -1)
2015 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
2018 * Ticks needed for sending a medium-sized packet.
2019 * Unfortunately, when we are configuring a WF2Q+ queue, we
2020 * do not have bandwidth information, because that is stored
2021 * in the parent pipe, and also we have multiple queues
2022 * competing for it. So we set s=0, which is not very
2023 * correct. But on the other hand, why do we want RED with
2026 if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
2029 s = clock.hz * avg_pkt_size * 8 / pipe.bandwidth;
2032 * max idle time (in ticks) before avg queue size becomes 0.
2033 * NOTA: (3/w_q) is approx the value x so that
2034 * (1-w_q)^x < 10^-3.
2036 w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
2037 idle = s * 3. / w_q;
2038 pipe.fs.lookup_step = (int)idle / lookup_depth;
2039 if (!pipe.fs.lookup_step)
2040 pipe.fs.lookup_step = 1;
2042 for (t = pipe.fs.lookup_step; t > 0; --t)
2044 pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2046 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
2049 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2053 get_mac_addr_mask(char *p, u_char *addr, u_char *mask)
2058 addr[i] = mask[i] = 0;
2059 if (!strcmp(p, "any"))
2062 for (i=0; *p && i<6;i++, p++) {
2063 addr[i] = strtol(p, &p, 16);
2064 if (*p != ':') /* we start with the mask */
2067 if (*p == '/') { /* mask len */
2068 l = strtol(p+1, &p, 0);
2069 for (i=0; l>0; l -=8, i++)
2070 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2071 } else if (*p == '&') { /* mask */
2072 for (i=0, p++; *p && i<6;i++, p++) {
2073 mask[i] = strtol(p, &p, 16);
2077 } else if (*p == '\0') {
2086 * helper function, updates the pointer to cmd with the length
2087 * of the current command, and also cleans up the first word of
2088 * the new command in case it has been clobbered before.
2091 next_cmd(ipfw_insn *cmd)
2094 bzero(cmd, sizeof(*cmd));
2099 * A function to fill simple commands of size 1.
2100 * Existing flags are preserved.
2103 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg)
2105 cmd->opcode = opcode;
2106 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2111 * Fetch and add the MAC address and type, with masks. This generates one or
2112 * two microinstructions, and returns the pointer to the last one.
2115 add_mac(ipfw_insn *cmd, int ac, char *av[])
2117 ipfw_insn_mac *mac; /* also *src */
2120 errx(EX_DATAERR, "MAC dst src type");
2122 cmd->opcode = O_MACADDR2;
2123 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2125 mac = (ipfw_insn_mac *)cmd;
2126 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2127 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2130 if (strcmp(av[0], "any") != 0) { /* we have a non-null port */
2133 fill_newports((ipfw_insn_u16 *)cmd, av[0], IPPROTO_ETHERTYPE);
2134 cmd->opcode = O_MAC_TYPE;
2141 * Parse arguments and assemble the microinstructions which make up a rule.
2142 * Rules are added into the 'rulebuf' and then copied in the correct order
2143 * into the actual rule.
2145 * The syntax for a rule starts with the action, followed by an
2146 * optional log action, and the various match patterns.
2147 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2148 * (generated if the rule includes a keep-state option), then the
2149 * various match patterns, the "log" action, and the actual action.
2153 add(int ac, char *av[])
2156 * rules are added into the 'rulebuf' and then copied in
2157 * the correct order into the actual rule.
2158 * Some things that need to go out of order (prob, action etc.)
2161 static u_int32_t rulebuf[255], actbuf[255], cmdbuf[255];
2163 ipfw_insn *src, *dst, *cmd, *action, *prev;
2168 * various flags used to record that we entered some fields.
2170 int have_mac = 0; /* set if we have a MAC address */
2171 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2175 int open_par = 0; /* open parenthesis ( */
2177 /* proto is here because it is used to fetch ports */
2178 u_char proto = IPPROTO_IP; /* default protocol */
2180 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2181 bzero(cmdbuf, sizeof(cmdbuf));
2182 bzero(rulebuf, sizeof(rulebuf));
2184 rule = (struct ip_fw *)rulebuf;
2185 cmd = (ipfw_insn *)cmdbuf;
2186 action = (ipfw_insn *)actbuf;
2190 /* [rule N] -- Rule number optional */
2191 if (ac && isdigit(**av)) {
2192 rule->rulenum = atoi(*av);
2197 /* [prob D] -- match probability, optional */
2198 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2199 double d = strtod(av[1], NULL);
2201 if (d <= 0 || d > 1)
2202 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2203 if (d != 1) { /* 1 means always match */
2204 action->opcode = O_PROB;
2206 *((int32_t *)(action+1)) =
2207 (int32_t)((1 - d) * 0x7fffffff);
2208 action += action->len;
2213 /* action -- mandatory */
2214 NEED1("missing action");
2215 i = match_token(rule_actions, *av);
2217 action->len = 1; /* default */
2219 case TOK_CHECKSTATE:
2220 have_state = action;
2221 action->opcode = O_CHECK_STATE;
2225 action->opcode = O_ACCEPT;
2229 action->opcode = O_DENY;
2234 action->opcode = O_REJECT;
2235 action->arg1 = ICMP_UNREACH_HOST;
2239 action->opcode = O_REJECT;
2240 action->arg1 = ICMP_REJECT_RST;
2244 action->opcode = O_REJECT;
2245 NEED1("missing reject code");
2246 fill_reject_code(&action->arg1, *av);
2251 action->opcode = O_COUNT;
2256 action->len = F_INSN_SIZE(ipfw_insn_pipe);
2259 action->opcode = O_QUEUE;
2260 else if (i == TOK_PIPE)
2261 action->opcode = O_PIPE;
2262 else if (i == TOK_SKIPTO)
2263 action->opcode = O_SKIPTO;
2264 NEED1("missing skipto/pipe/queue number");
2265 action->arg1 = strtoul(*av, NULL, 10);
2271 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2272 NEED1("missing divert/tee port");
2273 action->arg1 = strtoul(*av, NULL, 0);
2274 if (action->arg1 == 0) {
2277 s = getservbyname(av[0], "divert");
2279 action->arg1 = ntohs(s->s_port);
2281 errx(EX_DATAERR, "illegal divert/tee port");
2287 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2290 NEED1("missing forward address[:port]");
2292 action->opcode = O_FORWARD_IP;
2293 action->len = F_INSN_SIZE(ipfw_insn_sa);
2295 p->sa.sin_len = sizeof(struct sockaddr_in);
2296 p->sa.sin_family = AF_INET;
2299 * locate the address-port separator (':' or ',')
2301 s = strchr(*av, ':');
2303 s = strchr(*av, ',');
2306 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2309 "illegal forwarding port ``%s''", s);
2310 p->sa.sin_port = htons( (u_short)i );
2312 lookup_host(*av, &(p->sa.sin_addr));
2318 errx(EX_DATAERR, "invalid action %s\n", *av);
2320 action = next_cmd(action);
2323 * [log [logamount N]] -- log, optional
2325 * If exists, it goes first in the cmdbuf, but then it is
2326 * skipped in the copy section to the end of the buffer.
2328 if (ac && !strncmp(*av, "log", strlen(*av))) {
2329 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2331 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2332 cmd->opcode = O_LOG;
2334 if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2336 NEED1("logamount requires argument");
2337 c->max_log = atoi(*av);
2339 errx(EX_DATAERR, "logamount must be positive");
2342 cmd = next_cmd(cmd);
2345 if (have_state) /* must be a check-state, we are done */
2348 #define OR_START(target) \
2349 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2351 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2353 if ( (av[0])[1] == '\0') { \
2364 !strncmp(*av, ")", strlen(*av)) || \
2365 !strncmp(*av, "}", strlen(*av)) )) { \
2369 errx(EX_USAGE, "missing \")\"\n"); \
2373 if (ac && !strncmp(*av, "not", strlen(*av))) { \
2374 if (cmd->len & F_NOT) \
2375 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2376 cmd->len |= F_NOT; \
2380 #define OR_BLOCK(target) \
2381 if (ac && !strncmp(*av, "or", strlen(*av))) { \
2382 if (prev == NULL || open_par == 0) \
2383 errx(EX_DATAERR, "invalid OR block"); \
2384 prev->len |= F_OR; \
2391 * protocol, mandatory
2393 OR_START(get_proto);
2395 NEED1("missing protocol");
2397 struct protoent *pe;
2399 if (!strncmp(*av, "all", strlen(*av)))
2400 ; /* same as "ip" */
2401 else if (!strncmp(*av, "MAC", strlen(*av))) {
2402 /* need exactly 3 fields */
2403 cmd = add_mac(cmd, ac-1, av+1); /* exits in case of errors */
2407 } else if ((proto = atoi(*av)) > 0)
2409 else if ((pe = getprotobyname(*av)) != NULL)
2410 proto = pe->p_proto;
2412 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
2414 if (proto != IPPROTO_IP)
2415 fill_cmd(cmd, O_PROTO, 0, proto);
2417 cmd = next_cmd(cmd);
2418 OR_BLOCK(get_proto);
2421 * "from", mandatory (unless we have a MAC address)
2423 if (!ac || strncmp(*av, "from", strlen(*av))) {
2424 if (have_mac) /* we do not need a "to" address */
2426 errx(EX_USAGE, "missing ``from''");
2431 * source IP, mandatory
2433 OR_START(source_ip);
2434 NOT_BLOCK; /* optional "not" */
2435 NEED1("missing source address");
2437 /* source -- mandatory */
2438 fill_ip((ipfw_insn_ip *)cmd, *av);
2439 if (cmd->opcode == O_IP_DST_SET) /* set */
2440 cmd->opcode = O_IP_SRC_SET;
2441 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2442 cmd->opcode = O_IP_SRC_ME;
2443 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2444 cmd->opcode = O_IP_SRC;
2445 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2446 cmd->opcode = O_IP_SRC_MASK;
2447 /* otherwise len will be zero and the command skipped */
2449 prev = cmd; /* in case we need to backtrack */
2450 cmd = next_cmd(cmd);
2451 OR_BLOCK(source_ip);
2454 * source ports, optional
2456 NOT_BLOCK; /* optional "not" */
2457 if (ac && fill_newports((ipfw_insn_u16 *)cmd, *av, proto)) {
2458 /* XXX todo: check that we have a protocol with ports */
2459 cmd->opcode = O_IP_SRCPORT;
2462 cmd = next_cmd(cmd);
2467 * "to", mandatory (unless we have a MAC address
2469 if (!ac || strncmp(*av, "to", strlen(*av))) {
2472 errx(EX_USAGE, "missing ``to''");
2477 * destination, mandatory
2480 NOT_BLOCK; /* optional "not" */
2481 NEED1("missing dst address");
2482 fill_ip((ipfw_insn_ip *)cmd, *av);
2483 if (cmd->opcode == O_IP_DST_SET) /* set */
2485 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2486 cmd->opcode = O_IP_DST_ME;
2487 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2488 cmd->opcode = O_IP_DST;
2489 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2490 cmd->opcode = O_IP_DST_MASK;
2494 cmd = next_cmd(cmd);
2498 * dest. ports, optional
2500 NOT_BLOCK; /* optional "not" */
2501 if (ac && fill_newports((ipfw_insn_u16 *)cmd, *av, proto)) {
2502 /* XXX todo: check that we have a protocol with ports */
2503 cmd->opcode = O_IP_DSTPORT;
2513 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; /* alias */
2515 if (*s == '!') { /* alternate syntax for NOT */
2516 if (cmd->len & F_NOT)
2517 errx(EX_USAGE, "double \"not\" not allowed\n");
2521 i = match_token(rule_options, s);
2525 if (cmd->len & F_NOT)
2526 errx(EX_USAGE, "double \"not\" not allowed\n");
2532 errx(EX_USAGE, "invalid \"or\" block\n");
2537 fill_cmd(cmd, O_IN, 0, 0);
2541 cmd->len ^= F_NOT; /* toggle F_NOT */
2542 fill_cmd(cmd, O_IN, 0, 0);
2546 fill_cmd(cmd, O_FRAG, 0, 0);
2550 fill_cmd(cmd, O_LAYER2, 0, 0);
2556 NEED1("recv, xmit, via require interface name"
2558 fill_iface((ipfw_insn_if *)cmd, av[0]);
2560 if (F_LEN(cmd) == 0) /* not a valid address */
2563 cmd->opcode = O_XMIT;
2564 else if (i == TOK_RECV)
2565 cmd->opcode = O_RECV;
2566 else if (i == TOK_VIA)
2567 cmd->opcode = O_VIA;
2571 NEED1("icmptypes requires list of types");
2572 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
2577 NEED1("ipttl requires TTL");
2578 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
2583 NEED1("ipid requires length");
2584 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
2589 NEED1("iplen requires length");
2590 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
2595 NEED1("ipver requires version");
2596 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
2600 case TOK_IPPRECEDENCE:
2601 NEED1("ipprecedence requires value");
2602 fill_cmd(cmd, O_IPPRECEDENCE, 0,
2603 (strtoul(*av, NULL, 0) & 7) << 5);
2608 NEED1("missing argument for ipoptions");
2609 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
2614 NEED1("missing argument for iptos");
2615 fill_flags(cmd, O_IPTOS, f_iptos, *av);
2620 NEED1("uid requires argument");
2626 cmd->opcode = O_UID;
2627 uid = strtoul(*av, &end, 0);
2628 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
2630 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
2632 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2638 NEED1("gid requires argument");
2644 cmd->opcode = O_GID;
2645 gid = strtoul(*av, &end, 0);
2646 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
2648 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
2651 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2657 fill_cmd(cmd, O_ESTAB, 0, 0);
2661 fill_cmd(cmd, O_TCPFLAGS, 0,
2662 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
2666 NEED1("missing argument for tcpoptions");
2667 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
2673 NEED1("tcpseq/tcpack requires argument");
2674 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
2675 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
2676 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
2681 NEED1("tcpwin requires length");
2682 fill_cmd(cmd, O_TCPWIN, 0,
2683 htons(strtoul(*av, NULL, 0)));
2688 NEED1("missing argument for tcpflags");
2689 cmd->opcode = O_TCPFLAGS;
2690 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
2696 errx(EX_USAGE, "only one of keep-state "
2697 "and limit is allowed");
2699 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
2703 NEED1("limit needs mask and # of connections");
2705 errx(EX_USAGE, "only one of keep-state "
2706 "and limit is allowed");
2709 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2711 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
2712 cmd->opcode = O_LIMIT;
2718 val = match_token(limit_masks, *av);
2721 c->limit_mask |= val;
2724 c->conn_limit = atoi(*av);
2725 if (c->conn_limit == 0)
2726 errx(EX_USAGE, "limit: limit must be >0");
2727 if (c->limit_mask == 0)
2728 errx(EX_USAGE, "missing limit mask");
2734 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
2736 if (F_LEN(cmd) > 0) { /* prepare to advance */
2738 cmd = next_cmd(cmd);
2744 * Now copy stuff into the rule.
2745 * If we have a keep-state option, the first instruction
2746 * must be a PROBE_STATE (which is generated here).
2747 * If we have a LOG option, it was stored as the first command,
2748 * and now must be moved to the top of the action part.
2750 dst = (ipfw_insn *)rule->cmd;
2753 * generate O_PROBE_STATE if necessary
2755 if (have_state && have_state->opcode != O_CHECK_STATE) {
2756 fill_cmd(dst, O_PROBE_STATE, 0, 0);
2757 dst = next_cmd(dst);
2760 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT
2762 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
2765 switch (src->opcode) {
2771 bcopy(src, dst, i * sizeof(u_int32_t));
2777 * put back the have_state command as last opcode
2780 i = F_LEN(have_state);
2781 bcopy(have_state, dst, i * sizeof(u_int32_t));
2785 * start action section
2787 rule->act_ofs = dst - rule->cmd;
2790 * put back O_LOG if necessary
2792 src = (ipfw_insn *)cmdbuf;
2793 if ( src->opcode == O_LOG ) {
2795 bcopy(src, dst, i * sizeof(u_int32_t));
2799 * copy all other actions
2801 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
2803 bcopy(src, dst, i * sizeof(u_int32_t));
2807 rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
2808 i = (void *)dst - (void *)rule;
2809 if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
2810 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
2816 zero (int ac, char *av[])
2824 /* clear all entries */
2825 if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
2826 err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
2828 printf("Accounting cleared.\n");
2835 if (isdigit(**av)) {
2836 rulenum = atoi(*av);
2839 if (setsockopt(s, IPPROTO_IP,
2840 IP_FW_ZERO, &rulenum, sizeof rulenum)) {
2841 warn("rule %u: setsockopt(IP_FW_ZERO)",
2843 failed = EX_UNAVAILABLE;
2844 } else if (!do_quiet)
2845 printf("Entry %d cleared\n", rulenum);
2847 errx(EX_USAGE, "invalid rule number ``%s''", *av);
2850 if (failed != EX_OK)
2855 resetlog (int ac, char *av[])
2863 /* clear all entries */
2864 if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
2865 err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
2867 printf("Logging counts reset.\n");
2874 if (isdigit(**av)) {
2875 rulenum = atoi(*av);
2878 if (setsockopt(s, IPPROTO_IP,
2879 IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
2880 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
2882 failed = EX_UNAVAILABLE;
2883 } else if (!do_quiet)
2884 printf("Entry %d logging count reset\n",
2887 errx(EX_DATAERR, "invalid rule number ``%s''", *av);
2890 if (failed != EX_OK)
2897 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
2899 if (!do_force && !do_quiet) { /* need to ask user */
2902 printf("Are you sure? [yn] ");
2905 c = toupper(getc(stdin));
2906 while (c != '\n' && getc(stdin) != '\n')
2908 return; /* and do not flush */
2909 } while (c != 'Y' && c != 'N');
2911 if (c == 'N') /* user said no */
2914 if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
2915 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
2916 do_pipe ? "DUMMYNET" : "FW");
2918 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
2922 ipfw_main(int ac, char **av)
2929 /* Set the force flag for non-interactive processes */
2930 do_force = !isatty(STDIN_FILENO);
2932 optind = optreset = 1;
2933 while ((ch = getopt(ac, av, "hs:adefNqtv")) != -1)
2935 case 'h': /* help */
2937 break; /* NOTREACHED */
2939 case 's': /* sort */
2940 do_sort = atoi(optarg);
2963 case 'v': /* verbose */
2972 NEED1("bad arguments, for usage summary ``ipfw''");
2975 * optional: pipe or queue
2977 if (!strncmp(*av, "pipe", strlen(*av))) {
2981 } else if (!strncmp(*av, "queue", strlen(*av))) {
2986 NEED1("missing command");
2989 * for pipes and queues we normally say 'pipe NN config'
2990 * but the code is easier to parse as 'pipe config NN'
2991 * so we swap the two arguments.
2993 if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
2998 if (!strncmp(*av, "add", strlen(*av)))
3000 else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
3001 config_pipe(ac, av);
3002 else if (!strncmp(*av, "delete", strlen(*av)))
3004 else if (!strncmp(*av, "flush", strlen(*av)))
3006 else if (!strncmp(*av, "zero", strlen(*av)))
3008 else if (!strncmp(*av, "resetlog", strlen(*av)))
3010 else if (!strncmp(*av, "print", strlen(*av)) ||
3011 !strncmp(*av, "list", strlen(*av)))
3013 else if (!strncmp(*av, "show", strlen(*av))) {
3017 errx(EX_USAGE, "bad command `%s'", *av);
3023 ipfw_readfile(int ac, char *av[])
3026 #define WHITESP " \t\f\v\n\r"
3028 char *a, *p, *args[MAX_ARGS], *cmd = NULL;
3030 int i=0, lineno=0, qflag=0, pflag=0, status;
3035 while ((c = getopt(ac, av, "D:U:p:q")) != -1)
3039 errx(EX_USAGE, "-D requires -p");
3040 if (i > MAX_ARGS - 2)
3042 "too many -D or -U options");
3049 errx(EX_USAGE, "-U requires -p");
3050 if (i > MAX_ARGS - 2)
3052 "too many -D or -U options");
3069 errx(EX_USAGE, "bad arguments, for usage"
3070 " summary ``ipfw''");
3076 errx(EX_USAGE, "extraneous filename arguments");
3078 if ((f = fopen(av[0], "r")) == NULL)
3079 err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3082 /* pipe through preprocessor (cpp or m4) */
3087 if (pipe(pipedes) == -1)
3088 err(EX_OSERR, "cannot create pipe");
3090 switch((preproc = fork())) {
3092 err(EX_OSERR, "cannot fork");
3096 if (dup2(fileno(f), 0) == -1
3097 || dup2(pipedes[1], 1) == -1)
3098 err(EX_OSERR, "dup2()");
3103 err(EX_OSERR, "execvp(%s) failed", cmd);
3109 if ((f = fdopen(pipedes[0], "r")) == NULL) {
3110 int savederrno = errno;
3112 (void)kill(preproc, SIGTERM);
3114 err(EX_OSERR, "fdopen()");
3119 while (fgets(buf, BUFSIZ, f)) {
3121 sprintf(linename, "Line %d", lineno);
3126 if ((p = strchr(buf, '#')) != NULL)
3131 for (a = strtok(buf, WHITESP);
3132 a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3134 if (i == (qflag? 2: 1))
3137 errx(EX_USAGE, "%s: too many arguments",
3145 if (waitpid(preproc, &status, 0) == -1)
3146 errx(EX_OSERR, "waitpid()");
3147 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3148 errx(EX_UNAVAILABLE,
3149 "preprocessor exited with status %d",
3150 WEXITSTATUS(status));
3151 else if (WIFSIGNALED(status))
3152 errx(EX_UNAVAILABLE,
3153 "preprocessor exited with signal %d",
3159 main(int ac, char *av[])
3161 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3163 err(EX_UNAVAILABLE, "socket");
3166 * If the last argument is an absolute pathname, interpret it
3167 * as a file to be preprocessed.
3170 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3171 ipfw_readfile(ac, av);