2 * Copyright (c) 2002-2003 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>
30 #include <sys/queue.h>
44 #include <timeconv.h> /* XXX do we need this ? */
51 #include <net/pfvar.h>
52 #include <net/route.h> /* def. of struct route */
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/ip_icmp.h>
57 #include <netinet/icmp6.h>
58 #include <netinet/ip_fw.h>
59 #include <netinet/ip_dummynet.h>
60 #include <netinet/tcp.h>
61 #include <arpa/inet.h>
64 do_resolv, /* Would try to resolve all */
65 do_time, /* Show time stamps */
66 do_quiet, /* Be quiet in add and flush */
67 do_pipe, /* this cmd refers to a pipe */
68 do_sort, /* field to sort results (0 = no) */
69 do_dynamic, /* display dynamic rules */
70 do_expired, /* display expired dynamic rules */
71 do_compact, /* show rules in compact mode */
72 do_force, /* do not ask for confirmation */
73 show_sets, /* display rule sets */
74 test_only, /* only check syntax */
75 comment_only, /* only print action and comment */
78 #define IP_MASK_ALL 0xffffffff
80 * the following macro returns an error message if we run out of
83 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
86 * _s_x is a structure that stores a string <-> token pairs, used in
87 * various places in the parser. Entries are stored in arrays,
88 * with an entry with s=NULL as terminator.
89 * The search routines are match_token() and match_value().
90 * Often, an element with x=0 contains an error string.
98 static struct _s_x f_tcpflags[] = {
109 static struct _s_x f_tcpopts[] = {
110 { "mss", IP_FW_TCPOPT_MSS },
111 { "maxseg", IP_FW_TCPOPT_MSS },
112 { "window", IP_FW_TCPOPT_WINDOW },
113 { "sack", IP_FW_TCPOPT_SACK },
114 { "ts", IP_FW_TCPOPT_TS },
115 { "timestamp", IP_FW_TCPOPT_TS },
116 { "cc", IP_FW_TCPOPT_CC },
122 * IP options span the range 0 to 255 so we need to remap them
123 * (though in fact only the low 5 bits are significant).
125 static struct _s_x f_ipopts[] = {
126 { "ssrr", IP_FW_IPOPT_SSRR},
127 { "lsrr", IP_FW_IPOPT_LSRR},
128 { "rr", IP_FW_IPOPT_RR},
129 { "ts", IP_FW_IPOPT_TS},
134 static struct _s_x f_iptos[] = {
135 { "lowdelay", IPTOS_LOWDELAY},
136 { "throughput", IPTOS_THROUGHPUT},
137 { "reliability", IPTOS_RELIABILITY},
138 { "mincost", IPTOS_MINCOST},
139 { "congestion", IPTOS_CE},
140 { "ecntransport", IPTOS_ECT},
141 { "ip tos option", 0},
145 static struct _s_x limit_masks[] = {
146 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
147 {"src-addr", DYN_SRC_ADDR},
148 {"src-port", DYN_SRC_PORT},
149 {"dst-addr", DYN_DST_ADDR},
150 {"dst-port", DYN_DST_PORT},
155 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
156 * This is only used in this code.
158 #define IPPROTO_ETHERTYPE 0x1000
159 static struct _s_x ether_types[] = {
161 * Note, we cannot use "-:&/" in the names because they are field
162 * separators in the type specifications. Also, we use s = NULL as
163 * end-delimiter, because a type of 0 can be legal.
176 { "pppoe_disc", 0x8863 },
177 { "pppoe_sess", 0x8864 },
178 { "ipx_8022", 0x00E0 },
179 { "ipx_8023", 0x0000 },
180 { "ipx_ii", 0x8137 },
181 { "ipx_snap", 0x8137 },
187 static void show_usage(void);
225 TOK_DIVERTEDLOOPBACK,
282 struct _s_x dummynet_params[] = {
284 { "noerror", TOK_NOERROR },
285 { "buckets", TOK_BUCKETS },
286 { "dst-ip", TOK_DSTIP },
287 { "src-ip", TOK_SRCIP },
288 { "dst-port", TOK_DSTPORT },
289 { "src-port", TOK_SRCPORT },
290 { "proto", TOK_PROTO },
291 { "weight", TOK_WEIGHT },
293 { "mask", TOK_MASK },
294 { "droptail", TOK_DROPTAIL },
296 { "gred", TOK_GRED },
298 { "bandwidth", TOK_BW },
299 { "delay", TOK_DELAY },
300 { "pipe", TOK_PIPE },
301 { "queue", TOK_QUEUE },
302 { "flow-id", TOK_FLOWID},
303 { "dst-ipv6", TOK_DSTIP6},
304 { "dst-ip6", TOK_DSTIP6},
305 { "src-ipv6", TOK_SRCIP6},
306 { "src-ip6", TOK_SRCIP6},
307 { "dummynet-params", TOK_NULL },
308 { NULL, 0 } /* terminator */
311 struct _s_x rule_actions[] = {
312 { "accept", TOK_ACCEPT },
313 { "pass", TOK_ACCEPT },
314 { "allow", TOK_ACCEPT },
315 { "permit", TOK_ACCEPT },
316 { "count", TOK_COUNT },
317 { "pipe", TOK_PIPE },
318 { "queue", TOK_QUEUE },
319 { "divert", TOK_DIVERT },
321 { "netgraph", TOK_NETGRAPH },
322 { "ngtee", TOK_NGTEE },
323 { "fwd", TOK_FORWARD },
324 { "forward", TOK_FORWARD },
325 { "skipto", TOK_SKIPTO },
326 { "deny", TOK_DENY },
327 { "drop", TOK_DENY },
328 { "reject", TOK_REJECT },
329 { "reset", TOK_RESET },
330 { "unreach", TOK_UNREACH },
331 { "check-state", TOK_CHECKSTATE },
332 { "//", TOK_COMMENT },
333 { NULL, 0 } /* terminator */
336 struct _s_x rule_action_params[] = {
337 { "altq", TOK_ALTQ },
339 { NULL, 0 } /* terminator */
342 struct _s_x rule_options[] = {
345 { "jail", TOK_JAIL },
347 { "limit", TOK_LIMIT },
348 { "keep-state", TOK_KEEPSTATE },
349 { "bridged", TOK_LAYER2 },
350 { "layer2", TOK_LAYER2 },
352 { "diverted", TOK_DIVERTED },
353 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
354 { "diverted-output", TOK_DIVERTEDOUTPUT },
355 { "xmit", TOK_XMIT },
356 { "recv", TOK_RECV },
358 { "fragment", TOK_FRAG },
359 { "frag", TOK_FRAG },
360 { "ipoptions", TOK_IPOPTS },
361 { "ipopts", TOK_IPOPTS },
362 { "iplen", TOK_IPLEN },
363 { "ipid", TOK_IPID },
364 { "ipprecedence", TOK_IPPRECEDENCE },
365 { "iptos", TOK_IPTOS },
366 { "ipttl", TOK_IPTTL },
367 { "ipversion", TOK_IPVER },
368 { "ipver", TOK_IPVER },
369 { "estab", TOK_ESTAB },
370 { "established", TOK_ESTAB },
371 { "setup", TOK_SETUP },
372 { "tcpdatalen", TOK_TCPDATALEN },
373 { "tcpflags", TOK_TCPFLAGS },
374 { "tcpflgs", TOK_TCPFLAGS },
375 { "tcpoptions", TOK_TCPOPTS },
376 { "tcpopts", TOK_TCPOPTS },
377 { "tcpseq", TOK_TCPSEQ },
378 { "tcpack", TOK_TCPACK },
379 { "tcpwin", TOK_TCPWIN },
380 { "icmptype", TOK_ICMPTYPES },
381 { "icmptypes", TOK_ICMPTYPES },
382 { "dst-ip", TOK_DSTIP },
383 { "src-ip", TOK_SRCIP },
384 { "dst-port", TOK_DSTPORT },
385 { "src-port", TOK_SRCPORT },
386 { "proto", TOK_PROTO },
389 { "mac-type", TOK_MACTYPE },
390 { "verrevpath", TOK_VERREVPATH },
391 { "versrcreach", TOK_VERSRCREACH },
392 { "antispoof", TOK_ANTISPOOF },
393 { "ipsec", TOK_IPSEC },
394 { "icmp6type", TOK_ICMP6TYPES },
395 { "icmp6types", TOK_ICMP6TYPES },
396 { "ext6hdr", TOK_EXT6HDR},
397 { "flow-id", TOK_FLOWID},
402 { "dst-ipv6", TOK_DSTIP6},
403 { "dst-ip6", TOK_DSTIP6},
404 { "src-ipv6", TOK_SRCIP6},
405 { "src-ip6", TOK_SRCIP6},
406 { "//", TOK_COMMENT },
408 { "not", TOK_NOT }, /* pseudo option */
409 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
410 { "or", TOK_OR }, /* pseudo option */
411 { "|", /* escape */ TOK_OR }, /* pseudo option */
412 { "{", TOK_STARTBRACE }, /* pseudo option */
413 { "(", TOK_STARTBRACE }, /* pseudo option */
414 { "}", TOK_ENDBRACE }, /* pseudo option */
415 { ")", TOK_ENDBRACE }, /* pseudo option */
416 { NULL, 0 } /* terminator */
419 static __inline uint64_t
420 align_uint64(uint64_t *pll) {
423 bcopy (pll, &ret, sizeof(ret));
428 * conditionally runs the command.
431 do_cmd(int optname, void *optval, uintptr_t optlen)
433 static int s = -1; /* the socket */
440 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
442 err(EX_UNAVAILABLE, "socket");
444 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
445 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
446 optname == IP_FW_TABLE_GETSIZE)
447 i = getsockopt(s, IPPROTO_IP, optname, optval,
448 (socklen_t *)optlen);
450 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
455 * match_token takes a table and a string, returns the value associated
456 * with the string (-1 in case of failure).
459 match_token(struct _s_x *table, char *string)
462 uint i = strlen(string);
464 for (pt = table ; i && pt->s != NULL ; pt++)
465 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
471 * match_value takes a table and a value, returns the string associated
472 * with the value (NULL in case of failure).
475 match_value(struct _s_x *p, int value)
477 for (; p->s != NULL; p++)
484 * _substrcmp takes two strings and returns 1 if they do not match,
485 * and 0 if they match exactly or the first string is a sub-string
486 * of the second. A warning is printed to stderr in the case that the
487 * first string is a sub-string of the second.
489 * This function will be removed in the future through the usual
490 * deprecation process.
493 _substrcmp(const char *str1, const char* str2)
496 if (strncmp(str1, str2, strlen(str1)) != 0)
499 if (strlen(str1) != strlen(str2))
500 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
506 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
507 * and 0 if they match exactly or the second string is a sub-string
508 * of the first. A warning is printed to stderr in the case that the
509 * first string does not match the third.
511 * This function exists to warn about the bizzare construction
512 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
513 * for "bytes". The problem is that in addition to accepting "by",
514 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
515 * other string beginning with "by".
517 * This function will be removed in the future through the usual
518 * deprecation process.
521 _substrcmp2(const char *str1, const char* str2, const char* str3)
524 if (strncmp(str1, str2, strlen(str2)) != 0)
527 if (strcmp(str1, str3) != 0)
528 warnx("DEPRECATED: '%s' matched '%s'",
534 * prints one port, symbolic or numeric
537 print_port(int proto, uint16_t port)
540 if (proto == IPPROTO_ETHERTYPE) {
543 if (do_resolv && (s = match_value(ether_types, port)) )
546 printf("0x%04x", port);
548 struct servent *se = NULL;
550 struct protoent *pe = getprotobynumber(proto);
552 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
555 printf("%s", se->s_name);
561 struct _s_x _port_name[] = {
562 {"dst-port", O_IP_DSTPORT},
563 {"src-port", O_IP_SRCPORT},
567 {"mac-type", O_MAC_TYPE},
568 {"tcpdatalen", O_TCPDATALEN},
573 * Print the values in a list 16-bit items of the types above.
574 * XXX todo: add support for mask.
577 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
579 uint16_t *p = cmd->ports;
583 if (cmd->o.len & F_NOT)
586 sep = match_value(_port_name, opcode);
592 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
594 print_port(proto, p[0]);
597 print_port(proto, p[1]);
604 * Like strtol, but also translates service names into port numbers
605 * for some protocols.
607 * proto == -1 disables the protocol check;
608 * proto == IPPROTO_ETHERTYPE looks up an internal table
609 * proto == <some value in /etc/protocols> matches the values there.
610 * Returns *end == s in case the parameter is not found.
613 strtoport(char *s, char **end, int base, int proto)
619 *end = s; /* default - not found */
621 return 0; /* not found */
624 return strtol(s, end, base);
627 * find separator. '\\' escapes the next char.
629 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
630 if (*s1 == '\\' && s1[1] != '\0')
633 buf = malloc(s1 - s + 1);
638 * copy into a buffer skipping backslashes
640 for (p = s, i = 0; p != s1 ; p++)
645 if (proto == IPPROTO_ETHERTYPE) {
646 i = match_token(ether_types, buf);
648 if (i != -1) { /* found */
653 struct protoent *pe = NULL;
657 pe = getprotobynumber(proto);
659 se = getservbyname(buf, pe ? pe->p_name : NULL);
663 return ntohs(se->s_port);
666 return 0; /* not found */
670 * Map between current altq queue id numbers and names.
672 static int altq_fetched = 0;
673 static TAILQ_HEAD(, pf_altq) altq_entries =
674 TAILQ_HEAD_INITIALIZER(altq_entries);
677 altq_set_enabled(int enabled)
681 pffd = open("/dev/pf", O_RDWR);
684 "altq support opening pf(4) control device");
686 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST)
687 err(EX_UNAVAILABLE, "enabling altq");
689 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT)
690 err(EX_UNAVAILABLE, "disabling altq");
698 struct pfioc_altq pfioc;
699 struct pf_altq *altq;
705 pffd = open("/dev/pf", O_RDONLY);
707 warn("altq support opening pf(4) control device");
710 bzero(&pfioc, sizeof(pfioc));
711 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) {
712 warn("altq support getting queue list");
717 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) {
718 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) {
721 warn("altq support getting queue list");
725 if (pfioc.altq.qid == 0)
727 altq = malloc(sizeof(*altq));
729 err(EX_OSERR, "malloc");
731 TAILQ_INSERT_TAIL(&altq_entries, altq, entries);
737 altq_name_to_qid(const char *name)
739 struct pf_altq *altq;
742 TAILQ_FOREACH(altq, &altq_entries, entries)
743 if (strcmp(name, altq->qname) == 0)
746 errx(EX_DATAERR, "altq has no queue named `%s'", name);
751 altq_qid_to_name(u_int32_t qid)
753 struct pf_altq *altq;
756 TAILQ_FOREACH(altq, &altq_entries, entries)
757 if (qid == altq->qid)
765 fill_altq_qid(u_int32_t *qid, const char *av)
767 *qid = altq_name_to_qid(av);
771 * Fill the body of the command with the list of port ranges.
774 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
776 uint16_t a, b, *p = cmd->ports;
781 a = strtoport(av, &s, 0, proto);
782 if (s == av) /* no parameter */
784 if (*s == '-') { /* a range */
786 b = strtoport(av, &s, 0, proto);
787 if (s == av) /* no parameter */
791 } else if (*s == ',' || *s == '\0' )
793 else /* invalid separator */
794 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n",
801 if (i+1 > F_LEN_MASK)
802 errx(EX_DATAERR, "too many ports/ranges\n");
803 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
808 static struct _s_x icmpcodes[] = {
809 { "net", ICMP_UNREACH_NET },
810 { "host", ICMP_UNREACH_HOST },
811 { "protocol", ICMP_UNREACH_PROTOCOL },
812 { "port", ICMP_UNREACH_PORT },
813 { "needfrag", ICMP_UNREACH_NEEDFRAG },
814 { "srcfail", ICMP_UNREACH_SRCFAIL },
815 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
816 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
817 { "isolated", ICMP_UNREACH_ISOLATED },
818 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
819 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
820 { "tosnet", ICMP_UNREACH_TOSNET },
821 { "toshost", ICMP_UNREACH_TOSHOST },
822 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
823 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
824 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
829 fill_reject_code(u_short *codep, char *str)
834 val = strtoul(str, &s, 0);
835 if (s == str || *s != '\0' || val >= 0x100)
836 val = match_token(icmpcodes, str);
838 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
844 print_reject_code(uint16_t code)
846 char const *s = match_value(icmpcodes, code);
849 printf("unreach %s", s);
851 printf("unreach %u", code);
855 * Returns the number of bits set (from left) in a contiguous bitmask,
856 * or -1 if the mask is not contiguous.
857 * XXX this needs a proper fix.
858 * This effectively works on masks in big-endian (network) format.
859 * when compiled on little endian architectures.
861 * First bit is bit 7 of the first byte -- note, for MAC addresses,
862 * the first bit on the wire is bit 0 of the first byte.
863 * len is the max length in bits.
866 contigmask(uint8_t *p, int len)
870 for (i=0; i<len ; i++)
871 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
873 for (n=i+1; n < len; n++)
874 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
875 return -1; /* mask not contiguous */
880 * print flags set/clear in the two bitmasks passed as parameters.
881 * There is a specialized check for f_tcpflags.
884 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
886 char const *comma = "";
888 uint8_t set = cmd->arg1 & 0xff;
889 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
891 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
896 printf(" %s ", name);
897 for (i=0; list[i].x != 0; i++) {
898 if (set & list[i].x) {
900 printf("%s%s", comma, list[i].s);
903 if (clear & list[i].x) {
905 printf("%s!%s", comma, list[i].s);
912 * Print the ip address contained in a command.
915 print_ip(ipfw_insn_ip *cmd, char const *s)
917 struct hostent *he = NULL;
918 int len = F_LEN((ipfw_insn *)cmd);
919 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
921 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
923 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
927 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
928 cmd->o.opcode == O_IP_DST_LOOKUP) {
929 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
930 if (len == F_INSN_SIZE(ipfw_insn_u32))
935 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
936 uint32_t x, *map = (uint32_t *)&(cmd->mask);
942 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
943 printf("%s/%d", inet_ntoa(cmd->addr),
944 contigmask((uint8_t *)&x, 32));
945 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
946 x &= 0xff; /* base */
948 * Print bits and ranges.
949 * Locate first bit set (i), then locate first bit unset (j).
950 * If we have 3+ consecutive bits set, then print them as a
951 * range, otherwise only print the initial bit and rescan.
953 for (i=0; i < cmd->o.arg1; i++)
954 if (map[i/32] & (1<<(i & 31))) {
955 for (j=i+1; j < cmd->o.arg1; j++)
956 if (!(map[ j/32] & (1<<(j & 31))))
958 printf("%c%d", comma, i+x);
959 if (j>i+2) { /* range has at least 3 elements */
960 printf("-%d", j-1+x);
969 * len == 2 indicates a single IP, whereas lists of 1 or more
970 * addr/mask pairs have len = (2n+1). We convert len to n so we
971 * use that to count the number of entries.
973 for (len = len / 2; len > 0; len--, a += 2) {
974 int mb = /* mask length */
975 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
976 32 : contigmask((uint8_t *)&(a[1]), 32);
977 if (mb == 32 && do_resolv)
978 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
979 if (he != NULL) /* resolved to name */
980 printf("%s", he->h_name);
981 else if (mb == 0) /* any */
983 else { /* numeric IP followed by some kind of mask */
984 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
986 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
996 * prints a MAC address/mask pair
999 print_mac(uint8_t *addr, uint8_t *mask)
1001 int l = contigmask(mask, 48);
1006 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1007 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1009 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1010 mask[0], mask[1], mask[2],
1011 mask[3], mask[4], mask[5]);
1018 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1027 type = strtoul(av, &av, 0);
1029 if (*av != ',' && *av != '\0')
1030 errx(EX_DATAERR, "invalid ICMP type");
1033 errx(EX_DATAERR, "ICMP type out of range");
1035 cmd->d[0] |= 1 << type;
1037 cmd->o.opcode = O_ICMPTYPE;
1038 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1042 print_icmptypes(ipfw_insn_u32 *cmd)
1047 printf(" icmptypes");
1048 for (i = 0; i < 32; i++) {
1049 if ( (cmd->d[0] & (1 << (i))) == 0)
1051 printf("%c%d", sep, i);
1057 * Print the ip address contained in a command.
1060 print_ip6(ipfw_insn_ip6 *cmd, char const *s)
1062 struct hostent *he = NULL;
1063 int len = F_LEN((ipfw_insn *) cmd) - 1;
1064 struct in6_addr *a = &(cmd->addr6);
1067 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1069 if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) {
1073 if (cmd->o.opcode == O_IP6) {
1079 * len == 4 indicates a single IP, whereas lists of 1 or more
1080 * addr/mask pairs have len = (2n+1). We convert len to n so we
1081 * use that to count the number of entries.
1084 for (len = len / 4; len > 0; len -= 2, a += 2) {
1085 int mb = /* mask length */
1086 (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ?
1087 128 : contigmask((uint8_t *)&(a[1]), 128);
1089 if (mb == 128 && do_resolv)
1090 he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6);
1091 if (he != NULL) /* resolved to name */
1092 printf("%s", he->h_name);
1093 else if (mb == 0) /* any */
1095 else { /* numeric IP followed by some kind of mask */
1096 if (inet_ntop(AF_INET6, a, trad, sizeof( trad ) ) == NULL)
1097 printf("Error ntop in print_ip6\n");
1098 printf("%s", trad );
1099 if (mb < 0) /* XXX not really legal... */
1101 inet_ntop(AF_INET6, &a[1], trad, sizeof(trad)));
1111 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av)
1119 type = strtoul(av, &av, 0);
1120 if (*av != ',' && *av != '\0')
1121 errx(EX_DATAERR, "invalid ICMP6 type");
1123 * XXX: shouldn't this be 0xFF? I can't see any reason why
1124 * we shouldn't be able to filter all possiable values
1125 * regardless of the ability of the rest of the kernel to do
1126 * anything useful with them.
1128 if (type > ICMP6_MAXTYPE)
1129 errx(EX_DATAERR, "ICMP6 type out of range");
1130 cmd->d[type / 32] |= ( 1 << (type % 32));
1132 cmd->o.opcode = O_ICMP6TYPE;
1133 cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6);
1138 print_icmp6types(ipfw_insn_u32 *cmd)
1143 printf(" ipv6 icmp6types");
1144 for (i = 0; i < 7; i++)
1145 for (j=0; j < 32; ++j) {
1146 if ( (cmd->d[i] & (1 << (j))) == 0)
1148 printf("%c%d", sep, (i*32 + j));
1154 print_flow6id( ipfw_insn_u32 *cmd)
1156 uint16_t i, limit = cmd->o.arg1;
1159 printf(" flow-id ");
1160 for( i=0; i < limit; ++i) {
1163 printf("%d%c", cmd->d[i], sep);
1167 /* structure and define for the extension header in ipv6 */
1168 static struct _s_x ext6hdrcodes[] = {
1169 { "frag", EXT_FRAGMENT },
1170 { "hopopt", EXT_HOPOPTS },
1171 { "route", EXT_ROUTING },
1177 /* fills command for the extension header filtering */
1179 fill_ext6hdr( ipfw_insn *cmd, char *av)
1187 av = strsep( &s, ",") ;
1188 tok = match_token(ext6hdrcodes, av);
1191 cmd->arg1 |= EXT_FRAGMENT;
1195 cmd->arg1 |= EXT_HOPOPTS;
1199 cmd->arg1 |= EXT_ROUTING;
1203 cmd->arg1 |= EXT_AH;
1207 cmd->arg1 |= EXT_ESP;
1211 errx( EX_DATAERR, "invalid option for ipv6 exten header" );
1215 if (cmd->arg1 == 0 )
1217 cmd->opcode = O_EXT_HDR;
1218 cmd->len |= F_INSN_SIZE( ipfw_insn );
1223 print_ext6hdr( ipfw_insn *cmd )
1227 printf(" extension header:");
1228 if (cmd->arg1 & EXT_FRAGMENT ) {
1229 printf("%cfragmentation", sep);
1232 if (cmd->arg1 & EXT_HOPOPTS ) {
1233 printf("%chop options", sep);
1236 if (cmd->arg1 & EXT_ROUTING ) {
1237 printf("%crouting options", sep);
1240 if (cmd->arg1 & EXT_AH ) {
1241 printf("%cauthentication header", sep);
1244 if (cmd->arg1 & EXT_ESP ) {
1245 printf("%cencapsulated security payload", sep);
1250 * show_ipfw() prints the body of an ipfw rule.
1251 * Because the standard rule has at least proto src_ip dst_ip, we use
1252 * a helper function to produce these entries if not provided explicitly.
1253 * The first argument is the list of fields we have, the second is
1254 * the list of fields we want to be printed.
1256 * Special cases if we have provided a MAC header:
1257 * + if the rule does not contain IP addresses/ports, do not print them;
1258 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1260 * Once we have 'have_options', IP header fields are printed as options.
1262 #define HAVE_PROTO 0x0001
1263 #define HAVE_SRCIP 0x0002
1264 #define HAVE_DSTIP 0x0004
1265 #define HAVE_MAC 0x0008
1266 #define HAVE_MACTYPE 0x0010
1267 #define HAVE_PROTO4 0x0040
1268 #define HAVE_PROTO6 0x0080
1269 #define HAVE_OPTIONS 0x8000
1271 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
1273 show_prerequisites(int *flags, int want, int cmd)
1277 if ( (*flags & HAVE_IP) == HAVE_IP)
1278 *flags |= HAVE_OPTIONS;
1280 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC &&
1281 cmd != O_MAC_TYPE) {
1283 * mac-type was optimized out by the compiler,
1287 *flags |= HAVE_MACTYPE | HAVE_OPTIONS;
1290 if ( !(*flags & HAVE_OPTIONS)) {
1291 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
1292 if ( (*flags & HAVE_PROTO4))
1294 else if ( (*flags & HAVE_PROTO6))
1299 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1300 printf(" from any");
1301 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1308 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1310 static int twidth = 0;
1313 char *comment = NULL; /* ptr to comment if we have one */
1314 int proto = 0; /* default */
1315 int flags = 0; /* prerequisites */
1316 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1317 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1318 int or_block = 0; /* we are in an or block */
1319 uint32_t set_disable;
1321 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1323 if (set_disable & (1 << rule->set)) { /* disabled */
1327 printf("# DISABLED ");
1329 printf("%05u ", rule->rulenum);
1331 if (pcwidth>0 || bcwidth>0)
1332 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
1333 bcwidth, align_uint64(&rule->bcnt));
1336 printf("%10u ", rule->timestamp);
1337 else if (do_time == 1) {
1339 time_t t = (time_t)0;
1342 strcpy(timestr, ctime(&t));
1343 *strchr(timestr, '\n') = '\0';
1344 twidth = strlen(timestr);
1346 if (rule->timestamp) {
1347 #if _FreeBSD_version < 500000 /* XXX check */
1348 #define _long_to_time(x) (time_t)(x)
1350 t = _long_to_time(rule->timestamp);
1352 strcpy(timestr, ctime(&t));
1353 *strchr(timestr, '\n') = '\0';
1354 printf("%s ", timestr);
1356 printf("%*s", twidth, " ");
1361 printf("set %d ", rule->set);
1364 * print the optional "match probability"
1366 if (rule->cmd_len > 0) {
1368 if (cmd->opcode == O_PROB) {
1369 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1370 double d = 1.0 * p->d[0];
1372 d = (d / 0x7fffffff);
1373 printf("prob %f ", d);
1378 * first print actions
1380 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1381 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1382 switch(cmd->opcode) {
1384 printf("check-state");
1385 flags = HAVE_IP; /* avoid printing anything else */
1401 if (cmd->arg1 == ICMP_REJECT_RST)
1403 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1406 print_reject_code(cmd->arg1);
1410 printf("skipto %u", cmd->arg1);
1414 printf("pipe %u", cmd->arg1);
1418 printf("queue %u", cmd->arg1);
1422 printf("divert %u", cmd->arg1);
1426 printf("tee %u", cmd->arg1);
1430 printf("netgraph %u", cmd->arg1);
1434 printf("ngtee %u", cmd->arg1);
1439 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1441 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1443 printf(",%d", s->sa.sin_port);
1447 case O_LOG: /* O_LOG is printed last */
1448 logptr = (ipfw_insn_log *)cmd;
1451 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1452 altqptr = (ipfw_insn_altq *)cmd;
1456 printf("** unrecognized action %d len %d ",
1457 cmd->opcode, cmd->len);
1461 if (logptr->max_log > 0)
1462 printf(" log logamount %d", logptr->max_log);
1469 qname = altq_qid_to_name(altqptr->qid);
1471 printf(" altq ?<%u>", altqptr->qid);
1473 printf(" altq %s", qname);
1477 * then print the body.
1479 for (l = rule->act_ofs, cmd = rule->cmd ;
1480 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1481 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1483 if (cmd->opcode == O_IP4) {
1484 flags |= HAVE_PROTO4;
1486 } else if (cmd->opcode == O_IP6) {
1487 flags |= HAVE_PROTO6;
1491 if (rule->_pad & 1) { /* empty rules before options */
1493 show_prerequisites(&flags, HAVE_PROTO, 0);
1494 printf(" from any to any");
1496 flags |= HAVE_IP | HAVE_OPTIONS;
1502 for (l = rule->act_ofs, cmd = rule->cmd ;
1503 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1505 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1508 if (cmd->opcode != O_NOP)
1510 printf(" // %s\n", (char *)(cmd + 1));
1514 show_prerequisites(&flags, 0, cmd->opcode);
1516 switch(cmd->opcode) {
1518 break; /* done already */
1521 break; /* no need to print anything here */
1524 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1526 if ((cmd->len & F_OR) && !or_block)
1528 if (cmd->len & F_NOT)
1532 print_mac(m->addr, m->mask);
1533 print_mac(m->addr + 6, m->mask + 6);
1538 if ((cmd->len & F_OR) && !or_block)
1540 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE,
1541 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1542 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS;
1546 case O_IP_SRC_LOOKUP:
1550 show_prerequisites(&flags, HAVE_PROTO, 0);
1551 if (!(flags & HAVE_SRCIP))
1553 if ((cmd->len & F_OR) && !or_block)
1555 print_ip((ipfw_insn_ip *)cmd,
1556 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1557 flags |= HAVE_SRCIP;
1561 case O_IP_DST_LOOKUP:
1565 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1566 if (!(flags & HAVE_DSTIP))
1568 if ((cmd->len & F_OR) && !or_block)
1570 print_ip((ipfw_insn_ip *)cmd,
1571 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1572 flags |= HAVE_DSTIP;
1576 case O_IP6_SRC_MASK:
1578 show_prerequisites(&flags, HAVE_PROTO, 0);
1579 if (!(flags & HAVE_SRCIP))
1581 if ((cmd->len & F_OR) && !or_block)
1583 print_ip6((ipfw_insn_ip6 *)cmd,
1584 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1585 flags |= HAVE_SRCIP | HAVE_PROTO;
1589 case O_IP6_DST_MASK:
1591 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1592 if (!(flags & HAVE_DSTIP))
1594 if ((cmd->len & F_OR) && !or_block)
1596 print_ip6((ipfw_insn_ip6 *)cmd,
1597 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1598 flags |= HAVE_DSTIP;
1602 print_flow6id( (ipfw_insn_u32 *) cmd );
1603 flags |= HAVE_OPTIONS;
1607 show_prerequisites(&flags, HAVE_IP, 0);
1609 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1610 if ((cmd->len & F_OR) && !or_block)
1612 print_newports((ipfw_insn_u16 *)cmd, proto,
1613 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1617 struct protoent *pe = NULL;
1619 if ((cmd->len & F_OR) && !or_block)
1621 if (cmd->len & F_NOT)
1624 pe = getprotobynumber(cmd->arg1);
1625 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1626 !(flags & HAVE_PROTO))
1627 show_prerequisites(&flags,
1628 HAVE_IP | HAVE_OPTIONS, 0);
1629 if (flags & HAVE_OPTIONS)
1632 printf(" %s", pe->p_name);
1634 printf(" %u", cmd->arg1);
1636 flags |= HAVE_PROTO;
1639 default: /*options ... */
1640 if (!(cmd->len & (F_OR|F_NOT)))
1641 if (((cmd->opcode == O_IP6) &&
1642 (flags & HAVE_PROTO6)) ||
1643 ((cmd->opcode == O_IP4) &&
1644 (flags & HAVE_PROTO4)))
1646 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1647 if ((cmd->len & F_OR) && !or_block)
1649 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1651 switch(cmd->opcode) {
1657 printf(cmd->len & F_NOT ? " out" : " in");
1661 switch (cmd->arg1) {
1663 printf(" diverted");
1666 printf(" diverted-loopback");
1669 printf(" diverted-output");
1672 printf(" diverted-?<%u>", cmd->arg1);
1685 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1687 if (cmd->opcode == O_XMIT)
1689 else if (cmd->opcode == O_RECV)
1691 else /* if (cmd->opcode == O_VIA) */
1693 if (cmdif->name[0] == '\0')
1695 inet_ntoa(cmdif->p.ip));
1697 printf(" %s %s", s, cmdif->name);
1702 if (F_LEN(cmd) == 1)
1703 printf(" ipid %u", cmd->arg1 );
1705 print_newports((ipfw_insn_u16 *)cmd, 0,
1710 if (F_LEN(cmd) == 1)
1711 printf(" ipttl %u", cmd->arg1 );
1713 print_newports((ipfw_insn_u16 *)cmd, 0,
1718 printf(" ipver %u", cmd->arg1 );
1721 case O_IPPRECEDENCE:
1722 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1726 if (F_LEN(cmd) == 1)
1727 printf(" iplen %u", cmd->arg1 );
1729 print_newports((ipfw_insn_u16 *)cmd, 0,
1734 print_flags("ipoptions", cmd, f_ipopts);
1738 print_flags("iptos", cmd, f_iptos);
1742 print_icmptypes((ipfw_insn_u32 *)cmd);
1746 printf(" established");
1750 if (F_LEN(cmd) == 1)
1751 printf(" tcpdatalen %u", cmd->arg1 );
1753 print_newports((ipfw_insn_u16 *)cmd, 0,
1758 print_flags("tcpflags", cmd, f_tcpflags);
1762 print_flags("tcpoptions", cmd, f_tcpopts);
1766 printf(" tcpwin %d", ntohs(cmd->arg1));
1770 printf(" tcpack %d", ntohl(cmd32->d[0]));
1774 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1779 struct passwd *pwd = getpwuid(cmd32->d[0]);
1782 printf(" uid %s", pwd->pw_name);
1784 printf(" uid %u", cmd32->d[0]);
1790 struct group *grp = getgrgid(cmd32->d[0]);
1793 printf(" gid %s", grp->gr_name);
1795 printf(" gid %u", cmd32->d[0]);
1800 printf(" jail %d", cmd32->d[0]);
1804 printf(" verrevpath");
1808 printf(" versrcreach");
1812 printf(" antispoof");
1820 comment = (char *)(cmd + 1);
1824 printf(" keep-state");
1829 struct _s_x *p = limit_masks;
1830 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1831 uint8_t x = c->limit_mask;
1832 char const *comma = " ";
1835 for (; p->x != 0 ; p++)
1836 if ((x & p->x) == p->x) {
1838 printf("%s%s", comma, p->s);
1841 printf(" %d", c->conn_limit);
1854 print_icmp6types((ipfw_insn_u32 *)cmd);
1858 print_ext6hdr( (ipfw_insn *) cmd );
1862 printf(" [opcode %d len %d]",
1863 cmd->opcode, cmd->len);
1866 if (cmd->len & F_OR) {
1869 } else if (or_block) {
1874 show_prerequisites(&flags, HAVE_IP, 0);
1876 printf(" // %s", comment);
1881 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1883 struct protoent *pe;
1888 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1891 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1892 printf("%05d", rulenum);
1893 if (pcwidth>0 || bcwidth>0)
1894 printf(" %*llu %*llu (%ds)", pcwidth,
1895 align_uint64(&d->pcnt), bcwidth,
1896 align_uint64(&d->bcnt), d->expire);
1897 switch (d->dyn_type) {
1898 case O_LIMIT_PARENT:
1899 printf(" PARENT %d", d->count);
1904 case O_KEEP_STATE: /* bidir, no mask */
1909 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1910 printf(" %s", pe->p_name);
1912 printf(" proto %u", d->id.proto);
1914 a.s_addr = htonl(d->id.src_ip);
1915 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1917 a.s_addr = htonl(d->id.dst_ip);
1918 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1923 sort_q(const void *pa, const void *pb)
1925 int rev = (do_sort < 0);
1926 int field = rev ? -do_sort : do_sort;
1928 const struct dn_flow_queue *a = pa;
1929 const struct dn_flow_queue *b = pb;
1933 res = a->len - b->len;
1936 res = a->len_bytes - b->len_bytes;
1939 case 3: /* tot pkts */
1940 res = a->tot_pkts - b->tot_pkts;
1943 case 4: /* tot bytes */
1944 res = a->tot_bytes - b->tot_bytes;
1951 return (int)(rev ? res : -res);
1955 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
1958 int index_printed, indexes = 0;
1960 struct protoent *pe;
1962 if (fs->rq_elements == 0)
1966 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
1968 /* Print IPv4 flows */
1970 for (l = 0; l < fs->rq_elements; l++) {
1973 /* XXX: Should check for IPv4 flows */
1974 if (IS_IP6_FLOW_ID(&(q[l].id)))
1977 if (!index_printed) {
1979 if (indexes > 0) /* currently a no-op */
1983 "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1984 fs->flow_mask.proto,
1985 fs->flow_mask.src_ip, fs->flow_mask.src_port,
1986 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
1988 printf("BKT Prot ___Source IP/port____ "
1989 "____Dest. IP/port____ "
1990 "Tot_pkt/bytes Pkt/Byte Drp\n");
1993 printf("%3d ", q[l].hash_slot);
1994 pe = getprotobynumber(q[l].id.proto);
1996 printf("%-4s ", pe->p_name);
1998 printf("%4u ", q[l].id.proto);
1999 ina.s_addr = htonl(q[l].id.src_ip);
2000 printf("%15s/%-5d ",
2001 inet_ntoa(ina), q[l].id.src_port);
2002 ina.s_addr = htonl(q[l].id.dst_ip);
2003 printf("%15s/%-5d ",
2004 inet_ntoa(ina), q[l].id.dst_port);
2005 printf("%4qu %8qu %2u %4u %3u\n",
2006 q[l].tot_pkts, q[l].tot_bytes,
2007 q[l].len, q[l].len_bytes, q[l].drops);
2009 printf(" S %20qd F %20qd\n",
2013 /* Print IPv6 flows */
2015 for (l = 0; l < fs->rq_elements; l++) {
2016 if (!IS_IP6_FLOW_ID(&(q[l].id)))
2019 if (!index_printed) {
2024 printf("\n mask: proto: 0x%02x, flow_id: 0x%08x, ",
2025 fs->flow_mask.proto, fs->flow_mask.flow_id6);
2026 inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
2027 buff, sizeof(buff));
2028 printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
2029 inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
2030 buff, sizeof(buff) );
2031 printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
2033 printf("BKT ___Prot___ _flow-id_ "
2034 "______________Source IPv6/port_______________ "
2035 "_______________Dest. IPv6/port_______________ "
2036 "Tot_pkt/bytes Pkt/Byte Drp\n");
2038 printf("%3d ", q[l].hash_slot);
2039 pe = getprotobynumber(q[l].id.proto);
2041 printf("%9s ", pe->p_name);
2043 printf("%9u ", q[l].id.proto);
2044 printf("%7d %39s/%-5d ", q[l].id.flow_id6,
2045 inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
2047 printf(" %39s/%-5d ",
2048 inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
2050 printf(" %4qu %8qu %2u %4u %3u\n",
2051 q[l].tot_pkts, q[l].tot_bytes,
2052 q[l].len, q[l].len_bytes, q[l].drops);
2054 printf(" S %20qd F %20qd\n", q[l].S, q[l].F);
2059 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
2064 char red[90]; /* Display RED parameters */
2067 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
2069 sprintf(qs, "%d KB", l / 1024);
2071 sprintf(qs, "%d B", l);
2073 sprintf(qs, "%3d sl.", l);
2075 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
2078 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
2080 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
2081 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
2082 1.0 * fs->w_q / (double)(1 << SCALE_RED),
2083 SCALE_VAL(fs->min_th),
2084 SCALE_VAL(fs->max_th),
2085 1.0 * fs->max_p / (double)(1 << SCALE_RED));
2087 sprintf(red, "droptail");
2089 printf("%s %s%s %d queues (%d buckets) %s\n",
2090 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
2094 list_pipes(void *data, uint nbytes, int ac, char *av[])
2098 struct dn_pipe *p = (struct dn_pipe *) data;
2099 struct dn_flow_set *fs;
2100 struct dn_flow_queue *q;
2104 rulenum = strtoul(*av++, NULL, 10);
2107 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
2108 double b = p->bandwidth;
2112 if (p->next != (struct dn_pipe *)DN_IS_PIPE)
2113 break; /* done with pipes, now queues */
2116 * compute length, as pipe have variable size
2118 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
2119 next = (char *)p + l;
2122 if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2)
2126 * Print rate (or clocking interface)
2128 if (p->if_name[0] != '\0')
2129 sprintf(buf, "%s", p->if_name);
2131 sprintf(buf, "unlimited");
2132 else if (b >= 1000000)
2133 sprintf(buf, "%7.3f Mbit/s", b/1000000);
2135 sprintf(buf, "%7.3f Kbit/s", b/1000);
2137 sprintf(buf, "%7.3f bit/s ", b);
2139 sprintf(prefix, "%05d: %s %4d ms ",
2140 p->pipe_nr, buf, p->delay);
2141 print_flowset_parms(&(p->fs), prefix);
2143 printf(" V %20qd\n", p->V >> MY_M);
2145 q = (struct dn_flow_queue *)(p+1);
2146 list_queues(&(p->fs), q);
2148 for (fs = next; nbytes >= sizeof *fs; fs = next) {
2151 if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE)
2153 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
2154 next = (char *)fs + l;
2157 if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) ||
2158 (rulenum != fs->parent_nr && do_pipe == 1))) {
2162 q = (struct dn_flow_queue *)(fs+1);
2163 sprintf(prefix, "q%05d: weight %d pipe %d ",
2164 fs->fs_nr, fs->weight, fs->parent_nr);
2165 print_flowset_parms(fs, prefix);
2171 * This one handles all set-related commands
2172 * ipfw set { show | enable | disable }
2174 * ipfw set move X to Y
2175 * ipfw set move rule X to Y
2178 sets_handler(int ac, char *av[])
2180 uint32_t set_disable, masks[2];
2183 uint8_t cmd, new_set;
2189 errx(EX_USAGE, "set needs command");
2190 if (_substrcmp(*av, "show") == 0) {
2194 nbytes = sizeof(struct ip_fw);
2195 if ((data = calloc(1, nbytes)) == NULL)
2196 err(EX_OSERR, "calloc");
2197 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2198 err(EX_OSERR, "getsockopt(IP_FW_GET)");
2199 bcopy(&((struct ip_fw *)data)->next_rule,
2200 &set_disable, sizeof(set_disable));
2202 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2203 if ((set_disable & (1<<i))) {
2204 printf("%s %d", msg, i);
2207 msg = (set_disable) ? " enable" : "enable";
2208 for (i = 0; i < RESVD_SET; i++)
2209 if (!(set_disable & (1<<i))) {
2210 printf("%s %d", msg, i);
2214 } else if (_substrcmp(*av, "swap") == 0) {
2217 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2218 rulenum = atoi(av[0]);
2219 new_set = atoi(av[1]);
2220 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2221 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2222 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2223 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2224 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2225 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2226 } else if (_substrcmp(*av, "move") == 0) {
2228 if (ac && _substrcmp(*av, "rule") == 0) {
2233 if (ac != 3 || _substrcmp(av[1], "to") != 0)
2234 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2235 rulenum = atoi(av[0]);
2236 new_set = atoi(av[2]);
2237 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2238 (cmd == 2 && rulenum == 65535) )
2239 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2240 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2241 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2242 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2243 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2244 } else if (_substrcmp(*av, "disable") == 0 ||
2245 _substrcmp(*av, "enable") == 0 ) {
2246 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2249 masks[0] = masks[1] = 0;
2252 if (isdigit(**av)) {
2254 if (i < 0 || i > RESVD_SET)
2256 "invalid set number %d\n", i);
2257 masks[which] |= (1<<i);
2258 } else if (_substrcmp(*av, "disable") == 0)
2260 else if (_substrcmp(*av, "enable") == 0)
2264 "invalid set command %s\n", *av);
2267 if ( (masks[0] & masks[1]) != 0 )
2269 "cannot enable and disable the same set\n");
2271 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2273 warn("set enable/disable: setsockopt(IP_FW_DEL)");
2275 errx(EX_USAGE, "invalid set command %s\n", *av);
2279 sysctl_handler(int ac, char *av[], int which)
2285 warnx("missing keyword to enable/disable\n");
2286 } else if (_substrcmp(*av, "firewall") == 0) {
2287 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2288 &which, sizeof(which));
2289 } else if (_substrcmp(*av, "one_pass") == 0) {
2290 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2291 &which, sizeof(which));
2292 } else if (_substrcmp(*av, "debug") == 0) {
2293 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2294 &which, sizeof(which));
2295 } else if (_substrcmp(*av, "verbose") == 0) {
2296 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2297 &which, sizeof(which));
2298 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2299 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2300 &which, sizeof(which));
2301 } else if (_substrcmp(*av, "altq") == 0) {
2302 altq_set_enabled(which);
2304 warnx("unrecognize enable/disable keyword: %s\n", *av);
2309 list(int ac, char *av[], int show_counters)
2312 ipfw_dyn_rule *dynrules, *d;
2314 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
2317 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2318 int exitval = EX_OK;
2325 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2326 int nalloc = 1024; /* start somewhere... */
2331 fprintf(stderr, "Testing only, list disabled\n");
2338 /* get rules or pipes from kernel, resizing array as necessary */
2341 while (nbytes >= nalloc) {
2342 nalloc = nalloc * 2 + 200;
2344 if ((data = realloc(data, nbytes)) == NULL)
2345 err(EX_OSERR, "realloc");
2346 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2347 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2348 do_pipe ? "DUMMYNET" : "FW");
2352 list_pipes(data, nbytes, ac, av);
2357 * Count static rules. They have variable size so we
2358 * need to scan the list to count them.
2360 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2361 r->rulenum < 65535 && (char *)r < lim;
2362 ++nstat, r = NEXT(r) )
2366 * Count dynamic rules. This is easier as they have
2370 dynrules = (ipfw_dyn_rule *)r ;
2371 n = (char *)r - (char *)data;
2372 ndyn = (nbytes - n) / sizeof *dynrules;
2374 /* if showing stats, figure out column widths ahead of time */
2375 bcwidth = pcwidth = 0;
2376 if (show_counters) {
2377 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2378 /* packet counter */
2379 width = snprintf(NULL, 0, "%llu",
2380 align_uint64(&r->pcnt));
2381 if (width > pcwidth)
2385 width = snprintf(NULL, 0, "%llu",
2386 align_uint64(&r->bcnt));
2387 if (width > bcwidth)
2391 if (do_dynamic && ndyn) {
2392 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2393 width = snprintf(NULL, 0, "%llu",
2394 align_uint64(&d->pcnt));
2395 if (width > pcwidth)
2398 width = snprintf(NULL, 0, "%llu",
2399 align_uint64(&d->bcnt));
2400 if (width > bcwidth)
2404 /* if no rule numbers were specified, list all rules */
2406 for (n = 0, r = data; n < nstat; n++, r = NEXT(r) )
2407 show_ipfw(r, pcwidth, bcwidth);
2409 if (do_dynamic && ndyn) {
2410 printf("## Dynamic rules (%d):\n", ndyn);
2411 for (n = 0, d = dynrules; n < ndyn; n++, d++)
2412 show_dyn_ipfw(d, pcwidth, bcwidth);
2417 /* display specific rules requested on command line */
2419 for (lac = ac, lav = av; lac != 0; lac--) {
2420 /* convert command line rule # */
2421 last = rnum = strtoul(*lav++, &endptr, 10);
2423 last = strtoul(endptr+1, &endptr, 10);
2426 warnx("invalid rule number: %s", *(lav - 1));
2429 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2430 if (r->rulenum > last)
2432 if (r->rulenum >= rnum && r->rulenum <= last) {
2433 show_ipfw(r, pcwidth, bcwidth);
2438 /* give precedence to other error(s) */
2439 if (exitval == EX_OK)
2440 exitval = EX_UNAVAILABLE;
2441 warnx("rule %lu does not exist", rnum);
2445 if (do_dynamic && ndyn) {
2446 printf("## Dynamic rules:\n");
2447 for (lac = ac, lav = av; lac != 0; lac--) {
2448 last = rnum = strtoul(*lav++, &endptr, 10);
2450 last = strtoul(endptr+1, &endptr, 10);
2452 /* already warned */
2454 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2457 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2460 if (r->rulenum >= rnum && r->rulenum <= last)
2461 show_dyn_ipfw(d, pcwidth, bcwidth);
2471 if (exitval != EX_OK)
2479 fprintf(stderr, "usage: ipfw [options]\n"
2480 "do \"ipfw -h\" or see ipfw manpage for details\n"
2489 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n"
2490 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n"
2491 "add [num] [set N] [prob x] RULE-BODY\n"
2492 "{pipe|queue} N config PIPE-BODY\n"
2493 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
2494 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
2495 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
2497 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
2498 "ACTION: check-state | allow | count | deny | unreach CODE | skipto N |\n"
2499 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
2500 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
2501 "ADDR: [ MAC dst src ether_type ] \n"
2502 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
2503 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
2504 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
2505 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
2506 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
2507 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
2508 "OPTION_LIST: OPTION [OPTION_LIST]\n"
2509 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
2510 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
2511 " {dst-port|src-port} LIST |\n"
2512 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
2513 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
2514 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
2515 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] |\n"
2516 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
2517 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
2518 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
2525 lookup_host (char *host, struct in_addr *ipaddr)
2529 if (!inet_aton(host, ipaddr)) {
2530 if ((he = gethostbyname(host)) == NULL)
2532 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2538 * fills the addr and mask fields in the instruction as appropriate from av.
2539 * Update length as appropriate.
2540 * The following formats are allowed:
2541 * me returns O_IP_*_ME
2542 * 1.2.3.4 single IP address
2543 * 1.2.3.4:5.6.7.8 address:mask
2544 * 1.2.3.4/24 address/mask
2545 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2546 * We can have multiple comma-separated address/mask entries.
2549 fill_ip(ipfw_insn_ip *cmd, char *av)
2552 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2554 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2556 if (_substrcmp(av, "any") == 0)
2559 if (_substrcmp(av, "me") == 0) {
2560 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2564 if (strncmp(av, "table(", 6) == 0) {
2565 char *p = strchr(av + 6, ',');
2569 cmd->o.opcode = O_IP_DST_LOOKUP;
2570 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2572 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2573 d[0] = strtoul(p, NULL, 0);
2575 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2581 * After the address we can have '/' or ':' indicating a mask,
2582 * ',' indicating another address follows, '{' indicating a
2583 * set of addresses of unspecified size.
2585 char *p = strpbrk(av, "/:,{");
2595 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2596 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2599 if (!inet_aton(p, (struct in_addr *)&d[1]))
2600 errx(EX_DATAERR, "bad netmask ``%s''", p);
2605 d[1] = htonl(0); /* mask */
2606 else if (masklen > 32)
2607 errx(EX_DATAERR, "bad width ``%s''", p);
2609 d[1] = htonl(~0 << (32 - masklen));
2611 case '{': /* no mask, assume /24 and put back the '{' */
2612 d[1] = htonl(~0 << (32 - 24));
2616 case ',': /* single address plus continuation */
2619 case 0: /* initialization value */
2621 d[1] = htonl(~0); /* force /32 */
2624 d[0] &= d[1]; /* mask base address with mask */
2625 /* find next separator */
2627 p = strpbrk(p, ",{");
2628 if (p && *p == '{') {
2630 * We have a set of addresses. They are stored as follows:
2631 * arg1 is the set size (powers of 2, 2..256)
2632 * addr is the base address IN HOST FORMAT
2633 * mask.. is an array of arg1 bits (rounded up to
2634 * the next multiple of 32) with bits set
2635 * for each host in the map.
2637 uint32_t *map = (uint32_t *)&cmd->mask;
2639 int i = contigmask((uint8_t *)&(d[1]), 32);
2642 errx(EX_DATAERR, "address set cannot be in a list");
2643 if (i < 24 || i > 31)
2644 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2645 cmd->o.arg1 = 1<<(32-i); /* map length */
2646 d[0] = ntohl(d[0]); /* base addr in host format */
2647 cmd->o.opcode = O_IP_DST_SET; /* default */
2648 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2649 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2650 map[i] = 0; /* clear map */
2654 high = low + cmd->o.arg1 - 1;
2656 * Here, i stores the previous value when we specify a range
2657 * of addresses within a mask, e.g. 45-63. i = -1 means we
2658 * have no previous value.
2660 i = -1; /* previous value in a range */
2661 while (isdigit(*av)) {
2663 int a = strtol(av, &s, 0);
2665 if (s == av) { /* no parameter */
2667 errx(EX_DATAERR, "set not closed\n");
2669 errx(EX_DATAERR, "incomplete range %d-", i);
2672 if (a < low || a > high)
2673 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2676 if (i == -1) /* no previous in range */
2678 else { /* check that range is valid */
2680 errx(EX_DATAERR, "invalid range %d-%d",
2683 errx(EX_DATAERR, "double '-' in range");
2686 map[i/32] |= 1<<(i & 31);
2697 if (av) /* then *av must be a ',' */
2700 /* Check this entry */
2701 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2703 * 'any' turns the entire list into a NOP.
2704 * 'not any' never matches, so it is removed from the
2705 * list unless it is the only item, in which case we
2708 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2709 if (av == NULL && len == 0) /* only this entry */
2710 errx(EX_DATAERR, "not any never matches");
2712 /* else do nothing and skip this entry */
2715 /* A single IP can be stored in an optimized format */
2716 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) {
2717 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2720 len += 2; /* two words... */
2723 cmd->o.len |= len+1;
2727 /* Try to find ipv6 address by hostname */
2729 lookup_host6 (char *host, struct in6_addr *ip6addr)
2733 if (!inet_pton(AF_INET6, host, ip6addr)) {
2734 if ((he = gethostbyname2(host, AF_INET6)) == NULL)
2736 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr));
2742 /* n2mask sets n bits of the mask */
2744 n2mask(struct in6_addr *mask, int n)
2746 static int minimask[9] =
2747 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2750 memset(mask, 0, sizeof(struct in6_addr));
2751 p = (u_char *) mask;
2752 for (; n > 0; p++, n -= 8) {
2763 * fill the addr and mask fields in the instruction as appropriate from av.
2764 * Update length as appropriate.
2765 * The following formats are allowed:
2766 * any matches any IP6. Actually returns an empty instruction.
2767 * me returns O_IP6_*_ME
2769 * 03f1::234:123:0342 single IP6 addres
2770 * 03f1::234:123:0342/24 address/mask
2771 * 03f1::234:123:0342/24,03f1::234:123:0343/ List of address
2773 * Set of address (as in ipv6) not supported because ipv6 address
2774 * are typically random past the initial prefix.
2775 * Return 1 on success, 0 on failure.
2778 fill_ip6(ipfw_insn_ip6 *cmd, char *av)
2781 struct in6_addr *d = &(cmd->addr6);
2783 * Needed for multiple address.
2784 * Note d[1] points to struct in6_add r mask6 of cmd
2787 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2789 if (strcmp(av, "any") == 0)
2793 if (strcmp(av, "me") == 0) { /* Set the data for "me" opt*/
2794 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2798 if (strcmp(av, "me6") == 0) { /* Set the data for "me" opt*/
2799 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2806 * After the address we can have '/' indicating a mask,
2807 * or ',' indicating another address follows.
2814 if ((p = strpbrk(av, "/,")) ) {
2815 md = *p; /* save the separator */
2816 *p = '\0'; /* terminate address string */
2817 p++; /* and skip past it */
2819 /* now p points to NULL, mask or next entry */
2821 /* lookup stores address in *d as a side effect */
2822 if (lookup_host6(av, d) != 0) {
2823 /* XXX: failed. Free memory and go */
2824 errx(EX_DATAERR, "bad address \"%s\"", av);
2826 /* next, look at the mask, if any */
2827 masklen = (md == '/') ? atoi(p) : 128;
2828 if (masklen > 128 || masklen < 0)
2829 errx(EX_DATAERR, "bad width \"%s\''", p);
2831 n2mask(&d[1], masklen);
2833 APPLY_MASK(d, &d[1]) /* mask base address with mask */
2835 /* find next separator */
2837 if (md == '/') { /* find separator past the mask */
2838 p = strpbrk(p, ",");
2844 /* Check this entry */
2847 * 'any' turns the entire list into a NOP.
2848 * 'not any' never matches, so it is removed from the
2849 * list unless it is the only item, in which case we
2852 if (cmd->o.len & F_NOT && av == NULL && len == 0)
2853 errx(EX_DATAERR, "not any never matches");
2858 * A single IP can be stored alone
2860 if (masklen == 128 && av == NULL && len == 0) {
2861 len = F_INSN_SIZE(struct in6_addr);
2865 /* Update length and pointer to arguments */
2866 len += F_INSN_SIZE(struct in6_addr)*2;
2871 * Total length of the command, remember that 1 is the size of
2874 cmd->o.len |= len+1;
2880 * fills command for ipv6 flow-id filtering
2881 * note that the 20 bit flow number is stored in a array of u_int32_t
2882 * it's supported lists of flow-id, so in the o.arg1 we store how many
2883 * additional flow-id we want to filter, the basic is 1
2886 fill_flow6( ipfw_insn_u32 *cmd, char *av )
2888 u_int32_t type; /* Current flow number */
2889 u_int16_t nflow = 0; /* Current flow index */
2891 cmd->d[0] = 0; /* Initializing the base number*/
2894 av = strsep( &s, ",") ;
2895 type = strtoul(av, &av, 0);
2896 if (*av != ',' && *av != '\0')
2897 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
2899 errx(EX_DATAERR, "flow number out of range %s", av);
2900 cmd->d[nflow] |= type;
2904 cmd->o.opcode = O_FLOW6ID;
2905 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow;
2906 cmd->o.arg1 = nflow;
2909 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
2914 add_srcip6(ipfw_insn *cmd, char *av)
2917 fill_ip6((ipfw_insn_ip6 *)cmd, av);
2918 if (F_LEN(cmd) == 0) /* any */
2920 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
2921 cmd->opcode = O_IP6_SRC_ME;
2922 } else if (F_LEN(cmd) ==
2923 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
2924 /* single IP, no mask*/
2925 cmd->opcode = O_IP6_SRC;
2926 } else { /* addr/mask opt */
2927 cmd->opcode = O_IP6_SRC_MASK;
2933 add_dstip6(ipfw_insn *cmd, char *av)
2936 fill_ip6((ipfw_insn_ip6 *)cmd, av);
2937 if (F_LEN(cmd) == 0) /* any */
2939 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
2940 cmd->opcode = O_IP6_DST_ME;
2941 } else if (F_LEN(cmd) ==
2942 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
2943 /* single IP, no mask*/
2944 cmd->opcode = O_IP6_DST;
2945 } else { /* addr/mask opt */
2946 cmd->opcode = O_IP6_DST_MASK;
2953 * helper function to process a set of flags and set bits in the
2954 * appropriate masks.
2957 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2958 struct _s_x *flags, char *p)
2960 uint8_t set=0, clear=0;
2963 char *q; /* points to the separator */
2965 uint8_t *which; /* mask we are working on */
2975 val = match_token(flags, p);
2977 errx(EX_DATAERR, "invalid flag %s", p);
2978 *which |= (uint8_t)val;
2981 cmd->opcode = opcode;
2982 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2983 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2988 delete(int ac, char *av[])
2993 int exitval = EX_OK;
2996 memset(&p, 0, sizeof p);
2999 NEED1("missing rule specification");
3000 if (ac > 0 && _substrcmp(*av, "set") == 0) {
3001 do_set = 1; /* delete set */
3006 while (ac && isdigit(**av)) {
3007 i = atoi(*av); av++; ac--;
3013 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
3016 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
3017 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
3020 rulenum = (i & 0xffff) | (do_set << 24);
3021 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
3023 exitval = EX_UNAVAILABLE;
3024 warn("rule %u: setsockopt(IP_FW_DEL)",
3029 if (exitval != EX_OK)
3035 * fill the interface structure. We do not check the name as we can
3036 * create interfaces dynamically, so checking them at insert time
3037 * makes relatively little sense.
3038 * Interface names containing '*', '?', or '[' are assumed to be shell
3039 * patterns which match interfaces.
3042 fill_iface(ipfw_insn_if *cmd, char *arg)
3044 cmd->name[0] = '\0';
3045 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3047 /* Parse the interface or address */
3048 if (strcmp(arg, "any") == 0)
3049 cmd->o.len = 0; /* effectively ignore this command */
3050 else if (!isdigit(*arg)) {
3051 strlcpy(cmd->name, arg, sizeof(cmd->name));
3052 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3053 } else if (!inet_aton(arg, &cmd->p.ip))
3054 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3058 config_pipe(int ac, char **av)
3065 memset(&p, 0, sizeof p);
3069 if (ac && isdigit(**av)) {
3070 i = atoi(*av); av++; ac--;
3078 int tok = match_token(dummynet_params, *av);
3083 p.fs.flags_fs |= DN_NOERROR;
3087 NEED1("plr needs argument 0..1\n");
3088 d = strtod(av[0], NULL);
3093 p.fs.plr = (int)(d*0x7fffffff);
3098 NEED1("queue needs queue size\n");
3100 p.fs.qsize = strtoul(av[0], &end, 0);
3101 if (*end == 'K' || *end == 'k') {
3102 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
3104 } else if (*end == 'B' ||
3105 _substrcmp2(end, "by", "bytes") == 0) {
3106 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
3112 NEED1("buckets needs argument\n");
3113 p.fs.rq_size = strtoul(av[0], NULL, 0);
3118 NEED1("mask needs mask specifier\n");
3120 * per-flow queue, mask is dst_ip, dst_port,
3121 * src_ip, src_port, proto measured in bits
3125 bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
3129 uint32_t *p32 = NULL;
3130 uint16_t *p16 = NULL;
3131 uint32_t *p20 = NULL;
3132 struct in6_addr *pa6 = NULL;
3135 tok = match_token(dummynet_params, *av);
3140 * special case, all bits significant
3142 p.fs.flow_mask.dst_ip = ~0;
3143 p.fs.flow_mask.src_ip = ~0;
3144 p.fs.flow_mask.dst_port = ~0;
3145 p.fs.flow_mask.src_port = ~0;
3146 p.fs.flow_mask.proto = ~0;
3147 n2mask(&(p.fs.flow_mask.dst_ip6), 128);
3148 n2mask(&(p.fs.flow_mask.src_ip6), 128);
3149 p.fs.flow_mask.flow_id6 = ~0;
3150 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
3154 p32 = &p.fs.flow_mask.dst_ip;
3158 p32 = &p.fs.flow_mask.src_ip;
3162 pa6 = &(p.fs.flow_mask.dst_ip6);
3166 pa6 = &(p.fs.flow_mask.src_ip6);
3170 p20 = &p.fs.flow_mask.flow_id6;
3174 p16 = &p.fs.flow_mask.dst_port;
3178 p16 = &p.fs.flow_mask.src_port;
3185 ac++; av--; /* backtrack */
3189 errx(EX_USAGE, "mask: value missing");
3190 if (*av[0] == '/') {
3191 a = strtoul(av[0]+1, &end, 0);
3193 a = (a == 32) ? ~0 : (1 << a) - 1;
3195 a = strtoul(av[0], &end, 0);
3198 else if (p16 != NULL) {
3201 "port mask must be 16 bit");
3203 } else if (p20 != NULL) {
3206 "flow_id mask must be 20 bit");
3208 } else if (pa6 != NULL) {
3209 if (a < 0 || a > 128)
3211 "in6addr invalid mask len");
3217 "proto mask must be 8 bit");
3218 p.fs.flow_mask.proto = (uint8_t)a;
3221 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
3223 } /* end while, config masks */
3229 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
3230 p.fs.flags_fs |= DN_IS_RED;
3231 if (tok == TOK_GRED)
3232 p.fs.flags_fs |= DN_IS_GENTLE_RED;
3234 * the format for parameters is w_q/min_th/max_th/max_p
3236 if ((end = strsep(&av[0], "/"))) {
3237 double w_q = strtod(end, NULL);
3238 if (w_q > 1 || w_q <= 0)
3239 errx(EX_DATAERR, "0 < w_q <= 1");
3240 p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
3242 if ((end = strsep(&av[0], "/"))) {
3243 p.fs.min_th = strtoul(end, &end, 0);
3244 if (*end == 'K' || *end == 'k')
3245 p.fs.min_th *= 1024;
3247 if ((end = strsep(&av[0], "/"))) {
3248 p.fs.max_th = strtoul(end, &end, 0);
3249 if (*end == 'K' || *end == 'k')
3250 p.fs.max_th *= 1024;
3252 if ((end = strsep(&av[0], "/"))) {
3253 double max_p = strtod(end, NULL);
3254 if (max_p > 1 || max_p <= 0)
3255 errx(EX_DATAERR, "0 < max_p <= 1");
3256 p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
3262 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
3266 NEED1("bw needs bandwidth or interface\n");
3268 errx(EX_DATAERR, "bandwidth only valid for pipes");
3270 * set clocking interface or bandwidth value
3272 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
3273 int l = sizeof(p.if_name)-1;
3274 /* interface name */
3275 strncpy(p.if_name, av[0], l);
3276 p.if_name[l] = '\0';
3279 p.if_name[0] = '\0';
3280 p.bandwidth = strtoul(av[0], &end, 0);
3281 if (*end == 'K' || *end == 'k') {
3283 p.bandwidth *= 1000;
3284 } else if (*end == 'M') {
3286 p.bandwidth *= 1000000;
3289 _substrcmp2(end, "by", "bytes") == 0)
3291 if (p.bandwidth < 0)
3292 errx(EX_DATAERR, "bandwidth too large");
3299 errx(EX_DATAERR, "delay only valid for pipes");
3300 NEED1("delay needs argument 0..10000ms\n");
3301 p.delay = strtoul(av[0], NULL, 0);
3307 errx(EX_DATAERR,"weight only valid for queues");
3308 NEED1("weight needs argument 0..100\n");
3309 p.fs.weight = strtoul(av[0], &end, 0);
3315 errx(EX_DATAERR,"pipe only valid for queues");
3316 NEED1("pipe needs pipe_number\n");
3317 p.fs.parent_nr = strtoul(av[0], &end, 0);
3322 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
3327 errx(EX_DATAERR, "pipe_nr must be > 0");
3328 if (p.delay > 10000)
3329 errx(EX_DATAERR, "delay must be < 10000");
3330 } else { /* do_pipe == 2, queue */
3331 if (p.fs.parent_nr == 0)
3332 errx(EX_DATAERR, "pipe must be > 0");
3333 if (p.fs.weight >100)
3334 errx(EX_DATAERR, "weight must be <= 100");
3336 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
3337 if (p.fs.qsize > 1024*1024)
3338 errx(EX_DATAERR, "queue size must be < 1MB");
3340 if (p.fs.qsize > 100)
3341 errx(EX_DATAERR, "2 <= queue size <= 100");
3343 if (p.fs.flags_fs & DN_IS_RED) {
3345 int lookup_depth, avg_pkt_size;
3346 double s, idle, weight, w_q;
3347 struct clockinfo ck;
3350 if (p.fs.min_th >= p.fs.max_th)
3351 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
3352 p.fs.min_th, p.fs.max_th);
3353 if (p.fs.max_th == 0)
3354 errx(EX_DATAERR, "max_th must be > 0");
3357 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
3358 &lookup_depth, &len, NULL, 0) == -1)
3360 errx(1, "sysctlbyname(\"%s\")",
3361 "net.inet.ip.dummynet.red_lookup_depth");
3362 if (lookup_depth == 0)
3363 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
3364 " must be greater than zero");
3367 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
3368 &avg_pkt_size, &len, NULL, 0) == -1)
3370 errx(1, "sysctlbyname(\"%s\")",
3371 "net.inet.ip.dummynet.red_avg_pkt_size");
3372 if (avg_pkt_size == 0)
3374 "net.inet.ip.dummynet.red_avg_pkt_size must"
3375 " be greater than zero");
3377 len = sizeof(struct clockinfo);
3378 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
3379 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
3382 * Ticks needed for sending a medium-sized packet.
3383 * Unfortunately, when we are configuring a WF2Q+ queue, we
3384 * do not have bandwidth information, because that is stored
3385 * in the parent pipe, and also we have multiple queues
3386 * competing for it. So we set s=0, which is not very
3387 * correct. But on the other hand, why do we want RED with
3390 if (p.bandwidth==0) /* this is a WF2Q+ queue */
3393 s = ck.hz * avg_pkt_size * 8 / p.bandwidth;
3396 * max idle time (in ticks) before avg queue size becomes 0.
3397 * NOTA: (3/w_q) is approx the value x so that
3398 * (1-w_q)^x < 10^-3.
3400 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
3401 idle = s * 3. / w_q;
3402 p.fs.lookup_step = (int)idle / lookup_depth;
3403 if (!p.fs.lookup_step)
3404 p.fs.lookup_step = 1;
3406 for (t = p.fs.lookup_step; t > 0; --t)
3408 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
3410 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
3412 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
3416 get_mac_addr_mask(char *p, uint8_t *addr, uint8_t *mask)
3421 addr[i] = mask[i] = 0;
3422 if (strcmp(p, "any") == 0)
3425 for (i=0; *p && i<6;i++, p++) {
3426 addr[i] = strtol(p, &p, 16);
3427 if (*p != ':') /* we start with the mask */
3430 if (*p == '/') { /* mask len */
3431 l = strtol(p+1, &p, 0);
3432 for (i=0; l>0; l -=8, i++)
3433 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
3434 } else if (*p == '&') { /* mask */
3435 for (i=0, p++; *p && i<6;i++, p++) {
3436 mask[i] = strtol(p, &p, 16);
3440 } else if (*p == '\0') {
3449 * helper function, updates the pointer to cmd with the length
3450 * of the current command, and also cleans up the first word of
3451 * the new command in case it has been clobbered before.
3454 next_cmd(ipfw_insn *cmd)
3457 bzero(cmd, sizeof(*cmd));
3462 * Takes arguments and copies them into a comment
3465 fill_comment(ipfw_insn *cmd, int ac, char **av)
3468 char *p = (char *)(cmd + 1);
3470 cmd->opcode = O_NOP;
3471 cmd->len = (cmd->len & (F_NOT | F_OR));
3473 /* Compute length of comment string. */
3474 for (i = 0, l = 0; i < ac; i++)
3475 l += strlen(av[i]) + 1;
3480 "comment too long (max 80 chars)");
3482 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3483 for (i = 0; i < ac; i++) {
3492 * A function to fill simple commands of size 1.
3493 * Existing flags are preserved.
3496 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3498 cmd->opcode = opcode;
3499 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3504 * Fetch and add the MAC address and type, with masks. This generates one or
3505 * two microinstructions, and returns the pointer to the last one.
3508 add_mac(ipfw_insn *cmd, int ac, char *av[])
3513 errx(EX_DATAERR, "MAC dst src");
3515 cmd->opcode = O_MACADDR2;
3516 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3518 mac = (ipfw_insn_mac *)cmd;
3519 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3520 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
3525 add_mactype(ipfw_insn *cmd, int ac, char *av)
3528 errx(EX_DATAERR, "missing MAC type");
3529 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3530 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
3531 cmd->opcode = O_MAC_TYPE;
3538 add_proto(ipfw_insn *cmd, char *av, u_char *proto)
3540 struct protoent *pe;
3542 *proto = IPPROTO_IP;
3544 if (_substrcmp(av, "all") == 0)
3545 ; /* do not set O_IP4 nor O_IP6 */
3546 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3547 /* explicit "just IPv4" rule */
3548 fill_cmd(cmd, O_IP4, 0, 0);
3549 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3550 /* explicit "just IPv6" rule */
3551 *proto = IPPROTO_IPV6;
3552 fill_cmd(cmd, O_IP6, 0, 0);
3553 } else if ((*proto = atoi(av)) > 0)
3555 else if ((pe = getprotobyname(av)) != NULL)
3556 *proto = pe->p_proto;
3559 if (*proto != IPPROTO_IP && *proto != IPPROTO_IPV6)
3560 fill_cmd(cmd, O_PROTO, 0, *proto);
3566 add_srcip(ipfw_insn *cmd, char *av)
3568 fill_ip((ipfw_insn_ip *)cmd, av);
3569 if (cmd->opcode == O_IP_DST_SET) /* set */
3570 cmd->opcode = O_IP_SRC_SET;
3571 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3572 cmd->opcode = O_IP_SRC_LOOKUP;
3573 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3574 cmd->opcode = O_IP_SRC_ME;
3575 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3576 cmd->opcode = O_IP_SRC;
3577 else /* addr/mask */
3578 cmd->opcode = O_IP_SRC_MASK;
3583 add_dstip(ipfw_insn *cmd, char *av)
3585 fill_ip((ipfw_insn_ip *)cmd, av);
3586 if (cmd->opcode == O_IP_DST_SET) /* set */
3588 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3590 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3591 cmd->opcode = O_IP_DST_ME;
3592 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3593 cmd->opcode = O_IP_DST;
3594 else /* addr/mask */
3595 cmd->opcode = O_IP_DST_MASK;
3600 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
3602 if (_substrcmp(av, "any") == 0) {
3604 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
3605 /* XXX todo: check that we have a protocol with ports */
3606 cmd->opcode = opcode;
3613 add_src(ipfw_insn *cmd, char *av, u_char proto)
3617 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3618 inet_pton(AF_INET6, av, &a))
3619 return add_srcip6(cmd, av);
3620 /* XXX: should check for IPv4, not !IPv6 */
3621 if (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3622 !inet_pton(AF_INET6, av, &a))
3623 return add_srcip(cmd, av);
3624 if (strcmp(av, "any") != 0)
3631 add_dst(ipfw_insn *cmd, char *av, u_char proto)
3635 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3636 inet_pton(AF_INET6, av, &a))
3637 return add_dstip6(cmd, av);
3638 /* XXX: should check for IPv4, not !IPv6 */
3639 if (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3640 !inet_pton(AF_INET6, av, &a))
3641 return add_dstip(cmd, av);
3642 if (strcmp(av, "any") != 0)
3649 * Parse arguments and assemble the microinstructions which make up a rule.
3650 * Rules are added into the 'rulebuf' and then copied in the correct order
3651 * into the actual rule.
3653 * The syntax for a rule starts with the action, followed by
3654 * optional action parameters, and the various match patterns.
3655 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3656 * (generated if the rule includes a keep-state option), then the
3657 * various match patterns, log/altq actions, and the actual action.
3661 add(int ac, char *av[])
3664 * rules are added into the 'rulebuf' and then copied in
3665 * the correct order into the actual rule.
3666 * Some things that need to go out of order (prob, action etc.)
3669 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
3671 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3672 ipfw_insn *first_cmd; /* first match pattern */
3677 * various flags used to record that we entered some fields.
3679 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3680 ipfw_insn *have_log = NULL, *have_altq = NULL;
3685 int open_par = 0; /* open parenthesis ( */
3687 /* proto is here because it is used to fetch ports */
3688 u_char proto = IPPROTO_IP; /* default protocol */
3690 double match_prob = 1; /* match probability, default is always match */
3692 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3693 bzero(cmdbuf, sizeof(cmdbuf));
3694 bzero(rulebuf, sizeof(rulebuf));
3696 rule = (struct ip_fw *)rulebuf;
3697 cmd = (ipfw_insn *)cmdbuf;
3698 action = (ipfw_insn *)actbuf;
3702 /* [rule N] -- Rule number optional */
3703 if (ac && isdigit(**av)) {
3704 rule->rulenum = atoi(*av);
3709 /* [set N] -- set number (0..RESVD_SET), optional */
3710 if (ac > 1 && _substrcmp(*av, "set") == 0) {
3711 int set = strtoul(av[1], NULL, 10);
3712 if (set < 0 || set > RESVD_SET)
3713 errx(EX_DATAERR, "illegal set %s", av[1]);
3718 /* [prob D] -- match probability, optional */
3719 if (ac > 1 && _substrcmp(*av, "prob") == 0) {
3720 match_prob = strtod(av[1], NULL);
3722 if (match_prob <= 0 || match_prob > 1)
3723 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3727 /* action -- mandatory */
3728 NEED1("missing action");
3729 i = match_token(rule_actions, *av);
3731 action->len = 1; /* default */
3733 case TOK_CHECKSTATE:
3734 have_state = action;
3735 action->opcode = O_CHECK_STATE;
3739 action->opcode = O_ACCEPT;
3743 action->opcode = O_DENY;
3748 action->opcode = O_REJECT;
3749 action->arg1 = ICMP_UNREACH_HOST;
3753 action->opcode = O_REJECT;
3754 action->arg1 = ICMP_REJECT_RST;
3758 action->opcode = O_REJECT;
3759 NEED1("missing reject code");
3760 fill_reject_code(&action->arg1, *av);
3765 action->opcode = O_COUNT;
3770 action->len = F_INSN_SIZE(ipfw_insn_pipe);
3773 action->opcode = O_QUEUE;
3774 else if (i == TOK_PIPE)
3775 action->opcode = O_PIPE;
3776 else if (i == TOK_SKIPTO)
3777 action->opcode = O_SKIPTO;
3778 NEED1("missing skipto/pipe/queue number");
3779 action->arg1 = strtoul(*av, NULL, 10);
3785 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
3786 NEED1("missing divert/tee port");
3787 action->arg1 = strtoul(*av, NULL, 0);
3788 if (action->arg1 == 0) {
3791 s = getservbyname(av[0], "divert");
3793 action->arg1 = ntohs(s->s_port);
3795 errx(EX_DATAERR, "illegal divert/tee port");
3802 action->opcode = (i == TOK_NETGRAPH ) ? O_NETGRAPH : O_NGTEE;
3803 NEED1("missing netgraph cookie");
3804 action->arg1 = strtoul(*av, NULL, 0);
3805 if (action->arg1 == 0)
3806 errx(EX_DATAERR, "illegal netgraph cookie");
3811 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3814 NEED1("missing forward address[:port]");
3816 action->opcode = O_FORWARD_IP;
3817 action->len = F_INSN_SIZE(ipfw_insn_sa);
3819 p->sa.sin_len = sizeof(struct sockaddr_in);
3820 p->sa.sin_family = AF_INET;
3823 * locate the address-port separator (':' or ',')
3825 s = strchr(*av, ':');
3827 s = strchr(*av, ',');
3830 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3833 "illegal forwarding port ``%s''", s);
3834 p->sa.sin_port = (u_short)i;
3836 lookup_host(*av, &(p->sa.sin_addr));
3842 /* pretend it is a 'count' rule followed by the comment */
3843 action->opcode = O_COUNT;
3844 ac++; av--; /* go back... */
3848 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3850 action = next_cmd(action);
3853 * [altq queuename] -- altq tag, optional
3854 * [log [logamount N]] -- log, optional
3856 * If they exist, it go first in the cmdbuf, but then it is
3857 * skipped in the copy section to the end of the buffer.
3859 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
3864 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3869 "log cannot be specified more than once");
3870 have_log = (ipfw_insn *)c;
3871 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3872 cmd->opcode = O_LOG;
3873 if (ac && _substrcmp(*av, "logamount") == 0) {
3875 NEED1("logamount requires argument");
3879 "logamount must be positive");
3883 len = sizeof(c->max_log);
3884 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3885 &c->max_log, &len, NULL, 0) == -1)
3886 errx(1, "sysctlbyname(\"%s\")",
3887 "net.inet.ip.fw.verbose_limit");
3894 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3896 NEED1("missing altq queue name");
3899 "altq cannot be specified more than once");
3900 have_altq = (ipfw_insn *)a;
3901 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3902 cmd->opcode = O_ALTQ;
3903 fill_altq_qid(&a->qid, *av);
3911 cmd = next_cmd(cmd);
3914 if (have_state) /* must be a check-state, we are done */
3917 #define OR_START(target) \
3918 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
3920 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3923 if ( (av[0])[1] == '\0') { \
3934 strcmp(*av, ")") == 0 || \
3935 strcmp(*av, "}") == 0)) { \
3940 errx(EX_USAGE, "missing \")\"\n"); \
3944 if (ac && _substrcmp(*av, "not") == 0) { \
3945 if (cmd->len & F_NOT) \
3946 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3947 cmd->len |= F_NOT; \
3951 #define OR_BLOCK(target) \
3952 if (ac && _substrcmp(*av, "or") == 0) { \
3953 if (prev == NULL || open_par == 0) \
3954 errx(EX_DATAERR, "invalid OR block"); \
3955 prev->len |= F_OR; \
3965 * MAC addresses, optional.
3966 * If we have this, we skip the part "proto from src to dst"
3967 * and jump straight to the option parsing.
3970 NEED1("missing protocol");
3971 if (_substrcmp(*av, "MAC") == 0 ||
3972 _substrcmp(*av, "mac") == 0) {
3973 ac--; av++; /* the "MAC" keyword */
3974 add_mac(cmd, ac, av); /* exits in case of errors */
3975 cmd = next_cmd(cmd);
3976 ac -= 2; av += 2; /* dst-mac and src-mac */
3978 NEED1("missing mac type");
3979 if (add_mactype(cmd, ac, av[0]))
3980 cmd = next_cmd(cmd);
3981 ac--; av++; /* any or mac-type */
3987 * protocol, mandatory
3989 OR_START(get_proto);
3991 NEED1("missing protocol");
3992 if (add_proto(cmd, *av, &proto)) {
3994 if (F_LEN(cmd) != 0) {
3996 cmd = next_cmd(cmd);
3998 } else if (first_cmd != cmd) {
3999 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4002 OR_BLOCK(get_proto);
4007 if (!ac || _substrcmp(*av, "from") != 0)
4008 errx(EX_USAGE, "missing ``from''");
4012 * source IP, mandatory
4014 OR_START(source_ip);
4015 NOT_BLOCK; /* optional "not" */
4016 NEED1("missing source address");
4017 if (add_src(cmd, *av, proto)) {
4019 if (F_LEN(cmd) != 0) { /* ! any */
4021 cmd = next_cmd(cmd);
4024 errx(EX_USAGE, "bad source address %s", *av);
4025 OR_BLOCK(source_ip);
4028 * source ports, optional
4030 NOT_BLOCK; /* optional "not" */
4032 if (_substrcmp(*av, "any") == 0 ||
4033 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
4035 if (F_LEN(cmd) != 0)
4036 cmd = next_cmd(cmd);
4043 if (!ac || _substrcmp(*av, "to") != 0)
4044 errx(EX_USAGE, "missing ``to''");
4048 * destination, mandatory
4051 NOT_BLOCK; /* optional "not" */
4052 NEED1("missing dst address");
4053 if (add_dst(cmd, *av, proto)) {
4055 if (F_LEN(cmd) != 0) { /* ! any */
4057 cmd = next_cmd(cmd);
4060 errx( EX_USAGE, "bad destination address %s", *av);
4064 * dest. ports, optional
4066 NOT_BLOCK; /* optional "not" */
4068 if (_substrcmp(*av, "any") == 0 ||
4069 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
4071 if (F_LEN(cmd) != 0)
4072 cmd = next_cmd(cmd);
4077 if (ac && first_cmd == cmd) {
4079 * nothing specified so far, store in the rule to ease
4087 ipfw_insn_u32 *cmd32; /* alias for cmd */
4090 cmd32 = (ipfw_insn_u32 *)cmd;
4092 if (*s == '!') { /* alternate syntax for NOT */
4093 if (cmd->len & F_NOT)
4094 errx(EX_USAGE, "double \"not\" not allowed\n");
4098 i = match_token(rule_options, s);
4102 if (cmd->len & F_NOT)
4103 errx(EX_USAGE, "double \"not\" not allowed\n");
4108 if (open_par == 0 || prev == NULL)
4109 errx(EX_USAGE, "invalid \"or\" block\n");
4113 case TOK_STARTBRACE:
4115 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4121 errx(EX_USAGE, "+missing \")\"\n");
4127 fill_cmd(cmd, O_IN, 0, 0);
4131 cmd->len ^= F_NOT; /* toggle F_NOT */
4132 fill_cmd(cmd, O_IN, 0, 0);
4136 fill_cmd(cmd, O_DIVERTED, 0, 3);
4139 case TOK_DIVERTEDLOOPBACK:
4140 fill_cmd(cmd, O_DIVERTED, 0, 1);
4143 case TOK_DIVERTEDOUTPUT:
4144 fill_cmd(cmd, O_DIVERTED, 0, 2);
4148 fill_cmd(cmd, O_FRAG, 0, 0);
4152 fill_cmd(cmd, O_LAYER2, 0, 0);
4158 NEED1("recv, xmit, via require interface name"
4160 fill_iface((ipfw_insn_if *)cmd, av[0]);
4162 if (F_LEN(cmd) == 0) /* not a valid address */
4165 cmd->opcode = O_XMIT;
4166 else if (i == TOK_RECV)
4167 cmd->opcode = O_RECV;
4168 else if (i == TOK_VIA)
4169 cmd->opcode = O_VIA;
4173 NEED1("icmptypes requires list of types");
4174 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4178 case TOK_ICMP6TYPES:
4179 NEED1("icmptypes requires list of types");
4180 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
4185 NEED1("ipttl requires TTL");
4186 if (strpbrk(*av, "-,")) {
4187 if (!add_ports(cmd, *av, 0, O_IPTTL))
4188 errx(EX_DATAERR, "invalid ipttl %s", *av);
4190 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4195 NEED1("ipid requires id");
4196 if (strpbrk(*av, "-,")) {
4197 if (!add_ports(cmd, *av, 0, O_IPID))
4198 errx(EX_DATAERR, "invalid ipid %s", *av);
4200 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4205 NEED1("iplen requires length");
4206 if (strpbrk(*av, "-,")) {
4207 if (!add_ports(cmd, *av, 0, O_IPLEN))
4208 errx(EX_DATAERR, "invalid ip len %s", *av);
4210 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4215 NEED1("ipver requires version");
4216 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4220 case TOK_IPPRECEDENCE:
4221 NEED1("ipprecedence requires value");
4222 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4223 (strtoul(*av, NULL, 0) & 7) << 5);
4228 NEED1("missing argument for ipoptions");
4229 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
4234 NEED1("missing argument for iptos");
4235 fill_flags(cmd, O_IPTOS, f_iptos, *av);
4240 NEED1("uid requires argument");
4246 cmd->opcode = O_UID;
4247 uid = strtoul(*av, &end, 0);
4248 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4250 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4251 cmd32->d[0] = pwd->pw_uid;
4252 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4258 NEED1("gid requires argument");
4264 cmd->opcode = O_GID;
4265 gid = strtoul(*av, &end, 0);
4266 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4268 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4269 cmd32->d[0] = grp->gr_gid;
4270 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4276 NEED1("jail requires argument");
4281 cmd->opcode = O_JAIL;
4282 jid = (int)strtol(*av, &end, 0);
4283 if (jid < 0 || *end != '\0')
4284 errx(EX_DATAERR, "jail requires prison ID");
4285 cmd32->d[0] = (uint32_t)jid;
4286 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4292 fill_cmd(cmd, O_ESTAB, 0, 0);
4296 fill_cmd(cmd, O_TCPFLAGS, 0,
4297 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4300 case TOK_TCPDATALEN:
4301 NEED1("tcpdatalen requires length");
4302 if (strpbrk(*av, "-,")) {
4303 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
4304 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4306 fill_cmd(cmd, O_TCPDATALEN, 0,
4307 strtoul(*av, NULL, 0));
4312 NEED1("missing argument for tcpoptions");
4313 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
4319 NEED1("tcpseq/tcpack requires argument");
4320 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4321 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4322 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4327 NEED1("tcpwin requires length");
4328 fill_cmd(cmd, O_TCPWIN, 0,
4329 htons(strtoul(*av, NULL, 0)));
4334 NEED1("missing argument for tcpflags");
4335 cmd->opcode = O_TCPFLAGS;
4336 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
4342 errx(EX_USAGE, "keep-state cannot be part "
4345 errx(EX_USAGE, "only one of keep-state "
4346 "and limit is allowed");
4348 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
4353 errx(EX_USAGE, "limit cannot be part "
4356 errx(EX_USAGE, "only one of keep-state "
4357 "and limit is allowed");
4358 NEED1("limit needs mask and # of connections");
4361 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4363 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4364 cmd->opcode = O_LIMIT;
4370 val = match_token(limit_masks, *av);
4373 c->limit_mask |= val;
4376 c->conn_limit = atoi(*av);
4377 if (c->conn_limit == 0)
4378 errx(EX_USAGE, "limit: limit must be >0");
4379 if (c->limit_mask == 0)
4380 errx(EX_USAGE, "missing limit mask");
4386 NEED1("missing protocol");
4387 if (add_proto(cmd, *av, &proto)) {
4390 errx(EX_DATAERR, "invalid protocol ``%s''",
4395 NEED1("missing source IP");
4396 if (add_srcip(cmd, *av)) {
4402 NEED1("missing destination IP");
4403 if (add_dstip(cmd, *av)) {
4409 NEED1("missing source IP6");
4410 if (add_srcip6(cmd, *av)) {
4416 NEED1("missing destination IP6");
4417 if (add_dstip6(cmd, *av)) {
4423 NEED1("missing source port");
4424 if (_substrcmp(*av, "any") == 0 ||
4425 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
4428 errx(EX_DATAERR, "invalid source port %s", *av);
4432 NEED1("missing destination port");
4433 if (_substrcmp(*av, "any") == 0 ||
4434 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
4437 errx(EX_DATAERR, "invalid destination port %s",
4442 if (add_mac(cmd, ac, av)) {
4448 NEED1("missing mac type");
4449 if (!add_mactype(cmd, ac, *av))
4450 errx(EX_DATAERR, "invalid mac type %s", *av);
4454 case TOK_VERREVPATH:
4455 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4458 case TOK_VERSRCREACH:
4459 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4463 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4467 fill_cmd(cmd, O_IPSEC, 0, 0);
4471 fill_cmd(cmd, O_IP6, 0, 0);
4475 fill_cmd(cmd, O_IP4, 0, 0);
4479 fill_ext6hdr( cmd, *av );
4484 if (proto != IPPROTO_IPV6 )
4485 errx( EX_USAGE, "flow-id filter is active "
4486 "only for ipv6 protocol\n");
4487 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
4492 fill_comment(cmd, ac, av);
4498 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4500 if (F_LEN(cmd) > 0) { /* prepare to advance */
4502 cmd = next_cmd(cmd);
4508 * Now copy stuff into the rule.
4509 * If we have a keep-state option, the first instruction
4510 * must be a PROBE_STATE (which is generated here).
4511 * If we have a LOG option, it was stored as the first command,
4512 * and now must be moved to the top of the action part.
4514 dst = (ipfw_insn *)rule->cmd;
4517 * First thing to write into the command stream is the match probability.
4519 if (match_prob != 1) { /* 1 means always match */
4520 dst->opcode = O_PROB;
4522 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4527 * generate O_PROBE_STATE if necessary
4529 if (have_state && have_state->opcode != O_CHECK_STATE) {
4530 fill_cmd(dst, O_PROBE_STATE, 0, 0);
4531 dst = next_cmd(dst);
4534 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ
4536 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4539 switch (src->opcode) {
4546 bcopy(src, dst, i * sizeof(uint32_t));
4552 * put back the have_state command as last opcode
4554 if (have_state && have_state->opcode != O_CHECK_STATE) {
4555 i = F_LEN(have_state);
4556 bcopy(have_state, dst, i * sizeof(uint32_t));
4560 * start action section
4562 rule->act_ofs = dst - rule->cmd;
4565 * put back O_LOG, O_ALTQ if necessary
4568 i = F_LEN(have_log);
4569 bcopy(have_log, dst, i * sizeof(uint32_t));
4573 i = F_LEN(have_altq);
4574 bcopy(have_altq, dst, i * sizeof(uint32_t));
4578 * copy all other actions
4580 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4582 bcopy(src, dst, i * sizeof(uint32_t));
4586 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4587 i = (char *)dst - (char *)rule;
4588 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4589 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4591 show_ipfw(rule, 0, 0);
4595 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */)
4599 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG";
4604 /* clear all entries */
4605 if (do_cmd(optname, NULL, 0) < 0)
4606 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4608 printf("%s.\n", optname == IP_FW_ZERO ?
4609 "Accounting cleared":"Logging counts reset");
4616 if (isdigit(**av)) {
4617 rulenum = atoi(*av);
4620 if (do_cmd(optname, &rulenum, sizeof rulenum)) {
4621 warn("rule %u: setsockopt(IP_FW_%s)",
4623 failed = EX_UNAVAILABLE;
4624 } else if (!do_quiet)
4625 printf("Entry %d %s.\n", rulenum,
4626 optname == IP_FW_ZERO ?
4627 "cleared" : "logging count reset");
4629 errx(EX_USAGE, "invalid rule number ``%s''", *av);
4632 if (failed != EX_OK)
4639 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4641 if (!force && !do_quiet) { /* need to ask user */
4644 printf("Are you sure? [yn] ");
4647 c = toupper(getc(stdin));
4648 while (c != '\n' && getc(stdin) != '\n')
4650 return; /* and do not flush */
4651 } while (c != 'Y' && c != 'N');
4653 if (c == 'N') /* user said no */
4656 if (do_cmd(cmd, NULL, 0) < 0)
4657 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4658 do_pipe ? "DUMMYNET" : "FW");
4660 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
4664 * Free a the (locally allocated) copy of command line arguments.
4667 free_args(int ac, char **av)
4671 for (i=0; i < ac; i++)
4677 * This one handles all table-related commands
4678 * ipfw table N add addr[/masklen] [value]
4679 * ipfw table N delete addr[/masklen]
4680 * ipfw table N flush
4684 table_handler(int ac, char *av[])
4686 ipfw_table_entry ent;
4694 if (ac && isdigit(**av)) {
4695 ent.tbl = atoi(*av);
4698 errx(EX_USAGE, "table number required");
4699 NEED1("table needs command");
4700 if (_substrcmp(*av, "add") == 0 ||
4701 _substrcmp(*av, "delete") == 0) {
4702 do_add = **av == 'a';
4705 errx(EX_USAGE, "IP address required");
4706 p = strchr(*av, '/');
4709 ent.masklen = atoi(p);
4710 if (ent.masklen > 32)
4711 errx(EX_DATAERR, "bad width ``%s''", p);
4714 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
4715 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4718 ent.value = strtoul(*av, NULL, 0);
4721 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
4722 &ent, sizeof(ent)) < 0)
4723 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4724 do_add ? "ADD" : "DEL");
4725 } else if (_substrcmp(*av, "flush") == 0) {
4726 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0)
4727 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4728 } else if (_substrcmp(*av, "list") == 0) {
4731 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
4732 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
4733 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
4736 err(EX_OSERR, "malloc");
4738 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
4739 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
4740 for (a = 0; a < tbl->cnt; a++) {
4741 printf("%s/%u %u\n",
4742 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
4743 tbl->ent[a].masklen, tbl->ent[a].value);
4746 errx(EX_USAGE, "invalid table command %s", *av);
4750 * Called with the arguments (excluding program name).
4751 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
4754 ipfw_main(int oldac, char **oldav)
4756 int ch, ac, save_ac;
4757 char **av, **save_av;
4758 int do_acct = 0; /* Show packet/byte count */
4760 #define WHITESP " \t\f\v\n\r"
4763 else if (oldac == 1) {
4765 * If we are called with a single string, try to split it into
4766 * arguments for subsequent parsing.
4767 * But first, remove spaces after a ',', by copying the string
4770 char *arg = oldav[0]; /* The string... */
4771 int l = strlen(arg);
4772 int copy = 0; /* 1 if we need to copy, 0 otherwise */
4774 for (i = j = 0; i < l; i++) {
4775 if (arg[i] == '#') /* comment marker */
4779 copy = !index("," WHITESP, arg[i]);
4781 copy = !index(WHITESP, arg[i]);
4786 if (!copy && j > 0) /* last char was a 'blank', remove it */
4788 l = j; /* the new argument length */
4790 if (l == 0) /* empty string! */
4794 * First, count number of arguments. Because of the previous
4795 * processing, this is just the number of blanks plus 1.
4797 for (i = 0, ac = 1; i < l; i++)
4798 if (index(WHITESP, arg[i]) != NULL)
4801 av = calloc(ac, sizeof(char *));
4804 * Second, copy arguments from cmd[] to av[]. For each one,
4805 * j is the initial character, i is the one past the end.
4807 for (ac = 0, i = j = 0; i < l; i++)
4808 if (index(WHITESP, arg[i]) != NULL || i == l-1) {
4811 av[ac] = calloc(i-j+1, 1);
4812 bcopy(arg+j, av[ac], i-j);
4818 * If an argument ends with ',' join with the next one.
4822 av = calloc(oldac, sizeof(char *));
4823 for (first = i = ac = 0, l = 0; i < oldac; i++) {
4824 char *arg = oldav[i];
4825 int k = strlen(arg);
4828 if (arg[k-1] != ',' || i == oldac-1) {
4830 av[ac] = calloc(l+1, 1);
4831 for (l=0; first <= i; first++) {
4832 strcat(av[ac]+l, oldav[first]);
4833 l += strlen(oldav[first]);
4842 /* Set the force flag for non-interactive processes */
4844 do_force = !isatty(STDIN_FILENO);
4846 /* Save arguments for final freeing of memory. */
4850 optind = optreset = 0;
4851 while ((ch = getopt(ac, av, "abcdefhnNqs:STtv")) != -1)
4878 case 'h': /* help */
4879 free_args(save_ac, save_av);
4881 break; /* NOTREACHED */
4895 case 's': /* sort */
4896 do_sort = atoi(optarg);
4908 do_time = 2; /* numeric timestamp */
4911 case 'v': /* verbose */
4916 free_args(save_ac, save_av);
4922 NEED1("bad arguments, for usage summary ``ipfw''");
4925 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
4926 * e.g. "100 add allow ..." instead of "add 100 allow ...".
4927 * In case, swap first and second argument to get the normal form.
4929 if (ac > 1 && isdigit(*av[0])) {
4937 * optional: pipe or queue
4940 if (_substrcmp(*av, "pipe") == 0)
4942 else if (_substrcmp(*av, "queue") == 0)
4948 NEED1("missing command");
4951 * For pipes and queues we normally say 'pipe NN config'
4952 * but the code is easier to parse as 'pipe config NN'
4953 * so we swap the two arguments.
4955 if (do_pipe > 0 && ac > 1 && isdigit(*av[0])) {
4962 if (_substrcmp(*av, "add") == 0)
4964 else if (do_pipe && _substrcmp(*av, "config") == 0)
4965 config_pipe(ac, av);
4966 else if (_substrcmp(*av, "delete") == 0)
4968 else if (_substrcmp(*av, "flush") == 0)
4970 else if (_substrcmp(*av, "zero") == 0)
4971 zero(ac, av, IP_FW_ZERO);
4972 else if (_substrcmp(*av, "resetlog") == 0)
4973 zero(ac, av, IP_FW_RESETLOG);
4974 else if (_substrcmp(*av, "print") == 0 ||
4975 _substrcmp(*av, "list") == 0)
4976 list(ac, av, do_acct);
4977 else if (_substrcmp(*av, "set") == 0)
4978 sets_handler(ac, av);
4979 else if (_substrcmp(*av, "table") == 0)
4980 table_handler(ac, av);
4981 else if (_substrcmp(*av, "enable") == 0)
4982 sysctl_handler(ac, av, 1);
4983 else if (_substrcmp(*av, "disable") == 0)
4984 sysctl_handler(ac, av, 0);
4985 else if (_substrcmp(*av, "show") == 0)
4986 list(ac, av, 1 /* show counters */);
4988 errx(EX_USAGE, "bad command `%s'", *av);
4990 /* Free memory allocated in the argument parsing. */
4991 free_args(save_ac, save_av);
4997 ipfw_readfile(int ac, char *av[])
5001 char *cmd = NULL, *filename = av[ac-1];
5006 filename = av[ac-1];
5008 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
5029 * Skip previous args and delete last one, so we
5030 * pass all but the last argument to the preprocessor
5036 fprintf(stderr, "command is %s\n", av[0]);
5048 errx(EX_USAGE, "bad arguments, for usage"
5049 " summary ``ipfw''");
5056 if (cmd == NULL && ac != optind + 1) {
5057 fprintf(stderr, "ac %d, optind %d\n", ac, optind);
5058 errx(EX_USAGE, "extraneous filename arguments");
5061 if ((f = fopen(filename, "r")) == NULL)
5062 err(EX_UNAVAILABLE, "fopen: %s", filename);
5064 if (cmd != NULL) { /* pipe through preprocessor */
5067 if (pipe(pipedes) == -1)
5068 err(EX_OSERR, "cannot create pipe");
5072 err(EX_OSERR, "cannot fork");
5076 * Child, will run the preprocessor with the
5077 * file on stdin and the pipe on stdout.
5079 if (dup2(fileno(f), 0) == -1
5080 || dup2(pipedes[1], 1) == -1)
5081 err(EX_OSERR, "dup2()");
5086 err(EX_OSERR, "execvp(%s) failed", cmd);
5087 } else { /* parent, will reopen f as the pipe */
5090 if ((f = fdopen(pipedes[0], "r")) == NULL) {
5091 int savederrno = errno;
5093 (void)kill(preproc, SIGTERM);
5095 err(EX_OSERR, "fdopen()");
5100 while (fgets(buf, BUFSIZ, f)) { /* read commands */
5105 sprintf(linename, "Line %d", lineno);
5106 setprogname(linename); /* XXX */
5114 if (waitpid(preproc, &status, 0) == -1)
5115 errx(EX_OSERR, "waitpid()");
5116 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
5117 errx(EX_UNAVAILABLE,
5118 "preprocessor exited with status %d",
5119 WEXITSTATUS(status));
5120 else if (WIFSIGNALED(status))
5121 errx(EX_UNAVAILABLE,
5122 "preprocessor exited with signal %d",
5128 main(int ac, char *av[])
5131 * If the last argument is an absolute pathname, interpret it
5132 * as a file to be preprocessed.
5135 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
5136 ipfw_readfile(ac, av);
5138 if (ipfw_main(ac-1, av+1))