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,
284 struct _s_x dummynet_params[] = {
286 { "noerror", TOK_NOERROR },
287 { "buckets", TOK_BUCKETS },
288 { "dst-ip", TOK_DSTIP },
289 { "src-ip", TOK_SRCIP },
290 { "dst-port", TOK_DSTPORT },
291 { "src-port", TOK_SRCPORT },
292 { "proto", TOK_PROTO },
293 { "weight", TOK_WEIGHT },
295 { "mask", TOK_MASK },
296 { "droptail", TOK_DROPTAIL },
298 { "gred", TOK_GRED },
300 { "bandwidth", TOK_BW },
301 { "delay", TOK_DELAY },
302 { "pipe", TOK_PIPE },
303 { "queue", TOK_QUEUE },
304 { "flow-id", TOK_FLOWID},
305 { "dst-ipv6", TOK_DSTIP6},
306 { "dst-ip6", TOK_DSTIP6},
307 { "src-ipv6", TOK_SRCIP6},
308 { "src-ip6", TOK_SRCIP6},
309 { "dummynet-params", TOK_NULL },
310 { NULL, 0 } /* terminator */
313 struct _s_x rule_actions[] = {
314 { "accept", TOK_ACCEPT },
315 { "pass", TOK_ACCEPT },
316 { "allow", TOK_ACCEPT },
317 { "permit", TOK_ACCEPT },
318 { "count", TOK_COUNT },
319 { "pipe", TOK_PIPE },
320 { "queue", TOK_QUEUE },
321 { "divert", TOK_DIVERT },
323 { "netgraph", TOK_NETGRAPH },
324 { "ngtee", TOK_NGTEE },
325 { "fwd", TOK_FORWARD },
326 { "forward", TOK_FORWARD },
327 { "skipto", TOK_SKIPTO },
328 { "deny", TOK_DENY },
329 { "drop", TOK_DENY },
330 { "reject", TOK_REJECT },
331 { "reset6", TOK_RESET6 },
332 { "reset", TOK_RESET },
333 { "unreach6", TOK_UNREACH6 },
334 { "unreach", TOK_UNREACH },
335 { "check-state", TOK_CHECKSTATE },
336 { "//", TOK_COMMENT },
337 { NULL, 0 } /* terminator */
340 struct _s_x rule_action_params[] = {
341 { "altq", TOK_ALTQ },
343 { NULL, 0 } /* terminator */
346 struct _s_x rule_options[] = {
349 { "jail", TOK_JAIL },
351 { "limit", TOK_LIMIT },
352 { "keep-state", TOK_KEEPSTATE },
353 { "bridged", TOK_LAYER2 },
354 { "layer2", TOK_LAYER2 },
356 { "diverted", TOK_DIVERTED },
357 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
358 { "diverted-output", TOK_DIVERTEDOUTPUT },
359 { "xmit", TOK_XMIT },
360 { "recv", TOK_RECV },
362 { "fragment", TOK_FRAG },
363 { "frag", TOK_FRAG },
364 { "ipoptions", TOK_IPOPTS },
365 { "ipopts", TOK_IPOPTS },
366 { "iplen", TOK_IPLEN },
367 { "ipid", TOK_IPID },
368 { "ipprecedence", TOK_IPPRECEDENCE },
369 { "iptos", TOK_IPTOS },
370 { "ipttl", TOK_IPTTL },
371 { "ipversion", TOK_IPVER },
372 { "ipver", TOK_IPVER },
373 { "estab", TOK_ESTAB },
374 { "established", TOK_ESTAB },
375 { "setup", TOK_SETUP },
376 { "tcpdatalen", TOK_TCPDATALEN },
377 { "tcpflags", TOK_TCPFLAGS },
378 { "tcpflgs", TOK_TCPFLAGS },
379 { "tcpoptions", TOK_TCPOPTS },
380 { "tcpopts", TOK_TCPOPTS },
381 { "tcpseq", TOK_TCPSEQ },
382 { "tcpack", TOK_TCPACK },
383 { "tcpwin", TOK_TCPWIN },
384 { "icmptype", TOK_ICMPTYPES },
385 { "icmptypes", TOK_ICMPTYPES },
386 { "dst-ip", TOK_DSTIP },
387 { "src-ip", TOK_SRCIP },
388 { "dst-port", TOK_DSTPORT },
389 { "src-port", TOK_SRCPORT },
390 { "proto", TOK_PROTO },
393 { "mac-type", TOK_MACTYPE },
394 { "verrevpath", TOK_VERREVPATH },
395 { "versrcreach", TOK_VERSRCREACH },
396 { "antispoof", TOK_ANTISPOOF },
397 { "ipsec", TOK_IPSEC },
398 { "icmp6type", TOK_ICMP6TYPES },
399 { "icmp6types", TOK_ICMP6TYPES },
400 { "ext6hdr", TOK_EXT6HDR},
401 { "flow-id", TOK_FLOWID},
406 { "dst-ipv6", TOK_DSTIP6},
407 { "dst-ip6", TOK_DSTIP6},
408 { "src-ipv6", TOK_SRCIP6},
409 { "src-ip6", TOK_SRCIP6},
410 { "//", TOK_COMMENT },
412 { "not", TOK_NOT }, /* pseudo option */
413 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
414 { "or", TOK_OR }, /* pseudo option */
415 { "|", /* escape */ TOK_OR }, /* pseudo option */
416 { "{", TOK_STARTBRACE }, /* pseudo option */
417 { "(", TOK_STARTBRACE }, /* pseudo option */
418 { "}", TOK_ENDBRACE }, /* pseudo option */
419 { ")", TOK_ENDBRACE }, /* pseudo option */
420 { NULL, 0 } /* terminator */
423 #define TABLEARG "tablearg"
425 static __inline uint64_t
426 align_uint64(uint64_t *pll) {
429 bcopy (pll, &ret, sizeof(ret));
434 * conditionally runs the command.
437 do_cmd(int optname, void *optval, uintptr_t optlen)
439 static int s = -1; /* the socket */
446 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
448 err(EX_UNAVAILABLE, "socket");
450 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
451 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
452 optname == IP_FW_TABLE_GETSIZE)
453 i = getsockopt(s, IPPROTO_IP, optname, optval,
454 (socklen_t *)optlen);
456 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
461 * match_token takes a table and a string, returns the value associated
462 * with the string (-1 in case of failure).
465 match_token(struct _s_x *table, char *string)
468 uint i = strlen(string);
470 for (pt = table ; i && pt->s != NULL ; pt++)
471 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
477 * match_value takes a table and a value, returns the string associated
478 * with the value (NULL in case of failure).
481 match_value(struct _s_x *p, int value)
483 for (; p->s != NULL; p++)
490 * _substrcmp takes two strings and returns 1 if they do not match,
491 * and 0 if they match exactly or the first string is a sub-string
492 * of the second. A warning is printed to stderr in the case that the
493 * first string is a sub-string of the second.
495 * This function will be removed in the future through the usual
496 * deprecation process.
499 _substrcmp(const char *str1, const char* str2)
502 if (strncmp(str1, str2, strlen(str1)) != 0)
505 if (strlen(str1) != strlen(str2))
506 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
512 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
513 * and 0 if they match exactly or the second string is a sub-string
514 * of the first. A warning is printed to stderr in the case that the
515 * first string does not match the third.
517 * This function exists to warn about the bizzare construction
518 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
519 * for "bytes". The problem is that in addition to accepting "by",
520 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
521 * other string beginning with "by".
523 * This function will be removed in the future through the usual
524 * deprecation process.
527 _substrcmp2(const char *str1, const char* str2, const char* str3)
530 if (strncmp(str1, str2, strlen(str2)) != 0)
533 if (strcmp(str1, str3) != 0)
534 warnx("DEPRECATED: '%s' matched '%s'",
540 * prints one port, symbolic or numeric
543 print_port(int proto, uint16_t port)
546 if (proto == IPPROTO_ETHERTYPE) {
549 if (do_resolv && (s = match_value(ether_types, port)) )
552 printf("0x%04x", port);
554 struct servent *se = NULL;
556 struct protoent *pe = getprotobynumber(proto);
558 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
561 printf("%s", se->s_name);
567 struct _s_x _port_name[] = {
568 {"dst-port", O_IP_DSTPORT},
569 {"src-port", O_IP_SRCPORT},
573 {"mac-type", O_MAC_TYPE},
574 {"tcpdatalen", O_TCPDATALEN},
579 * Print the values in a list 16-bit items of the types above.
580 * XXX todo: add support for mask.
583 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
585 uint16_t *p = cmd->ports;
589 if (cmd->o.len & F_NOT)
592 sep = match_value(_port_name, opcode);
598 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
600 print_port(proto, p[0]);
603 print_port(proto, p[1]);
610 * Like strtol, but also translates service names into port numbers
611 * for some protocols.
613 * proto == -1 disables the protocol check;
614 * proto == IPPROTO_ETHERTYPE looks up an internal table
615 * proto == <some value in /etc/protocols> matches the values there.
616 * Returns *end == s in case the parameter is not found.
619 strtoport(char *s, char **end, int base, int proto)
625 *end = s; /* default - not found */
627 return 0; /* not found */
630 return strtol(s, end, base);
633 * find separator. '\\' escapes the next char.
635 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
636 if (*s1 == '\\' && s1[1] != '\0')
639 buf = malloc(s1 - s + 1);
644 * copy into a buffer skipping backslashes
646 for (p = s, i = 0; p != s1 ; p++)
651 if (proto == IPPROTO_ETHERTYPE) {
652 i = match_token(ether_types, buf);
654 if (i != -1) { /* found */
659 struct protoent *pe = NULL;
663 pe = getprotobynumber(proto);
665 se = getservbyname(buf, pe ? pe->p_name : NULL);
669 return ntohs(se->s_port);
672 return 0; /* not found */
676 * Map between current altq queue id numbers and names.
678 static int altq_fetched = 0;
679 static TAILQ_HEAD(, pf_altq) altq_entries =
680 TAILQ_HEAD_INITIALIZER(altq_entries);
683 altq_set_enabled(int enabled)
687 pffd = open("/dev/pf", O_RDWR);
690 "altq support opening pf(4) control device");
692 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST)
693 err(EX_UNAVAILABLE, "enabling altq");
695 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT)
696 err(EX_UNAVAILABLE, "disabling altq");
704 struct pfioc_altq pfioc;
705 struct pf_altq *altq;
711 pffd = open("/dev/pf", O_RDONLY);
713 warn("altq support opening pf(4) control device");
716 bzero(&pfioc, sizeof(pfioc));
717 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) {
718 warn("altq support getting queue list");
723 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) {
724 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) {
727 warn("altq support getting queue list");
731 if (pfioc.altq.qid == 0)
733 altq = malloc(sizeof(*altq));
735 err(EX_OSERR, "malloc");
737 TAILQ_INSERT_TAIL(&altq_entries, altq, entries);
743 altq_name_to_qid(const char *name)
745 struct pf_altq *altq;
748 TAILQ_FOREACH(altq, &altq_entries, entries)
749 if (strcmp(name, altq->qname) == 0)
752 errx(EX_DATAERR, "altq has no queue named `%s'", name);
757 altq_qid_to_name(u_int32_t qid)
759 struct pf_altq *altq;
762 TAILQ_FOREACH(altq, &altq_entries, entries)
763 if (qid == altq->qid)
771 fill_altq_qid(u_int32_t *qid, const char *av)
773 *qid = altq_name_to_qid(av);
777 * Fill the body of the command with the list of port ranges.
780 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
782 uint16_t a, b, *p = cmd->ports;
787 a = strtoport(av, &s, 0, proto);
788 if (s == av) /* no parameter */
790 if (*s == '-') { /* a range */
792 b = strtoport(av, &s, 0, proto);
793 if (s == av) /* no parameter */
797 } else if (*s == ',' || *s == '\0' )
799 else /* invalid separator */
800 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n",
807 if (i+1 > F_LEN_MASK)
808 errx(EX_DATAERR, "too many ports/ranges\n");
809 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
814 static struct _s_x icmpcodes[] = {
815 { "net", ICMP_UNREACH_NET },
816 { "host", ICMP_UNREACH_HOST },
817 { "protocol", ICMP_UNREACH_PROTOCOL },
818 { "port", ICMP_UNREACH_PORT },
819 { "needfrag", ICMP_UNREACH_NEEDFRAG },
820 { "srcfail", ICMP_UNREACH_SRCFAIL },
821 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
822 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
823 { "isolated", ICMP_UNREACH_ISOLATED },
824 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
825 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
826 { "tosnet", ICMP_UNREACH_TOSNET },
827 { "toshost", ICMP_UNREACH_TOSHOST },
828 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
829 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
830 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
835 fill_reject_code(u_short *codep, char *str)
840 val = strtoul(str, &s, 0);
841 if (s == str || *s != '\0' || val >= 0x100)
842 val = match_token(icmpcodes, str);
844 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
850 print_reject_code(uint16_t code)
852 char const *s = match_value(icmpcodes, code);
855 printf("unreach %s", s);
857 printf("unreach %u", code);
860 static struct _s_x icmp6codes[] = {
861 { "no-route", ICMP6_DST_UNREACH_NOROUTE },
862 { "admin-prohib", ICMP6_DST_UNREACH_ADMIN },
863 { "address", ICMP6_DST_UNREACH_ADDR },
864 { "port", ICMP6_DST_UNREACH_NOPORT },
869 fill_unreach6_code(u_short *codep, char *str)
874 val = strtoul(str, &s, 0);
875 if (s == str || *s != '\0' || val >= 0x100)
876 val = match_token(icmp6codes, str);
878 errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str);
884 print_unreach6_code(uint16_t code)
886 char const *s = match_value(icmp6codes, code);
889 printf("unreach6 %s", s);
891 printf("unreach6 %u", code);
895 * Returns the number of bits set (from left) in a contiguous bitmask,
896 * or -1 if the mask is not contiguous.
897 * XXX this needs a proper fix.
898 * This effectively works on masks in big-endian (network) format.
899 * when compiled on little endian architectures.
901 * First bit is bit 7 of the first byte -- note, for MAC addresses,
902 * the first bit on the wire is bit 0 of the first byte.
903 * len is the max length in bits.
906 contigmask(uint8_t *p, int len)
910 for (i=0; i<len ; i++)
911 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
913 for (n=i+1; n < len; n++)
914 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
915 return -1; /* mask not contiguous */
920 * print flags set/clear in the two bitmasks passed as parameters.
921 * There is a specialized check for f_tcpflags.
924 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
926 char const *comma = "";
928 uint8_t set = cmd->arg1 & 0xff;
929 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
931 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
936 printf(" %s ", name);
937 for (i=0; list[i].x != 0; i++) {
938 if (set & list[i].x) {
940 printf("%s%s", comma, list[i].s);
943 if (clear & list[i].x) {
945 printf("%s!%s", comma, list[i].s);
952 * Print the ip address contained in a command.
955 print_ip(ipfw_insn_ip *cmd, char const *s)
957 struct hostent *he = NULL;
958 int len = F_LEN((ipfw_insn *)cmd);
959 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
961 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
963 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
967 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
968 cmd->o.opcode == O_IP_DST_LOOKUP) {
969 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
970 if (len == F_INSN_SIZE(ipfw_insn_u32))
975 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
976 uint32_t x, *map = (uint32_t *)&(cmd->mask);
982 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
983 printf("%s/%d", inet_ntoa(cmd->addr),
984 contigmask((uint8_t *)&x, 32));
985 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
986 x &= 0xff; /* base */
988 * Print bits and ranges.
989 * Locate first bit set (i), then locate first bit unset (j).
990 * If we have 3+ consecutive bits set, then print them as a
991 * range, otherwise only print the initial bit and rescan.
993 for (i=0; i < cmd->o.arg1; i++)
994 if (map[i/32] & (1<<(i & 31))) {
995 for (j=i+1; j < cmd->o.arg1; j++)
996 if (!(map[ j/32] & (1<<(j & 31))))
998 printf("%c%d", comma, i+x);
999 if (j>i+2) { /* range has at least 3 elements */
1000 printf("-%d", j-1+x);
1009 * len == 2 indicates a single IP, whereas lists of 1 or more
1010 * addr/mask pairs have len = (2n+1). We convert len to n so we
1011 * use that to count the number of entries.
1013 for (len = len / 2; len > 0; len--, a += 2) {
1014 int mb = /* mask length */
1015 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1016 32 : contigmask((uint8_t *)&(a[1]), 32);
1017 if (mb == 32 && do_resolv)
1018 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1019 if (he != NULL) /* resolved to name */
1020 printf("%s", he->h_name);
1021 else if (mb == 0) /* any */
1023 else { /* numeric IP followed by some kind of mask */
1024 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
1026 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
1036 * prints a MAC address/mask pair
1039 print_mac(uint8_t *addr, uint8_t *mask)
1041 int l = contigmask(mask, 48);
1046 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1047 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1049 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1050 mask[0], mask[1], mask[2],
1051 mask[3], mask[4], mask[5]);
1058 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1067 type = strtoul(av, &av, 0);
1069 if (*av != ',' && *av != '\0')
1070 errx(EX_DATAERR, "invalid ICMP type");
1073 errx(EX_DATAERR, "ICMP type out of range");
1075 cmd->d[0] |= 1 << type;
1077 cmd->o.opcode = O_ICMPTYPE;
1078 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1082 print_icmptypes(ipfw_insn_u32 *cmd)
1087 printf(" icmptypes");
1088 for (i = 0; i < 32; i++) {
1089 if ( (cmd->d[0] & (1 << (i))) == 0)
1091 printf("%c%d", sep, i);
1097 * Print the ip address contained in a command.
1100 print_ip6(ipfw_insn_ip6 *cmd, char const *s)
1102 struct hostent *he = NULL;
1103 int len = F_LEN((ipfw_insn *) cmd) - 1;
1104 struct in6_addr *a = &(cmd->addr6);
1107 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1109 if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) {
1113 if (cmd->o.opcode == O_IP6) {
1119 * len == 4 indicates a single IP, whereas lists of 1 or more
1120 * addr/mask pairs have len = (2n+1). We convert len to n so we
1121 * use that to count the number of entries.
1124 for (len = len / 4; len > 0; len -= 2, a += 2) {
1125 int mb = /* mask length */
1126 (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ?
1127 128 : contigmask((uint8_t *)&(a[1]), 128);
1129 if (mb == 128 && do_resolv)
1130 he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6);
1131 if (he != NULL) /* resolved to name */
1132 printf("%s", he->h_name);
1133 else if (mb == 0) /* any */
1135 else { /* numeric IP followed by some kind of mask */
1136 if (inet_ntop(AF_INET6, a, trad, sizeof( trad ) ) == NULL)
1137 printf("Error ntop in print_ip6\n");
1138 printf("%s", trad );
1139 if (mb < 0) /* XXX not really legal... */
1141 inet_ntop(AF_INET6, &a[1], trad, sizeof(trad)));
1151 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av)
1159 type = strtoul(av, &av, 0);
1160 if (*av != ',' && *av != '\0')
1161 errx(EX_DATAERR, "invalid ICMP6 type");
1163 * XXX: shouldn't this be 0xFF? I can't see any reason why
1164 * we shouldn't be able to filter all possiable values
1165 * regardless of the ability of the rest of the kernel to do
1166 * anything useful with them.
1168 if (type > ICMP6_MAXTYPE)
1169 errx(EX_DATAERR, "ICMP6 type out of range");
1170 cmd->d[type / 32] |= ( 1 << (type % 32));
1172 cmd->o.opcode = O_ICMP6TYPE;
1173 cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6);
1178 print_icmp6types(ipfw_insn_u32 *cmd)
1183 printf(" ip6 icmp6types");
1184 for (i = 0; i < 7; i++)
1185 for (j=0; j < 32; ++j) {
1186 if ( (cmd->d[i] & (1 << (j))) == 0)
1188 printf("%c%d", sep, (i*32 + j));
1194 print_flow6id( ipfw_insn_u32 *cmd)
1196 uint16_t i, limit = cmd->o.arg1;
1199 printf(" flow-id ");
1200 for( i=0; i < limit; ++i) {
1203 printf("%d%c", cmd->d[i], sep);
1207 /* structure and define for the extension header in ipv6 */
1208 static struct _s_x ext6hdrcodes[] = {
1209 { "frag", EXT_FRAGMENT },
1210 { "hopopt", EXT_HOPOPTS },
1211 { "route", EXT_ROUTING },
1212 { "dstopt", EXT_DSTOPTS },
1218 /* fills command for the extension header filtering */
1220 fill_ext6hdr( ipfw_insn *cmd, char *av)
1228 av = strsep( &s, ",") ;
1229 tok = match_token(ext6hdrcodes, av);
1232 cmd->arg1 |= EXT_FRAGMENT;
1236 cmd->arg1 |= EXT_HOPOPTS;
1240 cmd->arg1 |= EXT_ROUTING;
1244 cmd->arg1 |= EXT_DSTOPTS;
1248 cmd->arg1 |= EXT_AH;
1252 cmd->arg1 |= EXT_ESP;
1256 errx( EX_DATAERR, "invalid option for ipv6 exten header" );
1260 if (cmd->arg1 == 0 )
1262 cmd->opcode = O_EXT_HDR;
1263 cmd->len |= F_INSN_SIZE( ipfw_insn );
1268 print_ext6hdr( ipfw_insn *cmd )
1272 printf(" extension header:");
1273 if (cmd->arg1 & EXT_FRAGMENT ) {
1274 printf("%cfragmentation", sep);
1277 if (cmd->arg1 & EXT_HOPOPTS ) {
1278 printf("%chop options", sep);
1281 if (cmd->arg1 & EXT_ROUTING ) {
1282 printf("%crouting options", sep);
1285 if (cmd->arg1 & EXT_DSTOPTS ) {
1286 printf("%cdestination options", sep);
1289 if (cmd->arg1 & EXT_AH ) {
1290 printf("%cauthentication header", sep);
1293 if (cmd->arg1 & EXT_ESP ) {
1294 printf("%cencapsulated security payload", sep);
1299 * show_ipfw() prints the body of an ipfw rule.
1300 * Because the standard rule has at least proto src_ip dst_ip, we use
1301 * a helper function to produce these entries if not provided explicitly.
1302 * The first argument is the list of fields we have, the second is
1303 * the list of fields we want to be printed.
1305 * Special cases if we have provided a MAC header:
1306 * + if the rule does not contain IP addresses/ports, do not print them;
1307 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1309 * Once we have 'have_options', IP header fields are printed as options.
1311 #define HAVE_PROTO 0x0001
1312 #define HAVE_SRCIP 0x0002
1313 #define HAVE_DSTIP 0x0004
1314 #define HAVE_MAC 0x0008
1315 #define HAVE_MACTYPE 0x0010
1316 #define HAVE_PROTO4 0x0040
1317 #define HAVE_PROTO6 0x0080
1318 #define HAVE_OPTIONS 0x8000
1320 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
1322 show_prerequisites(int *flags, int want, int cmd)
1326 if ( (*flags & HAVE_IP) == HAVE_IP)
1327 *flags |= HAVE_OPTIONS;
1329 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC &&
1330 cmd != O_MAC_TYPE) {
1332 * mac-type was optimized out by the compiler,
1336 *flags |= HAVE_MACTYPE | HAVE_OPTIONS;
1339 if ( !(*flags & HAVE_OPTIONS)) {
1340 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
1341 if ( (*flags & HAVE_PROTO4))
1343 else if ( (*flags & HAVE_PROTO6))
1348 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1349 printf(" from any");
1350 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1357 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1359 static int twidth = 0;
1362 char *comment = NULL; /* ptr to comment if we have one */
1363 int proto = 0; /* default */
1364 int flags = 0; /* prerequisites */
1365 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1366 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1367 int or_block = 0; /* we are in an or block */
1368 uint32_t set_disable;
1370 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1372 if (set_disable & (1 << rule->set)) { /* disabled */
1376 printf("# DISABLED ");
1378 printf("%05u ", rule->rulenum);
1380 if (pcwidth>0 || bcwidth>0)
1381 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
1382 bcwidth, align_uint64(&rule->bcnt));
1385 printf("%10u ", rule->timestamp);
1386 else if (do_time == 1) {
1388 time_t t = (time_t)0;
1391 strcpy(timestr, ctime(&t));
1392 *strchr(timestr, '\n') = '\0';
1393 twidth = strlen(timestr);
1395 if (rule->timestamp) {
1396 t = _long_to_time(rule->timestamp);
1398 strcpy(timestr, ctime(&t));
1399 *strchr(timestr, '\n') = '\0';
1400 printf("%s ", timestr);
1402 printf("%*s", twidth, " ");
1407 printf("set %d ", rule->set);
1410 * print the optional "match probability"
1412 if (rule->cmd_len > 0) {
1414 if (cmd->opcode == O_PROB) {
1415 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1416 double d = 1.0 * p->d[0];
1418 d = (d / 0x7fffffff);
1419 printf("prob %f ", d);
1424 * first print actions
1426 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1427 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1428 switch(cmd->opcode) {
1430 printf("check-state");
1431 flags = HAVE_IP; /* avoid printing anything else */
1447 if (cmd->arg1 == ICMP_REJECT_RST)
1449 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1452 print_reject_code(cmd->arg1);
1456 if (cmd->arg1 == ICMP6_UNREACH_RST)
1459 print_unreach6_code(cmd->arg1);
1462 #define PRINT_WITH_ARG(o) \
1463 if (cmd->arg1 == IP_FW_TABLEARG) \
1464 printf("%s tablearg", (o)); \
1466 printf("%s %u", (o), cmd->arg1); \
1470 PRINT_WITH_ARG("skipto");
1472 PRINT_WITH_ARG("pipe");
1474 PRINT_WITH_ARG("queue");
1476 PRINT_WITH_ARG("divert");
1478 PRINT_WITH_ARG("tee");
1480 PRINT_WITH_ARG("netgraph");
1482 PRINT_WITH_ARG("ngtee");
1483 #undef PRINT_WITH_ARG
1487 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1489 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1491 printf(",%d", s->sa.sin_port);
1495 case O_LOG: /* O_LOG is printed last */
1496 logptr = (ipfw_insn_log *)cmd;
1499 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1500 altqptr = (ipfw_insn_altq *)cmd;
1504 printf("** unrecognized action %d len %d ",
1505 cmd->opcode, cmd->len);
1509 if (logptr->max_log > 0)
1510 printf(" log logamount %d", logptr->max_log);
1517 qname = altq_qid_to_name(altqptr->qid);
1519 printf(" altq ?<%u>", altqptr->qid);
1521 printf(" altq %s", qname);
1525 * then print the body.
1527 for (l = rule->act_ofs, cmd = rule->cmd ;
1528 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1529 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1531 if (cmd->opcode == O_IP4) {
1532 flags |= HAVE_PROTO4;
1534 } else if (cmd->opcode == O_IP6) {
1535 flags |= HAVE_PROTO6;
1539 if (rule->_pad & 1) { /* empty rules before options */
1541 show_prerequisites(&flags, HAVE_PROTO, 0);
1542 printf(" from any to any");
1544 flags |= HAVE_IP | HAVE_OPTIONS;
1550 for (l = rule->act_ofs, cmd = rule->cmd ;
1551 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1553 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1556 if (cmd->opcode != O_NOP)
1558 printf(" // %s\n", (char *)(cmd + 1));
1562 show_prerequisites(&flags, 0, cmd->opcode);
1564 switch(cmd->opcode) {
1566 break; /* done already */
1569 break; /* no need to print anything here */
1572 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1574 if ((cmd->len & F_OR) && !or_block)
1576 if (cmd->len & F_NOT)
1580 print_mac(m->addr, m->mask);
1581 print_mac(m->addr + 6, m->mask + 6);
1586 if ((cmd->len & F_OR) && !or_block)
1588 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE,
1589 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1590 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS;
1594 case O_IP_SRC_LOOKUP:
1598 show_prerequisites(&flags, HAVE_PROTO, 0);
1599 if (!(flags & HAVE_SRCIP))
1601 if ((cmd->len & F_OR) && !or_block)
1603 print_ip((ipfw_insn_ip *)cmd,
1604 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1605 flags |= HAVE_SRCIP;
1609 case O_IP_DST_LOOKUP:
1613 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1614 if (!(flags & HAVE_DSTIP))
1616 if ((cmd->len & F_OR) && !or_block)
1618 print_ip((ipfw_insn_ip *)cmd,
1619 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1620 flags |= HAVE_DSTIP;
1624 case O_IP6_SRC_MASK:
1626 show_prerequisites(&flags, HAVE_PROTO, 0);
1627 if (!(flags & HAVE_SRCIP))
1629 if ((cmd->len & F_OR) && !or_block)
1631 print_ip6((ipfw_insn_ip6 *)cmd,
1632 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1633 flags |= HAVE_SRCIP | HAVE_PROTO;
1637 case O_IP6_DST_MASK:
1639 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1640 if (!(flags & HAVE_DSTIP))
1642 if ((cmd->len & F_OR) && !or_block)
1644 print_ip6((ipfw_insn_ip6 *)cmd,
1645 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1646 flags |= HAVE_DSTIP;
1650 print_flow6id( (ipfw_insn_u32 *) cmd );
1651 flags |= HAVE_OPTIONS;
1655 show_prerequisites(&flags, HAVE_IP, 0);
1657 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1658 if ((cmd->len & F_OR) && !or_block)
1660 print_newports((ipfw_insn_u16 *)cmd, proto,
1661 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1665 struct protoent *pe = NULL;
1667 if ((cmd->len & F_OR) && !or_block)
1669 if (cmd->len & F_NOT)
1672 pe = getprotobynumber(cmd->arg1);
1673 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1674 !(flags & HAVE_PROTO))
1675 show_prerequisites(&flags,
1676 HAVE_IP | HAVE_OPTIONS, 0);
1677 if (flags & HAVE_OPTIONS)
1680 printf(" %s", pe->p_name);
1682 printf(" %u", cmd->arg1);
1684 flags |= HAVE_PROTO;
1687 default: /*options ... */
1688 if (!(cmd->len & (F_OR|F_NOT)))
1689 if (((cmd->opcode == O_IP6) &&
1690 (flags & HAVE_PROTO6)) ||
1691 ((cmd->opcode == O_IP4) &&
1692 (flags & HAVE_PROTO4)))
1694 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1695 if ((cmd->len & F_OR) && !or_block)
1697 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1699 switch(cmd->opcode) {
1705 printf(cmd->len & F_NOT ? " out" : " in");
1709 switch (cmd->arg1) {
1711 printf(" diverted");
1714 printf(" diverted-loopback");
1717 printf(" diverted-output");
1720 printf(" diverted-?<%u>", cmd->arg1);
1733 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1735 if (cmd->opcode == O_XMIT)
1737 else if (cmd->opcode == O_RECV)
1739 else /* if (cmd->opcode == O_VIA) */
1741 if (cmdif->name[0] == '\0')
1743 inet_ntoa(cmdif->p.ip));
1745 printf(" %s %s", s, cmdif->name);
1750 if (F_LEN(cmd) == 1)
1751 printf(" ipid %u", cmd->arg1 );
1753 print_newports((ipfw_insn_u16 *)cmd, 0,
1758 if (F_LEN(cmd) == 1)
1759 printf(" ipttl %u", cmd->arg1 );
1761 print_newports((ipfw_insn_u16 *)cmd, 0,
1766 printf(" ipver %u", cmd->arg1 );
1769 case O_IPPRECEDENCE:
1770 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1774 if (F_LEN(cmd) == 1)
1775 printf(" iplen %u", cmd->arg1 );
1777 print_newports((ipfw_insn_u16 *)cmd, 0,
1782 print_flags("ipoptions", cmd, f_ipopts);
1786 print_flags("iptos", cmd, f_iptos);
1790 print_icmptypes((ipfw_insn_u32 *)cmd);
1794 printf(" established");
1798 if (F_LEN(cmd) == 1)
1799 printf(" tcpdatalen %u", cmd->arg1 );
1801 print_newports((ipfw_insn_u16 *)cmd, 0,
1806 print_flags("tcpflags", cmd, f_tcpflags);
1810 print_flags("tcpoptions", cmd, f_tcpopts);
1814 printf(" tcpwin %d", ntohs(cmd->arg1));
1818 printf(" tcpack %d", ntohl(cmd32->d[0]));
1822 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1827 struct passwd *pwd = getpwuid(cmd32->d[0]);
1830 printf(" uid %s", pwd->pw_name);
1832 printf(" uid %u", cmd32->d[0]);
1838 struct group *grp = getgrgid(cmd32->d[0]);
1841 printf(" gid %s", grp->gr_name);
1843 printf(" gid %u", cmd32->d[0]);
1848 printf(" jail %d", cmd32->d[0]);
1852 printf(" verrevpath");
1856 printf(" versrcreach");
1860 printf(" antispoof");
1868 comment = (char *)(cmd + 1);
1872 printf(" keep-state");
1877 struct _s_x *p = limit_masks;
1878 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1879 uint8_t x = c->limit_mask;
1880 char const *comma = " ";
1883 for (; p->x != 0 ; p++)
1884 if ((x & p->x) == p->x) {
1886 printf("%s%s", comma, p->s);
1889 printf(" %d", c->conn_limit);
1902 print_icmp6types((ipfw_insn_u32 *)cmd);
1906 print_ext6hdr( (ipfw_insn *) cmd );
1910 printf(" [opcode %d len %d]",
1911 cmd->opcode, cmd->len);
1914 if (cmd->len & F_OR) {
1917 } else if (or_block) {
1922 show_prerequisites(&flags, HAVE_IP, 0);
1924 printf(" // %s", comment);
1929 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1931 struct protoent *pe;
1936 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1939 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1940 printf("%05d", rulenum);
1941 if (pcwidth>0 || bcwidth>0)
1942 printf(" %*llu %*llu (%ds)", pcwidth,
1943 align_uint64(&d->pcnt), bcwidth,
1944 align_uint64(&d->bcnt), d->expire);
1945 switch (d->dyn_type) {
1946 case O_LIMIT_PARENT:
1947 printf(" PARENT %d", d->count);
1952 case O_KEEP_STATE: /* bidir, no mask */
1957 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1958 printf(" %s", pe->p_name);
1960 printf(" proto %u", d->id.proto);
1962 a.s_addr = htonl(d->id.src_ip);
1963 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1965 a.s_addr = htonl(d->id.dst_ip);
1966 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1971 sort_q(const void *pa, const void *pb)
1973 int rev = (do_sort < 0);
1974 int field = rev ? -do_sort : do_sort;
1976 const struct dn_flow_queue *a = pa;
1977 const struct dn_flow_queue *b = pb;
1981 res = a->len - b->len;
1984 res = a->len_bytes - b->len_bytes;
1987 case 3: /* tot pkts */
1988 res = a->tot_pkts - b->tot_pkts;
1991 case 4: /* tot bytes */
1992 res = a->tot_bytes - b->tot_bytes;
1999 return (int)(rev ? res : -res);
2003 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
2006 int index_printed, indexes = 0;
2008 struct protoent *pe;
2010 if (fs->rq_elements == 0)
2014 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
2016 /* Print IPv4 flows */
2018 for (l = 0; l < fs->rq_elements; l++) {
2021 /* XXX: Should check for IPv4 flows */
2022 if (IS_IP6_FLOW_ID(&(q[l].id)))
2025 if (!index_printed) {
2027 if (indexes > 0) /* currently a no-op */
2031 "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
2032 fs->flow_mask.proto,
2033 fs->flow_mask.src_ip, fs->flow_mask.src_port,
2034 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
2036 printf("BKT Prot ___Source IP/port____ "
2037 "____Dest. IP/port____ "
2038 "Tot_pkt/bytes Pkt/Byte Drp\n");
2041 printf("%3d ", q[l].hash_slot);
2042 pe = getprotobynumber(q[l].id.proto);
2044 printf("%-4s ", pe->p_name);
2046 printf("%4u ", q[l].id.proto);
2047 ina.s_addr = htonl(q[l].id.src_ip);
2048 printf("%15s/%-5d ",
2049 inet_ntoa(ina), q[l].id.src_port);
2050 ina.s_addr = htonl(q[l].id.dst_ip);
2051 printf("%15s/%-5d ",
2052 inet_ntoa(ina), q[l].id.dst_port);
2053 printf("%4qu %8qu %2u %4u %3u\n",
2054 q[l].tot_pkts, q[l].tot_bytes,
2055 q[l].len, q[l].len_bytes, q[l].drops);
2057 printf(" S %20qd F %20qd\n",
2061 /* Print IPv6 flows */
2063 for (l = 0; l < fs->rq_elements; l++) {
2064 if (!IS_IP6_FLOW_ID(&(q[l].id)))
2067 if (!index_printed) {
2072 printf("\n mask: proto: 0x%02x, flow_id: 0x%08x, ",
2073 fs->flow_mask.proto, fs->flow_mask.flow_id6);
2074 inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
2075 buff, sizeof(buff));
2076 printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
2077 inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
2078 buff, sizeof(buff) );
2079 printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
2081 printf("BKT ___Prot___ _flow-id_ "
2082 "______________Source IPv6/port_______________ "
2083 "_______________Dest. IPv6/port_______________ "
2084 "Tot_pkt/bytes Pkt/Byte Drp\n");
2086 printf("%3d ", q[l].hash_slot);
2087 pe = getprotobynumber(q[l].id.proto);
2089 printf("%9s ", pe->p_name);
2091 printf("%9u ", q[l].id.proto);
2092 printf("%7d %39s/%-5d ", q[l].id.flow_id6,
2093 inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
2095 printf(" %39s/%-5d ",
2096 inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
2098 printf(" %4qu %8qu %2u %4u %3u\n",
2099 q[l].tot_pkts, q[l].tot_bytes,
2100 q[l].len, q[l].len_bytes, q[l].drops);
2102 printf(" S %20qd F %20qd\n", q[l].S, q[l].F);
2107 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
2112 char red[90]; /* Display RED parameters */
2115 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
2117 sprintf(qs, "%d KB", l / 1024);
2119 sprintf(qs, "%d B", l);
2121 sprintf(qs, "%3d sl.", l);
2123 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
2126 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
2128 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
2129 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
2130 1.0 * fs->w_q / (double)(1 << SCALE_RED),
2131 SCALE_VAL(fs->min_th),
2132 SCALE_VAL(fs->max_th),
2133 1.0 * fs->max_p / (double)(1 << SCALE_RED));
2135 sprintf(red, "droptail");
2137 printf("%s %s%s %d queues (%d buckets) %s\n",
2138 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
2142 list_pipes(void *data, uint nbytes, int ac, char *av[])
2146 struct dn_pipe *p = (struct dn_pipe *) data;
2147 struct dn_flow_set *fs;
2148 struct dn_flow_queue *q;
2152 rulenum = strtoul(*av++, NULL, 10);
2155 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
2156 double b = p->bandwidth;
2160 if (p->next.sle_next != (struct dn_pipe *)DN_IS_PIPE)
2161 break; /* done with pipes, now queues */
2164 * compute length, as pipe have variable size
2166 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
2167 next = (char *)p + l;
2170 if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2)
2174 * Print rate (or clocking interface)
2176 if (p->if_name[0] != '\0')
2177 sprintf(buf, "%s", p->if_name);
2179 sprintf(buf, "unlimited");
2180 else if (b >= 1000000)
2181 sprintf(buf, "%7.3f Mbit/s", b/1000000);
2183 sprintf(buf, "%7.3f Kbit/s", b/1000);
2185 sprintf(buf, "%7.3f bit/s ", b);
2187 sprintf(prefix, "%05d: %s %4d ms ",
2188 p->pipe_nr, buf, p->delay);
2189 print_flowset_parms(&(p->fs), prefix);
2191 printf(" V %20qd\n", p->V >> MY_M);
2193 q = (struct dn_flow_queue *)(p+1);
2194 list_queues(&(p->fs), q);
2196 for (fs = next; nbytes >= sizeof *fs; fs = next) {
2199 if (fs->next.sle_next != (struct dn_flow_set *)DN_IS_QUEUE)
2201 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
2202 next = (char *)fs + l;
2205 if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) ||
2206 (rulenum != fs->parent_nr && do_pipe == 1))) {
2210 q = (struct dn_flow_queue *)(fs+1);
2211 sprintf(prefix, "q%05d: weight %d pipe %d ",
2212 fs->fs_nr, fs->weight, fs->parent_nr);
2213 print_flowset_parms(fs, prefix);
2219 * This one handles all set-related commands
2220 * ipfw set { show | enable | disable }
2222 * ipfw set move X to Y
2223 * ipfw set move rule X to Y
2226 sets_handler(int ac, char *av[])
2228 uint32_t set_disable, masks[2];
2231 uint8_t cmd, new_set;
2237 errx(EX_USAGE, "set needs command");
2238 if (_substrcmp(*av, "show") == 0) {
2242 nbytes = sizeof(struct ip_fw);
2243 if ((data = calloc(1, nbytes)) == NULL)
2244 err(EX_OSERR, "calloc");
2245 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2246 err(EX_OSERR, "getsockopt(IP_FW_GET)");
2247 bcopy(&((struct ip_fw *)data)->next_rule,
2248 &set_disable, sizeof(set_disable));
2250 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2251 if ((set_disable & (1<<i))) {
2252 printf("%s %d", msg, i);
2255 msg = (set_disable) ? " enable" : "enable";
2256 for (i = 0; i < RESVD_SET; i++)
2257 if (!(set_disable & (1<<i))) {
2258 printf("%s %d", msg, i);
2262 } else if (_substrcmp(*av, "swap") == 0) {
2265 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2266 rulenum = atoi(av[0]);
2267 new_set = atoi(av[1]);
2268 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2269 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2270 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2271 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2272 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2273 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2274 } else if (_substrcmp(*av, "move") == 0) {
2276 if (ac && _substrcmp(*av, "rule") == 0) {
2281 if (ac != 3 || _substrcmp(av[1], "to") != 0)
2282 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2283 rulenum = atoi(av[0]);
2284 new_set = atoi(av[2]);
2285 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2286 (cmd == 2 && rulenum == 65535) )
2287 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2288 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2289 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2290 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2291 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2292 } else if (_substrcmp(*av, "disable") == 0 ||
2293 _substrcmp(*av, "enable") == 0 ) {
2294 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2297 masks[0] = masks[1] = 0;
2300 if (isdigit(**av)) {
2302 if (i < 0 || i > RESVD_SET)
2304 "invalid set number %d\n", i);
2305 masks[which] |= (1<<i);
2306 } else if (_substrcmp(*av, "disable") == 0)
2308 else if (_substrcmp(*av, "enable") == 0)
2312 "invalid set command %s\n", *av);
2315 if ( (masks[0] & masks[1]) != 0 )
2317 "cannot enable and disable the same set\n");
2319 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2321 warn("set enable/disable: setsockopt(IP_FW_DEL)");
2323 errx(EX_USAGE, "invalid set command %s\n", *av);
2327 sysctl_handler(int ac, char *av[], int which)
2333 warnx("missing keyword to enable/disable\n");
2334 } else if (_substrcmp(*av, "firewall") == 0) {
2335 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2336 &which, sizeof(which));
2337 } else if (_substrcmp(*av, "one_pass") == 0) {
2338 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2339 &which, sizeof(which));
2340 } else if (_substrcmp(*av, "debug") == 0) {
2341 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2342 &which, sizeof(which));
2343 } else if (_substrcmp(*av, "verbose") == 0) {
2344 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2345 &which, sizeof(which));
2346 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2347 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2348 &which, sizeof(which));
2349 } else if (_substrcmp(*av, "altq") == 0) {
2350 altq_set_enabled(which);
2352 warnx("unrecognize enable/disable keyword: %s\n", *av);
2357 list(int ac, char *av[], int show_counters)
2360 ipfw_dyn_rule *dynrules, *d;
2362 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
2365 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2366 int exitval = EX_OK;
2373 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2374 int nalloc = 1024; /* start somewhere... */
2379 fprintf(stderr, "Testing only, list disabled\n");
2386 /* get rules or pipes from kernel, resizing array as necessary */
2389 while (nbytes >= nalloc) {
2390 nalloc = nalloc * 2 + 200;
2392 if ((data = realloc(data, nbytes)) == NULL)
2393 err(EX_OSERR, "realloc");
2394 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2395 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2396 do_pipe ? "DUMMYNET" : "FW");
2400 list_pipes(data, nbytes, ac, av);
2405 * Count static rules. They have variable size so we
2406 * need to scan the list to count them.
2408 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2409 r->rulenum < 65535 && (char *)r < lim;
2410 ++nstat, r = NEXT(r) )
2414 * Count dynamic rules. This is easier as they have
2418 dynrules = (ipfw_dyn_rule *)r ;
2419 n = (char *)r - (char *)data;
2420 ndyn = (nbytes - n) / sizeof *dynrules;
2422 /* if showing stats, figure out column widths ahead of time */
2423 bcwidth = pcwidth = 0;
2424 if (show_counters) {
2425 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2426 /* packet counter */
2427 width = snprintf(NULL, 0, "%llu",
2428 align_uint64(&r->pcnt));
2429 if (width > pcwidth)
2433 width = snprintf(NULL, 0, "%llu",
2434 align_uint64(&r->bcnt));
2435 if (width > bcwidth)
2439 if (do_dynamic && ndyn) {
2440 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2441 width = snprintf(NULL, 0, "%llu",
2442 align_uint64(&d->pcnt));
2443 if (width > pcwidth)
2446 width = snprintf(NULL, 0, "%llu",
2447 align_uint64(&d->bcnt));
2448 if (width > bcwidth)
2452 /* if no rule numbers were specified, list all rules */
2454 for (n = 0, r = data; n < nstat; n++, r = NEXT(r) )
2455 show_ipfw(r, pcwidth, bcwidth);
2457 if (do_dynamic && ndyn) {
2458 printf("## Dynamic rules (%d):\n", ndyn);
2459 for (n = 0, d = dynrules; n < ndyn; n++, d++)
2460 show_dyn_ipfw(d, pcwidth, bcwidth);
2465 /* display specific rules requested on command line */
2467 for (lac = ac, lav = av; lac != 0; lac--) {
2468 /* convert command line rule # */
2469 last = rnum = strtoul(*lav++, &endptr, 10);
2471 last = strtoul(endptr+1, &endptr, 10);
2474 warnx("invalid rule number: %s", *(lav - 1));
2477 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2478 if (r->rulenum > last)
2480 if (r->rulenum >= rnum && r->rulenum <= last) {
2481 show_ipfw(r, pcwidth, bcwidth);
2486 /* give precedence to other error(s) */
2487 if (exitval == EX_OK)
2488 exitval = EX_UNAVAILABLE;
2489 warnx("rule %lu does not exist", rnum);
2493 if (do_dynamic && ndyn) {
2494 printf("## Dynamic rules:\n");
2495 for (lac = ac, lav = av; lac != 0; lac--) {
2496 last = rnum = strtoul(*lav++, &endptr, 10);
2498 last = strtoul(endptr+1, &endptr, 10);
2500 /* already warned */
2502 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2505 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2508 if (r->rulenum >= rnum && r->rulenum <= last)
2509 show_dyn_ipfw(d, pcwidth, bcwidth);
2519 if (exitval != EX_OK)
2527 fprintf(stderr, "usage: ipfw [options]\n"
2528 "do \"ipfw -h\" or see ipfw manpage for details\n"
2537 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n"
2538 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n"
2539 "add [num] [set N] [prob x] RULE-BODY\n"
2540 "{pipe|queue} N config PIPE-BODY\n"
2541 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
2542 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
2543 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
2545 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
2546 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n"
2547 " skipto N | {divert|tee} PORT | forward ADDR |\n"
2548 " pipe N | queue N\n"
2549 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
2550 "ADDR: [ MAC dst src ether_type ] \n"
2551 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
2552 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
2553 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
2554 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
2555 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
2556 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
2557 "OPTION_LIST: OPTION [OPTION_LIST]\n"
2558 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
2559 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
2560 " {dst-port|src-port} LIST |\n"
2561 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
2562 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
2563 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
2564 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] |\n"
2565 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
2566 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
2567 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
2574 lookup_host (char *host, struct in_addr *ipaddr)
2578 if (!inet_aton(host, ipaddr)) {
2579 if ((he = gethostbyname(host)) == NULL)
2581 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2587 * fills the addr and mask fields in the instruction as appropriate from av.
2588 * Update length as appropriate.
2589 * The following formats are allowed:
2590 * me returns O_IP_*_ME
2591 * 1.2.3.4 single IP address
2592 * 1.2.3.4:5.6.7.8 address:mask
2593 * 1.2.3.4/24 address/mask
2594 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2595 * We can have multiple comma-separated address/mask entries.
2598 fill_ip(ipfw_insn_ip *cmd, char *av)
2601 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2603 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2605 if (_substrcmp(av, "any") == 0)
2608 if (_substrcmp(av, "me") == 0) {
2609 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2613 if (strncmp(av, "table(", 6) == 0) {
2614 char *p = strchr(av + 6, ',');
2618 cmd->o.opcode = O_IP_DST_LOOKUP;
2619 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2621 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2622 d[0] = strtoul(p, NULL, 0);
2624 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2630 * After the address we can have '/' or ':' indicating a mask,
2631 * ',' indicating another address follows, '{' indicating a
2632 * set of addresses of unspecified size.
2634 char *p = strpbrk(av, "/:,{");
2644 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2645 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2648 if (!inet_aton(p, (struct in_addr *)&d[1]))
2649 errx(EX_DATAERR, "bad netmask ``%s''", p);
2654 d[1] = htonl(0); /* mask */
2655 else if (masklen > 32)
2656 errx(EX_DATAERR, "bad width ``%s''", p);
2658 d[1] = htonl(~0 << (32 - masklen));
2660 case '{': /* no mask, assume /24 and put back the '{' */
2661 d[1] = htonl(~0 << (32 - 24));
2665 case ',': /* single address plus continuation */
2668 case 0: /* initialization value */
2670 d[1] = htonl(~0); /* force /32 */
2673 d[0] &= d[1]; /* mask base address with mask */
2674 /* find next separator */
2676 p = strpbrk(p, ",{");
2677 if (p && *p == '{') {
2679 * We have a set of addresses. They are stored as follows:
2680 * arg1 is the set size (powers of 2, 2..256)
2681 * addr is the base address IN HOST FORMAT
2682 * mask.. is an array of arg1 bits (rounded up to
2683 * the next multiple of 32) with bits set
2684 * for each host in the map.
2686 uint32_t *map = (uint32_t *)&cmd->mask;
2688 int i = contigmask((uint8_t *)&(d[1]), 32);
2691 errx(EX_DATAERR, "address set cannot be in a list");
2692 if (i < 24 || i > 31)
2693 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2694 cmd->o.arg1 = 1<<(32-i); /* map length */
2695 d[0] = ntohl(d[0]); /* base addr in host format */
2696 cmd->o.opcode = O_IP_DST_SET; /* default */
2697 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2698 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2699 map[i] = 0; /* clear map */
2703 high = low + cmd->o.arg1 - 1;
2705 * Here, i stores the previous value when we specify a range
2706 * of addresses within a mask, e.g. 45-63. i = -1 means we
2707 * have no previous value.
2709 i = -1; /* previous value in a range */
2710 while (isdigit(*av)) {
2712 int a = strtol(av, &s, 0);
2714 if (s == av) { /* no parameter */
2716 errx(EX_DATAERR, "set not closed\n");
2718 errx(EX_DATAERR, "incomplete range %d-", i);
2721 if (a < low || a > high)
2722 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2725 if (i == -1) /* no previous in range */
2727 else { /* check that range is valid */
2729 errx(EX_DATAERR, "invalid range %d-%d",
2732 errx(EX_DATAERR, "double '-' in range");
2735 map[i/32] |= 1<<(i & 31);
2746 if (av) /* then *av must be a ',' */
2749 /* Check this entry */
2750 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2752 * 'any' turns the entire list into a NOP.
2753 * 'not any' never matches, so it is removed from the
2754 * list unless it is the only item, in which case we
2757 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2758 if (av == NULL && len == 0) /* only this entry */
2759 errx(EX_DATAERR, "not any never matches");
2761 /* else do nothing and skip this entry */
2764 /* A single IP can be stored in an optimized format */
2765 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) {
2766 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2769 len += 2; /* two words... */
2772 cmd->o.len |= len+1;
2776 /* Try to find ipv6 address by hostname */
2778 lookup_host6 (char *host, struct in6_addr *ip6addr)
2782 if (!inet_pton(AF_INET6, host, ip6addr)) {
2783 if ((he = gethostbyname2(host, AF_INET6)) == NULL)
2785 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr));
2791 /* n2mask sets n bits of the mask */
2793 n2mask(struct in6_addr *mask, int n)
2795 static int minimask[9] =
2796 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2799 memset(mask, 0, sizeof(struct in6_addr));
2800 p = (u_char *) mask;
2801 for (; n > 0; p++, n -= 8) {
2812 * fill the addr and mask fields in the instruction as appropriate from av.
2813 * Update length as appropriate.
2814 * The following formats are allowed:
2815 * any matches any IP6. Actually returns an empty instruction.
2816 * me returns O_IP6_*_ME
2818 * 03f1::234:123:0342 single IP6 addres
2819 * 03f1::234:123:0342/24 address/mask
2820 * 03f1::234:123:0342/24,03f1::234:123:0343/ List of address
2822 * Set of address (as in ipv6) not supported because ipv6 address
2823 * are typically random past the initial prefix.
2824 * Return 1 on success, 0 on failure.
2827 fill_ip6(ipfw_insn_ip6 *cmd, char *av)
2830 struct in6_addr *d = &(cmd->addr6);
2832 * Needed for multiple address.
2833 * Note d[1] points to struct in6_add r mask6 of cmd
2836 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2838 if (strcmp(av, "any") == 0)
2842 if (strcmp(av, "me") == 0) { /* Set the data for "me" opt*/
2843 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2847 if (strcmp(av, "me6") == 0) { /* Set the data for "me" opt*/
2848 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2855 * After the address we can have '/' indicating a mask,
2856 * or ',' indicating another address follows.
2863 if ((p = strpbrk(av, "/,")) ) {
2864 md = *p; /* save the separator */
2865 *p = '\0'; /* terminate address string */
2866 p++; /* and skip past it */
2868 /* now p points to NULL, mask or next entry */
2870 /* lookup stores address in *d as a side effect */
2871 if (lookup_host6(av, d) != 0) {
2872 /* XXX: failed. Free memory and go */
2873 errx(EX_DATAERR, "bad address \"%s\"", av);
2875 /* next, look at the mask, if any */
2876 masklen = (md == '/') ? atoi(p) : 128;
2877 if (masklen > 128 || masklen < 0)
2878 errx(EX_DATAERR, "bad width \"%s\''", p);
2880 n2mask(&d[1], masklen);
2882 APPLY_MASK(d, &d[1]) /* mask base address with mask */
2884 /* find next separator */
2886 if (md == '/') { /* find separator past the mask */
2887 p = strpbrk(p, ",");
2893 /* Check this entry */
2896 * 'any' turns the entire list into a NOP.
2897 * 'not any' never matches, so it is removed from the
2898 * list unless it is the only item, in which case we
2901 if (cmd->o.len & F_NOT && av == NULL && len == 0)
2902 errx(EX_DATAERR, "not any never matches");
2907 * A single IP can be stored alone
2909 if (masklen == 128 && av == NULL && len == 0) {
2910 len = F_INSN_SIZE(struct in6_addr);
2914 /* Update length and pointer to arguments */
2915 len += F_INSN_SIZE(struct in6_addr)*2;
2920 * Total length of the command, remember that 1 is the size of
2923 cmd->o.len |= len+1;
2929 * fills command for ipv6 flow-id filtering
2930 * note that the 20 bit flow number is stored in a array of u_int32_t
2931 * it's supported lists of flow-id, so in the o.arg1 we store how many
2932 * additional flow-id we want to filter, the basic is 1
2935 fill_flow6( ipfw_insn_u32 *cmd, char *av )
2937 u_int32_t type; /* Current flow number */
2938 u_int16_t nflow = 0; /* Current flow index */
2940 cmd->d[0] = 0; /* Initializing the base number*/
2943 av = strsep( &s, ",") ;
2944 type = strtoul(av, &av, 0);
2945 if (*av != ',' && *av != '\0')
2946 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
2948 errx(EX_DATAERR, "flow number out of range %s", av);
2949 cmd->d[nflow] |= type;
2953 cmd->o.opcode = O_FLOW6ID;
2954 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow;
2955 cmd->o.arg1 = nflow;
2958 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
2963 add_srcip6(ipfw_insn *cmd, char *av)
2966 fill_ip6((ipfw_insn_ip6 *)cmd, av);
2967 if (F_LEN(cmd) == 0) /* any */
2969 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
2970 cmd->opcode = O_IP6_SRC_ME;
2971 } else if (F_LEN(cmd) ==
2972 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
2973 /* single IP, no mask*/
2974 cmd->opcode = O_IP6_SRC;
2975 } else { /* addr/mask opt */
2976 cmd->opcode = O_IP6_SRC_MASK;
2982 add_dstip6(ipfw_insn *cmd, char *av)
2985 fill_ip6((ipfw_insn_ip6 *)cmd, av);
2986 if (F_LEN(cmd) == 0) /* any */
2988 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
2989 cmd->opcode = O_IP6_DST_ME;
2990 } else if (F_LEN(cmd) ==
2991 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
2992 /* single IP, no mask*/
2993 cmd->opcode = O_IP6_DST;
2994 } else { /* addr/mask opt */
2995 cmd->opcode = O_IP6_DST_MASK;
3002 * helper function to process a set of flags and set bits in the
3003 * appropriate masks.
3006 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3007 struct _s_x *flags, char *p)
3009 uint8_t set=0, clear=0;
3012 char *q; /* points to the separator */
3014 uint8_t *which; /* mask we are working on */
3024 val = match_token(flags, p);
3026 errx(EX_DATAERR, "invalid flag %s", p);
3027 *which |= (uint8_t)val;
3030 cmd->opcode = opcode;
3031 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3032 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3037 delete(int ac, char *av[])
3042 int exitval = EX_OK;
3045 memset(&p, 0, sizeof p);
3048 NEED1("missing rule specification");
3049 if (ac > 0 && _substrcmp(*av, "set") == 0) {
3050 do_set = 1; /* delete set */
3055 while (ac && isdigit(**av)) {
3056 i = atoi(*av); av++; ac--;
3062 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
3065 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
3066 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
3069 rulenum = (i & 0xffff) | (do_set << 24);
3070 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
3072 exitval = EX_UNAVAILABLE;
3073 warn("rule %u: setsockopt(IP_FW_DEL)",
3078 if (exitval != EX_OK)
3084 * fill the interface structure. We do not check the name as we can
3085 * create interfaces dynamically, so checking them at insert time
3086 * makes relatively little sense.
3087 * Interface names containing '*', '?', or '[' are assumed to be shell
3088 * patterns which match interfaces.
3091 fill_iface(ipfw_insn_if *cmd, char *arg)
3093 cmd->name[0] = '\0';
3094 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3096 /* Parse the interface or address */
3097 if (strcmp(arg, "any") == 0)
3098 cmd->o.len = 0; /* effectively ignore this command */
3099 else if (!isdigit(*arg)) {
3100 strlcpy(cmd->name, arg, sizeof(cmd->name));
3101 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3102 } else if (!inet_aton(arg, &cmd->p.ip))
3103 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3107 config_pipe(int ac, char **av)
3114 memset(&p, 0, sizeof p);
3118 if (ac && isdigit(**av)) {
3119 i = atoi(*av); av++; ac--;
3127 int tok = match_token(dummynet_params, *av);
3132 p.fs.flags_fs |= DN_NOERROR;
3136 NEED1("plr needs argument 0..1\n");
3137 d = strtod(av[0], NULL);
3142 p.fs.plr = (int)(d*0x7fffffff);
3147 NEED1("queue needs queue size\n");
3149 p.fs.qsize = strtoul(av[0], &end, 0);
3150 if (*end == 'K' || *end == 'k') {
3151 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
3153 } else if (*end == 'B' ||
3154 _substrcmp2(end, "by", "bytes") == 0) {
3155 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
3161 NEED1("buckets needs argument\n");
3162 p.fs.rq_size = strtoul(av[0], NULL, 0);
3167 NEED1("mask needs mask specifier\n");
3169 * per-flow queue, mask is dst_ip, dst_port,
3170 * src_ip, src_port, proto measured in bits
3174 bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
3178 uint32_t *p32 = NULL;
3179 uint16_t *p16 = NULL;
3180 uint32_t *p20 = NULL;
3181 struct in6_addr *pa6 = NULL;
3184 tok = match_token(dummynet_params, *av);
3189 * special case, all bits significant
3191 p.fs.flow_mask.dst_ip = ~0;
3192 p.fs.flow_mask.src_ip = ~0;
3193 p.fs.flow_mask.dst_port = ~0;
3194 p.fs.flow_mask.src_port = ~0;
3195 p.fs.flow_mask.proto = ~0;
3196 n2mask(&(p.fs.flow_mask.dst_ip6), 128);
3197 n2mask(&(p.fs.flow_mask.src_ip6), 128);
3198 p.fs.flow_mask.flow_id6 = ~0;
3199 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
3203 p32 = &p.fs.flow_mask.dst_ip;
3207 p32 = &p.fs.flow_mask.src_ip;
3211 pa6 = &(p.fs.flow_mask.dst_ip6);
3215 pa6 = &(p.fs.flow_mask.src_ip6);
3219 p20 = &p.fs.flow_mask.flow_id6;
3223 p16 = &p.fs.flow_mask.dst_port;
3227 p16 = &p.fs.flow_mask.src_port;
3234 ac++; av--; /* backtrack */
3238 errx(EX_USAGE, "mask: value missing");
3239 if (*av[0] == '/') {
3240 a = strtoul(av[0]+1, &end, 0);
3242 a = (a == 32) ? ~0 : (1 << a) - 1;
3244 a = strtoul(av[0], &end, 0);
3247 else if (p16 != NULL) {
3250 "port mask must be 16 bit");
3252 } else if (p20 != NULL) {
3255 "flow_id mask must be 20 bit");
3257 } else if (pa6 != NULL) {
3258 if (a < 0 || a > 128)
3260 "in6addr invalid mask len");
3266 "proto mask must be 8 bit");
3267 p.fs.flow_mask.proto = (uint8_t)a;
3270 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
3272 } /* end while, config masks */
3278 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
3279 p.fs.flags_fs |= DN_IS_RED;
3280 if (tok == TOK_GRED)
3281 p.fs.flags_fs |= DN_IS_GENTLE_RED;
3283 * the format for parameters is w_q/min_th/max_th/max_p
3285 if ((end = strsep(&av[0], "/"))) {
3286 double w_q = strtod(end, NULL);
3287 if (w_q > 1 || w_q <= 0)
3288 errx(EX_DATAERR, "0 < w_q <= 1");
3289 p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
3291 if ((end = strsep(&av[0], "/"))) {
3292 p.fs.min_th = strtoul(end, &end, 0);
3293 if (*end == 'K' || *end == 'k')
3294 p.fs.min_th *= 1024;
3296 if ((end = strsep(&av[0], "/"))) {
3297 p.fs.max_th = strtoul(end, &end, 0);
3298 if (*end == 'K' || *end == 'k')
3299 p.fs.max_th *= 1024;
3301 if ((end = strsep(&av[0], "/"))) {
3302 double max_p = strtod(end, NULL);
3303 if (max_p > 1 || max_p <= 0)
3304 errx(EX_DATAERR, "0 < max_p <= 1");
3305 p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
3311 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
3315 NEED1("bw needs bandwidth or interface\n");
3317 errx(EX_DATAERR, "bandwidth only valid for pipes");
3319 * set clocking interface or bandwidth value
3321 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
3322 int l = sizeof(p.if_name)-1;
3323 /* interface name */
3324 strncpy(p.if_name, av[0], l);
3325 p.if_name[l] = '\0';
3328 p.if_name[0] = '\0';
3329 p.bandwidth = strtoul(av[0], &end, 0);
3330 if (*end == 'K' || *end == 'k') {
3332 p.bandwidth *= 1000;
3333 } else if (*end == 'M') {
3335 p.bandwidth *= 1000000;
3338 _substrcmp2(end, "by", "bytes") == 0)
3340 if (p.bandwidth < 0)
3341 errx(EX_DATAERR, "bandwidth too large");
3348 errx(EX_DATAERR, "delay only valid for pipes");
3349 NEED1("delay needs argument 0..10000ms\n");
3350 p.delay = strtoul(av[0], NULL, 0);
3356 errx(EX_DATAERR,"weight only valid for queues");
3357 NEED1("weight needs argument 0..100\n");
3358 p.fs.weight = strtoul(av[0], &end, 0);
3364 errx(EX_DATAERR,"pipe only valid for queues");
3365 NEED1("pipe needs pipe_number\n");
3366 p.fs.parent_nr = strtoul(av[0], &end, 0);
3371 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
3376 errx(EX_DATAERR, "pipe_nr must be > 0");
3377 if (p.delay > 10000)
3378 errx(EX_DATAERR, "delay must be < 10000");
3379 } else { /* do_pipe == 2, queue */
3380 if (p.fs.parent_nr == 0)
3381 errx(EX_DATAERR, "pipe must be > 0");
3382 if (p.fs.weight >100)
3383 errx(EX_DATAERR, "weight must be <= 100");
3385 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
3386 if (p.fs.qsize > 1024*1024)
3387 errx(EX_DATAERR, "queue size must be < 1MB");
3389 if (p.fs.qsize > 100)
3390 errx(EX_DATAERR, "2 <= queue size <= 100");
3392 if (p.fs.flags_fs & DN_IS_RED) {
3394 int lookup_depth, avg_pkt_size;
3395 double s, idle, weight, w_q;
3396 struct clockinfo ck;
3399 if (p.fs.min_th >= p.fs.max_th)
3400 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
3401 p.fs.min_th, p.fs.max_th);
3402 if (p.fs.max_th == 0)
3403 errx(EX_DATAERR, "max_th must be > 0");
3406 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
3407 &lookup_depth, &len, NULL, 0) == -1)
3409 errx(1, "sysctlbyname(\"%s\")",
3410 "net.inet.ip.dummynet.red_lookup_depth");
3411 if (lookup_depth == 0)
3412 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
3413 " must be greater than zero");
3416 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
3417 &avg_pkt_size, &len, NULL, 0) == -1)
3419 errx(1, "sysctlbyname(\"%s\")",
3420 "net.inet.ip.dummynet.red_avg_pkt_size");
3421 if (avg_pkt_size == 0)
3423 "net.inet.ip.dummynet.red_avg_pkt_size must"
3424 " be greater than zero");
3426 len = sizeof(struct clockinfo);
3427 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
3428 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
3431 * Ticks needed for sending a medium-sized packet.
3432 * Unfortunately, when we are configuring a WF2Q+ queue, we
3433 * do not have bandwidth information, because that is stored
3434 * in the parent pipe, and also we have multiple queues
3435 * competing for it. So we set s=0, which is not very
3436 * correct. But on the other hand, why do we want RED with
3439 if (p.bandwidth==0) /* this is a WF2Q+ queue */
3442 s = ck.hz * avg_pkt_size * 8 / p.bandwidth;
3445 * max idle time (in ticks) before avg queue size becomes 0.
3446 * NOTA: (3/w_q) is approx the value x so that
3447 * (1-w_q)^x < 10^-3.
3449 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
3450 idle = s * 3. / w_q;
3451 p.fs.lookup_step = (int)idle / lookup_depth;
3452 if (!p.fs.lookup_step)
3453 p.fs.lookup_step = 1;
3455 for (t = p.fs.lookup_step; t > 0; --t)
3457 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
3459 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
3461 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
3465 get_mac_addr_mask(char *p, uint8_t *addr, uint8_t *mask)
3470 addr[i] = mask[i] = 0;
3471 if (strcmp(p, "any") == 0)
3474 for (i=0; *p && i<6;i++, p++) {
3475 addr[i] = strtol(p, &p, 16);
3476 if (*p != ':') /* we start with the mask */
3479 if (*p == '/') { /* mask len */
3480 l = strtol(p+1, &p, 0);
3481 for (i=0; l>0; l -=8, i++)
3482 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
3483 } else if (*p == '&') { /* mask */
3484 for (i=0, p++; *p && i<6;i++, p++) {
3485 mask[i] = strtol(p, &p, 16);
3489 } else if (*p == '\0') {
3498 * helper function, updates the pointer to cmd with the length
3499 * of the current command, and also cleans up the first word of
3500 * the new command in case it has been clobbered before.
3503 next_cmd(ipfw_insn *cmd)
3506 bzero(cmd, sizeof(*cmd));
3511 * Takes arguments and copies them into a comment
3514 fill_comment(ipfw_insn *cmd, int ac, char **av)
3517 char *p = (char *)(cmd + 1);
3519 cmd->opcode = O_NOP;
3520 cmd->len = (cmd->len & (F_NOT | F_OR));
3522 /* Compute length of comment string. */
3523 for (i = 0, l = 0; i < ac; i++)
3524 l += strlen(av[i]) + 1;
3529 "comment too long (max 80 chars)");
3531 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3532 for (i = 0; i < ac; i++) {
3541 * A function to fill simple commands of size 1.
3542 * Existing flags are preserved.
3545 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3547 cmd->opcode = opcode;
3548 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3553 * Fetch and add the MAC address and type, with masks. This generates one or
3554 * two microinstructions, and returns the pointer to the last one.
3557 add_mac(ipfw_insn *cmd, int ac, char *av[])
3562 errx(EX_DATAERR, "MAC dst src");
3564 cmd->opcode = O_MACADDR2;
3565 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3567 mac = (ipfw_insn_mac *)cmd;
3568 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3569 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
3574 add_mactype(ipfw_insn *cmd, int ac, char *av)
3577 errx(EX_DATAERR, "missing MAC type");
3578 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3579 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
3580 cmd->opcode = O_MAC_TYPE;
3587 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3589 struct protoent *pe;
3593 proto = strtol(av, &ep, 10);
3594 if (*ep != '\0' || proto <= 0) {
3595 if ((pe = getprotobyname(av)) == NULL)
3597 proto = pe->p_proto;
3600 fill_cmd(cmd, O_PROTO, 0, proto);
3606 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3608 u_char proto = IPPROTO_IP;
3610 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3611 ; /* do not set O_IP4 nor O_IP6 */
3612 else if (strcmp(av, "ip4") == 0)
3613 /* explicit "just IPv4" rule */
3614 fill_cmd(cmd, O_IP4, 0, 0);
3615 else if (strcmp(av, "ip6") == 0) {
3616 /* explicit "just IPv6" rule */
3617 proto = IPPROTO_IPV6;
3618 fill_cmd(cmd, O_IP6, 0, 0);
3620 return add_proto0(cmd, av, protop);
3627 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3629 u_char proto = IPPROTO_IP;
3631 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3632 ; /* do not set O_IP4 nor O_IP6 */
3633 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3634 /* explicit "just IPv4" rule */
3635 fill_cmd(cmd, O_IP4, 0, 0);
3636 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3637 /* explicit "just IPv6" rule */
3638 proto = IPPROTO_IPV6;
3639 fill_cmd(cmd, O_IP6, 0, 0);
3641 return add_proto0(cmd, av, protop);
3648 add_srcip(ipfw_insn *cmd, char *av)
3650 fill_ip((ipfw_insn_ip *)cmd, av);
3651 if (cmd->opcode == O_IP_DST_SET) /* set */
3652 cmd->opcode = O_IP_SRC_SET;
3653 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3654 cmd->opcode = O_IP_SRC_LOOKUP;
3655 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3656 cmd->opcode = O_IP_SRC_ME;
3657 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3658 cmd->opcode = O_IP_SRC;
3659 else /* addr/mask */
3660 cmd->opcode = O_IP_SRC_MASK;
3665 add_dstip(ipfw_insn *cmd, char *av)
3667 fill_ip((ipfw_insn_ip *)cmd, av);
3668 if (cmd->opcode == O_IP_DST_SET) /* set */
3670 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3672 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3673 cmd->opcode = O_IP_DST_ME;
3674 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3675 cmd->opcode = O_IP_DST;
3676 else /* addr/mask */
3677 cmd->opcode = O_IP_DST_MASK;
3682 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
3684 if (_substrcmp(av, "any") == 0) {
3686 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
3687 /* XXX todo: check that we have a protocol with ports */
3688 cmd->opcode = opcode;
3695 add_src(ipfw_insn *cmd, char *av, u_char proto)
3699 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3700 inet_pton(AF_INET6, av, &a))
3701 return add_srcip6(cmd, av);
3702 /* XXX: should check for IPv4, not !IPv6 */
3703 if (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3704 !inet_pton(AF_INET6, av, &a))
3705 return add_srcip(cmd, av);
3706 if (strcmp(av, "any") != 0)
3713 add_dst(ipfw_insn *cmd, char *av, u_char proto)
3717 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3718 inet_pton(AF_INET6, av, &a))
3719 return add_dstip6(cmd, av);
3720 /* XXX: should check for IPv4, not !IPv6 */
3721 if (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3722 !inet_pton(AF_INET6, av, &a))
3723 return add_dstip(cmd, av);
3724 if (strcmp(av, "any") != 0)
3731 * Parse arguments and assemble the microinstructions which make up a rule.
3732 * Rules are added into the 'rulebuf' and then copied in the correct order
3733 * into the actual rule.
3735 * The syntax for a rule starts with the action, followed by
3736 * optional action parameters, and the various match patterns.
3737 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3738 * (generated if the rule includes a keep-state option), then the
3739 * various match patterns, log/altq actions, and the actual action.
3743 add(int ac, char *av[])
3746 * rules are added into the 'rulebuf' and then copied in
3747 * the correct order into the actual rule.
3748 * Some things that need to go out of order (prob, action etc.)
3751 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
3753 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3754 ipfw_insn *first_cmd; /* first match pattern */
3759 * various flags used to record that we entered some fields.
3761 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3762 ipfw_insn *have_log = NULL, *have_altq = NULL;
3767 int open_par = 0; /* open parenthesis ( */
3769 /* proto is here because it is used to fetch ports */
3770 u_char proto = IPPROTO_IP; /* default protocol */
3772 double match_prob = 1; /* match probability, default is always match */
3774 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3775 bzero(cmdbuf, sizeof(cmdbuf));
3776 bzero(rulebuf, sizeof(rulebuf));
3778 rule = (struct ip_fw *)rulebuf;
3779 cmd = (ipfw_insn *)cmdbuf;
3780 action = (ipfw_insn *)actbuf;
3784 /* [rule N] -- Rule number optional */
3785 if (ac && isdigit(**av)) {
3786 rule->rulenum = atoi(*av);
3791 /* [set N] -- set number (0..RESVD_SET), optional */
3792 if (ac > 1 && _substrcmp(*av, "set") == 0) {
3793 int set = strtoul(av[1], NULL, 10);
3794 if (set < 0 || set > RESVD_SET)
3795 errx(EX_DATAERR, "illegal set %s", av[1]);
3800 /* [prob D] -- match probability, optional */
3801 if (ac > 1 && _substrcmp(*av, "prob") == 0) {
3802 match_prob = strtod(av[1], NULL);
3804 if (match_prob <= 0 || match_prob > 1)
3805 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3809 /* action -- mandatory */
3810 NEED1("missing action");
3811 i = match_token(rule_actions, *av);
3813 action->len = 1; /* default */
3815 case TOK_CHECKSTATE:
3816 have_state = action;
3817 action->opcode = O_CHECK_STATE;
3821 action->opcode = O_ACCEPT;
3825 action->opcode = O_DENY;
3830 action->opcode = O_REJECT;
3831 action->arg1 = ICMP_UNREACH_HOST;
3835 action->opcode = O_REJECT;
3836 action->arg1 = ICMP_REJECT_RST;
3840 action->opcode = O_UNREACH6;
3841 action->arg1 = ICMP6_UNREACH_RST;
3845 action->opcode = O_REJECT;
3846 NEED1("missing reject code");
3847 fill_reject_code(&action->arg1, *av);
3852 action->opcode = O_UNREACH6;
3853 NEED1("missing unreach code");
3854 fill_unreach6_code(&action->arg1, *av);
3859 action->opcode = O_COUNT;
3863 action->opcode = O_QUEUE;
3866 action->opcode = O_PIPE;
3869 action->opcode = O_SKIPTO;
3872 action->opcode = O_NETGRAPH;
3875 action->opcode = O_NGTEE;
3878 action->opcode = O_DIVERT;
3881 action->opcode = O_TEE;
3884 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3885 if (isdigit(**av)) {
3886 action->arg1 = strtoul(*av, NULL, 10);
3887 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3888 errx(EX_DATAERR, "illegal argument for %s",
3890 } else if (_substrcmp(*av, TABLEARG) == 0) {
3891 action->arg1 = IP_FW_TABLEARG;
3892 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3895 s = getservbyname(av[0], "divert");
3897 action->arg1 = ntohs(s->s_port);
3899 errx(EX_DATAERR, "illegal divert/tee port");
3901 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3906 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3909 NEED1("missing forward address[:port]");
3911 action->opcode = O_FORWARD_IP;
3912 action->len = F_INSN_SIZE(ipfw_insn_sa);
3914 p->sa.sin_len = sizeof(struct sockaddr_in);
3915 p->sa.sin_family = AF_INET;
3918 * locate the address-port separator (':' or ',')
3920 s = strchr(*av, ':');
3922 s = strchr(*av, ',');
3925 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3928 "illegal forwarding port ``%s''", s);
3929 p->sa.sin_port = (u_short)i;
3931 lookup_host(*av, &(p->sa.sin_addr));
3937 /* pretend it is a 'count' rule followed by the comment */
3938 action->opcode = O_COUNT;
3939 ac++; av--; /* go back... */
3943 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3945 action = next_cmd(action);
3948 * [altq queuename] -- altq tag, optional
3949 * [log [logamount N]] -- log, optional
3951 * If they exist, it go first in the cmdbuf, but then it is
3952 * skipped in the copy section to the end of the buffer.
3954 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
3959 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3964 "log cannot be specified more than once");
3965 have_log = (ipfw_insn *)c;
3966 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3967 cmd->opcode = O_LOG;
3968 if (ac && _substrcmp(*av, "logamount") == 0) {
3970 NEED1("logamount requires argument");
3974 "logamount must be positive");
3978 len = sizeof(c->max_log);
3979 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3980 &c->max_log, &len, NULL, 0) == -1)
3981 errx(1, "sysctlbyname(\"%s\")",
3982 "net.inet.ip.fw.verbose_limit");
3989 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3991 NEED1("missing altq queue name");
3994 "altq cannot be specified more than once");
3995 have_altq = (ipfw_insn *)a;
3996 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3997 cmd->opcode = O_ALTQ;
3998 fill_altq_qid(&a->qid, *av);
4006 cmd = next_cmd(cmd);
4009 if (have_state) /* must be a check-state, we are done */
4012 #define OR_START(target) \
4013 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
4015 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4018 if ( (av[0])[1] == '\0') { \
4029 strcmp(*av, ")") == 0 || \
4030 strcmp(*av, "}") == 0)) { \
4035 errx(EX_USAGE, "missing \")\"\n"); \
4039 if (ac && _substrcmp(*av, "not") == 0) { \
4040 if (cmd->len & F_NOT) \
4041 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4042 cmd->len |= F_NOT; \
4046 #define OR_BLOCK(target) \
4047 if (ac && _substrcmp(*av, "or") == 0) { \
4048 if (prev == NULL || open_par == 0) \
4049 errx(EX_DATAERR, "invalid OR block"); \
4050 prev->len |= F_OR; \
4060 * MAC addresses, optional.
4061 * If we have this, we skip the part "proto from src to dst"
4062 * and jump straight to the option parsing.
4065 NEED1("missing protocol");
4066 if (_substrcmp(*av, "MAC") == 0 ||
4067 _substrcmp(*av, "mac") == 0) {
4068 ac--; av++; /* the "MAC" keyword */
4069 add_mac(cmd, ac, av); /* exits in case of errors */
4070 cmd = next_cmd(cmd);
4071 ac -= 2; av += 2; /* dst-mac and src-mac */
4073 NEED1("missing mac type");
4074 if (add_mactype(cmd, ac, av[0]))
4075 cmd = next_cmd(cmd);
4076 ac--; av++; /* any or mac-type */
4082 * protocol, mandatory
4084 OR_START(get_proto);
4086 NEED1("missing protocol");
4087 if (add_proto_compat(cmd, *av, &proto)) {
4089 if (F_LEN(cmd) != 0) {
4091 cmd = next_cmd(cmd);
4093 } else if (first_cmd != cmd) {
4094 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4097 OR_BLOCK(get_proto);
4102 if (!ac || _substrcmp(*av, "from") != 0)
4103 errx(EX_USAGE, "missing ``from''");
4107 * source IP, mandatory
4109 OR_START(source_ip);
4110 NOT_BLOCK; /* optional "not" */
4111 NEED1("missing source address");
4112 if (add_src(cmd, *av, proto)) {
4114 if (F_LEN(cmd) != 0) { /* ! any */
4116 cmd = next_cmd(cmd);
4119 errx(EX_USAGE, "bad source address %s", *av);
4120 OR_BLOCK(source_ip);
4123 * source ports, optional
4125 NOT_BLOCK; /* optional "not" */
4127 if (_substrcmp(*av, "any") == 0 ||
4128 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
4130 if (F_LEN(cmd) != 0)
4131 cmd = next_cmd(cmd);
4138 if (!ac || _substrcmp(*av, "to") != 0)
4139 errx(EX_USAGE, "missing ``to''");
4143 * destination, mandatory
4146 NOT_BLOCK; /* optional "not" */
4147 NEED1("missing dst address");
4148 if (add_dst(cmd, *av, proto)) {
4150 if (F_LEN(cmd) != 0) { /* ! any */
4152 cmd = next_cmd(cmd);
4155 errx( EX_USAGE, "bad destination address %s", *av);
4159 * dest. ports, optional
4161 NOT_BLOCK; /* optional "not" */
4163 if (_substrcmp(*av, "any") == 0 ||
4164 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
4166 if (F_LEN(cmd) != 0)
4167 cmd = next_cmd(cmd);
4172 if (ac && first_cmd == cmd) {
4174 * nothing specified so far, store in the rule to ease
4182 ipfw_insn_u32 *cmd32; /* alias for cmd */
4185 cmd32 = (ipfw_insn_u32 *)cmd;
4187 if (*s == '!') { /* alternate syntax for NOT */
4188 if (cmd->len & F_NOT)
4189 errx(EX_USAGE, "double \"not\" not allowed\n");
4193 i = match_token(rule_options, s);
4197 if (cmd->len & F_NOT)
4198 errx(EX_USAGE, "double \"not\" not allowed\n");
4203 if (open_par == 0 || prev == NULL)
4204 errx(EX_USAGE, "invalid \"or\" block\n");
4208 case TOK_STARTBRACE:
4210 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4216 errx(EX_USAGE, "+missing \")\"\n");
4222 fill_cmd(cmd, O_IN, 0, 0);
4226 cmd->len ^= F_NOT; /* toggle F_NOT */
4227 fill_cmd(cmd, O_IN, 0, 0);
4231 fill_cmd(cmd, O_DIVERTED, 0, 3);
4234 case TOK_DIVERTEDLOOPBACK:
4235 fill_cmd(cmd, O_DIVERTED, 0, 1);
4238 case TOK_DIVERTEDOUTPUT:
4239 fill_cmd(cmd, O_DIVERTED, 0, 2);
4243 fill_cmd(cmd, O_FRAG, 0, 0);
4247 fill_cmd(cmd, O_LAYER2, 0, 0);
4253 NEED1("recv, xmit, via require interface name"
4255 fill_iface((ipfw_insn_if *)cmd, av[0]);
4257 if (F_LEN(cmd) == 0) /* not a valid address */
4260 cmd->opcode = O_XMIT;
4261 else if (i == TOK_RECV)
4262 cmd->opcode = O_RECV;
4263 else if (i == TOK_VIA)
4264 cmd->opcode = O_VIA;
4268 NEED1("icmptypes requires list of types");
4269 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4273 case TOK_ICMP6TYPES:
4274 NEED1("icmptypes requires list of types");
4275 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
4280 NEED1("ipttl requires TTL");
4281 if (strpbrk(*av, "-,")) {
4282 if (!add_ports(cmd, *av, 0, O_IPTTL))
4283 errx(EX_DATAERR, "invalid ipttl %s", *av);
4285 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4290 NEED1("ipid requires id");
4291 if (strpbrk(*av, "-,")) {
4292 if (!add_ports(cmd, *av, 0, O_IPID))
4293 errx(EX_DATAERR, "invalid ipid %s", *av);
4295 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4300 NEED1("iplen requires length");
4301 if (strpbrk(*av, "-,")) {
4302 if (!add_ports(cmd, *av, 0, O_IPLEN))
4303 errx(EX_DATAERR, "invalid ip len %s", *av);
4305 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4310 NEED1("ipver requires version");
4311 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4315 case TOK_IPPRECEDENCE:
4316 NEED1("ipprecedence requires value");
4317 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4318 (strtoul(*av, NULL, 0) & 7) << 5);
4323 NEED1("missing argument for ipoptions");
4324 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
4329 NEED1("missing argument for iptos");
4330 fill_flags(cmd, O_IPTOS, f_iptos, *av);
4335 NEED1("uid requires argument");
4341 cmd->opcode = O_UID;
4342 uid = strtoul(*av, &end, 0);
4343 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4345 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4346 cmd32->d[0] = pwd->pw_uid;
4347 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4353 NEED1("gid requires argument");
4359 cmd->opcode = O_GID;
4360 gid = strtoul(*av, &end, 0);
4361 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4363 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4364 cmd32->d[0] = grp->gr_gid;
4365 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4371 NEED1("jail requires argument");
4376 cmd->opcode = O_JAIL;
4377 jid = (int)strtol(*av, &end, 0);
4378 if (jid < 0 || *end != '\0')
4379 errx(EX_DATAERR, "jail requires prison ID");
4380 cmd32->d[0] = (uint32_t)jid;
4381 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4387 fill_cmd(cmd, O_ESTAB, 0, 0);
4391 fill_cmd(cmd, O_TCPFLAGS, 0,
4392 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4395 case TOK_TCPDATALEN:
4396 NEED1("tcpdatalen requires length");
4397 if (strpbrk(*av, "-,")) {
4398 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
4399 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4401 fill_cmd(cmd, O_TCPDATALEN, 0,
4402 strtoul(*av, NULL, 0));
4407 NEED1("missing argument for tcpoptions");
4408 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
4414 NEED1("tcpseq/tcpack requires argument");
4415 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4416 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4417 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4422 NEED1("tcpwin requires length");
4423 fill_cmd(cmd, O_TCPWIN, 0,
4424 htons(strtoul(*av, NULL, 0)));
4429 NEED1("missing argument for tcpflags");
4430 cmd->opcode = O_TCPFLAGS;
4431 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
4437 errx(EX_USAGE, "keep-state cannot be part "
4440 errx(EX_USAGE, "only one of keep-state "
4441 "and limit is allowed");
4443 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
4448 errx(EX_USAGE, "limit cannot be part "
4451 errx(EX_USAGE, "only one of keep-state "
4452 "and limit is allowed");
4453 NEED1("limit needs mask and # of connections");
4456 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4458 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4459 cmd->opcode = O_LIMIT;
4465 val = match_token(limit_masks, *av);
4468 c->limit_mask |= val;
4471 c->conn_limit = atoi(*av);
4472 if (c->conn_limit == 0)
4473 errx(EX_USAGE, "limit: limit must be >0");
4474 if (c->limit_mask == 0)
4475 errx(EX_USAGE, "missing limit mask");
4481 NEED1("missing protocol");
4482 if (add_proto(cmd, *av, &proto)) {
4485 errx(EX_DATAERR, "invalid protocol ``%s''",
4490 NEED1("missing source IP");
4491 if (add_srcip(cmd, *av)) {
4497 NEED1("missing destination IP");
4498 if (add_dstip(cmd, *av)) {
4504 NEED1("missing source IP6");
4505 if (add_srcip6(cmd, *av)) {
4511 NEED1("missing destination IP6");
4512 if (add_dstip6(cmd, *av)) {
4518 NEED1("missing source port");
4519 if (_substrcmp(*av, "any") == 0 ||
4520 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
4523 errx(EX_DATAERR, "invalid source port %s", *av);
4527 NEED1("missing destination port");
4528 if (_substrcmp(*av, "any") == 0 ||
4529 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
4532 errx(EX_DATAERR, "invalid destination port %s",
4537 if (add_mac(cmd, ac, av)) {
4543 NEED1("missing mac type");
4544 if (!add_mactype(cmd, ac, *av))
4545 errx(EX_DATAERR, "invalid mac type %s", *av);
4549 case TOK_VERREVPATH:
4550 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4553 case TOK_VERSRCREACH:
4554 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4558 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4562 fill_cmd(cmd, O_IPSEC, 0, 0);
4566 fill_cmd(cmd, O_IP6, 0, 0);
4570 fill_cmd(cmd, O_IP4, 0, 0);
4574 fill_ext6hdr( cmd, *av );
4579 if (proto != IPPROTO_IPV6 )
4580 errx( EX_USAGE, "flow-id filter is active "
4581 "only for ipv6 protocol\n");
4582 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
4587 fill_comment(cmd, ac, av);
4593 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4595 if (F_LEN(cmd) > 0) { /* prepare to advance */
4597 cmd = next_cmd(cmd);
4603 * Now copy stuff into the rule.
4604 * If we have a keep-state option, the first instruction
4605 * must be a PROBE_STATE (which is generated here).
4606 * If we have a LOG option, it was stored as the first command,
4607 * and now must be moved to the top of the action part.
4609 dst = (ipfw_insn *)rule->cmd;
4612 * First thing to write into the command stream is the match probability.
4614 if (match_prob != 1) { /* 1 means always match */
4615 dst->opcode = O_PROB;
4617 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4622 * generate O_PROBE_STATE if necessary
4624 if (have_state && have_state->opcode != O_CHECK_STATE) {
4625 fill_cmd(dst, O_PROBE_STATE, 0, 0);
4626 dst = next_cmd(dst);
4629 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ
4631 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4634 switch (src->opcode) {
4641 bcopy(src, dst, i * sizeof(uint32_t));
4647 * put back the have_state command as last opcode
4649 if (have_state && have_state->opcode != O_CHECK_STATE) {
4650 i = F_LEN(have_state);
4651 bcopy(have_state, dst, i * sizeof(uint32_t));
4655 * start action section
4657 rule->act_ofs = dst - rule->cmd;
4660 * put back O_LOG, O_ALTQ if necessary
4663 i = F_LEN(have_log);
4664 bcopy(have_log, dst, i * sizeof(uint32_t));
4668 i = F_LEN(have_altq);
4669 bcopy(have_altq, dst, i * sizeof(uint32_t));
4673 * copy all other actions
4675 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4677 bcopy(src, dst, i * sizeof(uint32_t));
4681 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4682 i = (char *)dst - (char *)rule;
4683 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4684 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4686 show_ipfw(rule, 0, 0);
4690 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */)
4694 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG";
4699 /* clear all entries */
4700 if (do_cmd(optname, NULL, 0) < 0)
4701 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4703 printf("%s.\n", optname == IP_FW_ZERO ?
4704 "Accounting cleared":"Logging counts reset");
4711 if (isdigit(**av)) {
4712 rulenum = atoi(*av);
4715 if (do_cmd(optname, &rulenum, sizeof rulenum)) {
4716 warn("rule %u: setsockopt(IP_FW_%s)",
4718 failed = EX_UNAVAILABLE;
4719 } else if (!do_quiet)
4720 printf("Entry %d %s.\n", rulenum,
4721 optname == IP_FW_ZERO ?
4722 "cleared" : "logging count reset");
4724 errx(EX_USAGE, "invalid rule number ``%s''", *av);
4727 if (failed != EX_OK)
4734 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4736 if (!force && !do_quiet) { /* need to ask user */
4739 printf("Are you sure? [yn] ");
4742 c = toupper(getc(stdin));
4743 while (c != '\n' && getc(stdin) != '\n')
4745 return; /* and do not flush */
4746 } while (c != 'Y' && c != 'N');
4748 if (c == 'N') /* user said no */
4751 if (do_cmd(cmd, NULL, 0) < 0)
4752 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4753 do_pipe ? "DUMMYNET" : "FW");
4755 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
4759 * Free a the (locally allocated) copy of command line arguments.
4762 free_args(int ac, char **av)
4766 for (i=0; i < ac; i++)
4772 * This one handles all table-related commands
4773 * ipfw table N add addr[/masklen] [value]
4774 * ipfw table N delete addr[/masklen]
4775 * ipfw table N flush
4779 table_handler(int ac, char *av[])
4781 ipfw_table_entry ent;
4789 if (ac && isdigit(**av)) {
4790 ent.tbl = atoi(*av);
4793 errx(EX_USAGE, "table number required");
4794 NEED1("table needs command");
4795 if (_substrcmp(*av, "add") == 0 ||
4796 _substrcmp(*av, "delete") == 0) {
4797 do_add = **av == 'a';
4800 errx(EX_USAGE, "IP address required");
4801 p = strchr(*av, '/');
4804 ent.masklen = atoi(p);
4805 if (ent.masklen > 32)
4806 errx(EX_DATAERR, "bad width ``%s''", p);
4809 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
4810 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4813 ent.value = strtoul(*av, NULL, 0);
4816 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
4817 &ent, sizeof(ent)) < 0)
4818 /* If running silent, don't bomb out on these errors. */
4819 if (!(do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
4820 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4821 do_add ? "ADD" : "DEL");
4822 /* In silent mode, react to a failed add by deleting */
4824 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
4825 if (do_cmd(IP_FW_TABLE_ADD,
4826 &ent, sizeof(ent)) < 0)
4828 "setsockopt(IP_FW_TABLE_ADD)");
4829 } else if (_substrcmp(*av, "flush") == 0) {
4830 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0)
4831 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4832 } else if (_substrcmp(*av, "list") == 0) {
4835 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
4836 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
4837 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
4840 err(EX_OSERR, "malloc");
4842 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
4843 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
4844 for (a = 0; a < tbl->cnt; a++) {
4845 printf("%s/%u %u\n",
4846 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
4847 tbl->ent[a].masklen, tbl->ent[a].value);
4850 errx(EX_USAGE, "invalid table command %s", *av);
4854 * Called with the arguments (excluding program name).
4855 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
4858 ipfw_main(int oldac, char **oldav)
4860 int ch, ac, save_ac;
4861 char **av, **save_av;
4862 int do_acct = 0; /* Show packet/byte count */
4864 #define WHITESP " \t\f\v\n\r"
4867 else if (oldac == 1) {
4869 * If we are called with a single string, try to split it into
4870 * arguments for subsequent parsing.
4871 * But first, remove spaces after a ',', by copying the string
4874 char *arg = oldav[0]; /* The string... */
4875 int l = strlen(arg);
4876 int copy = 0; /* 1 if we need to copy, 0 otherwise */
4878 for (i = j = 0; i < l; i++) {
4879 if (arg[i] == '#') /* comment marker */
4883 copy = !index("," WHITESP, arg[i]);
4885 copy = !index(WHITESP, arg[i]);
4890 if (!copy && j > 0) /* last char was a 'blank', remove it */
4892 l = j; /* the new argument length */
4894 if (l == 0) /* empty string! */
4898 * First, count number of arguments. Because of the previous
4899 * processing, this is just the number of blanks plus 1.
4901 for (i = 0, ac = 1; i < l; i++)
4902 if (index(WHITESP, arg[i]) != NULL)
4905 av = calloc(ac, sizeof(char *));
4908 * Second, copy arguments from cmd[] to av[]. For each one,
4909 * j is the initial character, i is the one past the end.
4911 for (ac = 0, i = j = 0; i < l; i++)
4912 if (index(WHITESP, arg[i]) != NULL || i == l-1) {
4915 av[ac] = calloc(i-j+1, 1);
4916 bcopy(arg+j, av[ac], i-j);
4922 * If an argument ends with ',' join with the next one.
4926 av = calloc(oldac, sizeof(char *));
4927 for (first = i = ac = 0, l = 0; i < oldac; i++) {
4928 char *arg = oldav[i];
4929 int k = strlen(arg);
4932 if (arg[k-1] != ',' || i == oldac-1) {
4934 av[ac] = calloc(l+1, 1);
4935 for (l=0; first <= i; first++) {
4936 strcat(av[ac]+l, oldav[first]);
4937 l += strlen(oldav[first]);
4946 /* Set the force flag for non-interactive processes */
4948 do_force = !isatty(STDIN_FILENO);
4950 /* Save arguments for final freeing of memory. */
4954 optind = optreset = 0;
4955 while ((ch = getopt(ac, av, "abcdefhnNqs:STtv")) != -1)
4982 case 'h': /* help */
4983 free_args(save_ac, save_av);
4985 break; /* NOTREACHED */
4999 case 's': /* sort */
5000 do_sort = atoi(optarg);
5012 do_time = 2; /* numeric timestamp */
5015 case 'v': /* verbose */
5020 free_args(save_ac, save_av);
5026 NEED1("bad arguments, for usage summary ``ipfw''");
5029 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
5030 * e.g. "100 add allow ..." instead of "add 100 allow ...".
5031 * In case, swap first and second argument to get the normal form.
5033 if (ac > 1 && isdigit(*av[0])) {
5041 * optional: pipe or queue
5044 if (_substrcmp(*av, "pipe") == 0)
5046 else if (_substrcmp(*av, "queue") == 0)
5052 NEED1("missing command");
5055 * For pipes and queues we normally say 'pipe NN config'
5056 * but the code is easier to parse as 'pipe config NN'
5057 * so we swap the two arguments.
5059 if (do_pipe > 0 && ac > 1 && isdigit(*av[0])) {
5066 if (_substrcmp(*av, "add") == 0)
5068 else if (do_pipe && _substrcmp(*av, "config") == 0)
5069 config_pipe(ac, av);
5070 else if (_substrcmp(*av, "delete") == 0)
5072 else if (_substrcmp(*av, "flush") == 0)
5074 else if (_substrcmp(*av, "zero") == 0)
5075 zero(ac, av, IP_FW_ZERO);
5076 else if (_substrcmp(*av, "resetlog") == 0)
5077 zero(ac, av, IP_FW_RESETLOG);
5078 else if (_substrcmp(*av, "print") == 0 ||
5079 _substrcmp(*av, "list") == 0)
5080 list(ac, av, do_acct);
5081 else if (_substrcmp(*av, "set") == 0)
5082 sets_handler(ac, av);
5083 else if (_substrcmp(*av, "table") == 0)
5084 table_handler(ac, av);
5085 else if (_substrcmp(*av, "enable") == 0)
5086 sysctl_handler(ac, av, 1);
5087 else if (_substrcmp(*av, "disable") == 0)
5088 sysctl_handler(ac, av, 0);
5089 else if (_substrcmp(*av, "show") == 0)
5090 list(ac, av, 1 /* show counters */);
5092 errx(EX_USAGE, "bad command `%s'", *av);
5094 /* Free memory allocated in the argument parsing. */
5095 free_args(save_ac, save_av);
5101 ipfw_readfile(int ac, char *av[])
5105 char *cmd = NULL, *filename = av[ac-1];
5110 filename = av[ac-1];
5112 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
5133 * Skip previous args and delete last one, so we
5134 * pass all but the last argument to the preprocessor
5140 fprintf(stderr, "command is %s\n", av[0]);
5152 errx(EX_USAGE, "bad arguments, for usage"
5153 " summary ``ipfw''");
5160 if (cmd == NULL && ac != optind + 1) {
5161 fprintf(stderr, "ac %d, optind %d\n", ac, optind);
5162 errx(EX_USAGE, "extraneous filename arguments");
5165 if ((f = fopen(filename, "r")) == NULL)
5166 err(EX_UNAVAILABLE, "fopen: %s", filename);
5168 if (cmd != NULL) { /* pipe through preprocessor */
5171 if (pipe(pipedes) == -1)
5172 err(EX_OSERR, "cannot create pipe");
5176 err(EX_OSERR, "cannot fork");
5180 * Child, will run the preprocessor with the
5181 * file on stdin and the pipe on stdout.
5183 if (dup2(fileno(f), 0) == -1
5184 || dup2(pipedes[1], 1) == -1)
5185 err(EX_OSERR, "dup2()");
5190 err(EX_OSERR, "execvp(%s) failed", cmd);
5191 } else { /* parent, will reopen f as the pipe */
5194 if ((f = fdopen(pipedes[0], "r")) == NULL) {
5195 int savederrno = errno;
5197 (void)kill(preproc, SIGTERM);
5199 err(EX_OSERR, "fdopen()");
5204 while (fgets(buf, BUFSIZ, f)) { /* read commands */
5209 sprintf(linename, "Line %d", lineno);
5210 setprogname(linename); /* XXX */
5218 if (waitpid(preproc, &status, 0) == -1)
5219 errx(EX_OSERR, "waitpid()");
5220 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
5221 errx(EX_UNAVAILABLE,
5222 "preprocessor exited with status %d",
5223 WEXITSTATUS(status));
5224 else if (WIFSIGNALED(status))
5225 errx(EX_UNAVAILABLE,
5226 "preprocessor exited with signal %d",
5232 main(int ac, char *av[])
5235 * If the last argument is an absolute pathname, interpret it
5236 * as a file to be preprocessed.
5239 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
5240 ipfw_readfile(ac, av);
5242 if (ipfw_main(ac-1, av+1))