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 static __inline uint64_t
424 align_uint64(uint64_t *pll) {
427 bcopy (pll, &ret, sizeof(ret));
432 * conditionally runs the command.
435 do_cmd(int optname, void *optval, uintptr_t optlen)
437 static int s = -1; /* the socket */
444 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
446 err(EX_UNAVAILABLE, "socket");
448 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
449 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
450 optname == IP_FW_TABLE_GETSIZE)
451 i = getsockopt(s, IPPROTO_IP, optname, optval,
452 (socklen_t *)optlen);
454 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
459 * match_token takes a table and a string, returns the value associated
460 * with the string (-1 in case of failure).
463 match_token(struct _s_x *table, char *string)
466 uint i = strlen(string);
468 for (pt = table ; i && pt->s != NULL ; pt++)
469 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
475 * match_value takes a table and a value, returns the string associated
476 * with the value (NULL in case of failure).
479 match_value(struct _s_x *p, int value)
481 for (; p->s != NULL; p++)
488 * _substrcmp takes two strings and returns 1 if they do not match,
489 * and 0 if they match exactly or the first string is a sub-string
490 * of the second. A warning is printed to stderr in the case that the
491 * first string is a sub-string of the second.
493 * This function will be removed in the future through the usual
494 * deprecation process.
497 _substrcmp(const char *str1, const char* str2)
500 if (strncmp(str1, str2, strlen(str1)) != 0)
503 if (strlen(str1) != strlen(str2))
504 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
510 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
511 * and 0 if they match exactly or the second string is a sub-string
512 * of the first. A warning is printed to stderr in the case that the
513 * first string does not match the third.
515 * This function exists to warn about the bizzare construction
516 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
517 * for "bytes". The problem is that in addition to accepting "by",
518 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
519 * other string beginning with "by".
521 * This function will be removed in the future through the usual
522 * deprecation process.
525 _substrcmp2(const char *str1, const char* str2, const char* str3)
528 if (strncmp(str1, str2, strlen(str2)) != 0)
531 if (strcmp(str1, str3) != 0)
532 warnx("DEPRECATED: '%s' matched '%s'",
538 * prints one port, symbolic or numeric
541 print_port(int proto, uint16_t port)
544 if (proto == IPPROTO_ETHERTYPE) {
547 if (do_resolv && (s = match_value(ether_types, port)) )
550 printf("0x%04x", port);
552 struct servent *se = NULL;
554 struct protoent *pe = getprotobynumber(proto);
556 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
559 printf("%s", se->s_name);
565 struct _s_x _port_name[] = {
566 {"dst-port", O_IP_DSTPORT},
567 {"src-port", O_IP_SRCPORT},
571 {"mac-type", O_MAC_TYPE},
572 {"tcpdatalen", O_TCPDATALEN},
577 * Print the values in a list 16-bit items of the types above.
578 * XXX todo: add support for mask.
581 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
583 uint16_t *p = cmd->ports;
587 if (cmd->o.len & F_NOT)
590 sep = match_value(_port_name, opcode);
596 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
598 print_port(proto, p[0]);
601 print_port(proto, p[1]);
608 * Like strtol, but also translates service names into port numbers
609 * for some protocols.
611 * proto == -1 disables the protocol check;
612 * proto == IPPROTO_ETHERTYPE looks up an internal table
613 * proto == <some value in /etc/protocols> matches the values there.
614 * Returns *end == s in case the parameter is not found.
617 strtoport(char *s, char **end, int base, int proto)
623 *end = s; /* default - not found */
625 return 0; /* not found */
628 return strtol(s, end, base);
631 * find separator. '\\' escapes the next char.
633 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
634 if (*s1 == '\\' && s1[1] != '\0')
637 buf = malloc(s1 - s + 1);
642 * copy into a buffer skipping backslashes
644 for (p = s, i = 0; p != s1 ; p++)
649 if (proto == IPPROTO_ETHERTYPE) {
650 i = match_token(ether_types, buf);
652 if (i != -1) { /* found */
657 struct protoent *pe = NULL;
661 pe = getprotobynumber(proto);
663 se = getservbyname(buf, pe ? pe->p_name : NULL);
667 return ntohs(se->s_port);
670 return 0; /* not found */
674 * Map between current altq queue id numbers and names.
676 static int altq_fetched = 0;
677 static TAILQ_HEAD(, pf_altq) altq_entries =
678 TAILQ_HEAD_INITIALIZER(altq_entries);
681 altq_set_enabled(int enabled)
685 pffd = open("/dev/pf", O_RDWR);
688 "altq support opening pf(4) control device");
690 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST)
691 err(EX_UNAVAILABLE, "enabling altq");
693 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT)
694 err(EX_UNAVAILABLE, "disabling altq");
702 struct pfioc_altq pfioc;
703 struct pf_altq *altq;
709 pffd = open("/dev/pf", O_RDONLY);
711 warn("altq support opening pf(4) control device");
714 bzero(&pfioc, sizeof(pfioc));
715 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) {
716 warn("altq support getting queue list");
721 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) {
722 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) {
725 warn("altq support getting queue list");
729 if (pfioc.altq.qid == 0)
731 altq = malloc(sizeof(*altq));
733 err(EX_OSERR, "malloc");
735 TAILQ_INSERT_TAIL(&altq_entries, altq, entries);
741 altq_name_to_qid(const char *name)
743 struct pf_altq *altq;
746 TAILQ_FOREACH(altq, &altq_entries, entries)
747 if (strcmp(name, altq->qname) == 0)
750 errx(EX_DATAERR, "altq has no queue named `%s'", name);
755 altq_qid_to_name(u_int32_t qid)
757 struct pf_altq *altq;
760 TAILQ_FOREACH(altq, &altq_entries, entries)
761 if (qid == altq->qid)
769 fill_altq_qid(u_int32_t *qid, const char *av)
771 *qid = altq_name_to_qid(av);
775 * Fill the body of the command with the list of port ranges.
778 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
780 uint16_t a, b, *p = cmd->ports;
785 a = strtoport(av, &s, 0, proto);
786 if (s == av) /* no parameter */
788 if (*s == '-') { /* a range */
790 b = strtoport(av, &s, 0, proto);
791 if (s == av) /* no parameter */
795 } else if (*s == ',' || *s == '\0' )
797 else /* invalid separator */
798 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n",
805 if (i+1 > F_LEN_MASK)
806 errx(EX_DATAERR, "too many ports/ranges\n");
807 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
812 static struct _s_x icmpcodes[] = {
813 { "net", ICMP_UNREACH_NET },
814 { "host", ICMP_UNREACH_HOST },
815 { "protocol", ICMP_UNREACH_PROTOCOL },
816 { "port", ICMP_UNREACH_PORT },
817 { "needfrag", ICMP_UNREACH_NEEDFRAG },
818 { "srcfail", ICMP_UNREACH_SRCFAIL },
819 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
820 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
821 { "isolated", ICMP_UNREACH_ISOLATED },
822 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
823 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
824 { "tosnet", ICMP_UNREACH_TOSNET },
825 { "toshost", ICMP_UNREACH_TOSHOST },
826 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
827 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
828 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
833 fill_reject_code(u_short *codep, char *str)
838 val = strtoul(str, &s, 0);
839 if (s == str || *s != '\0' || val >= 0x100)
840 val = match_token(icmpcodes, str);
842 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
848 print_reject_code(uint16_t code)
850 char const *s = match_value(icmpcodes, code);
853 printf("unreach %s", s);
855 printf("unreach %u", code);
858 static struct _s_x icmp6codes[] = {
859 { "no-route", ICMP6_DST_UNREACH_NOROUTE },
860 { "admin-prohib", ICMP6_DST_UNREACH_ADMIN },
861 { "address", ICMP6_DST_UNREACH_ADDR },
862 { "port", ICMP6_DST_UNREACH_NOPORT },
867 fill_unreach6_code(u_short *codep, char *str)
872 val = strtoul(str, &s, 0);
873 if (s == str || *s != '\0' || val >= 0x100)
874 val = match_token(icmp6codes, str);
876 errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str);
882 print_unreach6_code(uint16_t code)
884 char const *s = match_value(icmp6codes, code);
887 printf("unreach6 %s", s);
889 printf("unreach6 %u", code);
893 * Returns the number of bits set (from left) in a contiguous bitmask,
894 * or -1 if the mask is not contiguous.
895 * XXX this needs a proper fix.
896 * This effectively works on masks in big-endian (network) format.
897 * when compiled on little endian architectures.
899 * First bit is bit 7 of the first byte -- note, for MAC addresses,
900 * the first bit on the wire is bit 0 of the first byte.
901 * len is the max length in bits.
904 contigmask(uint8_t *p, int len)
908 for (i=0; i<len ; i++)
909 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
911 for (n=i+1; n < len; n++)
912 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
913 return -1; /* mask not contiguous */
918 * print flags set/clear in the two bitmasks passed as parameters.
919 * There is a specialized check for f_tcpflags.
922 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
924 char const *comma = "";
926 uint8_t set = cmd->arg1 & 0xff;
927 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
929 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
934 printf(" %s ", name);
935 for (i=0; list[i].x != 0; i++) {
936 if (set & list[i].x) {
938 printf("%s%s", comma, list[i].s);
941 if (clear & list[i].x) {
943 printf("%s!%s", comma, list[i].s);
950 * Print the ip address contained in a command.
953 print_ip(ipfw_insn_ip *cmd, char const *s)
955 struct hostent *he = NULL;
956 int len = F_LEN((ipfw_insn *)cmd);
957 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
959 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
961 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
965 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
966 cmd->o.opcode == O_IP_DST_LOOKUP) {
967 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
968 if (len == F_INSN_SIZE(ipfw_insn_u32))
973 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
974 uint32_t x, *map = (uint32_t *)&(cmd->mask);
980 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
981 printf("%s/%d", inet_ntoa(cmd->addr),
982 contigmask((uint8_t *)&x, 32));
983 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
984 x &= 0xff; /* base */
986 * Print bits and ranges.
987 * Locate first bit set (i), then locate first bit unset (j).
988 * If we have 3+ consecutive bits set, then print them as a
989 * range, otherwise only print the initial bit and rescan.
991 for (i=0; i < cmd->o.arg1; i++)
992 if (map[i/32] & (1<<(i & 31))) {
993 for (j=i+1; j < cmd->o.arg1; j++)
994 if (!(map[ j/32] & (1<<(j & 31))))
996 printf("%c%d", comma, i+x);
997 if (j>i+2) { /* range has at least 3 elements */
998 printf("-%d", j-1+x);
1007 * len == 2 indicates a single IP, whereas lists of 1 or more
1008 * addr/mask pairs have len = (2n+1). We convert len to n so we
1009 * use that to count the number of entries.
1011 for (len = len / 2; len > 0; len--, a += 2) {
1012 int mb = /* mask length */
1013 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1014 32 : contigmask((uint8_t *)&(a[1]), 32);
1015 if (mb == 32 && do_resolv)
1016 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1017 if (he != NULL) /* resolved to name */
1018 printf("%s", he->h_name);
1019 else if (mb == 0) /* any */
1021 else { /* numeric IP followed by some kind of mask */
1022 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
1024 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
1034 * prints a MAC address/mask pair
1037 print_mac(uint8_t *addr, uint8_t *mask)
1039 int l = contigmask(mask, 48);
1044 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1045 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1047 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1048 mask[0], mask[1], mask[2],
1049 mask[3], mask[4], mask[5]);
1056 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1065 type = strtoul(av, &av, 0);
1067 if (*av != ',' && *av != '\0')
1068 errx(EX_DATAERR, "invalid ICMP type");
1071 errx(EX_DATAERR, "ICMP type out of range");
1073 cmd->d[0] |= 1 << type;
1075 cmd->o.opcode = O_ICMPTYPE;
1076 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1080 print_icmptypes(ipfw_insn_u32 *cmd)
1085 printf(" icmptypes");
1086 for (i = 0; i < 32; i++) {
1087 if ( (cmd->d[0] & (1 << (i))) == 0)
1089 printf("%c%d", sep, i);
1095 * Print the ip address contained in a command.
1098 print_ip6(ipfw_insn_ip6 *cmd, char const *s)
1100 struct hostent *he = NULL;
1101 int len = F_LEN((ipfw_insn *) cmd) - 1;
1102 struct in6_addr *a = &(cmd->addr6);
1105 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1107 if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) {
1111 if (cmd->o.opcode == O_IP6) {
1117 * len == 4 indicates a single IP, whereas lists of 1 or more
1118 * addr/mask pairs have len = (2n+1). We convert len to n so we
1119 * use that to count the number of entries.
1122 for (len = len / 4; len > 0; len -= 2, a += 2) {
1123 int mb = /* mask length */
1124 (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ?
1125 128 : contigmask((uint8_t *)&(a[1]), 128);
1127 if (mb == 128 && do_resolv)
1128 he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6);
1129 if (he != NULL) /* resolved to name */
1130 printf("%s", he->h_name);
1131 else if (mb == 0) /* any */
1133 else { /* numeric IP followed by some kind of mask */
1134 if (inet_ntop(AF_INET6, a, trad, sizeof( trad ) ) == NULL)
1135 printf("Error ntop in print_ip6\n");
1136 printf("%s", trad );
1137 if (mb < 0) /* XXX not really legal... */
1139 inet_ntop(AF_INET6, &a[1], trad, sizeof(trad)));
1149 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av)
1157 type = strtoul(av, &av, 0);
1158 if (*av != ',' && *av != '\0')
1159 errx(EX_DATAERR, "invalid ICMP6 type");
1161 * XXX: shouldn't this be 0xFF? I can't see any reason why
1162 * we shouldn't be able to filter all possiable values
1163 * regardless of the ability of the rest of the kernel to do
1164 * anything useful with them.
1166 if (type > ICMP6_MAXTYPE)
1167 errx(EX_DATAERR, "ICMP6 type out of range");
1168 cmd->d[type / 32] |= ( 1 << (type % 32));
1170 cmd->o.opcode = O_ICMP6TYPE;
1171 cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6);
1176 print_icmp6types(ipfw_insn_u32 *cmd)
1181 printf(" ipv6 icmp6types");
1182 for (i = 0; i < 7; i++)
1183 for (j=0; j < 32; ++j) {
1184 if ( (cmd->d[i] & (1 << (j))) == 0)
1186 printf("%c%d", sep, (i*32 + j));
1192 print_flow6id( ipfw_insn_u32 *cmd)
1194 uint16_t i, limit = cmd->o.arg1;
1197 printf(" flow-id ");
1198 for( i=0; i < limit; ++i) {
1201 printf("%d%c", cmd->d[i], sep);
1205 /* structure and define for the extension header in ipv6 */
1206 static struct _s_x ext6hdrcodes[] = {
1207 { "frag", EXT_FRAGMENT },
1208 { "hopopt", EXT_HOPOPTS },
1209 { "route", EXT_ROUTING },
1210 { "dstopt", EXT_DSTOPTS },
1216 /* fills command for the extension header filtering */
1218 fill_ext6hdr( ipfw_insn *cmd, char *av)
1226 av = strsep( &s, ",") ;
1227 tok = match_token(ext6hdrcodes, av);
1230 cmd->arg1 |= EXT_FRAGMENT;
1234 cmd->arg1 |= EXT_HOPOPTS;
1238 cmd->arg1 |= EXT_ROUTING;
1242 cmd->arg1 |= EXT_DSTOPTS;
1246 cmd->arg1 |= EXT_AH;
1250 cmd->arg1 |= EXT_ESP;
1254 errx( EX_DATAERR, "invalid option for ipv6 exten header" );
1258 if (cmd->arg1 == 0 )
1260 cmd->opcode = O_EXT_HDR;
1261 cmd->len |= F_INSN_SIZE( ipfw_insn );
1266 print_ext6hdr( ipfw_insn *cmd )
1270 printf(" extension header:");
1271 if (cmd->arg1 & EXT_FRAGMENT ) {
1272 printf("%cfragmentation", sep);
1275 if (cmd->arg1 & EXT_HOPOPTS ) {
1276 printf("%chop options", sep);
1279 if (cmd->arg1 & EXT_ROUTING ) {
1280 printf("%crouting options", sep);
1283 if (cmd->arg1 & EXT_DSTOPTS ) {
1284 printf("%cdestination options", sep);
1287 if (cmd->arg1 & EXT_AH ) {
1288 printf("%cauthentication header", sep);
1291 if (cmd->arg1 & EXT_ESP ) {
1292 printf("%cencapsulated security payload", sep);
1297 * show_ipfw() prints the body of an ipfw rule.
1298 * Because the standard rule has at least proto src_ip dst_ip, we use
1299 * a helper function to produce these entries if not provided explicitly.
1300 * The first argument is the list of fields we have, the second is
1301 * the list of fields we want to be printed.
1303 * Special cases if we have provided a MAC header:
1304 * + if the rule does not contain IP addresses/ports, do not print them;
1305 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1307 * Once we have 'have_options', IP header fields are printed as options.
1309 #define HAVE_PROTO 0x0001
1310 #define HAVE_SRCIP 0x0002
1311 #define HAVE_DSTIP 0x0004
1312 #define HAVE_MAC 0x0008
1313 #define HAVE_MACTYPE 0x0010
1314 #define HAVE_PROTO4 0x0040
1315 #define HAVE_PROTO6 0x0080
1316 #define HAVE_OPTIONS 0x8000
1318 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
1320 show_prerequisites(int *flags, int want, int cmd)
1324 if ( (*flags & HAVE_IP) == HAVE_IP)
1325 *flags |= HAVE_OPTIONS;
1327 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC &&
1328 cmd != O_MAC_TYPE) {
1330 * mac-type was optimized out by the compiler,
1334 *flags |= HAVE_MACTYPE | HAVE_OPTIONS;
1337 if ( !(*flags & HAVE_OPTIONS)) {
1338 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
1339 if ( (*flags & HAVE_PROTO4))
1341 else if ( (*flags & HAVE_PROTO6))
1346 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1347 printf(" from any");
1348 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1355 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1357 static int twidth = 0;
1360 char *comment = NULL; /* ptr to comment if we have one */
1361 int proto = 0; /* default */
1362 int flags = 0; /* prerequisites */
1363 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1364 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1365 int or_block = 0; /* we are in an or block */
1366 uint32_t set_disable;
1368 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1370 if (set_disable & (1 << rule->set)) { /* disabled */
1374 printf("# DISABLED ");
1376 printf("%05u ", rule->rulenum);
1378 if (pcwidth>0 || bcwidth>0)
1379 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
1380 bcwidth, align_uint64(&rule->bcnt));
1383 printf("%10u ", rule->timestamp);
1384 else if (do_time == 1) {
1386 time_t t = (time_t)0;
1389 strcpy(timestr, ctime(&t));
1390 *strchr(timestr, '\n') = '\0';
1391 twidth = strlen(timestr);
1393 if (rule->timestamp) {
1394 #if _FreeBSD_version < 500000 /* XXX check */
1395 #define _long_to_time(x) (time_t)(x)
1397 t = _long_to_time(rule->timestamp);
1399 strcpy(timestr, ctime(&t));
1400 *strchr(timestr, '\n') = '\0';
1401 printf("%s ", timestr);
1403 printf("%*s", twidth, " ");
1408 printf("set %d ", rule->set);
1411 * print the optional "match probability"
1413 if (rule->cmd_len > 0) {
1415 if (cmd->opcode == O_PROB) {
1416 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1417 double d = 1.0 * p->d[0];
1419 d = (d / 0x7fffffff);
1420 printf("prob %f ", d);
1425 * first print actions
1427 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1428 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1429 switch(cmd->opcode) {
1431 printf("check-state");
1432 flags = HAVE_IP; /* avoid printing anything else */
1448 if (cmd->arg1 == ICMP_REJECT_RST)
1450 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1453 print_reject_code(cmd->arg1);
1457 if (cmd->arg1 == ICMP6_UNREACH_RST)
1460 print_unreach6_code(cmd->arg1);
1464 printf("skipto %u", cmd->arg1);
1468 printf("pipe %u", cmd->arg1);
1472 printf("queue %u", cmd->arg1);
1476 printf("divert %u", cmd->arg1);
1480 printf("tee %u", cmd->arg1);
1484 printf("netgraph %u", cmd->arg1);
1488 printf("ngtee %u", cmd->arg1);
1493 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1495 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1497 printf(",%d", s->sa.sin_port);
1501 case O_LOG: /* O_LOG is printed last */
1502 logptr = (ipfw_insn_log *)cmd;
1505 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1506 altqptr = (ipfw_insn_altq *)cmd;
1510 printf("** unrecognized action %d len %d ",
1511 cmd->opcode, cmd->len);
1515 if (logptr->max_log > 0)
1516 printf(" log logamount %d", logptr->max_log);
1523 qname = altq_qid_to_name(altqptr->qid);
1525 printf(" altq ?<%u>", altqptr->qid);
1527 printf(" altq %s", qname);
1531 * then print the body.
1533 for (l = rule->act_ofs, cmd = rule->cmd ;
1534 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1535 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1537 if (cmd->opcode == O_IP4) {
1538 flags |= HAVE_PROTO4;
1540 } else if (cmd->opcode == O_IP6) {
1541 flags |= HAVE_PROTO6;
1545 if (rule->_pad & 1) { /* empty rules before options */
1547 show_prerequisites(&flags, HAVE_PROTO, 0);
1548 printf(" from any to any");
1550 flags |= HAVE_IP | HAVE_OPTIONS;
1556 for (l = rule->act_ofs, cmd = rule->cmd ;
1557 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1559 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1562 if (cmd->opcode != O_NOP)
1564 printf(" // %s\n", (char *)(cmd + 1));
1568 show_prerequisites(&flags, 0, cmd->opcode);
1570 switch(cmd->opcode) {
1572 break; /* done already */
1575 break; /* no need to print anything here */
1578 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1580 if ((cmd->len & F_OR) && !or_block)
1582 if (cmd->len & F_NOT)
1586 print_mac(m->addr, m->mask);
1587 print_mac(m->addr + 6, m->mask + 6);
1592 if ((cmd->len & F_OR) && !or_block)
1594 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE,
1595 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1596 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS;
1600 case O_IP_SRC_LOOKUP:
1604 show_prerequisites(&flags, HAVE_PROTO, 0);
1605 if (!(flags & HAVE_SRCIP))
1607 if ((cmd->len & F_OR) && !or_block)
1609 print_ip((ipfw_insn_ip *)cmd,
1610 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1611 flags |= HAVE_SRCIP;
1615 case O_IP_DST_LOOKUP:
1619 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1620 if (!(flags & HAVE_DSTIP))
1622 if ((cmd->len & F_OR) && !or_block)
1624 print_ip((ipfw_insn_ip *)cmd,
1625 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1626 flags |= HAVE_DSTIP;
1630 case O_IP6_SRC_MASK:
1632 show_prerequisites(&flags, HAVE_PROTO, 0);
1633 if (!(flags & HAVE_SRCIP))
1635 if ((cmd->len & F_OR) && !or_block)
1637 print_ip6((ipfw_insn_ip6 *)cmd,
1638 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1639 flags |= HAVE_SRCIP | HAVE_PROTO;
1643 case O_IP6_DST_MASK:
1645 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1646 if (!(flags & HAVE_DSTIP))
1648 if ((cmd->len & F_OR) && !or_block)
1650 print_ip6((ipfw_insn_ip6 *)cmd,
1651 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1652 flags |= HAVE_DSTIP;
1656 print_flow6id( (ipfw_insn_u32 *) cmd );
1657 flags |= HAVE_OPTIONS;
1661 show_prerequisites(&flags, HAVE_IP, 0);
1663 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1664 if ((cmd->len & F_OR) && !or_block)
1666 print_newports((ipfw_insn_u16 *)cmd, proto,
1667 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1671 struct protoent *pe = NULL;
1673 if ((cmd->len & F_OR) && !or_block)
1675 if (cmd->len & F_NOT)
1678 pe = getprotobynumber(cmd->arg1);
1679 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1680 !(flags & HAVE_PROTO))
1681 show_prerequisites(&flags,
1682 HAVE_IP | HAVE_OPTIONS, 0);
1683 if (flags & HAVE_OPTIONS)
1686 printf(" %s", pe->p_name);
1688 printf(" %u", cmd->arg1);
1690 flags |= HAVE_PROTO;
1693 default: /*options ... */
1694 if (!(cmd->len & (F_OR|F_NOT)))
1695 if (((cmd->opcode == O_IP6) &&
1696 (flags & HAVE_PROTO6)) ||
1697 ((cmd->opcode == O_IP4) &&
1698 (flags & HAVE_PROTO4)))
1700 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1701 if ((cmd->len & F_OR) && !or_block)
1703 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1705 switch(cmd->opcode) {
1711 printf(cmd->len & F_NOT ? " out" : " in");
1715 switch (cmd->arg1) {
1717 printf(" diverted");
1720 printf(" diverted-loopback");
1723 printf(" diverted-output");
1726 printf(" diverted-?<%u>", cmd->arg1);
1739 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1741 if (cmd->opcode == O_XMIT)
1743 else if (cmd->opcode == O_RECV)
1745 else /* if (cmd->opcode == O_VIA) */
1747 if (cmdif->name[0] == '\0')
1749 inet_ntoa(cmdif->p.ip));
1751 printf(" %s %s", s, cmdif->name);
1756 if (F_LEN(cmd) == 1)
1757 printf(" ipid %u", cmd->arg1 );
1759 print_newports((ipfw_insn_u16 *)cmd, 0,
1764 if (F_LEN(cmd) == 1)
1765 printf(" ipttl %u", cmd->arg1 );
1767 print_newports((ipfw_insn_u16 *)cmd, 0,
1772 printf(" ipver %u", cmd->arg1 );
1775 case O_IPPRECEDENCE:
1776 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1780 if (F_LEN(cmd) == 1)
1781 printf(" iplen %u", cmd->arg1 );
1783 print_newports((ipfw_insn_u16 *)cmd, 0,
1788 print_flags("ipoptions", cmd, f_ipopts);
1792 print_flags("iptos", cmd, f_iptos);
1796 print_icmptypes((ipfw_insn_u32 *)cmd);
1800 printf(" established");
1804 if (F_LEN(cmd) == 1)
1805 printf(" tcpdatalen %u", cmd->arg1 );
1807 print_newports((ipfw_insn_u16 *)cmd, 0,
1812 print_flags("tcpflags", cmd, f_tcpflags);
1816 print_flags("tcpoptions", cmd, f_tcpopts);
1820 printf(" tcpwin %d", ntohs(cmd->arg1));
1824 printf(" tcpack %d", ntohl(cmd32->d[0]));
1828 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1833 struct passwd *pwd = getpwuid(cmd32->d[0]);
1836 printf(" uid %s", pwd->pw_name);
1838 printf(" uid %u", cmd32->d[0]);
1844 struct group *grp = getgrgid(cmd32->d[0]);
1847 printf(" gid %s", grp->gr_name);
1849 printf(" gid %u", cmd32->d[0]);
1854 printf(" jail %d", cmd32->d[0]);
1858 printf(" verrevpath");
1862 printf(" versrcreach");
1866 printf(" antispoof");
1874 comment = (char *)(cmd + 1);
1878 printf(" keep-state");
1883 struct _s_x *p = limit_masks;
1884 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1885 uint8_t x = c->limit_mask;
1886 char const *comma = " ";
1889 for (; p->x != 0 ; p++)
1890 if ((x & p->x) == p->x) {
1892 printf("%s%s", comma, p->s);
1895 printf(" %d", c->conn_limit);
1908 print_icmp6types((ipfw_insn_u32 *)cmd);
1912 print_ext6hdr( (ipfw_insn *) cmd );
1916 printf(" [opcode %d len %d]",
1917 cmd->opcode, cmd->len);
1920 if (cmd->len & F_OR) {
1923 } else if (or_block) {
1928 show_prerequisites(&flags, HAVE_IP, 0);
1930 printf(" // %s", comment);
1935 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1937 struct protoent *pe;
1942 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1945 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1946 printf("%05d", rulenum);
1947 if (pcwidth>0 || bcwidth>0)
1948 printf(" %*llu %*llu (%ds)", pcwidth,
1949 align_uint64(&d->pcnt), bcwidth,
1950 align_uint64(&d->bcnt), d->expire);
1951 switch (d->dyn_type) {
1952 case O_LIMIT_PARENT:
1953 printf(" PARENT %d", d->count);
1958 case O_KEEP_STATE: /* bidir, no mask */
1963 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1964 printf(" %s", pe->p_name);
1966 printf(" proto %u", d->id.proto);
1968 a.s_addr = htonl(d->id.src_ip);
1969 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1971 a.s_addr = htonl(d->id.dst_ip);
1972 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1977 sort_q(const void *pa, const void *pb)
1979 int rev = (do_sort < 0);
1980 int field = rev ? -do_sort : do_sort;
1982 const struct dn_flow_queue *a = pa;
1983 const struct dn_flow_queue *b = pb;
1987 res = a->len - b->len;
1990 res = a->len_bytes - b->len_bytes;
1993 case 3: /* tot pkts */
1994 res = a->tot_pkts - b->tot_pkts;
1997 case 4: /* tot bytes */
1998 res = a->tot_bytes - b->tot_bytes;
2005 return (int)(rev ? res : -res);
2009 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
2012 int index_printed, indexes = 0;
2014 struct protoent *pe;
2016 if (fs->rq_elements == 0)
2020 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
2022 /* Print IPv4 flows */
2024 for (l = 0; l < fs->rq_elements; l++) {
2027 /* XXX: Should check for IPv4 flows */
2028 if (IS_IP6_FLOW_ID(&(q[l].id)))
2031 if (!index_printed) {
2033 if (indexes > 0) /* currently a no-op */
2037 "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
2038 fs->flow_mask.proto,
2039 fs->flow_mask.src_ip, fs->flow_mask.src_port,
2040 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
2042 printf("BKT Prot ___Source IP/port____ "
2043 "____Dest. IP/port____ "
2044 "Tot_pkt/bytes Pkt/Byte Drp\n");
2047 printf("%3d ", q[l].hash_slot);
2048 pe = getprotobynumber(q[l].id.proto);
2050 printf("%-4s ", pe->p_name);
2052 printf("%4u ", q[l].id.proto);
2053 ina.s_addr = htonl(q[l].id.src_ip);
2054 printf("%15s/%-5d ",
2055 inet_ntoa(ina), q[l].id.src_port);
2056 ina.s_addr = htonl(q[l].id.dst_ip);
2057 printf("%15s/%-5d ",
2058 inet_ntoa(ina), q[l].id.dst_port);
2059 printf("%4qu %8qu %2u %4u %3u\n",
2060 q[l].tot_pkts, q[l].tot_bytes,
2061 q[l].len, q[l].len_bytes, q[l].drops);
2063 printf(" S %20qd F %20qd\n",
2067 /* Print IPv6 flows */
2069 for (l = 0; l < fs->rq_elements; l++) {
2070 if (!IS_IP6_FLOW_ID(&(q[l].id)))
2073 if (!index_printed) {
2078 printf("\n mask: proto: 0x%02x, flow_id: 0x%08x, ",
2079 fs->flow_mask.proto, fs->flow_mask.flow_id6);
2080 inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
2081 buff, sizeof(buff));
2082 printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
2083 inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
2084 buff, sizeof(buff) );
2085 printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
2087 printf("BKT ___Prot___ _flow-id_ "
2088 "______________Source IPv6/port_______________ "
2089 "_______________Dest. IPv6/port_______________ "
2090 "Tot_pkt/bytes Pkt/Byte Drp\n");
2092 printf("%3d ", q[l].hash_slot);
2093 pe = getprotobynumber(q[l].id.proto);
2095 printf("%9s ", pe->p_name);
2097 printf("%9u ", q[l].id.proto);
2098 printf("%7d %39s/%-5d ", q[l].id.flow_id6,
2099 inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
2101 printf(" %39s/%-5d ",
2102 inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
2104 printf(" %4qu %8qu %2u %4u %3u\n",
2105 q[l].tot_pkts, q[l].tot_bytes,
2106 q[l].len, q[l].len_bytes, q[l].drops);
2108 printf(" S %20qd F %20qd\n", q[l].S, q[l].F);
2113 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
2118 char red[90]; /* Display RED parameters */
2121 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
2123 sprintf(qs, "%d KB", l / 1024);
2125 sprintf(qs, "%d B", l);
2127 sprintf(qs, "%3d sl.", l);
2129 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
2132 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
2134 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
2135 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
2136 1.0 * fs->w_q / (double)(1 << SCALE_RED),
2137 SCALE_VAL(fs->min_th),
2138 SCALE_VAL(fs->max_th),
2139 1.0 * fs->max_p / (double)(1 << SCALE_RED));
2141 sprintf(red, "droptail");
2143 printf("%s %s%s %d queues (%d buckets) %s\n",
2144 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
2148 list_pipes(void *data, uint nbytes, int ac, char *av[])
2152 struct dn_pipe *p = (struct dn_pipe *) data;
2153 struct dn_flow_set *fs;
2154 struct dn_flow_queue *q;
2158 rulenum = strtoul(*av++, NULL, 10);
2161 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
2162 double b = p->bandwidth;
2166 if (p->next.sle_next != (struct dn_pipe *)DN_IS_PIPE)
2167 break; /* done with pipes, now queues */
2170 * compute length, as pipe have variable size
2172 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
2173 next = (char *)p + l;
2176 if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2)
2180 * Print rate (or clocking interface)
2182 if (p->if_name[0] != '\0')
2183 sprintf(buf, "%s", p->if_name);
2185 sprintf(buf, "unlimited");
2186 else if (b >= 1000000)
2187 sprintf(buf, "%7.3f Mbit/s", b/1000000);
2189 sprintf(buf, "%7.3f Kbit/s", b/1000);
2191 sprintf(buf, "%7.3f bit/s ", b);
2193 sprintf(prefix, "%05d: %s %4d ms ",
2194 p->pipe_nr, buf, p->delay);
2195 print_flowset_parms(&(p->fs), prefix);
2197 printf(" V %20qd\n", p->V >> MY_M);
2199 q = (struct dn_flow_queue *)(p+1);
2200 list_queues(&(p->fs), q);
2202 for (fs = next; nbytes >= sizeof *fs; fs = next) {
2205 if (fs->next.sle_next != (struct dn_flow_set *)DN_IS_QUEUE)
2207 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
2208 next = (char *)fs + l;
2211 if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) ||
2212 (rulenum != fs->parent_nr && do_pipe == 1))) {
2216 q = (struct dn_flow_queue *)(fs+1);
2217 sprintf(prefix, "q%05d: weight %d pipe %d ",
2218 fs->fs_nr, fs->weight, fs->parent_nr);
2219 print_flowset_parms(fs, prefix);
2225 * This one handles all set-related commands
2226 * ipfw set { show | enable | disable }
2228 * ipfw set move X to Y
2229 * ipfw set move rule X to Y
2232 sets_handler(int ac, char *av[])
2234 uint32_t set_disable, masks[2];
2237 uint8_t cmd, new_set;
2243 errx(EX_USAGE, "set needs command");
2244 if (_substrcmp(*av, "show") == 0) {
2248 nbytes = sizeof(struct ip_fw);
2249 if ((data = calloc(1, nbytes)) == NULL)
2250 err(EX_OSERR, "calloc");
2251 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2252 err(EX_OSERR, "getsockopt(IP_FW_GET)");
2253 bcopy(&((struct ip_fw *)data)->next_rule,
2254 &set_disable, sizeof(set_disable));
2256 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2257 if ((set_disable & (1<<i))) {
2258 printf("%s %d", msg, i);
2261 msg = (set_disable) ? " enable" : "enable";
2262 for (i = 0; i < RESVD_SET; i++)
2263 if (!(set_disable & (1<<i))) {
2264 printf("%s %d", msg, i);
2268 } else if (_substrcmp(*av, "swap") == 0) {
2271 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2272 rulenum = atoi(av[0]);
2273 new_set = atoi(av[1]);
2274 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2275 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2276 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2277 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2278 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2279 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2280 } else if (_substrcmp(*av, "move") == 0) {
2282 if (ac && _substrcmp(*av, "rule") == 0) {
2287 if (ac != 3 || _substrcmp(av[1], "to") != 0)
2288 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2289 rulenum = atoi(av[0]);
2290 new_set = atoi(av[2]);
2291 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2292 (cmd == 2 && rulenum == 65535) )
2293 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2294 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2295 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2296 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2297 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2298 } else if (_substrcmp(*av, "disable") == 0 ||
2299 _substrcmp(*av, "enable") == 0 ) {
2300 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2303 masks[0] = masks[1] = 0;
2306 if (isdigit(**av)) {
2308 if (i < 0 || i > RESVD_SET)
2310 "invalid set number %d\n", i);
2311 masks[which] |= (1<<i);
2312 } else if (_substrcmp(*av, "disable") == 0)
2314 else if (_substrcmp(*av, "enable") == 0)
2318 "invalid set command %s\n", *av);
2321 if ( (masks[0] & masks[1]) != 0 )
2323 "cannot enable and disable the same set\n");
2325 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2327 warn("set enable/disable: setsockopt(IP_FW_DEL)");
2329 errx(EX_USAGE, "invalid set command %s\n", *av);
2333 sysctl_handler(int ac, char *av[], int which)
2339 warnx("missing keyword to enable/disable\n");
2340 } else if (_substrcmp(*av, "firewall") == 0) {
2341 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2342 &which, sizeof(which));
2343 } else if (_substrcmp(*av, "one_pass") == 0) {
2344 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2345 &which, sizeof(which));
2346 } else if (_substrcmp(*av, "debug") == 0) {
2347 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2348 &which, sizeof(which));
2349 } else if (_substrcmp(*av, "verbose") == 0) {
2350 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2351 &which, sizeof(which));
2352 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2353 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2354 &which, sizeof(which));
2355 } else if (_substrcmp(*av, "altq") == 0) {
2356 altq_set_enabled(which);
2358 warnx("unrecognize enable/disable keyword: %s\n", *av);
2363 list(int ac, char *av[], int show_counters)
2366 ipfw_dyn_rule *dynrules, *d;
2368 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
2371 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2372 int exitval = EX_OK;
2379 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2380 int nalloc = 1024; /* start somewhere... */
2385 fprintf(stderr, "Testing only, list disabled\n");
2392 /* get rules or pipes from kernel, resizing array as necessary */
2395 while (nbytes >= nalloc) {
2396 nalloc = nalloc * 2 + 200;
2398 if ((data = realloc(data, nbytes)) == NULL)
2399 err(EX_OSERR, "realloc");
2400 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2401 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2402 do_pipe ? "DUMMYNET" : "FW");
2406 list_pipes(data, nbytes, ac, av);
2411 * Count static rules. They have variable size so we
2412 * need to scan the list to count them.
2414 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2415 r->rulenum < 65535 && (char *)r < lim;
2416 ++nstat, r = NEXT(r) )
2420 * Count dynamic rules. This is easier as they have
2424 dynrules = (ipfw_dyn_rule *)r ;
2425 n = (char *)r - (char *)data;
2426 ndyn = (nbytes - n) / sizeof *dynrules;
2428 /* if showing stats, figure out column widths ahead of time */
2429 bcwidth = pcwidth = 0;
2430 if (show_counters) {
2431 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2432 /* packet counter */
2433 width = snprintf(NULL, 0, "%llu",
2434 align_uint64(&r->pcnt));
2435 if (width > pcwidth)
2439 width = snprintf(NULL, 0, "%llu",
2440 align_uint64(&r->bcnt));
2441 if (width > bcwidth)
2445 if (do_dynamic && ndyn) {
2446 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2447 width = snprintf(NULL, 0, "%llu",
2448 align_uint64(&d->pcnt));
2449 if (width > pcwidth)
2452 width = snprintf(NULL, 0, "%llu",
2453 align_uint64(&d->bcnt));
2454 if (width > bcwidth)
2458 /* if no rule numbers were specified, list all rules */
2460 for (n = 0, r = data; n < nstat; n++, r = NEXT(r) )
2461 show_ipfw(r, pcwidth, bcwidth);
2463 if (do_dynamic && ndyn) {
2464 printf("## Dynamic rules (%d):\n", ndyn);
2465 for (n = 0, d = dynrules; n < ndyn; n++, d++)
2466 show_dyn_ipfw(d, pcwidth, bcwidth);
2471 /* display specific rules requested on command line */
2473 for (lac = ac, lav = av; lac != 0; lac--) {
2474 /* convert command line rule # */
2475 last = rnum = strtoul(*lav++, &endptr, 10);
2477 last = strtoul(endptr+1, &endptr, 10);
2480 warnx("invalid rule number: %s", *(lav - 1));
2483 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2484 if (r->rulenum > last)
2486 if (r->rulenum >= rnum && r->rulenum <= last) {
2487 show_ipfw(r, pcwidth, bcwidth);
2492 /* give precedence to other error(s) */
2493 if (exitval == EX_OK)
2494 exitval = EX_UNAVAILABLE;
2495 warnx("rule %lu does not exist", rnum);
2499 if (do_dynamic && ndyn) {
2500 printf("## Dynamic rules:\n");
2501 for (lac = ac, lav = av; lac != 0; lac--) {
2502 last = rnum = strtoul(*lav++, &endptr, 10);
2504 last = strtoul(endptr+1, &endptr, 10);
2506 /* already warned */
2508 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2511 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2514 if (r->rulenum >= rnum && r->rulenum <= last)
2515 show_dyn_ipfw(d, pcwidth, bcwidth);
2525 if (exitval != EX_OK)
2533 fprintf(stderr, "usage: ipfw [options]\n"
2534 "do \"ipfw -h\" or see ipfw manpage for details\n"
2543 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n"
2544 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n"
2545 "add [num] [set N] [prob x] RULE-BODY\n"
2546 "{pipe|queue} N config PIPE-BODY\n"
2547 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
2548 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
2549 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
2551 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
2552 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n"
2553 " skipto N | {divert|tee} PORT | forward ADDR |\n"
2554 " pipe N | queue N\n"
2555 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
2556 "ADDR: [ MAC dst src ether_type ] \n"
2557 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
2558 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
2559 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
2560 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
2561 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
2562 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
2563 "OPTION_LIST: OPTION [OPTION_LIST]\n"
2564 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
2565 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
2566 " {dst-port|src-port} LIST |\n"
2567 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
2568 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
2569 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
2570 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] |\n"
2571 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
2572 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
2573 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
2580 lookup_host (char *host, struct in_addr *ipaddr)
2584 if (!inet_aton(host, ipaddr)) {
2585 if ((he = gethostbyname(host)) == NULL)
2587 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2593 * fills the addr and mask fields in the instruction as appropriate from av.
2594 * Update length as appropriate.
2595 * The following formats are allowed:
2596 * me returns O_IP_*_ME
2597 * 1.2.3.4 single IP address
2598 * 1.2.3.4:5.6.7.8 address:mask
2599 * 1.2.3.4/24 address/mask
2600 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2601 * We can have multiple comma-separated address/mask entries.
2604 fill_ip(ipfw_insn_ip *cmd, char *av)
2607 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2609 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2611 if (_substrcmp(av, "any") == 0)
2614 if (_substrcmp(av, "me") == 0) {
2615 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2619 if (strncmp(av, "table(", 6) == 0) {
2620 char *p = strchr(av + 6, ',');
2624 cmd->o.opcode = O_IP_DST_LOOKUP;
2625 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2627 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2628 d[0] = strtoul(p, NULL, 0);
2630 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2636 * After the address we can have '/' or ':' indicating a mask,
2637 * ',' indicating another address follows, '{' indicating a
2638 * set of addresses of unspecified size.
2640 char *p = strpbrk(av, "/:,{");
2650 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2651 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2654 if (!inet_aton(p, (struct in_addr *)&d[1]))
2655 errx(EX_DATAERR, "bad netmask ``%s''", p);
2660 d[1] = htonl(0); /* mask */
2661 else if (masklen > 32)
2662 errx(EX_DATAERR, "bad width ``%s''", p);
2664 d[1] = htonl(~0 << (32 - masklen));
2666 case '{': /* no mask, assume /24 and put back the '{' */
2667 d[1] = htonl(~0 << (32 - 24));
2671 case ',': /* single address plus continuation */
2674 case 0: /* initialization value */
2676 d[1] = htonl(~0); /* force /32 */
2679 d[0] &= d[1]; /* mask base address with mask */
2680 /* find next separator */
2682 p = strpbrk(p, ",{");
2683 if (p && *p == '{') {
2685 * We have a set of addresses. They are stored as follows:
2686 * arg1 is the set size (powers of 2, 2..256)
2687 * addr is the base address IN HOST FORMAT
2688 * mask.. is an array of arg1 bits (rounded up to
2689 * the next multiple of 32) with bits set
2690 * for each host in the map.
2692 uint32_t *map = (uint32_t *)&cmd->mask;
2694 int i = contigmask((uint8_t *)&(d[1]), 32);
2697 errx(EX_DATAERR, "address set cannot be in a list");
2698 if (i < 24 || i > 31)
2699 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2700 cmd->o.arg1 = 1<<(32-i); /* map length */
2701 d[0] = ntohl(d[0]); /* base addr in host format */
2702 cmd->o.opcode = O_IP_DST_SET; /* default */
2703 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2704 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2705 map[i] = 0; /* clear map */
2709 high = low + cmd->o.arg1 - 1;
2711 * Here, i stores the previous value when we specify a range
2712 * of addresses within a mask, e.g. 45-63. i = -1 means we
2713 * have no previous value.
2715 i = -1; /* previous value in a range */
2716 while (isdigit(*av)) {
2718 int a = strtol(av, &s, 0);
2720 if (s == av) { /* no parameter */
2722 errx(EX_DATAERR, "set not closed\n");
2724 errx(EX_DATAERR, "incomplete range %d-", i);
2727 if (a < low || a > high)
2728 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2731 if (i == -1) /* no previous in range */
2733 else { /* check that range is valid */
2735 errx(EX_DATAERR, "invalid range %d-%d",
2738 errx(EX_DATAERR, "double '-' in range");
2741 map[i/32] |= 1<<(i & 31);
2752 if (av) /* then *av must be a ',' */
2755 /* Check this entry */
2756 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2758 * 'any' turns the entire list into a NOP.
2759 * 'not any' never matches, so it is removed from the
2760 * list unless it is the only item, in which case we
2763 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2764 if (av == NULL && len == 0) /* only this entry */
2765 errx(EX_DATAERR, "not any never matches");
2767 /* else do nothing and skip this entry */
2770 /* A single IP can be stored in an optimized format */
2771 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) {
2772 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2775 len += 2; /* two words... */
2778 cmd->o.len |= len+1;
2782 /* Try to find ipv6 address by hostname */
2784 lookup_host6 (char *host, struct in6_addr *ip6addr)
2788 if (!inet_pton(AF_INET6, host, ip6addr)) {
2789 if ((he = gethostbyname2(host, AF_INET6)) == NULL)
2791 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr));
2797 /* n2mask sets n bits of the mask */
2799 n2mask(struct in6_addr *mask, int n)
2801 static int minimask[9] =
2802 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2805 memset(mask, 0, sizeof(struct in6_addr));
2806 p = (u_char *) mask;
2807 for (; n > 0; p++, n -= 8) {
2818 * fill the addr and mask fields in the instruction as appropriate from av.
2819 * Update length as appropriate.
2820 * The following formats are allowed:
2821 * any matches any IP6. Actually returns an empty instruction.
2822 * me returns O_IP6_*_ME
2824 * 03f1::234:123:0342 single IP6 addres
2825 * 03f1::234:123:0342/24 address/mask
2826 * 03f1::234:123:0342/24,03f1::234:123:0343/ List of address
2828 * Set of address (as in ipv6) not supported because ipv6 address
2829 * are typically random past the initial prefix.
2830 * Return 1 on success, 0 on failure.
2833 fill_ip6(ipfw_insn_ip6 *cmd, char *av)
2836 struct in6_addr *d = &(cmd->addr6);
2838 * Needed for multiple address.
2839 * Note d[1] points to struct in6_add r mask6 of cmd
2842 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2844 if (strcmp(av, "any") == 0)
2848 if (strcmp(av, "me") == 0) { /* Set the data for "me" opt*/
2849 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2853 if (strcmp(av, "me6") == 0) { /* Set the data for "me" opt*/
2854 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2861 * After the address we can have '/' indicating a mask,
2862 * or ',' indicating another address follows.
2869 if ((p = strpbrk(av, "/,")) ) {
2870 md = *p; /* save the separator */
2871 *p = '\0'; /* terminate address string */
2872 p++; /* and skip past it */
2874 /* now p points to NULL, mask or next entry */
2876 /* lookup stores address in *d as a side effect */
2877 if (lookup_host6(av, d) != 0) {
2878 /* XXX: failed. Free memory and go */
2879 errx(EX_DATAERR, "bad address \"%s\"", av);
2881 /* next, look at the mask, if any */
2882 masklen = (md == '/') ? atoi(p) : 128;
2883 if (masklen > 128 || masklen < 0)
2884 errx(EX_DATAERR, "bad width \"%s\''", p);
2886 n2mask(&d[1], masklen);
2888 APPLY_MASK(d, &d[1]) /* mask base address with mask */
2890 /* find next separator */
2892 if (md == '/') { /* find separator past the mask */
2893 p = strpbrk(p, ",");
2899 /* Check this entry */
2902 * 'any' turns the entire list into a NOP.
2903 * 'not any' never matches, so it is removed from the
2904 * list unless it is the only item, in which case we
2907 if (cmd->o.len & F_NOT && av == NULL && len == 0)
2908 errx(EX_DATAERR, "not any never matches");
2913 * A single IP can be stored alone
2915 if (masklen == 128 && av == NULL && len == 0) {
2916 len = F_INSN_SIZE(struct in6_addr);
2920 /* Update length and pointer to arguments */
2921 len += F_INSN_SIZE(struct in6_addr)*2;
2926 * Total length of the command, remember that 1 is the size of
2929 cmd->o.len |= len+1;
2935 * fills command for ipv6 flow-id filtering
2936 * note that the 20 bit flow number is stored in a array of u_int32_t
2937 * it's supported lists of flow-id, so in the o.arg1 we store how many
2938 * additional flow-id we want to filter, the basic is 1
2941 fill_flow6( ipfw_insn_u32 *cmd, char *av )
2943 u_int32_t type; /* Current flow number */
2944 u_int16_t nflow = 0; /* Current flow index */
2946 cmd->d[0] = 0; /* Initializing the base number*/
2949 av = strsep( &s, ",") ;
2950 type = strtoul(av, &av, 0);
2951 if (*av != ',' && *av != '\0')
2952 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
2954 errx(EX_DATAERR, "flow number out of range %s", av);
2955 cmd->d[nflow] |= type;
2959 cmd->o.opcode = O_FLOW6ID;
2960 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow;
2961 cmd->o.arg1 = nflow;
2964 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
2969 add_srcip6(ipfw_insn *cmd, char *av)
2972 fill_ip6((ipfw_insn_ip6 *)cmd, av);
2973 if (F_LEN(cmd) == 0) /* any */
2975 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
2976 cmd->opcode = O_IP6_SRC_ME;
2977 } else if (F_LEN(cmd) ==
2978 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
2979 /* single IP, no mask*/
2980 cmd->opcode = O_IP6_SRC;
2981 } else { /* addr/mask opt */
2982 cmd->opcode = O_IP6_SRC_MASK;
2988 add_dstip6(ipfw_insn *cmd, char *av)
2991 fill_ip6((ipfw_insn_ip6 *)cmd, av);
2992 if (F_LEN(cmd) == 0) /* any */
2994 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
2995 cmd->opcode = O_IP6_DST_ME;
2996 } else if (F_LEN(cmd) ==
2997 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
2998 /* single IP, no mask*/
2999 cmd->opcode = O_IP6_DST;
3000 } else { /* addr/mask opt */
3001 cmd->opcode = O_IP6_DST_MASK;
3008 * helper function to process a set of flags and set bits in the
3009 * appropriate masks.
3012 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3013 struct _s_x *flags, char *p)
3015 uint8_t set=0, clear=0;
3018 char *q; /* points to the separator */
3020 uint8_t *which; /* mask we are working on */
3030 val = match_token(flags, p);
3032 errx(EX_DATAERR, "invalid flag %s", p);
3033 *which |= (uint8_t)val;
3036 cmd->opcode = opcode;
3037 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3038 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3043 delete(int ac, char *av[])
3048 int exitval = EX_OK;
3051 memset(&p, 0, sizeof p);
3054 NEED1("missing rule specification");
3055 if (ac > 0 && _substrcmp(*av, "set") == 0) {
3056 do_set = 1; /* delete set */
3061 while (ac && isdigit(**av)) {
3062 i = atoi(*av); av++; ac--;
3068 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
3071 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
3072 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
3075 rulenum = (i & 0xffff) | (do_set << 24);
3076 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
3078 exitval = EX_UNAVAILABLE;
3079 warn("rule %u: setsockopt(IP_FW_DEL)",
3084 if (exitval != EX_OK)
3090 * fill the interface structure. We do not check the name as we can
3091 * create interfaces dynamically, so checking them at insert time
3092 * makes relatively little sense.
3093 * Interface names containing '*', '?', or '[' are assumed to be shell
3094 * patterns which match interfaces.
3097 fill_iface(ipfw_insn_if *cmd, char *arg)
3099 cmd->name[0] = '\0';
3100 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3102 /* Parse the interface or address */
3103 if (strcmp(arg, "any") == 0)
3104 cmd->o.len = 0; /* effectively ignore this command */
3105 else if (!isdigit(*arg)) {
3106 strlcpy(cmd->name, arg, sizeof(cmd->name));
3107 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3108 } else if (!inet_aton(arg, &cmd->p.ip))
3109 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3113 config_pipe(int ac, char **av)
3120 memset(&p, 0, sizeof p);
3124 if (ac && isdigit(**av)) {
3125 i = atoi(*av); av++; ac--;
3133 int tok = match_token(dummynet_params, *av);
3138 p.fs.flags_fs |= DN_NOERROR;
3142 NEED1("plr needs argument 0..1\n");
3143 d = strtod(av[0], NULL);
3148 p.fs.plr = (int)(d*0x7fffffff);
3153 NEED1("queue needs queue size\n");
3155 p.fs.qsize = strtoul(av[0], &end, 0);
3156 if (*end == 'K' || *end == 'k') {
3157 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
3159 } else if (*end == 'B' ||
3160 _substrcmp2(end, "by", "bytes") == 0) {
3161 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
3167 NEED1("buckets needs argument\n");
3168 p.fs.rq_size = strtoul(av[0], NULL, 0);
3173 NEED1("mask needs mask specifier\n");
3175 * per-flow queue, mask is dst_ip, dst_port,
3176 * src_ip, src_port, proto measured in bits
3180 bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
3184 uint32_t *p32 = NULL;
3185 uint16_t *p16 = NULL;
3186 uint32_t *p20 = NULL;
3187 struct in6_addr *pa6 = NULL;
3190 tok = match_token(dummynet_params, *av);
3195 * special case, all bits significant
3197 p.fs.flow_mask.dst_ip = ~0;
3198 p.fs.flow_mask.src_ip = ~0;
3199 p.fs.flow_mask.dst_port = ~0;
3200 p.fs.flow_mask.src_port = ~0;
3201 p.fs.flow_mask.proto = ~0;
3202 n2mask(&(p.fs.flow_mask.dst_ip6), 128);
3203 n2mask(&(p.fs.flow_mask.src_ip6), 128);
3204 p.fs.flow_mask.flow_id6 = ~0;
3205 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
3209 p32 = &p.fs.flow_mask.dst_ip;
3213 p32 = &p.fs.flow_mask.src_ip;
3217 pa6 = &(p.fs.flow_mask.dst_ip6);
3221 pa6 = &(p.fs.flow_mask.src_ip6);
3225 p20 = &p.fs.flow_mask.flow_id6;
3229 p16 = &p.fs.flow_mask.dst_port;
3233 p16 = &p.fs.flow_mask.src_port;
3240 ac++; av--; /* backtrack */
3244 errx(EX_USAGE, "mask: value missing");
3245 if (*av[0] == '/') {
3246 a = strtoul(av[0]+1, &end, 0);
3248 a = (a == 32) ? ~0 : (1 << a) - 1;
3250 a = strtoul(av[0], &end, 0);
3253 else if (p16 != NULL) {
3256 "port mask must be 16 bit");
3258 } else if (p20 != NULL) {
3261 "flow_id mask must be 20 bit");
3263 } else if (pa6 != NULL) {
3264 if (a < 0 || a > 128)
3266 "in6addr invalid mask len");
3272 "proto mask must be 8 bit");
3273 p.fs.flow_mask.proto = (uint8_t)a;
3276 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
3278 } /* end while, config masks */
3284 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
3285 p.fs.flags_fs |= DN_IS_RED;
3286 if (tok == TOK_GRED)
3287 p.fs.flags_fs |= DN_IS_GENTLE_RED;
3289 * the format for parameters is w_q/min_th/max_th/max_p
3291 if ((end = strsep(&av[0], "/"))) {
3292 double w_q = strtod(end, NULL);
3293 if (w_q > 1 || w_q <= 0)
3294 errx(EX_DATAERR, "0 < w_q <= 1");
3295 p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
3297 if ((end = strsep(&av[0], "/"))) {
3298 p.fs.min_th = strtoul(end, &end, 0);
3299 if (*end == 'K' || *end == 'k')
3300 p.fs.min_th *= 1024;
3302 if ((end = strsep(&av[0], "/"))) {
3303 p.fs.max_th = strtoul(end, &end, 0);
3304 if (*end == 'K' || *end == 'k')
3305 p.fs.max_th *= 1024;
3307 if ((end = strsep(&av[0], "/"))) {
3308 double max_p = strtod(end, NULL);
3309 if (max_p > 1 || max_p <= 0)
3310 errx(EX_DATAERR, "0 < max_p <= 1");
3311 p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
3317 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
3321 NEED1("bw needs bandwidth or interface\n");
3323 errx(EX_DATAERR, "bandwidth only valid for pipes");
3325 * set clocking interface or bandwidth value
3327 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
3328 int l = sizeof(p.if_name)-1;
3329 /* interface name */
3330 strncpy(p.if_name, av[0], l);
3331 p.if_name[l] = '\0';
3334 p.if_name[0] = '\0';
3335 p.bandwidth = strtoul(av[0], &end, 0);
3336 if (*end == 'K' || *end == 'k') {
3338 p.bandwidth *= 1000;
3339 } else if (*end == 'M') {
3341 p.bandwidth *= 1000000;
3344 _substrcmp2(end, "by", "bytes") == 0)
3346 if (p.bandwidth < 0)
3347 errx(EX_DATAERR, "bandwidth too large");
3354 errx(EX_DATAERR, "delay only valid for pipes");
3355 NEED1("delay needs argument 0..10000ms\n");
3356 p.delay = strtoul(av[0], NULL, 0);
3362 errx(EX_DATAERR,"weight only valid for queues");
3363 NEED1("weight needs argument 0..100\n");
3364 p.fs.weight = strtoul(av[0], &end, 0);
3370 errx(EX_DATAERR,"pipe only valid for queues");
3371 NEED1("pipe needs pipe_number\n");
3372 p.fs.parent_nr = strtoul(av[0], &end, 0);
3377 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
3382 errx(EX_DATAERR, "pipe_nr must be > 0");
3383 if (p.delay > 10000)
3384 errx(EX_DATAERR, "delay must be < 10000");
3385 } else { /* do_pipe == 2, queue */
3386 if (p.fs.parent_nr == 0)
3387 errx(EX_DATAERR, "pipe must be > 0");
3388 if (p.fs.weight >100)
3389 errx(EX_DATAERR, "weight must be <= 100");
3391 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
3392 if (p.fs.qsize > 1024*1024)
3393 errx(EX_DATAERR, "queue size must be < 1MB");
3395 if (p.fs.qsize > 100)
3396 errx(EX_DATAERR, "2 <= queue size <= 100");
3398 if (p.fs.flags_fs & DN_IS_RED) {
3400 int lookup_depth, avg_pkt_size;
3401 double s, idle, weight, w_q;
3402 struct clockinfo ck;
3405 if (p.fs.min_th >= p.fs.max_th)
3406 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
3407 p.fs.min_th, p.fs.max_th);
3408 if (p.fs.max_th == 0)
3409 errx(EX_DATAERR, "max_th must be > 0");
3412 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
3413 &lookup_depth, &len, NULL, 0) == -1)
3415 errx(1, "sysctlbyname(\"%s\")",
3416 "net.inet.ip.dummynet.red_lookup_depth");
3417 if (lookup_depth == 0)
3418 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
3419 " must be greater than zero");
3422 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
3423 &avg_pkt_size, &len, NULL, 0) == -1)
3425 errx(1, "sysctlbyname(\"%s\")",
3426 "net.inet.ip.dummynet.red_avg_pkt_size");
3427 if (avg_pkt_size == 0)
3429 "net.inet.ip.dummynet.red_avg_pkt_size must"
3430 " be greater than zero");
3432 len = sizeof(struct clockinfo);
3433 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
3434 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
3437 * Ticks needed for sending a medium-sized packet.
3438 * Unfortunately, when we are configuring a WF2Q+ queue, we
3439 * do not have bandwidth information, because that is stored
3440 * in the parent pipe, and also we have multiple queues
3441 * competing for it. So we set s=0, which is not very
3442 * correct. But on the other hand, why do we want RED with
3445 if (p.bandwidth==0) /* this is a WF2Q+ queue */
3448 s = ck.hz * avg_pkt_size * 8 / p.bandwidth;
3451 * max idle time (in ticks) before avg queue size becomes 0.
3452 * NOTA: (3/w_q) is approx the value x so that
3453 * (1-w_q)^x < 10^-3.
3455 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
3456 idle = s * 3. / w_q;
3457 p.fs.lookup_step = (int)idle / lookup_depth;
3458 if (!p.fs.lookup_step)
3459 p.fs.lookup_step = 1;
3461 for (t = p.fs.lookup_step; t > 0; --t)
3463 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
3465 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
3467 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
3471 get_mac_addr_mask(char *p, uint8_t *addr, uint8_t *mask)
3476 addr[i] = mask[i] = 0;
3477 if (strcmp(p, "any") == 0)
3480 for (i=0; *p && i<6;i++, p++) {
3481 addr[i] = strtol(p, &p, 16);
3482 if (*p != ':') /* we start with the mask */
3485 if (*p == '/') { /* mask len */
3486 l = strtol(p+1, &p, 0);
3487 for (i=0; l>0; l -=8, i++)
3488 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
3489 } else if (*p == '&') { /* mask */
3490 for (i=0, p++; *p && i<6;i++, p++) {
3491 mask[i] = strtol(p, &p, 16);
3495 } else if (*p == '\0') {
3504 * helper function, updates the pointer to cmd with the length
3505 * of the current command, and also cleans up the first word of
3506 * the new command in case it has been clobbered before.
3509 next_cmd(ipfw_insn *cmd)
3512 bzero(cmd, sizeof(*cmd));
3517 * Takes arguments and copies them into a comment
3520 fill_comment(ipfw_insn *cmd, int ac, char **av)
3523 char *p = (char *)(cmd + 1);
3525 cmd->opcode = O_NOP;
3526 cmd->len = (cmd->len & (F_NOT | F_OR));
3528 /* Compute length of comment string. */
3529 for (i = 0, l = 0; i < ac; i++)
3530 l += strlen(av[i]) + 1;
3535 "comment too long (max 80 chars)");
3537 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3538 for (i = 0; i < ac; i++) {
3547 * A function to fill simple commands of size 1.
3548 * Existing flags are preserved.
3551 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3553 cmd->opcode = opcode;
3554 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3559 * Fetch and add the MAC address and type, with masks. This generates one or
3560 * two microinstructions, and returns the pointer to the last one.
3563 add_mac(ipfw_insn *cmd, int ac, char *av[])
3568 errx(EX_DATAERR, "MAC dst src");
3570 cmd->opcode = O_MACADDR2;
3571 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3573 mac = (ipfw_insn_mac *)cmd;
3574 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3575 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
3580 add_mactype(ipfw_insn *cmd, int ac, char *av)
3583 errx(EX_DATAERR, "missing MAC type");
3584 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3585 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
3586 cmd->opcode = O_MAC_TYPE;
3593 add_proto(ipfw_insn *cmd, char *av, u_char *proto)
3595 struct protoent *pe;
3597 *proto = IPPROTO_IP;
3599 if (_substrcmp(av, "all") == 0)
3600 ; /* do not set O_IP4 nor O_IP6 */
3601 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3602 /* explicit "just IPv4" rule */
3603 fill_cmd(cmd, O_IP4, 0, 0);
3604 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3605 /* explicit "just IPv6" rule */
3606 *proto = IPPROTO_IPV6;
3607 fill_cmd(cmd, O_IP6, 0, 0);
3608 } else if ((*proto = atoi(av)) > 0)
3610 else if ((pe = getprotobyname(av)) != NULL)
3611 *proto = pe->p_proto;
3614 if (*proto != IPPROTO_IP && *proto != IPPROTO_IPV6)
3615 fill_cmd(cmd, O_PROTO, 0, *proto);
3621 add_srcip(ipfw_insn *cmd, char *av)
3623 fill_ip((ipfw_insn_ip *)cmd, av);
3624 if (cmd->opcode == O_IP_DST_SET) /* set */
3625 cmd->opcode = O_IP_SRC_SET;
3626 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3627 cmd->opcode = O_IP_SRC_LOOKUP;
3628 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3629 cmd->opcode = O_IP_SRC_ME;
3630 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3631 cmd->opcode = O_IP_SRC;
3632 else /* addr/mask */
3633 cmd->opcode = O_IP_SRC_MASK;
3638 add_dstip(ipfw_insn *cmd, char *av)
3640 fill_ip((ipfw_insn_ip *)cmd, av);
3641 if (cmd->opcode == O_IP_DST_SET) /* set */
3643 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3645 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3646 cmd->opcode = O_IP_DST_ME;
3647 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3648 cmd->opcode = O_IP_DST;
3649 else /* addr/mask */
3650 cmd->opcode = O_IP_DST_MASK;
3655 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
3657 if (_substrcmp(av, "any") == 0) {
3659 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
3660 /* XXX todo: check that we have a protocol with ports */
3661 cmd->opcode = opcode;
3668 add_src(ipfw_insn *cmd, char *av, u_char proto)
3672 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3673 inet_pton(AF_INET6, av, &a))
3674 return add_srcip6(cmd, av);
3675 /* XXX: should check for IPv4, not !IPv6 */
3676 if (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3677 !inet_pton(AF_INET6, av, &a))
3678 return add_srcip(cmd, av);
3679 if (strcmp(av, "any") != 0)
3686 add_dst(ipfw_insn *cmd, char *av, u_char proto)
3690 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3691 inet_pton(AF_INET6, av, &a))
3692 return add_dstip6(cmd, av);
3693 /* XXX: should check for IPv4, not !IPv6 */
3694 if (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3695 !inet_pton(AF_INET6, av, &a))
3696 return add_dstip(cmd, av);
3697 if (strcmp(av, "any") != 0)
3704 * Parse arguments and assemble the microinstructions which make up a rule.
3705 * Rules are added into the 'rulebuf' and then copied in the correct order
3706 * into the actual rule.
3708 * The syntax for a rule starts with the action, followed by
3709 * optional action parameters, and the various match patterns.
3710 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3711 * (generated if the rule includes a keep-state option), then the
3712 * various match patterns, log/altq actions, and the actual action.
3716 add(int ac, char *av[])
3719 * rules are added into the 'rulebuf' and then copied in
3720 * the correct order into the actual rule.
3721 * Some things that need to go out of order (prob, action etc.)
3724 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
3726 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3727 ipfw_insn *first_cmd; /* first match pattern */
3732 * various flags used to record that we entered some fields.
3734 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3735 ipfw_insn *have_log = NULL, *have_altq = NULL;
3740 int open_par = 0; /* open parenthesis ( */
3742 /* proto is here because it is used to fetch ports */
3743 u_char proto = IPPROTO_IP; /* default protocol */
3745 double match_prob = 1; /* match probability, default is always match */
3747 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3748 bzero(cmdbuf, sizeof(cmdbuf));
3749 bzero(rulebuf, sizeof(rulebuf));
3751 rule = (struct ip_fw *)rulebuf;
3752 cmd = (ipfw_insn *)cmdbuf;
3753 action = (ipfw_insn *)actbuf;
3757 /* [rule N] -- Rule number optional */
3758 if (ac && isdigit(**av)) {
3759 rule->rulenum = atoi(*av);
3764 /* [set N] -- set number (0..RESVD_SET), optional */
3765 if (ac > 1 && _substrcmp(*av, "set") == 0) {
3766 int set = strtoul(av[1], NULL, 10);
3767 if (set < 0 || set > RESVD_SET)
3768 errx(EX_DATAERR, "illegal set %s", av[1]);
3773 /* [prob D] -- match probability, optional */
3774 if (ac > 1 && _substrcmp(*av, "prob") == 0) {
3775 match_prob = strtod(av[1], NULL);
3777 if (match_prob <= 0 || match_prob > 1)
3778 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3782 /* action -- mandatory */
3783 NEED1("missing action");
3784 i = match_token(rule_actions, *av);
3786 action->len = 1; /* default */
3788 case TOK_CHECKSTATE:
3789 have_state = action;
3790 action->opcode = O_CHECK_STATE;
3794 action->opcode = O_ACCEPT;
3798 action->opcode = O_DENY;
3803 action->opcode = O_REJECT;
3804 action->arg1 = ICMP_UNREACH_HOST;
3808 action->opcode = O_REJECT;
3809 action->arg1 = ICMP_REJECT_RST;
3813 action->opcode = O_UNREACH6;
3814 action->arg1 = ICMP6_UNREACH_RST;
3818 action->opcode = O_REJECT;
3819 NEED1("missing reject code");
3820 fill_reject_code(&action->arg1, *av);
3825 action->opcode = O_UNREACH6;
3826 NEED1("missing unreach code");
3827 fill_unreach6_code(&action->arg1, *av);
3832 action->opcode = O_COUNT;
3837 action->len = F_INSN_SIZE(ipfw_insn);
3840 action->opcode = O_QUEUE;
3841 else if (i == TOK_PIPE)
3842 action->opcode = O_PIPE;
3843 else if (i == TOK_SKIPTO)
3844 action->opcode = O_SKIPTO;
3845 NEED1("missing skipto/pipe/queue number");
3846 action->arg1 = strtoul(*av, NULL, 10);
3852 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
3853 NEED1("missing divert/tee port");
3854 action->arg1 = strtoul(*av, NULL, 0);
3855 if (action->arg1 == 0) {
3858 s = getservbyname(av[0], "divert");
3860 action->arg1 = ntohs(s->s_port);
3862 errx(EX_DATAERR, "illegal divert/tee port");
3869 action->opcode = (i == TOK_NETGRAPH ) ? O_NETGRAPH : O_NGTEE;
3870 NEED1("missing netgraph cookie");
3871 action->arg1 = strtoul(*av, NULL, 0);
3872 if (action->arg1 == 0)
3873 errx(EX_DATAERR, "illegal netgraph cookie");
3878 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3881 NEED1("missing forward address[:port]");
3883 action->opcode = O_FORWARD_IP;
3884 action->len = F_INSN_SIZE(ipfw_insn_sa);
3886 p->sa.sin_len = sizeof(struct sockaddr_in);
3887 p->sa.sin_family = AF_INET;
3890 * locate the address-port separator (':' or ',')
3892 s = strchr(*av, ':');
3894 s = strchr(*av, ',');
3897 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3900 "illegal forwarding port ``%s''", s);
3901 p->sa.sin_port = (u_short)i;
3903 lookup_host(*av, &(p->sa.sin_addr));
3909 /* pretend it is a 'count' rule followed by the comment */
3910 action->opcode = O_COUNT;
3911 ac++; av--; /* go back... */
3915 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3917 action = next_cmd(action);
3920 * [altq queuename] -- altq tag, optional
3921 * [log [logamount N]] -- log, optional
3923 * If they exist, it go first in the cmdbuf, but then it is
3924 * skipped in the copy section to the end of the buffer.
3926 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
3931 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3936 "log cannot be specified more than once");
3937 have_log = (ipfw_insn *)c;
3938 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3939 cmd->opcode = O_LOG;
3940 if (ac && _substrcmp(*av, "logamount") == 0) {
3942 NEED1("logamount requires argument");
3946 "logamount must be positive");
3950 len = sizeof(c->max_log);
3951 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3952 &c->max_log, &len, NULL, 0) == -1)
3953 errx(1, "sysctlbyname(\"%s\")",
3954 "net.inet.ip.fw.verbose_limit");
3961 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3963 NEED1("missing altq queue name");
3966 "altq cannot be specified more than once");
3967 have_altq = (ipfw_insn *)a;
3968 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3969 cmd->opcode = O_ALTQ;
3970 fill_altq_qid(&a->qid, *av);
3978 cmd = next_cmd(cmd);
3981 if (have_state) /* must be a check-state, we are done */
3984 #define OR_START(target) \
3985 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
3987 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3990 if ( (av[0])[1] == '\0') { \
4001 strcmp(*av, ")") == 0 || \
4002 strcmp(*av, "}") == 0)) { \
4007 errx(EX_USAGE, "missing \")\"\n"); \
4011 if (ac && _substrcmp(*av, "not") == 0) { \
4012 if (cmd->len & F_NOT) \
4013 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4014 cmd->len |= F_NOT; \
4018 #define OR_BLOCK(target) \
4019 if (ac && _substrcmp(*av, "or") == 0) { \
4020 if (prev == NULL || open_par == 0) \
4021 errx(EX_DATAERR, "invalid OR block"); \
4022 prev->len |= F_OR; \
4032 * MAC addresses, optional.
4033 * If we have this, we skip the part "proto from src to dst"
4034 * and jump straight to the option parsing.
4037 NEED1("missing protocol");
4038 if (_substrcmp(*av, "MAC") == 0 ||
4039 _substrcmp(*av, "mac") == 0) {
4040 ac--; av++; /* the "MAC" keyword */
4041 add_mac(cmd, ac, av); /* exits in case of errors */
4042 cmd = next_cmd(cmd);
4043 ac -= 2; av += 2; /* dst-mac and src-mac */
4045 NEED1("missing mac type");
4046 if (add_mactype(cmd, ac, av[0]))
4047 cmd = next_cmd(cmd);
4048 ac--; av++; /* any or mac-type */
4054 * protocol, mandatory
4056 OR_START(get_proto);
4058 NEED1("missing protocol");
4059 if (add_proto(cmd, *av, &proto)) {
4061 if (F_LEN(cmd) != 0) {
4063 cmd = next_cmd(cmd);
4065 } else if (first_cmd != cmd) {
4066 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4069 OR_BLOCK(get_proto);
4074 if (!ac || _substrcmp(*av, "from") != 0)
4075 errx(EX_USAGE, "missing ``from''");
4079 * source IP, mandatory
4081 OR_START(source_ip);
4082 NOT_BLOCK; /* optional "not" */
4083 NEED1("missing source address");
4084 if (add_src(cmd, *av, proto)) {
4086 if (F_LEN(cmd) != 0) { /* ! any */
4088 cmd = next_cmd(cmd);
4091 errx(EX_USAGE, "bad source address %s", *av);
4092 OR_BLOCK(source_ip);
4095 * source ports, optional
4097 NOT_BLOCK; /* optional "not" */
4099 if (_substrcmp(*av, "any") == 0 ||
4100 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
4102 if (F_LEN(cmd) != 0)
4103 cmd = next_cmd(cmd);
4110 if (!ac || _substrcmp(*av, "to") != 0)
4111 errx(EX_USAGE, "missing ``to''");
4115 * destination, mandatory
4118 NOT_BLOCK; /* optional "not" */
4119 NEED1("missing dst address");
4120 if (add_dst(cmd, *av, proto)) {
4122 if (F_LEN(cmd) != 0) { /* ! any */
4124 cmd = next_cmd(cmd);
4127 errx( EX_USAGE, "bad destination address %s", *av);
4131 * dest. ports, optional
4133 NOT_BLOCK; /* optional "not" */
4135 if (_substrcmp(*av, "any") == 0 ||
4136 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
4138 if (F_LEN(cmd) != 0)
4139 cmd = next_cmd(cmd);
4144 if (ac && first_cmd == cmd) {
4146 * nothing specified so far, store in the rule to ease
4154 ipfw_insn_u32 *cmd32; /* alias for cmd */
4157 cmd32 = (ipfw_insn_u32 *)cmd;
4159 if (*s == '!') { /* alternate syntax for NOT */
4160 if (cmd->len & F_NOT)
4161 errx(EX_USAGE, "double \"not\" not allowed\n");
4165 i = match_token(rule_options, s);
4169 if (cmd->len & F_NOT)
4170 errx(EX_USAGE, "double \"not\" not allowed\n");
4175 if (open_par == 0 || prev == NULL)
4176 errx(EX_USAGE, "invalid \"or\" block\n");
4180 case TOK_STARTBRACE:
4182 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4188 errx(EX_USAGE, "+missing \")\"\n");
4194 fill_cmd(cmd, O_IN, 0, 0);
4198 cmd->len ^= F_NOT; /* toggle F_NOT */
4199 fill_cmd(cmd, O_IN, 0, 0);
4203 fill_cmd(cmd, O_DIVERTED, 0, 3);
4206 case TOK_DIVERTEDLOOPBACK:
4207 fill_cmd(cmd, O_DIVERTED, 0, 1);
4210 case TOK_DIVERTEDOUTPUT:
4211 fill_cmd(cmd, O_DIVERTED, 0, 2);
4215 fill_cmd(cmd, O_FRAG, 0, 0);
4219 fill_cmd(cmd, O_LAYER2, 0, 0);
4225 NEED1("recv, xmit, via require interface name"
4227 fill_iface((ipfw_insn_if *)cmd, av[0]);
4229 if (F_LEN(cmd) == 0) /* not a valid address */
4232 cmd->opcode = O_XMIT;
4233 else if (i == TOK_RECV)
4234 cmd->opcode = O_RECV;
4235 else if (i == TOK_VIA)
4236 cmd->opcode = O_VIA;
4240 NEED1("icmptypes requires list of types");
4241 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4245 case TOK_ICMP6TYPES:
4246 NEED1("icmptypes requires list of types");
4247 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
4252 NEED1("ipttl requires TTL");
4253 if (strpbrk(*av, "-,")) {
4254 if (!add_ports(cmd, *av, 0, O_IPTTL))
4255 errx(EX_DATAERR, "invalid ipttl %s", *av);
4257 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4262 NEED1("ipid requires id");
4263 if (strpbrk(*av, "-,")) {
4264 if (!add_ports(cmd, *av, 0, O_IPID))
4265 errx(EX_DATAERR, "invalid ipid %s", *av);
4267 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4272 NEED1("iplen requires length");
4273 if (strpbrk(*av, "-,")) {
4274 if (!add_ports(cmd, *av, 0, O_IPLEN))
4275 errx(EX_DATAERR, "invalid ip len %s", *av);
4277 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4282 NEED1("ipver requires version");
4283 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4287 case TOK_IPPRECEDENCE:
4288 NEED1("ipprecedence requires value");
4289 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4290 (strtoul(*av, NULL, 0) & 7) << 5);
4295 NEED1("missing argument for ipoptions");
4296 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
4301 NEED1("missing argument for iptos");
4302 fill_flags(cmd, O_IPTOS, f_iptos, *av);
4307 NEED1("uid requires argument");
4313 cmd->opcode = O_UID;
4314 uid = strtoul(*av, &end, 0);
4315 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4317 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4318 cmd32->d[0] = pwd->pw_uid;
4319 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4325 NEED1("gid requires argument");
4331 cmd->opcode = O_GID;
4332 gid = strtoul(*av, &end, 0);
4333 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4335 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4336 cmd32->d[0] = grp->gr_gid;
4337 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4343 NEED1("jail requires argument");
4348 cmd->opcode = O_JAIL;
4349 jid = (int)strtol(*av, &end, 0);
4350 if (jid < 0 || *end != '\0')
4351 errx(EX_DATAERR, "jail requires prison ID");
4352 cmd32->d[0] = (uint32_t)jid;
4353 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4359 fill_cmd(cmd, O_ESTAB, 0, 0);
4363 fill_cmd(cmd, O_TCPFLAGS, 0,
4364 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4367 case TOK_TCPDATALEN:
4368 NEED1("tcpdatalen requires length");
4369 if (strpbrk(*av, "-,")) {
4370 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
4371 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4373 fill_cmd(cmd, O_TCPDATALEN, 0,
4374 strtoul(*av, NULL, 0));
4379 NEED1("missing argument for tcpoptions");
4380 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
4386 NEED1("tcpseq/tcpack requires argument");
4387 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4388 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4389 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4394 NEED1("tcpwin requires length");
4395 fill_cmd(cmd, O_TCPWIN, 0,
4396 htons(strtoul(*av, NULL, 0)));
4401 NEED1("missing argument for tcpflags");
4402 cmd->opcode = O_TCPFLAGS;
4403 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
4409 errx(EX_USAGE, "keep-state cannot be part "
4412 errx(EX_USAGE, "only one of keep-state "
4413 "and limit is allowed");
4415 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
4420 errx(EX_USAGE, "limit cannot be part "
4423 errx(EX_USAGE, "only one of keep-state "
4424 "and limit is allowed");
4425 NEED1("limit needs mask and # of connections");
4428 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4430 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4431 cmd->opcode = O_LIMIT;
4437 val = match_token(limit_masks, *av);
4440 c->limit_mask |= val;
4443 c->conn_limit = atoi(*av);
4444 if (c->conn_limit == 0)
4445 errx(EX_USAGE, "limit: limit must be >0");
4446 if (c->limit_mask == 0)
4447 errx(EX_USAGE, "missing limit mask");
4453 NEED1("missing protocol");
4454 if (add_proto(cmd, *av, &proto)) {
4457 errx(EX_DATAERR, "invalid protocol ``%s''",
4462 NEED1("missing source IP");
4463 if (add_srcip(cmd, *av)) {
4469 NEED1("missing destination IP");
4470 if (add_dstip(cmd, *av)) {
4476 NEED1("missing source IP6");
4477 if (add_srcip6(cmd, *av)) {
4483 NEED1("missing destination IP6");
4484 if (add_dstip6(cmd, *av)) {
4490 NEED1("missing source port");
4491 if (_substrcmp(*av, "any") == 0 ||
4492 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
4495 errx(EX_DATAERR, "invalid source port %s", *av);
4499 NEED1("missing destination port");
4500 if (_substrcmp(*av, "any") == 0 ||
4501 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
4504 errx(EX_DATAERR, "invalid destination port %s",
4509 if (add_mac(cmd, ac, av)) {
4515 NEED1("missing mac type");
4516 if (!add_mactype(cmd, ac, *av))
4517 errx(EX_DATAERR, "invalid mac type %s", *av);
4521 case TOK_VERREVPATH:
4522 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4525 case TOK_VERSRCREACH:
4526 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4530 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4534 fill_cmd(cmd, O_IPSEC, 0, 0);
4538 fill_cmd(cmd, O_IP6, 0, 0);
4542 fill_cmd(cmd, O_IP4, 0, 0);
4546 fill_ext6hdr( cmd, *av );
4551 if (proto != IPPROTO_IPV6 )
4552 errx( EX_USAGE, "flow-id filter is active "
4553 "only for ipv6 protocol\n");
4554 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
4559 fill_comment(cmd, ac, av);
4565 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4567 if (F_LEN(cmd) > 0) { /* prepare to advance */
4569 cmd = next_cmd(cmd);
4575 * Now copy stuff into the rule.
4576 * If we have a keep-state option, the first instruction
4577 * must be a PROBE_STATE (which is generated here).
4578 * If we have a LOG option, it was stored as the first command,
4579 * and now must be moved to the top of the action part.
4581 dst = (ipfw_insn *)rule->cmd;
4584 * First thing to write into the command stream is the match probability.
4586 if (match_prob != 1) { /* 1 means always match */
4587 dst->opcode = O_PROB;
4589 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4594 * generate O_PROBE_STATE if necessary
4596 if (have_state && have_state->opcode != O_CHECK_STATE) {
4597 fill_cmd(dst, O_PROBE_STATE, 0, 0);
4598 dst = next_cmd(dst);
4601 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ
4603 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4606 switch (src->opcode) {
4613 bcopy(src, dst, i * sizeof(uint32_t));
4619 * put back the have_state command as last opcode
4621 if (have_state && have_state->opcode != O_CHECK_STATE) {
4622 i = F_LEN(have_state);
4623 bcopy(have_state, dst, i * sizeof(uint32_t));
4627 * start action section
4629 rule->act_ofs = dst - rule->cmd;
4632 * put back O_LOG, O_ALTQ if necessary
4635 i = F_LEN(have_log);
4636 bcopy(have_log, dst, i * sizeof(uint32_t));
4640 i = F_LEN(have_altq);
4641 bcopy(have_altq, dst, i * sizeof(uint32_t));
4645 * copy all other actions
4647 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4649 bcopy(src, dst, i * sizeof(uint32_t));
4653 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4654 i = (char *)dst - (char *)rule;
4655 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4656 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4658 show_ipfw(rule, 0, 0);
4662 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */)
4666 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG";
4671 /* clear all entries */
4672 if (do_cmd(optname, NULL, 0) < 0)
4673 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4675 printf("%s.\n", optname == IP_FW_ZERO ?
4676 "Accounting cleared":"Logging counts reset");
4683 if (isdigit(**av)) {
4684 rulenum = atoi(*av);
4687 if (do_cmd(optname, &rulenum, sizeof rulenum)) {
4688 warn("rule %u: setsockopt(IP_FW_%s)",
4690 failed = EX_UNAVAILABLE;
4691 } else if (!do_quiet)
4692 printf("Entry %d %s.\n", rulenum,
4693 optname == IP_FW_ZERO ?
4694 "cleared" : "logging count reset");
4696 errx(EX_USAGE, "invalid rule number ``%s''", *av);
4699 if (failed != EX_OK)
4706 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4708 if (!force && !do_quiet) { /* need to ask user */
4711 printf("Are you sure? [yn] ");
4714 c = toupper(getc(stdin));
4715 while (c != '\n' && getc(stdin) != '\n')
4717 return; /* and do not flush */
4718 } while (c != 'Y' && c != 'N');
4720 if (c == 'N') /* user said no */
4723 if (do_cmd(cmd, NULL, 0) < 0)
4724 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4725 do_pipe ? "DUMMYNET" : "FW");
4727 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
4731 * Free a the (locally allocated) copy of command line arguments.
4734 free_args(int ac, char **av)
4738 for (i=0; i < ac; i++)
4744 * This one handles all table-related commands
4745 * ipfw table N add addr[/masklen] [value]
4746 * ipfw table N delete addr[/masklen]
4747 * ipfw table N flush
4751 table_handler(int ac, char *av[])
4753 ipfw_table_entry ent;
4761 if (ac && isdigit(**av)) {
4762 ent.tbl = atoi(*av);
4765 errx(EX_USAGE, "table number required");
4766 NEED1("table needs command");
4767 if (_substrcmp(*av, "add") == 0 ||
4768 _substrcmp(*av, "delete") == 0) {
4769 do_add = **av == 'a';
4772 errx(EX_USAGE, "IP address required");
4773 p = strchr(*av, '/');
4776 ent.masklen = atoi(p);
4777 if (ent.masklen > 32)
4778 errx(EX_DATAERR, "bad width ``%s''", p);
4781 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
4782 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4785 ent.value = strtoul(*av, NULL, 0);
4788 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
4789 &ent, sizeof(ent)) < 0)
4790 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4791 do_add ? "ADD" : "DEL");
4792 } else if (_substrcmp(*av, "flush") == 0) {
4793 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0)
4794 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4795 } else if (_substrcmp(*av, "list") == 0) {
4798 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
4799 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
4800 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
4803 err(EX_OSERR, "malloc");
4805 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
4806 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
4807 for (a = 0; a < tbl->cnt; a++) {
4808 printf("%s/%u %u\n",
4809 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
4810 tbl->ent[a].masklen, tbl->ent[a].value);
4813 errx(EX_USAGE, "invalid table command %s", *av);
4817 * Called with the arguments (excluding program name).
4818 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
4821 ipfw_main(int oldac, char **oldav)
4823 int ch, ac, save_ac;
4824 char **av, **save_av;
4825 int do_acct = 0; /* Show packet/byte count */
4827 #define WHITESP " \t\f\v\n\r"
4830 else if (oldac == 1) {
4832 * If we are called with a single string, try to split it into
4833 * arguments for subsequent parsing.
4834 * But first, remove spaces after a ',', by copying the string
4837 char *arg = oldav[0]; /* The string... */
4838 int l = strlen(arg);
4839 int copy = 0; /* 1 if we need to copy, 0 otherwise */
4841 for (i = j = 0; i < l; i++) {
4842 if (arg[i] == '#') /* comment marker */
4846 copy = !index("," WHITESP, arg[i]);
4848 copy = !index(WHITESP, arg[i]);
4853 if (!copy && j > 0) /* last char was a 'blank', remove it */
4855 l = j; /* the new argument length */
4857 if (l == 0) /* empty string! */
4861 * First, count number of arguments. Because of the previous
4862 * processing, this is just the number of blanks plus 1.
4864 for (i = 0, ac = 1; i < l; i++)
4865 if (index(WHITESP, arg[i]) != NULL)
4868 av = calloc(ac, sizeof(char *));
4871 * Second, copy arguments from cmd[] to av[]. For each one,
4872 * j is the initial character, i is the one past the end.
4874 for (ac = 0, i = j = 0; i < l; i++)
4875 if (index(WHITESP, arg[i]) != NULL || i == l-1) {
4878 av[ac] = calloc(i-j+1, 1);
4879 bcopy(arg+j, av[ac], i-j);
4885 * If an argument ends with ',' join with the next one.
4889 av = calloc(oldac, sizeof(char *));
4890 for (first = i = ac = 0, l = 0; i < oldac; i++) {
4891 char *arg = oldav[i];
4892 int k = strlen(arg);
4895 if (arg[k-1] != ',' || i == oldac-1) {
4897 av[ac] = calloc(l+1, 1);
4898 for (l=0; first <= i; first++) {
4899 strcat(av[ac]+l, oldav[first]);
4900 l += strlen(oldav[first]);
4909 /* Set the force flag for non-interactive processes */
4911 do_force = !isatty(STDIN_FILENO);
4913 /* Save arguments for final freeing of memory. */
4917 optind = optreset = 0;
4918 while ((ch = getopt(ac, av, "abcdefhnNqs:STtv")) != -1)
4945 case 'h': /* help */
4946 free_args(save_ac, save_av);
4948 break; /* NOTREACHED */
4962 case 's': /* sort */
4963 do_sort = atoi(optarg);
4975 do_time = 2; /* numeric timestamp */
4978 case 'v': /* verbose */
4983 free_args(save_ac, save_av);
4989 NEED1("bad arguments, for usage summary ``ipfw''");
4992 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
4993 * e.g. "100 add allow ..." instead of "add 100 allow ...".
4994 * In case, swap first and second argument to get the normal form.
4996 if (ac > 1 && isdigit(*av[0])) {
5004 * optional: pipe or queue
5007 if (_substrcmp(*av, "pipe") == 0)
5009 else if (_substrcmp(*av, "queue") == 0)
5015 NEED1("missing command");
5018 * For pipes and queues we normally say 'pipe NN config'
5019 * but the code is easier to parse as 'pipe config NN'
5020 * so we swap the two arguments.
5022 if (do_pipe > 0 && ac > 1 && isdigit(*av[0])) {
5029 if (_substrcmp(*av, "add") == 0)
5031 else if (do_pipe && _substrcmp(*av, "config") == 0)
5032 config_pipe(ac, av);
5033 else if (_substrcmp(*av, "delete") == 0)
5035 else if (_substrcmp(*av, "flush") == 0)
5037 else if (_substrcmp(*av, "zero") == 0)
5038 zero(ac, av, IP_FW_ZERO);
5039 else if (_substrcmp(*av, "resetlog") == 0)
5040 zero(ac, av, IP_FW_RESETLOG);
5041 else if (_substrcmp(*av, "print") == 0 ||
5042 _substrcmp(*av, "list") == 0)
5043 list(ac, av, do_acct);
5044 else if (_substrcmp(*av, "set") == 0)
5045 sets_handler(ac, av);
5046 else if (_substrcmp(*av, "table") == 0)
5047 table_handler(ac, av);
5048 else if (_substrcmp(*av, "enable") == 0)
5049 sysctl_handler(ac, av, 1);
5050 else if (_substrcmp(*av, "disable") == 0)
5051 sysctl_handler(ac, av, 0);
5052 else if (_substrcmp(*av, "show") == 0)
5053 list(ac, av, 1 /* show counters */);
5055 errx(EX_USAGE, "bad command `%s'", *av);
5057 /* Free memory allocated in the argument parsing. */
5058 free_args(save_ac, save_av);
5064 ipfw_readfile(int ac, char *av[])
5068 char *cmd = NULL, *filename = av[ac-1];
5073 filename = av[ac-1];
5075 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
5096 * Skip previous args and delete last one, so we
5097 * pass all but the last argument to the preprocessor
5103 fprintf(stderr, "command is %s\n", av[0]);
5115 errx(EX_USAGE, "bad arguments, for usage"
5116 " summary ``ipfw''");
5123 if (cmd == NULL && ac != optind + 1) {
5124 fprintf(stderr, "ac %d, optind %d\n", ac, optind);
5125 errx(EX_USAGE, "extraneous filename arguments");
5128 if ((f = fopen(filename, "r")) == NULL)
5129 err(EX_UNAVAILABLE, "fopen: %s", filename);
5131 if (cmd != NULL) { /* pipe through preprocessor */
5134 if (pipe(pipedes) == -1)
5135 err(EX_OSERR, "cannot create pipe");
5139 err(EX_OSERR, "cannot fork");
5143 * Child, will run the preprocessor with the
5144 * file on stdin and the pipe on stdout.
5146 if (dup2(fileno(f), 0) == -1
5147 || dup2(pipedes[1], 1) == -1)
5148 err(EX_OSERR, "dup2()");
5153 err(EX_OSERR, "execvp(%s) failed", cmd);
5154 } else { /* parent, will reopen f as the pipe */
5157 if ((f = fdopen(pipedes[0], "r")) == NULL) {
5158 int savederrno = errno;
5160 (void)kill(preproc, SIGTERM);
5162 err(EX_OSERR, "fdopen()");
5167 while (fgets(buf, BUFSIZ, f)) { /* read commands */
5172 sprintf(linename, "Line %d", lineno);
5173 setprogname(linename); /* XXX */
5181 if (waitpid(preproc, &status, 0) == -1)
5182 errx(EX_OSERR, "waitpid()");
5183 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
5184 errx(EX_UNAVAILABLE,
5185 "preprocessor exited with status %d",
5186 WEXITSTATUS(status));
5187 else if (WIFSIGNALED(status))
5188 errx(EX_UNAVAILABLE,
5189 "preprocessor exited with signal %d",
5195 main(int ac, char *av[])
5198 * If the last argument is an absolute pathname, interpret it
5199 * as a file to be preprocessed.
5202 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
5203 ipfw_readfile(ac, av);
5205 if (ipfw_main(ac-1, av+1))