2 * Copyright (c) 2002 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
20 * $FreeBSD: src/sbin/ipfw/ipfw2.c,v 1.4.2.13 2003/05/27 22:21:11 gshapiro Exp $
23 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
51 #include <netinet/ip_icmp.h>
52 #include <net/ipfw/ip_fw.h>
53 #include <net/route.h> /* def. of struct route */
54 #include <net/ethernet.h>
55 #include <net/dummynet/ip_dummynet.h>
56 #include <netinet/tcp.h>
57 #include <arpa/inet.h>
59 int s
, /* main RAW socket */
60 do_resolv
, /* Would try to resolve all */
61 do_acct
, /* Show packet/byte count */
62 do_time
, /* Show time stamps */
63 do_quiet
, /* Be quiet in add and flush */
64 do_force
, /* Don't ask for confirmation */
65 do_pipe
, /* this cmd refers to a pipe */
66 do_table
, /* this cmd referes to a table */
67 do_sort
, /* field to sort results (0 = no) */
68 do_dynamic
, /* display dynamic rules */
69 do_expired
, /* display expired dynamic rules */
70 do_compact
, /* show rules in compact mode */
71 show_sets
, /* display rule sets */
74 #define IP_MASK_ALL 0xffffffff
77 * structure to hold flag names and associated values to be
78 * set in the appropriate masks.
79 * A NULL string terminates the array.
80 * Often, an element with 0 value contains an error string.
88 static struct _s_x f_tcpflags
[] = {
99 static struct _s_x f_tcpopts
[] = {
100 { "mss", IP_FW_TCPOPT_MSS
},
101 { "maxseg", IP_FW_TCPOPT_MSS
},
102 { "window", IP_FW_TCPOPT_WINDOW
},
103 { "sack", IP_FW_TCPOPT_SACK
},
104 { "ts", IP_FW_TCPOPT_TS
},
105 { "timestamp", IP_FW_TCPOPT_TS
},
106 { "cc", IP_FW_TCPOPT_CC
},
112 * IP options span the range 0 to 255 so we need to remap them
113 * (though in fact only the low 5 bits are significant).
115 static struct _s_x f_ipopts
[] = {
116 { "ssrr", IP_FW_IPOPT_SSRR
},
117 { "lsrr", IP_FW_IPOPT_LSRR
},
118 { "rr", IP_FW_IPOPT_RR
},
119 { "ts", IP_FW_IPOPT_TS
},
124 static struct _s_x f_iptos
[] = {
125 { "lowdelay", IPTOS_LOWDELAY
},
126 { "throughput", IPTOS_THROUGHPUT
},
127 { "reliability", IPTOS_RELIABILITY
},
128 { "mincost", IPTOS_MINCOST
},
129 { "congestion", IPTOS_CE
},
130 { "ecntransport", IPTOS_ECT
},
131 { "ip tos option", 0},
135 static struct _s_x limit_masks
[] = {
136 {"all", DYN_SRC_ADDR
|DYN_SRC_PORT
|DYN_DST_ADDR
|DYN_DST_PORT
},
137 {"src-addr", DYN_SRC_ADDR
},
138 {"src-port", DYN_SRC_PORT
},
139 {"dst-addr", DYN_DST_ADDR
},
140 {"dst-port", DYN_DST_PORT
},
145 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
146 * This is only used in this code.
148 #define IPPROTO_ETHERTYPE 0x1000
149 static struct _s_x ether_types
[] = {
151 * Note, we cannot use "-:&/" in the names because they are field
152 * separators in the type specifications. Also, we use s = NULL as
153 * end-delimiter, because a type of 0 can be legal.
163 { "pppoe_disc", 0x8863 },
164 { "pppoe_sess", 0x8864 },
165 { "ipx_8022", 0x00E0 },
166 { "ipx_8023", 0x0000 },
167 { "ipx_ii", 0x8137 },
168 { "ipx_snap", 0x8137 },
174 static void show_usage(void);
247 struct _s_x dummynet_params
[] = {
249 { "noerror", TOK_NOERROR
},
250 { "buckets", TOK_BUCKETS
},
251 { "dst-ip", TOK_DSTIP
},
252 { "src-ip", TOK_SRCIP
},
253 { "dst-port", TOK_DSTPORT
},
254 { "src-port", TOK_SRCPORT
},
255 { "proto", TOK_PROTO
},
256 { "weight", TOK_WEIGHT
},
258 { "mask", TOK_MASK
},
259 { "droptail", TOK_DROPTAIL
},
261 { "gred", TOK_GRED
},
263 { "bandwidth", TOK_BW
},
264 { "delay", TOK_DELAY
},
265 { "pipe", TOK_PIPE
},
266 { "queue", TOK_QUEUE
},
267 { "dummynet-params", TOK_NULL
},
271 struct _s_x rule_actions
[] = {
272 { "accept", TOK_ACCEPT
},
273 { "pass", TOK_ACCEPT
},
274 { "allow", TOK_ACCEPT
},
275 { "permit", TOK_ACCEPT
},
276 { "count", TOK_COUNT
},
277 { "pipe", TOK_PIPE
},
278 { "queue", TOK_QUEUE
},
279 { "divert", TOK_DIVERT
},
281 { "fwd", TOK_FORWARD
},
282 { "forward", TOK_FORWARD
},
283 { "skipto", TOK_SKIPTO
},
284 { "deny", TOK_DENY
},
285 { "drop", TOK_DENY
},
286 { "reject", TOK_REJECT
},
287 { "reset", TOK_RESET
},
288 { "unreach", TOK_UNREACH
},
289 { "check-state", TOK_CHECKSTATE
},
290 { "defrag", TOK_DEFRAG
},
295 struct _s_x rule_options
[] = {
299 { "limit", TOK_LIMIT
},
300 { "keep-state", TOK_KEEPSTATE
},
301 { "layer2", TOK_LAYER2
},
303 { "xmit", TOK_XMIT
},
304 { "recv", TOK_RECV
},
306 { "fragment", TOK_FRAG
},
307 { "frag", TOK_FRAG
},
308 { "ipfrag", TOK_IPFRAG
},
309 { "ipoptions", TOK_IPOPTS
},
310 { "ipopts", TOK_IPOPTS
},
311 { "iplen", TOK_IPLEN
},
312 { "ipid", TOK_IPID
},
313 { "ipprecedence", TOK_IPPRECEDENCE
},
314 { "iptos", TOK_IPTOS
},
315 { "ipttl", TOK_IPTTL
},
316 { "ipversion", TOK_IPVER
},
317 { "ipver", TOK_IPVER
},
318 { "estab", TOK_ESTAB
},
319 { "established", TOK_ESTAB
},
320 { "setup", TOK_SETUP
},
321 { "tcpflags", TOK_TCPFLAGS
},
322 { "tcpflgs", TOK_TCPFLAGS
},
323 { "tcpoptions", TOK_TCPOPTS
},
324 { "tcpopts", TOK_TCPOPTS
},
325 { "tcpseq", TOK_TCPSEQ
},
326 { "tcpack", TOK_TCPACK
},
327 { "tcpwin", TOK_TCPWIN
},
328 { "icmptype", TOK_ICMPTYPES
},
329 { "icmptypes", TOK_ICMPTYPES
},
330 { "dst-ip", TOK_DSTIP
},
331 { "src-ip", TOK_SRCIP
},
332 { "dst-port", TOK_DSTPORT
},
333 { "src-port", TOK_SRCPORT
},
334 { "proto", TOK_PROTO
},
337 { "mac-type", TOK_MACTYPE
},
339 { "not", TOK_NOT
}, /* pseudo option */
340 { "!", /* escape ? */ TOK_NOT
}, /* pseudo option */
341 { "or", TOK_OR
}, /* pseudo option */
342 { "|", /* escape */ TOK_OR
}, /* pseudo option */
343 { "{", TOK_STARTBRACE
}, /* pseudo option */
344 { "(", TOK_STARTBRACE
}, /* pseudo option */
345 { "}", TOK_ENDBRACE
}, /* pseudo option */
346 { ")", TOK_ENDBRACE
}, /* pseudo option */
352 * match_token takes a table and a string, returns the value associated
353 * with the string (0 meaning an error in most cases)
356 match_token(struct _s_x
*table
, char *string
)
359 int i
= strlen(string
);
361 for (pt
= table
; i
&& pt
->s
!= NULL
; pt
++)
362 if ((int)strlen(pt
->s
) == i
&& !bcmp(string
, pt
->s
, i
))
368 match_value(struct _s_x
*p
, u_int32_t value
)
370 for (; p
->s
!= NULL
; p
++)
377 * prints one port, symbolic or numeric
380 print_port(int proto
, u_int16_t port
)
383 if (proto
== IPPROTO_ETHERTYPE
) {
386 if (do_resolv
&& (str
= match_value(ether_types
, port
)) )
389 printf("0x%04x", port
);
391 struct servent
*se
= NULL
;
393 struct protoent
*pe
= getprotobynumber(proto
);
395 se
= getservbyport(htons(port
), pe
? pe
->p_name
: NULL
);
398 printf("%s", se
->s_name
);
405 * print the values in a list of ports
406 * XXX todo: add support for mask.
409 print_newports(ipfw_insn_u16
*cmd
, int proto
, int opcode
)
411 u_int16_t
*p
= cmd
->ports
;
413 const char *sep
= " ";
415 if (cmd
->o
.len
& F_NOT
)
418 printf ("%s", opcode
== O_MAC_TYPE
? " mac-type" :
419 (opcode
== O_IP_DSTPORT
? " dst-port" : " src-port"));
420 for (i
= F_LEN((ipfw_insn
*)cmd
) - 1; i
> 0; i
--, p
+= 2) {
422 print_port(proto
, p
[0]);
425 print_port(proto
, p
[1]);
432 * Like strtol, but also translates service names into port numbers
433 * for some protocols.
435 * proto == -1 disables the protocol check;
436 * proto == IPPROTO_ETHERTYPE looks up an internal table
437 * proto == <some value in /etc/protocols> matches the values there.
438 * Returns *end == s in case the parameter is not found.
441 strtoport(char *str
, char **end
, int base
, int proto
)
447 *end
= str
; /* default - not found */
449 return 0; /* not found */
452 return strtol(str
, end
, base
);
455 * find separator. '\\' escapes the next char.
457 for (s1
= str
; *s1
&& (isalnum(*s1
) || *s1
== '\\') ; s1
++)
458 if (*s1
== '\\' && s1
[1] != '\0')
461 buf
= malloc(s1
- str
+ 1);
466 * copy into a buffer skipping backslashes
468 for (p
= str
, i
= 0; p
!= s1
; p
++)
473 if (proto
== IPPROTO_ETHERTYPE
) {
474 i
= match_token(ether_types
, buf
);
476 if (i
!= -1) { /* found */
481 struct protoent
*pe
= NULL
;
485 pe
= getprotobynumber(proto
);
487 se
= getservbyname(buf
, pe
? pe
->p_name
: NULL
);
491 return ntohs(se
->s_port
);
494 return 0; /* not found */
498 * fill the body of the command with the list of port ranges.
499 * At the moment it only understands numeric ranges.
502 fill_newports(ipfw_insn_u16
*cmd
, char *av
, int proto
)
504 u_int16_t
*p
= cmd
->ports
;
511 a
= strtoport(av
, &str
, 0, proto
);
512 if (str
== av
) /* no parameter */
514 if (*str
== '-') { /* a range */
516 b
= strtoport(av
, &str
, 0, proto
);
517 if (str
== av
) /* no parameter */
521 } else if (*str
== ',' || *str
== '\0' ) {
523 } else { /* invalid separator */
524 errx(EX_DATAERR
, "invalid separator <%c> in <%s>\n",
532 if (i
+1 > F_LEN_MASK
)
533 errx(EX_DATAERR
, "too many ports/ranges\n");
534 cmd
->o
.len
|= i
+1; /* leave F_NOT and F_OR untouched */
539 static struct _s_x icmpcodes
[] = {
540 { "net", ICMP_UNREACH_NET
},
541 { "host", ICMP_UNREACH_HOST
},
542 { "protocol", ICMP_UNREACH_PROTOCOL
},
543 { "port", ICMP_UNREACH_PORT
},
544 { "needfrag", ICMP_UNREACH_NEEDFRAG
},
545 { "srcfail", ICMP_UNREACH_SRCFAIL
},
546 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN
},
547 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN
},
548 { "isolated", ICMP_UNREACH_ISOLATED
},
549 { "net-prohib", ICMP_UNREACH_NET_PROHIB
},
550 { "host-prohib", ICMP_UNREACH_HOST_PROHIB
},
551 { "tosnet", ICMP_UNREACH_TOSNET
},
552 { "toshost", ICMP_UNREACH_TOSHOST
},
553 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB
},
554 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE
},
555 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF
},
560 fill_reject_code(u_short
*codep
, char *str
)
565 val
= strtoul(str
, &s1
, 0);
566 if (s1
== str
|| *s1
!= '\0' || val
>= 0x100)
567 val
= match_token(icmpcodes
, str
);
569 errx(EX_DATAERR
, "unknown ICMP unreachable code ``%s''", str
);
575 print_reject_code(u_int16_t code
)
577 const char *str
= match_value(icmpcodes
, code
);
580 printf("unreach %s", str
);
582 printf("unreach %u", code
);
586 * Returns the number of bits set (from left) in a contiguous bitmask,
587 * or -1 if the mask is not contiguous.
588 * XXX this needs a proper fix.
589 * This effectively works on masks in big-endian (network) format.
590 * when compiled on little endian architectures.
592 * First bit is bit 7 of the first byte -- note, for MAC addresses,
593 * the first bit on the wire is bit 0 of the first byte.
594 * len is the max length in bits.
597 contigmask(u_char
*p
, int len
)
600 for (i
=0; i
<len
; i
++)
601 if ( (p
[i
/8] & (1 << (7 - (i
%8)))) == 0) /* first bit unset */
603 for (n
=i
+1; n
< len
; n
++)
604 if ( (p
[n
/8] & (1 << (7 - (n
%8)))) != 0)
605 return -1; /* mask not contiguous */
610 * print flags set/clear in the two bitmasks passed as parameters.
611 * There is a specialized check for f_tcpflags.
614 print_flags(const char *name
, ipfw_insn
*cmd
, struct _s_x
*list
)
616 const char *comma
="";
618 u_char set
= cmd
->arg1
& 0xff;
619 u_char clear
= (cmd
->arg1
>> 8) & 0xff;
621 if (list
== f_tcpflags
&& set
== TH_SYN
&& clear
== TH_ACK
) {
626 printf(" %s ", name
);
627 for (i
=0; list
[i
].x
!= 0; i
++) {
628 if (set
& list
[i
].x
) {
630 printf("%s%s", comma
, list
[i
].s
);
633 if (clear
& list
[i
].x
) {
635 printf("%s!%s", comma
, list
[i
].s
);
642 * Print the ip address contained in a command.
645 print_ip(ipfw_insn_ip
*cmd
, const char *str
)
647 struct hostent
*he
= NULL
;
650 printf("%s%s ", cmd
->o
.len
& F_NOT
? " not": "", str
);
652 if (cmd
->o
.opcode
== O_IP_SRC_ME
|| cmd
->o
.opcode
== O_IP_DST_ME
) {
656 if (cmd
->o
.opcode
== O_IP_SRC_TABLE
||
657 cmd
->o
.opcode
== O_IP_DST_TABLE
) {
658 printf("<%u>", cmd
->o
.arg1
);
661 if (cmd
->o
.opcode
== O_IP_SRC_SET
|| cmd
->o
.opcode
== O_IP_DST_SET
) {
668 cmd
->addr
.s_addr
= htonl(cmd
->addr
.s_addr
);
669 printf("%s/%d", inet_ntoa(cmd
->addr
),
670 contigmask((u_char
*)&x
, 32));
671 x
= cmd
->addr
.s_addr
= htonl(cmd
->addr
.s_addr
);
672 x
&= 0xff; /* base */
673 d
= (u_int32_t
*)&(cmd
->mask
);
674 for (i
=0; i
< cmd
->o
.arg1
; i
++)
675 if (d
[ i
/32] & (1<<(i
& 31))) {
676 printf("%c%d", comma
, i
+x
);
682 if (cmd
->o
.opcode
== O_IP_SRC
|| cmd
->o
.opcode
== O_IP_DST
)
685 mb
= contigmask((u_char
*)&(cmd
->mask
.s_addr
), 32);
686 if (mb
== 32 && do_resolv
)
687 he
= gethostbyaddr(&(cmd
->addr
.s_addr
), sizeof(u_long
),
689 if (he
!= NULL
) /* resolved to name */
690 printf("%s", he
->h_name
);
691 else if (mb
== 0) /* any */
693 else { /* numeric IP followed by some kind of mask */
694 printf("%s", inet_ntoa(cmd
->addr
));
696 printf(":%s", inet_ntoa(cmd
->mask
));
703 * prints a MAC address/mask pair
706 print_mac(u_char
*addr
, u_char
*mask
)
708 int l
= contigmask(mask
, 48);
713 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
714 addr
[0], addr
[1], addr
[2], addr
[3], addr
[4], addr
[5]);
716 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
717 mask
[0], mask
[1], mask
[2],
718 mask
[3], mask
[4], mask
[5]);
725 fill_icmptypes(ipfw_insn_u32
*cmd
, char *av
)
734 type
= strtoul(av
, &av
, 0);
736 if (*av
!= ',' && *av
!= '\0')
737 errx(EX_DATAERR
, "invalid ICMP type");
740 errx(EX_DATAERR
, "ICMP type out of range");
742 cmd
->d
[0] |= 1 << type
;
744 cmd
->o
.opcode
= O_ICMPTYPE
;
745 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_u32
);
749 print_icmptypes(ipfw_insn_u32
*cmd
)
754 printf(" icmptypes");
755 for (i
= 0; i
< 32; i
++) {
756 if ( (cmd
->d
[0] & (1 << (i
))) == 0)
758 printf("%c%d", sep
, i
);
764 * show_ipfw() prints the body of an ipfw rule.
765 * Because the standard rule has at least proto src_ip dst_ip, we use
766 * a helper function to produce these entries if not provided explicitly.
767 * The first argument is the list of fields we have, the second is
768 * the list of fields we want to be printed.
770 * Special cases if we have provided a MAC header:
771 * + if the rule does not contain IP addresses/ports, do not print them;
772 * + if the rule does not contain an IP proto, print "all" instead of "ip";
774 * Once we have 'have_options', IP header fields are printed as options.
776 #define HAVE_PROTO 0x0001
777 #define HAVE_SRCIP 0x0002
778 #define HAVE_DSTIP 0x0004
779 #define HAVE_MAC 0x0008
780 #define HAVE_MACTYPE 0x0010
781 #define HAVE_OPTIONS 0x8000
783 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
785 show_prerequisites(int *flags
, int want
, int cmd
)
787 if ( (*flags
& HAVE_IP
) == HAVE_IP
)
788 *flags
|= HAVE_OPTIONS
;
790 if ( (*flags
& (HAVE_MAC
|HAVE_MACTYPE
|HAVE_OPTIONS
)) == HAVE_MAC
&&
793 * mac-type was optimized out by the compiler,
797 *flags
|= HAVE_MACTYPE
| HAVE_OPTIONS
;
800 if ( !(*flags
& HAVE_OPTIONS
)) {
801 if ( !(*flags
& HAVE_PROTO
) && (want
& HAVE_PROTO
))
803 if ( !(*flags
& HAVE_SRCIP
) && (want
& HAVE_SRCIP
))
805 if ( !(*flags
& HAVE_DSTIP
) && (want
& HAVE_DSTIP
))
812 show_ipfw(struct ipfw_ioc_rule
*rule
, int pcwidth
, int bcwidth
)
814 static int twidth
= 0;
817 int proto
= 0; /* default */
818 int flags
= 0; /* prerequisites */
819 ipfw_insn_log
*logptr
= NULL
; /* set if we find an O_LOG */
820 int or_block
= 0; /* we are in an or block */
822 u_int32_t set_disable
= rule
->set_disable
;
824 if (set_disable
& (1 << rule
->set
)) { /* disabled */
828 printf("# DISABLED ");
830 printf("%05u ", rule
->rulenum
);
833 printf("%*ju %*ju ", pcwidth
, (uintmax_t)rule
->pcnt
, bcwidth
,
834 (uintmax_t)rule
->bcnt
);
842 strcpy(timestr
, ctime((time_t *)&t0
));
843 *strchr(timestr
, '\n') = '\0';
844 twidth
= strlen(timestr
);
846 if (rule
->timestamp
) {
847 time_t t
= _long_to_time(rule
->timestamp
);
849 strcpy(timestr
, ctime(&t
));
850 *strchr(timestr
, '\n') = '\0';
851 printf("%s ", timestr
);
853 printf("%*s ", twidth
, " ");
858 printf("set %d ", rule
->set
);
861 * print the optional "match probability"
863 if (rule
->cmd_len
> 0) {
865 if (cmd
->opcode
== O_PROB
) {
866 ipfw_insn_u32
*p
= (ipfw_insn_u32
*)cmd
;
867 double d
= 1.0 * p
->d
[0];
869 d
= (d
/ 0x7fffffff);
870 printf("prob %f ", d
);
875 * first print actions
877 for (l
= rule
->cmd_len
- rule
->act_ofs
, cmd
= ACTION_PTR(rule
);
878 l
> 0 ; l
-= F_LEN(cmd
), cmd
+= F_LEN(cmd
)) {
879 switch(cmd
->opcode
) {
881 printf("check-state");
882 flags
= HAVE_IP
; /* avoid printing anything else */
902 if (cmd
->arg1
== ICMP_REJECT_RST
)
904 else if (cmd
->arg1
== ICMP_UNREACH_HOST
)
907 print_reject_code(cmd
->arg1
);
911 printf("skipto %u", cmd
->arg1
);
915 printf("pipe %u", cmd
->arg1
);
919 printf("queue %u", cmd
->arg1
);
923 printf("divert %u", cmd
->arg1
);
927 printf("tee %u", cmd
->arg1
);
932 ipfw_insn_sa
*sa
= (ipfw_insn_sa
*)cmd
;
934 printf("fwd %s", inet_ntoa(sa
->sa
.sin_addr
));
936 printf(",%d", sa
->sa
.sin_port
);
940 case O_LOG
: /* O_LOG is printed last */
941 logptr
= (ipfw_insn_log
*)cmd
;
945 printf("** unrecognized action %d len %d",
946 cmd
->opcode
, cmd
->len
);
950 if (logptr
->max_log
> 0)
951 printf(" log logamount %d", logptr
->max_log
);
957 * then print the body.
959 if (rule
->usr_flags
& IPFW_USR_F_NORULE
) {
960 /* empty rules before options */
962 printf(" ip from any to any");
963 flags
|= HAVE_IP
| HAVE_OPTIONS
;
966 for (l
= rule
->act_ofs
, cmd
= rule
->cmd
;
967 l
> 0 ; l
-= F_LEN(cmd
) , cmd
+= F_LEN(cmd
)) {
969 ipfw_insn_u32
*cmd32
= (ipfw_insn_u32
*)cmd
;
971 show_prerequisites(&flags
, 0, cmd
->opcode
);
973 switch(cmd
->opcode
) {
975 break; /* done already */
978 break; /* no need to print anything here */
981 ipfw_insn_mac
*m
= (ipfw_insn_mac
*)cmd
;
983 if ((cmd
->len
& F_OR
) && !or_block
)
985 if (cmd
->len
& F_NOT
)
989 print_mac( m
->addr
, m
->mask
);
990 print_mac( m
->addr
+ 6, m
->mask
+ 6);
995 if ((cmd
->len
& F_OR
) && !or_block
)
997 print_newports((ipfw_insn_u16
*)cmd
, IPPROTO_ETHERTYPE
,
998 (flags
& HAVE_OPTIONS
) ? cmd
->opcode
: 0);
999 flags
|= HAVE_MAC
| HAVE_MACTYPE
| HAVE_OPTIONS
;
1006 case O_IP_SRC_TABLE
:
1007 show_prerequisites(&flags
, HAVE_PROTO
, 0);
1008 if (!(flags
& HAVE_SRCIP
))
1010 if ((cmd
->len
& F_OR
) && !or_block
)
1012 print_ip((ipfw_insn_ip
*)cmd
,
1013 (flags
& HAVE_OPTIONS
) ? " src-ip" : "");
1014 flags
|= HAVE_SRCIP
;
1021 case O_IP_DST_TABLE
:
1022 show_prerequisites(&flags
, HAVE_PROTO
|HAVE_SRCIP
, 0);
1023 if (!(flags
& HAVE_DSTIP
))
1025 if ((cmd
->len
& F_OR
) && !or_block
)
1027 print_ip((ipfw_insn_ip
*)cmd
,
1028 (flags
& HAVE_OPTIONS
) ? " dst-ip" : "");
1029 flags
|= HAVE_DSTIP
;
1033 show_prerequisites(&flags
, HAVE_IP
, 0);
1035 show_prerequisites(&flags
, HAVE_PROTO
|HAVE_SRCIP
, 0);
1036 if ((cmd
->len
& F_OR
) && !or_block
)
1038 print_newports((ipfw_insn_u16
*)cmd
, proto
,
1039 (flags
& HAVE_OPTIONS
) ? cmd
->opcode
: 0);
1043 struct protoent
*pe
;
1045 if ((cmd
->len
& F_OR
) && !or_block
)
1047 if (cmd
->len
& F_NOT
)
1050 pe
= getprotobynumber(cmd
->arg1
);
1051 if (flags
& HAVE_OPTIONS
)
1054 printf(" %s", pe
->p_name
);
1056 printf(" %u", cmd
->arg1
);
1058 flags
|= HAVE_PROTO
;
1061 default: /*options ... */
1062 show_prerequisites(&flags
, HAVE_IP
| HAVE_OPTIONS
, 0);
1063 if ((cmd
->len
& F_OR
) && !or_block
)
1065 if (cmd
->len
& F_NOT
&& cmd
->opcode
!= O_IN
)
1067 switch(cmd
->opcode
) {
1077 printf(cmd
->len
& F_NOT
? " out" : " in");
1087 ipfw_insn_if
*cmdif
= (ipfw_insn_if
*)cmd
;
1089 if (cmd
->opcode
== O_XMIT
)
1091 else if (cmd
->opcode
== O_RECV
)
1093 else if (cmd
->opcode
== O_VIA
)
1097 if (cmdif
->name
[0] == '\0')
1098 printf(" %s %s", dir
,
1099 inet_ntoa(cmdif
->p
.ip
));
1100 printf(" %s %s", dir
, cmdif
->name
);
1105 printf(" ipid %u", cmd
->arg1
);
1109 printf(" ipttl %u", cmd
->arg1
);
1113 printf(" ipver %u", cmd
->arg1
);
1116 case O_IPPRECEDENCE
:
1117 printf(" ipprecedence %u", (cmd
->arg1
) >> 5 );
1121 printf(" iplen %u", cmd
->arg1
);
1125 print_flags("ipoptions", cmd
, f_ipopts
);
1129 print_flags("iptos", cmd
, f_iptos
);
1133 print_icmptypes((ipfw_insn_u32
*)cmd
);
1137 printf(" established");
1141 print_flags("tcpflags", cmd
, f_tcpflags
);
1145 print_flags("tcpoptions", cmd
, f_tcpopts
);
1149 printf(" tcpwin %d", ntohs(cmd
->arg1
));
1153 printf(" tcpack %u", ntohl(cmd32
->d
[0]));
1157 printf(" tcpseq %u", ntohl(cmd32
->d
[0]));
1162 struct passwd
*pwd
= getpwuid(cmd32
->d
[0]);
1165 printf(" uid %s", pwd
->pw_name
);
1167 printf(" uid %u", cmd32
->d
[0]);
1173 struct group
*grp
= getgrgid(cmd32
->d
[0]);
1176 printf(" gid %s", grp
->gr_name
);
1178 printf(" gid %u", cmd32
->d
[0]);
1183 printf(" keep-state");
1188 struct _s_x
*p
= limit_masks
;
1189 ipfw_insn_limit
*c
= (ipfw_insn_limit
*)cmd
;
1190 u_int8_t x
= c
->limit_mask
;
1191 const char *comma
= " ";
1194 for ( ; p
->x
!= 0 ; p
++)
1195 if ((x
& p
->x
) == p
->x
) {
1197 printf("%s%s", comma
, p
->s
);
1200 printf(" %d", c
->conn_limit
);
1205 printf(" [opcode %d len %d]",
1206 cmd
->opcode
, cmd
->len
);
1209 if (cmd
->len
& F_OR
) {
1212 } else if (or_block
) {
1217 show_prerequisites(&flags
, HAVE_IP
, 0);
1223 show_dyn_ipfw(struct ipfw_ioc_state
*d
, int pcwidth
, int bcwidth
)
1225 struct protoent
*pe
;
1229 if (!d
->expire
&& !(d
->dyn_type
== O_LIMIT_PARENT
))
1233 printf("%05u %*ju %*ju (%ds)", d
->rulenum
, pcwidth
, (uintmax_t)d
->pcnt
,
1234 bcwidth
, (uintmax_t)d
->bcnt
, d
->expire
);
1235 switch (d
->dyn_type
) {
1236 case O_LIMIT_PARENT
:
1237 printf(" PARENT %d", d
->count
);
1242 case O_KEEP_STATE
: /* bidir, no mask */
1247 if ((pe
= getprotobynumber(d
->id
.u
.ip
.proto
)) != NULL
)
1248 printf(" %s", pe
->p_name
);
1250 printf(" proto %u", d
->id
.u
.ip
.proto
);
1252 a
.s_addr
= htonl(d
->id
.u
.ip
.src_ip
);
1253 printf(" %s %d", inet_ntoa(a
), d
->id
.u
.ip
.src_port
);
1255 a
.s_addr
= htonl(d
->id
.u
.ip
.dst_ip
);
1256 printf(" <-> %s %d", inet_ntoa(a
), d
->id
.u
.ip
.dst_port
);
1261 sort_q(const void *pa
, const void *pb
)
1263 int rev
= (do_sort
< 0);
1264 int field
= rev
? -do_sort
: do_sort
;
1266 const struct dn_ioc_flowqueue
*a
= pa
;
1267 const struct dn_ioc_flowqueue
*b
= pb
;
1271 res
= a
->len
- b
->len
;
1274 res
= a
->len_bytes
- b
->len_bytes
;
1277 case 3: /* tot pkts */
1278 res
= a
->tot_pkts
- b
->tot_pkts
;
1281 case 4: /* tot bytes */
1282 res
= a
->tot_bytes
- b
->tot_bytes
;
1289 return (int)(rev
? res
: -res
);
1293 list_queues(struct dn_ioc_flowset
*fs
, struct dn_ioc_flowqueue
*q
)
1297 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1298 fs
->flow_mask
.u
.ip
.proto
,
1299 fs
->flow_mask
.u
.ip
.src_ip
, fs
->flow_mask
.u
.ip
.src_port
,
1300 fs
->flow_mask
.u
.ip
.dst_ip
, fs
->flow_mask
.u
.ip
.dst_port
);
1301 if (fs
->rq_elements
== 0)
1304 printf("BKT Prot ___Source IP/port____ "
1305 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1307 heapsort(q
, fs
->rq_elements
, sizeof(*q
), sort_q
);
1308 for (l
= 0; l
< fs
->rq_elements
; l
++) {
1310 struct protoent
*pe
;
1312 ina
.s_addr
= htonl(q
[l
].id
.u
.ip
.src_ip
);
1313 printf("%3d ", q
[l
].hash_slot
);
1314 pe
= getprotobynumber(q
[l
].id
.u
.ip
.proto
);
1316 printf("%-4s ", pe
->p_name
);
1318 printf("%4u ", q
[l
].id
.u
.ip
.proto
);
1319 printf("%15s/%-5d ",
1320 inet_ntoa(ina
), q
[l
].id
.u
.ip
.src_port
);
1321 ina
.s_addr
= htonl(q
[l
].id
.u
.ip
.dst_ip
);
1322 printf("%15s/%-5d ",
1323 inet_ntoa(ina
), q
[l
].id
.u
.ip
.dst_port
);
1324 printf("%4ju %8ju %2u %4u %3u\n",
1325 (uintmax_t)q
[l
].tot_pkts
, (uintmax_t)q
[l
].tot_bytes
,
1326 q
[l
].len
, q
[l
].len_bytes
, q
[l
].drops
);
1328 printf(" S %20ju F %20ju\n",
1329 (uintmax_t)q
[l
].S
, (uintmax_t)q
[l
].F
);
1334 print_flowset_parms(struct dn_ioc_flowset
*fs
, char *prefix
)
1339 char red
[90]; /* Display RED parameters */
1342 if (fs
->flags_fs
& DN_QSIZE_IS_BYTES
) {
1344 sprintf(qs
, "%d KB", l
/ 1024);
1346 sprintf(qs
, "%d B", l
);
1348 sprintf(qs
, "%3d sl.", l
);
1350 sprintf(plr
, "plr %f", 1.0 * fs
->plr
/ (double)(0x7fffffff));
1353 if (fs
->flags_fs
& DN_IS_RED
) /* RED parameters */
1355 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
1356 (fs
->flags_fs
& DN_IS_GENTLE_RED
) ? 'G' : ' ',
1357 1.0 * fs
->w_q
/ (double)(1 << SCALE_RED
),
1358 SCALE_VAL(fs
->min_th
),
1359 SCALE_VAL(fs
->max_th
),
1360 1.0 * fs
->max_p
/ (double)(1 << SCALE_RED
));
1362 sprintf(red
, "droptail");
1364 printf("%s %s%s %d queues (%d buckets) %s\n",
1365 prefix
, qs
, plr
, fs
->rq_elements
, fs
->rq_size
, red
);
1369 list_pipes(void *data
, int nbytes
, int ac
, char *av
[])
1373 struct dn_ioc_pipe
*p
= (struct dn_ioc_pipe
*)data
;
1374 struct dn_ioc_flowset
*fs
;
1375 struct dn_ioc_flowqueue
*q
;
1379 rulenum
= strtoul(*av
++, NULL
, 10);
1382 for (; nbytes
>= (int)sizeof(*p
); p
= (struct dn_ioc_pipe
*)next
) {
1383 double b
= p
->bandwidth
;
1387 if (p
->fs
.fs_type
!= DN_IS_PIPE
)
1388 break; /* done with pipes, now queues */
1391 * compute length, as pipe have variable size
1393 l
= sizeof(*p
) + p
->fs
.rq_elements
* sizeof(*q
);
1394 next
= (uint8_t *)p
+ l
;
1397 if (rulenum
!= 0 && rulenum
!= (u_long
)p
->pipe_nr
)
1404 sprintf(buf
, "unlimited");
1405 else if (b
>= 1000000)
1406 sprintf(buf
, "%7.3f Mbit/s", b
/1000000);
1408 sprintf(buf
, "%7.3f Kbit/s", b
/1000);
1410 sprintf(buf
, "%7.3f bit/s ", b
);
1412 sprintf(prefix
, "%05d: %s %4d ms ",
1413 p
->pipe_nr
, buf
, p
->delay
);
1414 print_flowset_parms(&p
->fs
, prefix
);
1416 printf(" V %20ju\n", (uintmax_t)p
->V
>> MY_M
);
1418 q
= (struct dn_ioc_flowqueue
*)(p
+1);
1419 list_queues(&p
->fs
, q
);
1421 for (fs
= next
; nbytes
>= (int)sizeof(*fs
); fs
= next
) {
1424 if (fs
->fs_type
!= DN_IS_QUEUE
)
1426 l
= sizeof(*fs
) + fs
->rq_elements
* sizeof(*q
);
1427 next
= (uint8_t *)fs
+ l
;
1429 q
= (struct dn_ioc_flowqueue
*)(fs
+1);
1430 sprintf(prefix
, "q%05d: weight %d pipe %d ",
1431 fs
->fs_nr
, fs
->weight
, fs
->parent_nr
);
1432 print_flowset_parms(fs
, prefix
);
1438 * This one handles all set-related commands
1439 * ipfw set { show | enable | disable }
1441 * ipfw set move X to Y
1442 * ipfw set move rule X to Y
1445 sets_handler(int ac
, char *av
[])
1447 u_int32_t set_disable
, masks
[2];
1450 u_int8_t cmd
, new_set
;
1456 errx(EX_USAGE
, "set needs command");
1457 if (!strncmp(*av
, "show", strlen(*av
)) ) {
1461 nbytes
= sizeof(struct ipfw_ioc_rule
);
1462 if ((data
= malloc(nbytes
)) == NULL
)
1463 err(EX_OSERR
, "malloc");
1464 if (getsockopt(s
, IPPROTO_IP
, IP_FW_GET
, data
, &nbytes
) < 0)
1465 err(EX_OSERR
, "getsockopt(IP_FW_GET)");
1466 set_disable
= ((struct ipfw_ioc_rule
*)data
)->set_disable
;
1468 for (i
= 0, msg
= "disable" ; i
< 31; i
++)
1469 if ( (set_disable
& (1<<i
))) {
1470 printf("%s %d", msg
, i
);
1473 msg
= (set_disable
) ? " enable" : "enable";
1474 for (i
= 0; i
< 31; i
++)
1475 if ( !(set_disable
& (1<<i
))) {
1476 printf("%s %d", msg
, i
);
1480 } else if (!strncmp(*av
, "swap", strlen(*av
))) {
1483 errx(EX_USAGE
, "set swap needs 2 set numbers\n");
1484 rulenum
= atoi(av
[0]);
1485 new_set
= atoi(av
[1]);
1486 if (!isdigit(*(av
[0])) || rulenum
> 30)
1487 errx(EX_DATAERR
, "invalid set number %s\n", av
[0]);
1488 if (!isdigit(*(av
[1])) || new_set
> 30)
1489 errx(EX_DATAERR
, "invalid set number %s\n", av
[1]);
1490 masks
[0] = (4 << 24) | (new_set
<< 16) | (rulenum
);
1491 i
= setsockopt(s
, IPPROTO_IP
, IP_FW_DEL
,
1492 masks
, sizeof(u_int32_t
));
1493 } else if (!strncmp(*av
, "move", strlen(*av
))) {
1495 if (ac
&& !strncmp(*av
, "rule", strlen(*av
))) {
1500 if (ac
!= 3 || strncmp(av
[1], "to", strlen(*av
)))
1501 errx(EX_USAGE
, "syntax: set move [rule] X to Y\n");
1502 rulenum
= atoi(av
[0]);
1503 new_set
= atoi(av
[2]);
1504 if (!isdigit(*(av
[0])) || (cmd
== 3 && rulenum
> 30) ||
1505 (cmd
== 2 && rulenum
== 65535) )
1506 errx(EX_DATAERR
, "invalid source number %s\n", av
[0]);
1507 if (!isdigit(*(av
[2])) || new_set
> 30)
1508 errx(EX_DATAERR
, "invalid dest. set %s\n", av
[1]);
1509 masks
[0] = (cmd
<< 24) | (new_set
<< 16) | (rulenum
);
1510 i
= setsockopt(s
, IPPROTO_IP
, IP_FW_DEL
,
1511 masks
, sizeof(u_int32_t
));
1512 } else if (!strncmp(*av
, "disable", strlen(*av
)) ||
1513 !strncmp(*av
, "enable", strlen(*av
)) ) {
1514 int which
= !strncmp(*av
, "enable", strlen(*av
)) ? 1 : 0;
1517 masks
[0] = masks
[1] = 0;
1520 if (isdigit(**av
)) {
1522 if (i
< 0 || i
> 30)
1524 "invalid set number %d\n", i
);
1525 masks
[which
] |= (1<<i
);
1526 } else if (!strncmp(*av
, "disable", strlen(*av
)))
1528 else if (!strncmp(*av
, "enable", strlen(*av
)))
1532 "invalid set command %s\n", *av
);
1535 if ( (masks
[0] & masks
[1]) != 0 )
1537 "cannot enable and disable the same set\n");
1539 i
= setsockopt(s
, IPPROTO_IP
, IP_FW_DEL
, masks
, sizeof(masks
));
1541 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1543 errx(EX_USAGE
, "invalid set command %s\n", *av
);
1547 sysctl_handler(int ac
, char *av
[], int which
)
1553 warnx("missing keyword to enable/disable\n");
1554 } else if (strncmp(*av
, "firewall", strlen(*av
)) == 0) {
1555 sysctlbyname("net.inet.ip.fw.enable", NULL
, 0,
1556 &which
, sizeof(which
));
1557 } else if (strncmp(*av
, "one_pass", strlen(*av
)) == 0) {
1558 sysctlbyname("net.inet.ip.fw.one_pass", NULL
, 0,
1559 &which
, sizeof(which
));
1560 } else if (strncmp(*av
, "debug", strlen(*av
)) == 0) {
1561 sysctlbyname("net.inet.ip.fw.debug", NULL
, 0,
1562 &which
, sizeof(which
));
1563 } else if (strncmp(*av
, "verbose", strlen(*av
)) == 0) {
1564 sysctlbyname("net.inet.ip.fw.verbose", NULL
, 0,
1565 &which
, sizeof(which
));
1566 } else if (strncmp(*av
, "dyn_keepalive", strlen(*av
)) == 0) {
1567 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL
, 0,
1568 &which
, sizeof(which
));
1570 warnx("unrecognize enable/disable keyword: %s\n", *av
);
1575 list(int ac
, char *av
[])
1577 struct ipfw_ioc_rule
*r
;
1578 struct ipfw_ioc_state
*dynrules
, *d
;
1581 int bcwidth
, n
, nbytes
, nstat
, ndyn
, pcwidth
, width
;
1582 int exitval
= EX_OK
;
1589 const int ocmd
= do_pipe
? IP_DUMMYNET_GET
: IP_FW_GET
;
1590 int nalloc
= 1024; /* start somewhere... */
1595 /* get rules or pipes from kernel, resizing array as necessary */
1598 while (nbytes
>= nalloc
) {
1599 nalloc
= nalloc
* 2 + 200;
1601 if ((data
= realloc(data
, nbytes
)) == NULL
)
1602 err(EX_OSERR
, "realloc");
1603 if (getsockopt(s
, IPPROTO_IP
, ocmd
, data
, &nbytes
) < 0)
1604 err(EX_OSERR
, "getsockopt(IP_%s_GET)",
1605 do_pipe
? "DUMMYNET" : "FW");
1609 list_pipes(data
, nbytes
, ac
, av
);
1614 * Count static rules.
1617 nstat
= r
->static_count
;
1620 * Count dynamic rules. This is easier as they have
1623 dynrules
= (struct ipfw_ioc_state
*)((uint8_t *)r
+ r
->static_len
);
1624 ndyn
= (nbytes
- r
->static_len
) / sizeof(*dynrules
);
1626 /* if showing stats, figure out column widths ahead of time */
1627 bcwidth
= pcwidth
= 0;
1629 for (n
= 0, r
= data
; n
< nstat
; n
++,
1630 r
= (struct ipfw_ioc_rule
*)((uint8_t *)r
+ IOC_RULESIZE(r
))) {
1631 /* packet counter */
1632 width
= snprintf(NULL
, 0, "%ju", (uintmax_t)r
->pcnt
);
1633 if (width
> pcwidth
)
1637 width
= snprintf(NULL
, 0, "%ju", (uintmax_t)r
->bcnt
);
1638 if (width
> bcwidth
)
1642 if (do_dynamic
&& ndyn
) {
1643 for (n
= 0, d
= dynrules
; n
< ndyn
; n
++, d
++) {
1644 width
= snprintf(NULL
, 0, "%ju", (uintmax_t)d
->pcnt
);
1645 if (width
> pcwidth
)
1648 width
= snprintf(NULL
, 0, "%ju", (uintmax_t)d
->bcnt
);
1649 if (width
> bcwidth
)
1653 /* if no rule numbers were specified, list all rules */
1655 for (n
= 0, r
= data
; n
< nstat
; n
++,
1656 r
= (struct ipfw_ioc_rule
*)((uint8_t *)r
+ IOC_RULESIZE(r
)))
1657 show_ipfw(r
, pcwidth
, bcwidth
);
1659 if (do_dynamic
&& ndyn
) {
1660 printf("## Dynamic rules (%d):\n", ndyn
);
1661 for (n
= 0, d
= dynrules
; n
< ndyn
; n
++, d
++)
1662 show_dyn_ipfw(d
, pcwidth
, bcwidth
);
1667 /* display specific rules requested on command line */
1669 for (lac
= ac
, lav
= av
; lac
!= 0; lac
--) {
1670 /* convert command line rule # */
1671 rnum
= strtoul(*lav
++, &endptr
, 10);
1674 warnx("invalid rule number: %s", *(lav
- 1));
1677 for (n
= seen
= 0, r
= data
; n
< nstat
; n
++,
1678 r
= (struct ipfw_ioc_rule
*)((uint8_t *)r
+ IOC_RULESIZE(r
))) {
1679 if (r
->rulenum
> rnum
)
1681 if (r
->rulenum
== rnum
) {
1682 show_ipfw(r
, pcwidth
, bcwidth
);
1687 /* give precedence to other error(s) */
1688 if (exitval
== EX_OK
)
1689 exitval
= EX_UNAVAILABLE
;
1690 warnx("rule %lu does not exist", rnum
);
1694 if (do_dynamic
&& ndyn
) {
1695 printf("## Dynamic rules:\n");
1696 for (lac
= ac
, lav
= av
; lac
!= 0; lac
--) {
1697 rnum
= strtoul(*lav
++, &endptr
, 10);
1699 /* already warned */
1701 for (n
= 0, d
= dynrules
; n
< ndyn
; n
++, d
++) {
1702 if (d
->rulenum
> rnum
)
1704 if (d
->rulenum
== rnum
)
1705 show_dyn_ipfw(d
, pcwidth
, bcwidth
);
1715 if (exitval
!= EX_OK
)
1722 fprintf(stderr
, "usage: ipfw [options]\n"
1723 " add [number] rule\n"
1724 " pipe number config [pipeconfig]\n"
1725 " queue number config [queueconfig]\n"
1727 " [pipe] delete number ...\n"
1728 " [pipe] {list|show} [number ...]\n"
1729 " {zero|resetlog} [number ...]\n"
1730 "do \"ipfw -h\" or see ipfw manpage for details\n"
1740 fprintf(stderr
, "ipfw syntax summary:\n"
1741 "ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1742 "ipfw {pipe|queue} N config BODY\n"
1743 "ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1745 "RULE: [1..] [PROB] BODY\n"
1746 "RULENUM: INTEGER(1..65534)\n"
1747 "PROB: prob REAL(0..1)\n"
1748 "BODY: check-state [LOG] (no body) |\n"
1749 " ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1750 "ACTION: check-state | allow | count | deny | reject | skipto N |\n"
1751 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1752 "ADDR: [ MAC dst src ether_type ] \n"
1753 " [ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1754 "IPLIST: IPADDR | ( IPADDR or ... or IPADDR )\n"
1755 "IPADDR: [not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1756 "OPTION_LIST: OPTION [,OPTION_LIST]\n"
1763 lookup_host (char *host
, struct in_addr
*ipaddr
)
1767 if (!inet_aton(host
, ipaddr
)) {
1768 if ((he
= gethostbyname(host
)) == NULL
)
1770 *ipaddr
= *(struct in_addr
*)he
->h_addr_list
[0];
1776 * fills the addr and mask fields in the instruction as appropriate from av.
1777 * Update length as appropriate.
1778 * The following formats are allowed:
1779 * any matches any IP. Actually returns an empty instruction.
1780 * me returns O_IP_*_ME
1781 * 1.2.3.4 single IP address
1782 * 1.2.3.4:5.6.7.8 address:mask
1783 * 1.2.3.4/24 address/mask
1784 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1787 fill_ip(ipfw_insn_ip
*cmd
, char *av
)
1789 char *p
= NULL
, md
= 0;
1792 cmd
->o
.len
&= ~F_LEN_MASK
; /* zero len */
1794 if (!strncmp(av
, "any", strlen(av
)))
1797 if (!strncmp(av
, "me", strlen(av
))) {
1798 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn
);
1802 if (strlen(av
) >= 3 && av
[0] == '<' && av
[strlen(av
) - 1] == '>') {
1803 int pos
= strlen(av
) - 1;
1808 * Table: "<tableid>"
1811 tableid
= strtoul(&av
[1], &eptr
, 0);
1812 if (*eptr
!= '\0') {
1814 errx(EX_DATAERR
, "invalid tableid ``%s''", av
);
1817 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn
);
1818 cmd
->o
.opcode
= O_IP_DST_TABLE
;
1819 cmd
->o
.arg1
= tableid
;
1823 p
= strchr(av
, '/');
1825 p
= strchr(av
, ':');
1831 if (lookup_host(av
, &cmd
->addr
) != 0)
1832 errx(EX_NOHOST
, "hostname ``%s'' unknown", av
);
1835 if (!inet_aton(p
, &cmd
->mask
))
1836 errx(EX_DATAERR
, "bad netmask ``%s''", p
);
1841 cmd
->mask
.s_addr
= htonl(0);
1843 errx(EX_DATAERR
, "bad width ``%s''", p
);
1845 cmd
->mask
.s_addr
= htonl(~0 << (32 - i
));
1848 cmd
->mask
.s_addr
= htonl(~0);
1851 cmd
->addr
.s_addr
&= cmd
->mask
.s_addr
;
1853 * now look if we have a set of addresses. They are stored as follows:
1854 * arg1 is the set size (powers of 2, 2..256)
1855 * addr is the base address IN HOST FORMAT
1856 * mask.. is an array of u_int32_t with bits set.
1860 if (p
) { /* fetch addresses */
1863 int ii
= contigmask((u_char
*)&(cmd
->mask
), 32);
1865 if (ii
< 24 || ii
> 31) {
1866 fprintf(stderr
, "invalid set with mask %d\n",
1870 cmd
->o
.arg1
= 1<<(32-ii
);
1871 cmd
->addr
.s_addr
= ntohl(cmd
->addr
.s_addr
);
1872 d
= (u_int32_t
*)&cmd
->mask
;
1873 cmd
->o
.opcode
= O_IP_DST_SET
; /* default */
1874 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_u32
) + (cmd
->o
.arg1
+31)/32;
1875 for (ii
= 0; ii
< (cmd
->o
.arg1
+31)/32 ; ii
++)
1876 d
[ii
] = 0; /* clear masks */
1879 low
= cmd
->addr
.s_addr
& 0xff;
1880 high
= low
+ cmd
->o
.arg1
- 1;
1881 while (isdigit(*av
)) {
1883 u_int16_t a
= strtol(av
, &str
, 0);
1885 if (str
== av
) /* no parameter */
1887 if (a
< low
|| a
> high
) {
1888 fprintf(stderr
, "addr %d out of range [%d-%d]\n",
1893 d
[ a
/32] |= 1<<(a
& 31);
1901 if (cmd
->mask
.s_addr
== 0) { /* any */
1902 if (cmd
->o
.len
& F_NOT
)
1903 errx(EX_DATAERR
, "not any never matches");
1904 else /* useless, nuke it */
1906 } else if (cmd
->mask
.s_addr
== IP_MASK_ALL
) /* one IP */
1907 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_u32
);
1908 else /* addr/mask */
1909 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_ip
);
1914 * helper function to process a set of flags and set bits in the
1915 * appropriate masks.
1918 fill_flags(ipfw_insn
*cmd
, enum ipfw_opcodes opcode
,
1919 struct _s_x
*flags
, char *p
)
1921 u_int8_t set
=0, clear
=0;
1924 char *q
; /* points to the separator */
1926 u_int8_t
*which
; /* mask we are working on */
1936 val
= match_token(flags
, p
);
1938 errx(EX_DATAERR
, "invalid flag %s", p
);
1939 *which
|= (u_int8_t
)val
;
1942 cmd
->opcode
= opcode
;
1943 cmd
->len
= (cmd
->len
& (F_NOT
| F_OR
)) | 1;
1944 cmd
->arg1
= (set
& 0xff) | ( (clear
& 0xff) << 8);
1949 delete(int ac
, char *av
[])
1952 struct dn_ioc_pipe pipe
;
1954 int exitval
= EX_OK
;
1957 memset(&pipe
, 0, sizeof pipe
);
1960 if (ac
> 0 && !strncmp(*av
, "set", strlen(*av
))) {
1961 do_set
= 1; /* delete set */
1966 while (ac
&& isdigit(**av
)) {
1967 i
= atoi(*av
); av
++; ac
--;
1973 i
= setsockopt(s
, IPPROTO_IP
, IP_DUMMYNET_DEL
,
1974 &pipe
, sizeof pipe
);
1977 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1978 do_pipe
== 1 ? pipe
.pipe_nr
:
1982 rulenum
= (i
& 0xffff) | (do_set
<< 24);
1983 i
= setsockopt(s
, IPPROTO_IP
, IP_FW_DEL
, &rulenum
,
1986 exitval
= EX_UNAVAILABLE
;
1987 warn("rule %u: setsockopt(IP_FW_DEL)",
1992 if (exitval
!= EX_OK
)
1998 * fill the interface structure. We do not check the name as we can
1999 * create interfaces dynamically, so checking them at insert time
2000 * makes relatively little sense.
2001 * Interface names containing '*', '?', or '[' are assumed to be shell
2002 * patterns which match interfaces.
2005 fill_iface(ipfw_insn_if
*cmd
, char *arg
)
2007 cmd
->name
[0] = '\0';
2008 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_if
);
2010 /* Parse the interface or address */
2011 if (!strcmp(arg
, "any"))
2012 cmd
->o
.len
= 0; /* effectively ignore this command */
2013 else if (!isdigit(*arg
)) {
2014 strlcpy(cmd
->name
, arg
, sizeof(cmd
->name
));
2015 cmd
->p
.glob
= strpbrk(arg
, "*?[") != NULL
? 1 : 0;
2016 } else if (!inet_aton(arg
, &cmd
->p
.ip
))
2017 errx(EX_DATAERR
, "bad ip address ``%s''", arg
);
2020 static unsigned long
2021 getbw(const char *str
, u_short
*flags
, int kb
)
2027 val
= strtoul(str
, &end
, 0);
2028 if (*end
== 'k' || *end
== 'K') {
2031 } else if (*end
== 'm' || *end
== 'M') {
2037 * Deal with bits or bytes or b(bits) or B(bytes). If there is no
2038 * trailer assume bits.
2040 if (strncasecmp(end
, "bit", 3) == 0) {
2042 } else if (strncasecmp(end
, "byte", 4) == 0) {
2044 } else if (*end
== 'b') {
2046 } else if (*end
== 'B') {
2051 * Return in bits if flags is NULL, else flag bits
2052 * or bytes in flags and return the unconverted value.
2054 if (inbytes
&& flags
)
2055 *flags
|= DN_QSIZE_IS_BYTES
;
2056 else if (inbytes
&& flags
== NULL
)
2062 * the following macro returns an error message if we run out of
2065 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
2068 config_pipe(int ac
, char **av
)
2070 struct dn_ioc_pipe pipe
;
2075 memset(&pipe
, 0, sizeof pipe
);
2079 if (ac
&& isdigit(**av
)) {
2080 i
= atoi(*av
); av
++; ac
--;
2088 int tok
= match_token(dummynet_params
, *av
);
2093 pipe
.fs
.flags_fs
|= DN_NOERROR
;
2097 NEED1("plr needs argument 0..1\n");
2098 d
= strtod(av
[0], NULL
);
2103 pipe
.fs
.plr
= (int)(d
*0x7fffffff);
2108 NEED1("queue needs queue size\n");
2110 pipe
.fs
.qsize
= getbw(av
[0], &pipe
.fs
.flags_fs
, 1024);
2115 NEED1("buckets needs argument\n");
2116 pipe
.fs
.rq_size
= strtoul(av
[0], NULL
, 0);
2121 NEED1("mask needs mask specifier\n");
2123 * per-flow queue, mask is dst_ip, dst_port,
2124 * src_ip, src_port, proto measured in bits
2127 pipe
.fs
.flow_mask
.type
= ETHERTYPE_IP
;
2128 pipe
.fs
.flow_mask
.u
.ip
.dst_ip
= 0;
2129 pipe
.fs
.flow_mask
.u
.ip
.src_ip
= 0;
2130 pipe
.fs
.flow_mask
.u
.ip
.dst_port
= 0;
2131 pipe
.fs
.flow_mask
.u
.ip
.src_port
= 0;
2132 pipe
.fs
.flow_mask
.u
.ip
.proto
= 0;
2136 u_int32_t
*p32
= NULL
;
2137 u_int16_t
*p16
= NULL
;
2139 tok
= match_token(dummynet_params
, *av
);
2144 * special case, all bits significant
2146 pipe
.fs
.flow_mask
.u
.ip
.dst_ip
= ~0;
2147 pipe
.fs
.flow_mask
.u
.ip
.src_ip
= ~0;
2148 pipe
.fs
.flow_mask
.u
.ip
.dst_port
= ~0;
2149 pipe
.fs
.flow_mask
.u
.ip
.src_port
= ~0;
2150 pipe
.fs
.flow_mask
.u
.ip
.proto
= ~0;
2151 pipe
.fs
.flags_fs
|= DN_HAVE_FLOW_MASK
;
2155 p32
= &pipe
.fs
.flow_mask
.u
.ip
.dst_ip
;
2159 p32
= &pipe
.fs
.flow_mask
.u
.ip
.src_ip
;
2163 p16
= &pipe
.fs
.flow_mask
.u
.ip
.dst_port
;
2167 p16
= &pipe
.fs
.flow_mask
.u
.ip
.src_port
;
2174 ac
++; av
--; /* backtrack */
2178 errx(EX_USAGE
, "mask: value missing");
2179 if (*av
[0] == '/') {
2180 a
= strtoul(av
[0]+1, &end
, 0);
2181 a
= (a
== 32) ? ~0 : (1 << a
) - 1;
2183 a
= strtoul(av
[0], &end
, 0);
2186 else if (p16
!= NULL
) {
2189 "mask: must be 16 bit");
2190 *p16
= (u_int16_t
)a
;
2194 "mask: must be 8 bit");
2195 pipe
.fs
.flow_mask
.u
.ip
.proto
= (uint8_t)a
;
2198 pipe
.fs
.flags_fs
|= DN_HAVE_FLOW_MASK
;
2200 } /* end while, config masks */
2206 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
2207 pipe
.fs
.flags_fs
|= DN_IS_RED
;
2208 if (tok
== TOK_GRED
)
2209 pipe
.fs
.flags_fs
|= DN_IS_GENTLE_RED
;
2211 * the format for parameters is w_q/min_th/max_th/max_p
2213 if ((end
= strsep(&av
[0], "/"))) {
2214 double w_q
= strtod(end
, NULL
);
2215 if (w_q
> 1 || w_q
<= 0)
2216 errx(EX_DATAERR
, "0 < w_q <= 1");
2217 pipe
.fs
.w_q
= (int) (w_q
* (1 << SCALE_RED
));
2219 if ((end
= strsep(&av
[0], "/"))) {
2220 pipe
.fs
.min_th
= strtoul(end
, &end
, 0);
2221 if (*end
== 'K' || *end
== 'k')
2222 pipe
.fs
.min_th
*= 1024;
2224 if ((end
= strsep(&av
[0], "/"))) {
2225 pipe
.fs
.max_th
= strtoul(end
, &end
, 0);
2226 if (*end
== 'K' || *end
== 'k')
2227 pipe
.fs
.max_th
*= 1024;
2229 if ((end
= strsep(&av
[0], "/"))) {
2230 double max_p
= strtod(end
, NULL
);
2231 if (max_p
> 1 || max_p
<= 0)
2232 errx(EX_DATAERR
, "0 < max_p <= 1");
2233 pipe
.fs
.max_p
= (int)(max_p
* (1 << SCALE_RED
));
2239 pipe
.fs
.flags_fs
&= ~(DN_IS_RED
|DN_IS_GENTLE_RED
);
2243 NEED1("bw needs bandwidth\n");
2245 errx(EX_DATAERR
, "bandwidth only valid for pipes");
2247 * set bandwidth value
2249 pipe
.bandwidth
= getbw(av
[0], NULL
, 1000);
2250 if (pipe
.bandwidth
< 0)
2251 errx(EX_DATAERR
, "bandwidth too large");
2257 errx(EX_DATAERR
, "delay only valid for pipes");
2258 NEED1("delay needs argument 0..10000ms\n");
2259 pipe
.delay
= strtoul(av
[0], NULL
, 0);
2265 errx(EX_DATAERR
,"weight only valid for queues");
2266 NEED1("weight needs argument 0..100\n");
2267 pipe
.fs
.weight
= strtoul(av
[0], &end
, 0);
2273 errx(EX_DATAERR
,"pipe only valid for queues");
2274 NEED1("pipe needs pipe_number\n");
2275 pipe
.fs
.parent_nr
= strtoul(av
[0], &end
, 0);
2280 errx(EX_DATAERR
, "unrecognised option ``%s''", *av
);
2284 if (pipe
.pipe_nr
== 0)
2285 errx(EX_DATAERR
, "pipe_nr must be > 0");
2286 if (pipe
.delay
> 10000)
2287 errx(EX_DATAERR
, "delay must be < 10000");
2288 } else { /* do_pipe == 2, queue */
2289 if (pipe
.fs
.parent_nr
== 0)
2290 errx(EX_DATAERR
, "pipe must be > 0");
2291 if (pipe
.fs
.weight
>100)
2292 errx(EX_DATAERR
, "weight must be <= 100");
2294 if (pipe
.fs
.flags_fs
& DN_QSIZE_IS_BYTES
) {
2295 if (pipe
.fs
.qsize
> 1024*1024)
2296 errx(EX_DATAERR
, "queue size must be < 1MB");
2298 if (pipe
.fs
.qsize
> 100)
2299 errx(EX_DATAERR
, "2 <= queue size <= 100");
2301 if (pipe
.fs
.flags_fs
& DN_IS_RED
) {
2303 int lookup_depth
, avg_pkt_size
;
2304 double step
, idle
, weight
, w_q
;
2308 if (pipe
.fs
.min_th
>= pipe
.fs
.max_th
)
2309 errx(EX_DATAERR
, "min_th %d must be < than max_th %d",
2310 pipe
.fs
.min_th
, pipe
.fs
.max_th
);
2311 if (pipe
.fs
.max_th
== 0)
2312 errx(EX_DATAERR
, "max_th must be > 0");
2315 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
2316 &lookup_depth
, &len
, NULL
, 0) == -1)
2318 errx(1, "sysctlbyname(\"%s\")",
2319 "net.inet.ip.dummynet.red_lookup_depth");
2320 if (lookup_depth
== 0)
2321 errx(EX_DATAERR
, "net.inet.ip.dummynet.red_lookup_depth"
2322 " must be greater than zero");
2325 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2326 &avg_pkt_size
, &len
, NULL
, 0) == -1)
2328 errx(1, "sysctlbyname(\"%s\")",
2329 "net.inet.ip.dummynet.red_avg_pkt_size");
2330 if (avg_pkt_size
== 0)
2332 "net.inet.ip.dummynet.red_avg_pkt_size must"
2333 " be greater than zero");
2335 len
= sizeof(clock_hz
);
2336 if (sysctlbyname("net.inet.ip.dummynet.hz", &clock_hz
, &len
,
2338 errx(1, "sysctlbyname(\"%s\")",
2339 "net.inet.ip.dummynet.hz");
2343 * Ticks needed for sending a medium-sized packet.
2344 * Unfortunately, when we are configuring a WF2Q+ queue, we
2345 * do not have bandwidth information, because that is stored
2346 * in the parent pipe, and also we have multiple queues
2347 * competing for it. So we set step=0, which is not very
2348 * correct. But on the other hand, why do we want RED with
2351 if (pipe
.bandwidth
==0) /* this is a WF2Q+ queue */
2354 step
= clock_hz
* avg_pkt_size
* 8 / pipe
.bandwidth
;
2357 * max idle time (in ticks) before avg queue size becomes 0.
2358 * NOTA: (3/w_q) is approx the value x so that
2359 * (1-w_q)^x < 10^-3.
2361 w_q
= ((double)pipe
.fs
.w_q
) / (1 << SCALE_RED
);
2362 idle
= step
* 3. / w_q
;
2363 pipe
.fs
.lookup_step
= (int)idle
/ lookup_depth
;
2364 if (!pipe
.fs
.lookup_step
)
2365 pipe
.fs
.lookup_step
= 1;
2367 for (t
= pipe
.fs
.lookup_step
; t
> 0; --t
)
2369 pipe
.fs
.lookup_weight
= (int)(weight
* (1 << SCALE_RED
));
2371 i
= setsockopt(s
, IPPROTO_IP
, IP_DUMMYNET_CONFIGURE
, &pipe
,
2374 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2378 get_mac_addr_mask(char *p
, u_char
*addr
, u_char
*mask
)
2383 addr
[i
] = mask
[i
] = 0;
2384 if (!strcmp(p
, "any"))
2387 for (i
=0; *p
&& i
<6;i
++, p
++) {
2388 addr
[i
] = strtol(p
, &p
, 16);
2389 if (*p
!= ':') /* we start with the mask */
2392 if (*p
== '/') { /* mask len */
2393 l
= strtol(p
+1, &p
, 0);
2394 for (i
=0; l
>0; l
-=8, i
++)
2395 mask
[i
] = (l
>=8) ? 0xff : (~0) << (8-l
);
2396 } else if (*p
== '&') { /* mask */
2397 for (i
=0, p
++; *p
&& i
<6;i
++, p
++) {
2398 mask
[i
] = strtol(p
, &p
, 16);
2402 } else if (*p
== '\0') {
2411 * helper function, updates the pointer to cmd with the length
2412 * of the current command, and also cleans up the first word of
2413 * the new command in case it has been clobbered before.
2416 next_cmd(ipfw_insn
*cmd
)
2419 bzero(cmd
, sizeof(*cmd
));
2424 * A function to fill simple commands of size 1.
2425 * Existing flags are preserved.
2428 fill_cmd(ipfw_insn
*cmd
, enum ipfw_opcodes opcode
, int flags
, u_int16_t arg
)
2430 cmd
->opcode
= opcode
;
2431 cmd
->len
= ((cmd
->len
| flags
) & (F_NOT
| F_OR
)) | 1;
2436 * Fetch and add the MAC address and type, with masks. This generates one or
2437 * two microinstructions, and returns the pointer to the last one.
2440 add_mac(ipfw_insn
*cmd
, int ac
, char *av
[])
2445 errx(EX_DATAERR
, "MAC dst src");
2447 cmd
->opcode
= O_MACADDR2
;
2448 cmd
->len
= (cmd
->len
& (F_NOT
| F_OR
)) | F_INSN_SIZE(ipfw_insn_mac
);
2450 mac
= (ipfw_insn_mac
*)cmd
;
2451 get_mac_addr_mask(av
[0], mac
->addr
, mac
->mask
); /* dst */
2452 get_mac_addr_mask(av
[1], &(mac
->addr
[6]), &(mac
->mask
[6])); /* src */
2457 add_mactype(ipfw_insn
*cmd
, int ac
, char *av
)
2460 errx(EX_DATAERR
, "missing MAC type");
2461 if (strcmp(av
, "any") != 0) { /* we have a non-null type */
2462 fill_newports((ipfw_insn_u16
*)cmd
, av
, IPPROTO_ETHERTYPE
);
2463 cmd
->opcode
= O_MAC_TYPE
;
2470 add_proto(ipfw_insn
*cmd
, char *av
)
2472 struct protoent
*pe
;
2475 if (!strncmp(av
, "all", strlen(av
)))
2476 ; /* same as "ip" */
2477 else if ((proto
= atoi(av
)) > 0)
2479 else if ((pe
= getprotobyname(av
)) != NULL
)
2480 proto
= pe
->p_proto
;
2483 if (proto
!= IPPROTO_IP
)
2484 fill_cmd(cmd
, O_PROTO
, 0, proto
);
2489 add_srcip(ipfw_insn
*cmd
, char *av
)
2491 fill_ip((ipfw_insn_ip
*)cmd
, av
);
2492 if (cmd
->opcode
== O_IP_DST_SET
) /* set */
2493 cmd
->opcode
= O_IP_SRC_SET
;
2494 else if (cmd
->opcode
== O_IP_DST_TABLE
) /* table */
2495 cmd
->opcode
= O_IP_SRC_TABLE
;
2496 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn
)) /* me */
2497 cmd
->opcode
= O_IP_SRC_ME
;
2498 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn_u32
)) /* one IP */
2499 cmd
->opcode
= O_IP_SRC
;
2500 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn_ip
)) /* addr/mask */
2501 cmd
->opcode
= O_IP_SRC_MASK
;
2506 add_dstip(ipfw_insn
*cmd
, char *av
)
2508 fill_ip((ipfw_insn_ip
*)cmd
, av
);
2509 if (cmd
->opcode
== O_IP_DST_SET
) /* set */
2511 else if (cmd
->opcode
== O_IP_DST_TABLE
) /* table */
2513 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn
)) /* me */
2514 cmd
->opcode
= O_IP_DST_ME
;
2515 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn_u32
)) /* one IP */
2516 cmd
->opcode
= O_IP_DST
;
2517 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn_ip
)) /* addr/mask */
2518 cmd
->opcode
= O_IP_DST_MASK
;
2523 add_ports(ipfw_insn
*cmd
, char *av
, u_char proto
, int opcode
)
2525 if (!strncmp(av
, "any", strlen(av
))) {
2527 } else if (fill_newports((ipfw_insn_u16
*)cmd
, av
, proto
)) {
2528 /* XXX todo: check that we have a protocol with ports */
2529 cmd
->opcode
= opcode
;
2536 * Parse arguments and assemble the microinstructions which make up a rule.
2537 * Rules are added into the 'rulebuf' and then copied in the correct order
2538 * into the actual rule.
2540 * The syntax for a rule starts with the action, followed by an
2541 * optional log action, and the various match patterns.
2542 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2543 * (generated if the rule includes a keep-state option), then the
2544 * various match patterns, the "log" action, and the actual action.
2548 add(int ac
, char *av
[])
2551 * rules are added into the 'rulebuf' and then copied in
2552 * the correct order into the actual rule.
2553 * Some things that need to go out of order (prob, action etc.)
2556 static uint32_t rulebuf
[IPFW_RULE_SIZE_MAX
];
2557 static uint32_t actbuf
[IPFW_RULE_SIZE_MAX
];
2558 static uint32_t cmdbuf
[IPFW_RULE_SIZE_MAX
];
2560 ipfw_insn
*src
, *dst
, *cmd
, *action
, *prev
= NULL
;
2561 ipfw_insn
*first_cmd
; /* first match pattern */
2563 struct ipfw_ioc_rule
*rule
;
2566 * various flags used to record that we entered some fields.
2568 ipfw_insn
*have_state
= NULL
; /* check-state or keep-state */
2572 int open_par
= 0; /* open parenthesis ( */
2574 /* proto is here because it is used to fetch ports */
2575 u_char proto
= IPPROTO_IP
; /* default protocol */
2577 double match_prob
= 1; /* match probability, default is always match */
2579 bzero(actbuf
, sizeof(actbuf
)); /* actions go here */
2580 bzero(cmdbuf
, sizeof(cmdbuf
));
2581 bzero(rulebuf
, sizeof(rulebuf
));
2583 rule
= (struct ipfw_ioc_rule
*)rulebuf
;
2584 cmd
= (ipfw_insn
*)cmdbuf
;
2585 action
= (ipfw_insn
*)actbuf
;
2589 /* [rule N] -- Rule number optional */
2590 if (ac
&& isdigit(**av
)) {
2591 rule
->rulenum
= atoi(*av
);
2596 /* [set N] -- set number (0..30), optional */
2597 if (ac
> 1 && !strncmp(*av
, "set", strlen(*av
))) {
2598 int set
= strtoul(av
[1], NULL
, 10);
2599 if (set
< 0 || set
> 30)
2600 errx(EX_DATAERR
, "illegal set %s", av
[1]);
2605 /* [prob D] -- match probability, optional */
2606 if (ac
> 1 && !strncmp(*av
, "prob", strlen(*av
))) {
2607 match_prob
= strtod(av
[1], NULL
);
2609 if (match_prob
<= 0 || match_prob
> 1)
2610 errx(EX_DATAERR
, "illegal match prob. %s", av
[1]);
2614 /* action -- mandatory */
2615 NEED1("missing action");
2616 i
= match_token(rule_actions
, *av
);
2618 action
->len
= 1; /* default */
2620 case TOK_CHECKSTATE
:
2621 have_state
= action
;
2622 action
->opcode
= O_CHECK_STATE
;
2626 action
->opcode
= O_ACCEPT
;
2630 action
->opcode
= O_DEFRAG
;
2635 action
->opcode
= O_DENY
;
2640 action
->opcode
= O_REJECT
;
2641 action
->arg1
= ICMP_UNREACH_HOST
;
2645 action
->opcode
= O_REJECT
;
2646 action
->arg1
= ICMP_REJECT_RST
;
2650 action
->opcode
= O_REJECT
;
2651 NEED1("missing reject code");
2652 fill_reject_code(&action
->arg1
, *av
);
2657 action
->opcode
= O_COUNT
;
2662 action
->len
= F_INSN_SIZE(ipfw_insn_pipe
);
2665 action
->opcode
= O_QUEUE
;
2666 else if (i
== TOK_PIPE
)
2667 action
->opcode
= O_PIPE
;
2668 else if (i
== TOK_SKIPTO
)
2669 action
->opcode
= O_SKIPTO
;
2670 NEED1("missing skipto/pipe/queue number");
2671 action
->arg1
= strtoul(*av
, NULL
, 10);
2677 action
->opcode
= (i
== TOK_DIVERT
) ? O_DIVERT
: O_TEE
;
2678 NEED1("missing divert/tee port");
2679 action
->arg1
= strtoul(*av
, NULL
, 0);
2680 if (action
->arg1
== 0) {
2681 struct servent
*serv
;
2683 serv
= getservbyname(av
[0], "divert");
2685 action
->arg1
= ntohs(serv
->s_port
);
2687 errx(EX_DATAERR
, "illegal divert/tee port");
2693 ipfw_insn_sa
*p
= (ipfw_insn_sa
*)action
;
2696 NEED1("missing forward address[:port]");
2698 action
->opcode
= O_FORWARD_IP
;
2699 action
->len
= F_INSN_SIZE(ipfw_insn_sa
);
2701 p
->sa
.sin_len
= sizeof(struct sockaddr_in
);
2702 p
->sa
.sin_family
= AF_INET
;
2705 * locate the address-port separator (':' or ',')
2707 st
= strchr(*av
, ':');
2709 st
= strchr(*av
, ',');
2712 i
= strtoport(st
, &end
, 0 /* base */, 0 /* proto */);
2715 "illegal forwarding port ``%s''", st
);
2716 p
->sa
.sin_port
= (u_short
)i
;
2718 lookup_host(*av
, &(p
->sa
.sin_addr
));
2724 errx(EX_DATAERR
, "invalid action %s\n", av
[-1]);
2726 action
= next_cmd(action
);
2729 * [log [logamount N]] -- log, optional
2731 * If exists, it goes first in the cmdbuf, but then it is
2732 * skipped in the copy section to the end of the buffer.
2734 if (ac
&& !strncmp(*av
, "log", strlen(*av
))) {
2735 ipfw_insn_log
*c
= (ipfw_insn_log
*)cmd
;
2737 cmd
->len
= F_INSN_SIZE(ipfw_insn_log
);
2738 cmd
->opcode
= O_LOG
;
2740 if (ac
&& !strncmp(*av
, "logamount", strlen(*av
))) {
2742 NEED1("logamount requires argument");
2743 c
->max_log
= atoi(*av
);
2746 cmd
= next_cmd(cmd
);
2749 if (have_state
) /* must be a check-state, we are done */
2752 #define OR_START(target) \
2753 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2755 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2758 if ( (av[0])[1] == '\0') { \
2769 !strncmp(*av, ")", strlen(*av)) || \
2770 !strncmp(*av, "}", strlen(*av)) )) { \
2775 errx(EX_USAGE, "missing \")\"\n"); \
2779 if (ac && !strncmp(*av, "not", strlen(*av))) { \
2780 if (cmd->len & F_NOT) \
2781 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2782 cmd->len |= F_NOT; \
2786 #define OR_BLOCK(target) \
2787 if (ac && !strncmp(*av, "or", strlen(*av))) { \
2788 if (prev == NULL || open_par == 0) \
2789 errx(EX_DATAERR, "invalid OR block"); \
2790 prev->len |= F_OR; \
2800 * MAC addresses, optional.
2801 * If we have this, we skip the part "proto from src to dst"
2802 * and jump straight to the option parsing.
2805 NEED1("missing protocol");
2806 if (!strncmp(*av
, "MAC", strlen(*av
)) ||
2807 !strncmp(*av
, "mac", strlen(*av
))) {
2808 ac
--; av
++; /* the "MAC" keyword */
2809 add_mac(cmd
, ac
, av
); /* exits in case of errors */
2810 cmd
= next_cmd(cmd
);
2811 ac
-= 2; av
+= 2; /* dst-mac and src-mac */
2813 NEED1("missing mac type");
2814 if (add_mactype(cmd
, ac
, av
[0]))
2815 cmd
= next_cmd(cmd
);
2816 ac
--; av
++; /* any or mac-type */
2822 * protocol, mandatory
2824 OR_START(get_proto
);
2826 NEED1("missing protocol");
2827 if (add_proto(cmd
, *av
)) {
2829 if (F_LEN(cmd
) == 0) /* plain IP */
2834 cmd
= next_cmd(cmd
);
2836 } else if (first_cmd
!= cmd
) {
2837 errx(EX_DATAERR
, "invalid protocol ``%s''", *av
);
2840 OR_BLOCK(get_proto
);
2845 if (!ac
|| strncmp(*av
, "from", strlen(*av
)))
2846 errx(EX_USAGE
, "missing ``from''");
2850 * source IP, mandatory
2852 OR_START(source_ip
);
2853 NOT_BLOCK
; /* optional "not" */
2854 NEED1("missing source address");
2855 if (add_srcip(cmd
, *av
)) {
2857 if (F_LEN(cmd
) != 0) { /* ! any */
2859 cmd
= next_cmd(cmd
);
2862 OR_BLOCK(source_ip
);
2865 * source ports, optional
2867 NOT_BLOCK
; /* optional "not" */
2869 if (!strncmp(*av
, "any", strlen(*av
)) ||
2870 add_ports(cmd
, *av
, proto
, O_IP_SRCPORT
)) {
2872 if (F_LEN(cmd
) != 0)
2873 cmd
= next_cmd(cmd
);
2880 if (!ac
|| strncmp(*av
, "to", strlen(*av
)))
2881 errx(EX_USAGE
, "missing ``to''");
2885 * destination, mandatory
2888 NOT_BLOCK
; /* optional "not" */
2889 NEED1("missing dst address");
2890 if (add_dstip(cmd
, *av
)) {
2892 if (F_LEN(cmd
) != 0) { /* ! any */
2894 cmd
= next_cmd(cmd
);
2900 * dest. ports, optional
2902 NOT_BLOCK
; /* optional "not" */
2904 if (!strncmp(*av
, "any", strlen(*av
)) ||
2905 add_ports(cmd
, *av
, proto
, O_IP_DSTPORT
)) {
2907 if (F_LEN(cmd
) != 0)
2908 cmd
= next_cmd(cmd
);
2913 if (ac
&& first_cmd
== cmd
) {
2915 * nothing specified so far, store in the rule to ease
2918 rule
->usr_flags
= IPFW_USR_F_NORULE
;
2923 ipfw_insn_u32
*cmd32
; /* alias for cmd */
2926 cmd32
= (ipfw_insn_u32
*)cmd
;
2928 if (*s1
== '!') { /* alternate syntax for NOT */
2929 if (cmd
->len
& F_NOT
)
2930 errx(EX_USAGE
, "double \"not\" not allowed\n");
2934 i
= match_token(rule_options
, s1
);
2938 if (cmd
->len
& F_NOT
)
2939 errx(EX_USAGE
, "double \"not\" not allowed\n");
2944 if (open_par
== 0 || prev
== NULL
)
2945 errx(EX_USAGE
, "invalid \"or\" block\n");
2949 case TOK_STARTBRACE
:
2951 errx(EX_USAGE
, "+nested \"(\" not allowed\n");
2957 errx(EX_USAGE
, "+missing \")\"\n");
2963 fill_cmd(cmd
, O_IN
, 0, 0);
2967 cmd
->len
^= F_NOT
; /* toggle F_NOT */
2968 fill_cmd(cmd
, O_IN
, 0, 0);
2972 fill_cmd(cmd
, O_FRAG
, 0, 0);
2976 fill_cmd(cmd
, O_IPFRAG
, 0, 0);
2980 fill_cmd(cmd
, O_LAYER2
, 0, 0);
2986 NEED1("recv, xmit, via require interface name"
2988 fill_iface((ipfw_insn_if
*)cmd
, av
[0]);
2990 if (F_LEN(cmd
) == 0) /* not a valid address */
2993 cmd
->opcode
= O_XMIT
;
2994 else if (i
== TOK_RECV
)
2995 cmd
->opcode
= O_RECV
;
2996 else if (i
== TOK_VIA
)
2997 cmd
->opcode
= O_VIA
;
3001 NEED1("icmptypes requires list of types");
3002 fill_icmptypes((ipfw_insn_u32
*)cmd
, *av
);
3007 NEED1("ipttl requires TTL");
3008 fill_cmd(cmd
, O_IPTTL
, 0, strtoul(*av
, NULL
, 0));
3013 NEED1("ipid requires length");
3014 fill_cmd(cmd
, O_IPID
, 0, strtoul(*av
, NULL
, 0));
3019 NEED1("iplen requires length");
3020 fill_cmd(cmd
, O_IPLEN
, 0, strtoul(*av
, NULL
, 0));
3025 NEED1("ipver requires version");
3026 fill_cmd(cmd
, O_IPVER
, 0, strtoul(*av
, NULL
, 0));
3030 case TOK_IPPRECEDENCE
:
3031 NEED1("ipprecedence requires value");
3032 fill_cmd(cmd
, O_IPPRECEDENCE
, 0,
3033 (strtoul(*av
, NULL
, 0) & 7) << 5);
3038 NEED1("missing argument for ipoptions");
3039 fill_flags(cmd
, O_IPOPT
, f_ipopts
, *av
);
3044 NEED1("missing argument for iptos");
3045 fill_flags(cmd
, O_IPTOS
, f_iptos
, *av
);
3050 NEED1("uid requires argument");
3056 cmd
->opcode
= O_UID
;
3057 uid
= strtoul(*av
, &end
, 0);
3058 pwd
= (*end
== '\0') ? getpwuid(uid
) : getpwnam(*av
);
3060 errx(EX_DATAERR
, "uid \"%s\" nonexistent", *av
);
3061 cmd32
->d
[0] = pwd
->pw_uid
;
3062 cmd
->len
= F_INSN_SIZE(ipfw_insn_u32
);
3068 NEED1("gid requires argument");
3074 cmd
->opcode
= O_GID
;
3075 gid
= strtoul(*av
, &end
, 0);
3076 grp
= (*end
== '\0') ? getgrgid(gid
) : getgrnam(*av
);
3078 errx(EX_DATAERR
, "gid \"%s\" nonexistent", *av
);
3079 cmd32
->d
[0] = grp
->gr_gid
;
3080 cmd
->len
= F_INSN_SIZE(ipfw_insn_u32
);
3086 fill_cmd(cmd
, O_ESTAB
, 0, 0);
3090 fill_cmd(cmd
, O_TCPFLAGS
, 0,
3091 (TH_SYN
) | ( (TH_ACK
) & 0xff) <<8 );
3095 NEED1("missing argument for tcpoptions");
3096 fill_flags(cmd
, O_TCPOPTS
, f_tcpopts
, *av
);
3102 NEED1("tcpseq/tcpack requires argument");
3103 cmd
->len
= F_INSN_SIZE(ipfw_insn_u32
);
3104 cmd
->opcode
= (i
== TOK_TCPSEQ
) ? O_TCPSEQ
: O_TCPACK
;
3105 cmd32
->d
[0] = htonl(strtoul(*av
, NULL
, 0));
3110 NEED1("tcpwin requires length");
3111 fill_cmd(cmd
, O_TCPWIN
, 0,
3112 htons(strtoul(*av
, NULL
, 0)));
3117 NEED1("missing argument for tcpflags");
3118 cmd
->opcode
= O_TCPFLAGS
;
3119 fill_flags(cmd
, O_TCPFLAGS
, f_tcpflags
, *av
);
3125 errx(EX_USAGE
, "keep-state cannot be part "
3128 errx(EX_USAGE
, "only one of keep-state "
3129 "and limit is allowed");
3131 fill_cmd(cmd
, O_KEEP_STATE
, 0, 0);
3136 errx(EX_USAGE
, "limit cannot be part "
3139 errx(EX_USAGE
, "only one of keep-state "
3140 "and limit is allowed");
3141 NEED1("limit needs mask and # of connections");
3144 ipfw_insn_limit
*c
= (ipfw_insn_limit
*)cmd
;
3146 cmd
->len
= F_INSN_SIZE(ipfw_insn_limit
);
3147 cmd
->opcode
= O_LIMIT
;
3153 val
= match_token(limit_masks
, *av
);
3156 c
->limit_mask
|= val
;
3159 c
->conn_limit
= atoi(*av
);
3160 if (c
->conn_limit
== 0)
3161 errx(EX_USAGE
, "limit: limit must be >0");
3162 if (c
->limit_mask
== 0)
3163 errx(EX_USAGE
, "missing limit mask");
3169 NEED1("missing protocol");
3170 if (add_proto(cmd
, *av
)) {
3174 errx(EX_DATAERR
, "invalid protocol ``%s''", *av
);
3178 NEED1("missing source IP");
3179 if (add_srcip(cmd
, *av
)) {
3185 NEED1("missing destination IP");
3186 if (add_dstip(cmd
, *av
)) {
3192 NEED1("missing source port");
3193 if (!strncmp(*av
, "any", strlen(*av
)) ||
3194 add_ports(cmd
, *av
, proto
, O_IP_SRCPORT
)) {
3197 errx(EX_DATAERR
, "invalid source port %s", *av
);
3201 NEED1("missing destination port");
3202 if (!strncmp(*av
, "any", strlen(*av
)) ||
3203 add_ports(cmd
, *av
, proto
, O_IP_DSTPORT
)) {
3206 errx(EX_DATAERR
, "invalid destination port %s",
3212 errx(EX_USAGE
, "MAC dst-mac src-mac");
3213 if (add_mac(cmd
, ac
, av
)) {
3219 NEED1("missing mac type");
3220 if (!add_mactype(cmd
, ac
, *av
))
3221 errx(EX_DATAERR
, "invalid mac type %s", *av
);
3226 errx(EX_USAGE
, "unrecognised option [%d] %s\n", i
, s1
);
3228 if (F_LEN(cmd
) > 0) { /* prepare to advance */
3230 cmd
= next_cmd(cmd
);
3236 * Now copy stuff into the rule.
3237 * If we have a keep-state option, the first instruction
3238 * must be a PROBE_STATE (which is generated here).
3239 * If we have a LOG option, it was stored as the first command,
3240 * and now must be moved to the top of the action part.
3242 dst
= (ipfw_insn
*)rule
->cmd
;
3245 * First thing to write into the command stream is the match probability.
3247 if (match_prob
!= 1) { /* 1 means always match */
3248 dst
->opcode
= O_PROB
;
3250 *((int32_t *)(dst
+1)) = (int32_t)(match_prob
* 0x7fffffff);
3255 * generate O_PROBE_STATE if necessary
3257 if (have_state
&& have_state
->opcode
!= O_CHECK_STATE
) {
3258 fill_cmd(dst
, O_PROBE_STATE
, 0, 0);
3259 dst
= next_cmd(dst
);
3262 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT
3264 for (src
= (ipfw_insn
*)cmdbuf
; src
!= cmd
; src
+= i
) {
3267 switch (src
->opcode
) {
3273 bcopy(src
, dst
, i
* sizeof(u_int32_t
));
3279 * put back the have_state command as last opcode
3281 if (have_state
&& have_state
->opcode
!= O_CHECK_STATE
) {
3282 i
= F_LEN(have_state
);
3283 bcopy(have_state
, dst
, i
* sizeof(u_int32_t
));
3287 * start action section
3289 rule
->act_ofs
= dst
- rule
->cmd
;
3292 * put back O_LOG if necessary
3294 src
= (ipfw_insn
*)cmdbuf
;
3295 if ( src
->opcode
== O_LOG
) {
3297 bcopy(src
, dst
, i
* sizeof(u_int32_t
));
3301 * copy all other actions
3303 for (src
= (ipfw_insn
*)actbuf
; src
!= action
; src
+= i
) {
3305 bcopy(src
, dst
, i
* sizeof(u_int32_t
));
3309 rule
->cmd_len
= (u_int32_t
*)dst
- (u_int32_t
*)(rule
->cmd
);
3310 i
= (uint8_t *)dst
- (uint8_t *)rule
;
3311 if (getsockopt(s
, IPPROTO_IP
, IP_FW_ADD
, rule
, &i
) == -1)
3312 err(EX_UNAVAILABLE
, "getsockopt(%s)", "IP_FW_ADD");
3314 show_ipfw(rule
, 10, 10);
3318 zero(int ac
, char *av
[])
3326 /* clear all entries */
3327 if (setsockopt(s
, IPPROTO_IP
, IP_FW_ZERO
, NULL
, 0) < 0)
3328 err(EX_UNAVAILABLE
, "setsockopt(%s)", "IP_FW_ZERO");
3330 printf("Accounting cleared.\n");
3337 if (isdigit(**av
)) {
3338 rulenum
= atoi(*av
);
3341 if (setsockopt(s
, IPPROTO_IP
,
3342 IP_FW_ZERO
, &rulenum
, sizeof rulenum
)) {
3343 warn("rule %u: setsockopt(IP_FW_ZERO)",
3345 failed
= EX_UNAVAILABLE
;
3346 } else if (!do_quiet
)
3347 printf("Entry %d cleared\n", rulenum
);
3349 errx(EX_USAGE
, "invalid rule number ``%s''", *av
);
3352 if (failed
!= EX_OK
)
3357 resetlog(int ac
, char *av
[])
3365 /* clear all entries */
3366 if (setsockopt(s
, IPPROTO_IP
, IP_FW_RESETLOG
, NULL
, 0) < 0)
3367 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_RESETLOG)");
3369 printf("Logging counts reset.\n");
3376 if (isdigit(**av
)) {
3377 rulenum
= atoi(*av
);
3380 if (setsockopt(s
, IPPROTO_IP
,
3381 IP_FW_RESETLOG
, &rulenum
, sizeof rulenum
)) {
3382 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
3384 failed
= EX_UNAVAILABLE
;
3385 } else if (!do_quiet
)
3386 printf("Entry %d logging count reset\n",
3389 errx(EX_DATAERR
, "invalid rule number ``%s''", *av
);
3392 if (failed
!= EX_OK
)
3399 int cmd
= do_pipe
? IP_DUMMYNET_FLUSH
: IP_FW_FLUSH
;
3401 if (!do_force
&& !do_quiet
) { /* need to ask user */
3404 printf("Are you sure? [yn] ");
3407 c
= toupper(getc(stdin
));
3408 while (c
!= '\n' && getc(stdin
) != '\n')
3410 return; /* and do not flush */
3411 } while (c
!= 'Y' && c
!= 'N');
3413 if (c
== 'N') /* user said no */
3416 if (setsockopt(s
, IPPROTO_IP
, cmd
, NULL
, 0) < 0)
3417 err(EX_UNAVAILABLE
, "setsockopt(IP_%s_FLUSH)",
3418 do_pipe
? "DUMMYNET" : "FW");
3420 printf("Flushed all %s.\n", do_pipe
? "pipes" : "rules");
3424 table_create(int ac
, char **av
)
3426 struct ipfw_ioc_table tbl
;
3433 errx(EX_DATAERR
, "missing table id");
3435 memset(&tbl
, 0, sizeof(tbl
));
3436 tbl
.tableid
= strtoul(*av
, &eptr
, 0);
3438 errx(EX_DATAERR
, "invalid table id %s", *av
);
3439 if (setsockopt(s
, IPPROTO_IP
, IP_FW_TBL_CREATE
, &tbl
, sizeof(tbl
)) < 0)
3440 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_TBL_CREATE)");
3442 printf("Created table %d\n", tbl
.tableid
);
3446 table_flush(int ac
, char **av
, int opt
)
3448 struct ipfw_ioc_table tbl
;
3454 memset(&tbl
, 0, sizeof(tbl
));
3457 if (opt
== IP_FW_TBL_FLUSH
) {
3458 /* Flush all tables */
3462 errx(EX_DATAERR
, "missing table id");
3465 tbl
.tableid
= strtoul(*av
, &eptr
, 0);
3467 errx(EX_DATAERR
, "invalid table id %s", *av
);
3470 if (!do_force
&& !do_quiet
) { /* need to ask user */
3473 printf("Are you sure? [yn] ");
3476 c
= toupper(getc(stdin
));
3477 while (c
!= '\n' && getc(stdin
) != '\n')
3479 return; /* and do not flush */
3480 } while (c
!= 'Y' && c
!= 'N');
3482 if (c
== 'N') /* user said no */
3486 if (setsockopt(s
, IPPROTO_IP
, opt
, &tbl
, sizeof(tbl
)) < 0) {
3487 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_TBL_%s)",
3488 opt
== IP_FW_TBL_FLUSH
? "FLUSH" : "DESTROY");
3491 if (tbl
.tableid
>= 0) {
3492 printf("%sed table %d\n",
3493 opt
== IP_FW_TBL_FLUSH
? "Flush" : "Destroy",
3496 printf("Flushed all tables\n");
3504 struct ipfw_ioc_tbllist
*list
;
3509 len
= sizeof(table_max
);
3510 if (sysctlbyname("net.inet.ip.fw.table_max", &table_max
, &len
,
3512 err(EX_UNAVAILABLE
, "sysctl net.inet.ip.fw.table_max failed");
3514 len1
= __offsetof(struct ipfw_ioc_tbllist
, tables
[table_max
]);
3515 list
= malloc(len1
);
3518 if (getsockopt(s
, IPPROTO_IP
, IP_FW_TBL_GET
, list
, &len1
) < 0)
3519 err(EX_UNAVAILABLE
, "getsockopt(IP_FW_TBL_GET)");
3521 for (i
= 0; i
< list
->tablecnt
; ++i
)
3522 printf("%u\n", list
->tables
[i
]);
3525 /* XXX copied from route(8) */
3527 inet_makenetandmask(in_addr_t net
, struct sockaddr_in
*in
,
3528 struct sockaddr_in
*in_mask
, int bits
)
3530 in_addr_t addr
, mask
= 0;
3534 * XXX: This approach unable to handle 0.0.0.1/32 correctly
3535 * as inet_network() converts 0.0.0.1 and 1 equally.
3538 addr
= net
<< IN_CLASSA_NSHIFT
;
3539 else if (net
<= 0xffff)
3540 addr
= net
<< IN_CLASSB_NSHIFT
;
3541 else if (net
<= 0xffffff)
3542 addr
= net
<< IN_CLASSC_NSHIFT
;
3547 mask
= 0xffffffff << (32 - bits
);
3550 else if (IN_CLASSA(addr
))
3551 mask
= IN_CLASSA_NET
;
3552 else if (IN_CLASSB(addr
))
3553 mask
= IN_CLASSB_NET
;
3554 else if (IN_CLASSC(addr
))
3555 mask
= IN_CLASSC_NET
;
3556 else if (IN_MULTICAST(addr
))
3557 mask
= IN_CLASSD_NET
;
3561 in
->sin_family
= AF_INET
;
3562 in
->sin_len
= sizeof(struct sockaddr_in
);
3563 in
->sin_addr
.s_addr
= htonl(addr
);
3565 if (mask
!= 0xffffffff) {
3566 in_mask
->sin_addr
.s_addr
= htonl(mask
);
3567 cp
= (char *)(&in_mask
->sin_addr
+ 1);
3568 while (*--cp
== 0 && cp
> (char *)in_mask
)
3570 in_mask
->sin_len
= 1 + cp
- (char *)in_mask
;
3575 table_alt(int ac
, char **av
, int opt
)
3577 struct ipfw_ioc_tblcont ent
;
3578 struct ipfw_ioc_tblent
*te
;
3584 errx(EX_DATAERR
, "missing table id");
3586 memset(&ent
, 0, sizeof(ent
));
3587 ent
.tableid
= strtoul(*av
, &eptr
, 0);
3591 errx(EX_DATAERR
, "invalid table id %s", *av
);
3596 errx(EX_DATAERR
, "missing addresses");
3601 q
= strchr(*av
, '/');
3607 val
= inet_network(*av
);
3609 if (val
== INADDR_NONE
) {
3611 errx(EX_DATAERR
, "invalid address %s", *av
);
3614 bits
= strtoul(q
+ 1, &eptr
, 0);
3615 if (*eptr
!= '\0') {
3617 errx(EX_DATAERR
, "invalid address %s", *av
);
3619 inet_makenetandmask(val
, &te
->key
, &te
->netmask
, bits
);
3623 n
= inet_pton(AF_INET
, *av
, &te
->key
.sin_addr
);
3626 errx(EX_DATAERR
, "invalid address %s", *av
);
3629 err(EX_UNAVAILABLE
, "inet_pton failed");
3631 te
->key
.sin_family
= AF_INET
;
3632 te
->key
.sin_len
= sizeof(struct sockaddr_in
);
3635 if (setsockopt(s
, IPPROTO_IP
, opt
, &ent
, sizeof(ent
)) < 0) {
3636 if (opt
== IP_FW_TBL_ADD
&& errno
== EEXIST
) {
3637 printf("Failed to add %s to table %d\n",
3639 } else if (opt
== IP_FW_TBL_DEL
&& errno
== ESRCH
) {
3640 printf("Failed to delete %s from table %d\n",
3644 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_TBL_%s)",
3645 opt
== IP_FW_TBL_ADD
? "ADD" : "DEL");
3647 } else if (!do_quiet
) {
3648 printf("%sed %s %s table %d\n",
3649 opt
== IP_FW_TBL_ADD
? "Add" : "Delet", *av
,
3650 opt
== IP_FW_TBL_ADD
? "to" : "from", ent
.tableid
);
3659 table_show(int ac
, char **av
)
3661 struct ipfw_ioc_tblcont
*cont
= NULL
;
3662 int tableid
, count
= 128, i
, uwidth
= 0, lwidth
= 0;
3668 errx(EX_DATAERR
, "missing table id");
3670 tableid
= strtoul(*av
, &eptr
, 0);
3672 errx(EX_DATAERR
, "invalid table id %s", *av
);
3677 len
= __offsetof(struct ipfw_ioc_tblcont
, ent
[count
]);
3678 cont
= reallocf(cont
, len
);
3679 cont
->tableid
= tableid
;
3681 if (getsockopt(s
, IPPROTO_IP
, IP_FW_TBL_GET
, cont
, &len
) < 0) {
3682 if (errno
== E2BIG
) {
3686 err(EX_UNAVAILABLE
, "getsockopt(IP_FW_TBL_GET)");
3690 if (cont
->entcnt
== 0)
3694 for (i
= 0; i
< cont
->entcnt
; ++i
) {
3697 width
= snprintf(NULL
, 0, "%ju",
3698 (uintmax_t)cont
->ent
[i
].use
);
3704 for (i
= 0; i
< cont
->entcnt
; ++i
) {
3705 const struct ipfw_ioc_tblent
*te
= &cont
->ent
[i
];
3706 char addr
[INET_ADDRSTRLEN
];
3709 printf("%*ju ", uwidth
, (uintmax_t)te
->use
);
3716 strcpy(timestr
, ctime(&t0
));
3717 *strchr(timestr
, '\n') = '\0';
3718 lwidth
= strlen(timestr
);
3720 if (te
->last_used
) {
3721 time_t t
= _long_to_time(te
->last_used
);
3723 strcpy(timestr
, ctime(&t
));
3724 *strchr(timestr
, '\n') = '\0';
3725 printf("%s ", timestr
);
3727 printf("%*s ", lwidth
, " ");
3731 if (te
->netmask
.sin_len
== 0) {
3732 printf("%s\n", inet_ntop(AF_INET
,
3733 &te
->key
.sin_addr
, addr
, sizeof(addr
)));
3735 struct sockaddr_in mask
;
3738 memset(&mask
, 0, sizeof(mask
));
3739 memcpy(&mask
, &te
->netmask
,
3740 te
->netmask
.sin_len
);
3741 b
= ffs(ntohl(te
->netmask
.sin_addr
.s_addr
));
3744 printf("%s/%d\n", inet_ntop(AF_INET
,
3745 &te
->key
.sin_addr
, addr
, sizeof(addr
)), b
);
3751 table_zero(int ac
, char **av
)
3753 struct ipfw_ioc_table tbl
;
3758 memset(&tbl
, 0, sizeof(tbl
));
3764 tbl
.tableid
= strtoul(*av
, &eptr
, 0);
3766 errx(EX_DATAERR
, "invalid table id %s", *av
);
3769 if (setsockopt(s
, IPPROTO_IP
, IP_FW_TBL_ZERO
, &tbl
, sizeof(tbl
)) < 0)
3770 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_TBL_ZERO)");
3772 printf("Accounting cleared\n");
3776 table_expire(int ac
, char **av
)
3778 struct ipfw_ioc_tblexp tbl
;
3785 memset(&tbl
, 0, sizeof(tbl
));
3787 errx(EX_DATAERR
, "missing expire time");
3788 } else if (ac
== 1) {
3791 tbl
.tableid
= strtoul(*av
, &eptr
, 0);
3793 errx(EX_DATAERR
, "invalid table id %s", *av
);
3798 tbl
.expire
= strtoul(*av
, &eptr
, 0);
3800 errx(EX_DATAERR
, "invalid expire timeout %s", *av
);
3802 if (!do_force
&& !do_quiet
) { /* need to ask user */
3805 printf("Are you sure? [yn] ");
3808 c
= toupper(getc(stdin
));
3809 while (c
!= '\n' && getc(stdin
) != '\n')
3811 return; /* and do not flush */
3812 } while (c
!= 'Y' && c
!= 'N');
3814 if (c
== 'N') /* user said no */
3819 if (getsockopt(s
, IPPROTO_IP
, IP_FW_TBL_EXPIRE
, &tbl
, &len
) < 0)
3820 err(EX_UNAVAILABLE
, "getsockopt(IP_FW_TBL_EXPIRE)");
3822 printf("Expired %d address%s\n", tbl
.expcnt
,
3823 (tbl
.expcnt
== 0 || tbl
.expcnt
> 1) ? "es" : "");
3828 ipfw_main(int ac
, char **av
)
3835 /* Set the force flag for non-interactive processes */
3836 do_force
= !isatty(STDIN_FILENO
);
3838 optind
= optreset
= 1;
3839 while ((ch
= getopt(ac
, av
, "hs:acdefNqStv")) != -1)
3841 case 'h': /* help */
3843 break; /* NOTREACHED */
3845 case 's': /* sort */
3846 do_sort
= atoi(optarg
);
3875 case 'v': /* verbose */
3884 NEED1("bad arguments, for usage summary ``ipfw''");
3887 * optional: pipe, queue or table
3889 if (!strncmp(*av
, "pipe", strlen(*av
))) {
3893 } else if (!strncmp(*av
, "queue", strlen(*av
))) {
3897 } else if (!strncmp(*av
, "table", strlen(*av
))) {
3902 NEED1("missing command");
3905 * for pipes, queues and table we normally say 'pipe NN config'
3906 * but the code is easier to parse as 'pipe config NN' so we
3907 * swap the two arguments.
3909 if ((do_pipe
> 0 || do_table
> 0) && ac
> 1 &&
3910 *av
[0] >= '0' && *av
[0] <= '9') {
3916 if (!strncmp(*av
, "create", strlen(*av
)))
3917 table_create(ac
, av
);
3918 else if (!strncmp(*av
, "destroy", strlen(*av
)))
3919 table_flush(ac
, av
, IP_FW_TBL_DESTROY
);
3920 else if (!strncmp(*av
, "list", strlen(*av
)))
3922 else if (!strncmp(*av
, "add", strlen(*av
)))
3923 table_alt(ac
, av
, IP_FW_TBL_ADD
);
3924 else if (!strncmp(*av
, "delete", strlen(*av
)))
3925 table_alt(ac
, av
, IP_FW_TBL_DEL
);
3926 else if (!strncmp(*av
, "flush", strlen(*av
)))
3927 table_flush(ac
, av
, IP_FW_TBL_FLUSH
);
3928 else if (!strncmp(*av
, "print", strlen(*av
)))
3930 else if (!strncmp(*av
, "show", strlen(*av
))) {
3933 } else if (!strncmp(*av
, "zero", strlen(*av
)))
3935 else if (!strncmp(*av
, "expire", strlen(*av
)))
3936 table_expire(ac
, av
);
3938 errx(EX_USAGE
, "bad command `%s'", *av
);
3941 if (!strncmp(*av
, "add", strlen(*av
)))
3943 else if (do_pipe
&& !strncmp(*av
, "config", strlen(*av
)))
3944 config_pipe(ac
, av
);
3945 else if (!strncmp(*av
, "delete", strlen(*av
)))
3947 else if (!strncmp(*av
, "flush", strlen(*av
)))
3949 else if (!strncmp(*av
, "zero", strlen(*av
)))
3951 else if (!strncmp(*av
, "resetlog", strlen(*av
)))
3953 else if (!strncmp(*av
, "print", strlen(*av
)) ||
3954 !strncmp(*av
, "list", strlen(*av
)))
3956 else if (!strncmp(*av
, "enable", strlen(*av
)))
3957 sysctl_handler(ac
, av
, 1);
3958 else if (!strncmp(*av
, "disable", strlen(*av
)))
3959 sysctl_handler(ac
, av
, 0);
3960 else if (!strncmp(*av
, "set", strlen(*av
)))
3961 sets_handler(ac
, av
);
3962 else if (!strncmp(*av
, "show", strlen(*av
))) {
3966 errx(EX_USAGE
, "bad command `%s'", *av
);
3972 ipfw_readfile(int ac
, char *av
[])
3975 #define WHITESP " \t\f\v\n\r"
3977 char *a
, *p
, *args
[MAX_ARGS
], *cmd
= NULL
;
3979 int i
=0, lineno
=0, qflag
=0, pflag
=0, status
;
3984 while ((c
= getopt(ac
, av
, "D:U:p:q")) != -1)
3988 errx(EX_USAGE
, "-D requires -p");
3989 if (i
> MAX_ARGS
- 2)
3991 "too many -D or -U options");
3992 args
[i
++] = __DECONST(char *, "-D");
3998 errx(EX_USAGE
, "-U requires -p");
3999 if (i
> MAX_ARGS
- 2)
4001 "too many -D or -U options");
4002 args
[i
++] = __DECONST(char *, "-U");
4018 errx(EX_USAGE
, "bad arguments, for usage"
4019 " summary ``ipfw''");
4025 errx(EX_USAGE
, "extraneous filename arguments");
4027 if ((f
= fopen(av
[0], "r")) == NULL
)
4028 err(EX_UNAVAILABLE
, "fopen: %s", av
[0]);
4031 /* pipe through preprocessor (cpp or m4) */
4036 if (pipe(pipedes
) == -1)
4037 err(EX_OSERR
, "cannot create pipe");
4039 switch((preproc
= fork())) {
4041 err(EX_OSERR
, "cannot fork");
4045 if (dup2(fileno(f
), 0) == -1
4046 || dup2(pipedes
[1], 1) == -1)
4047 err(EX_OSERR
, "dup2()");
4052 err(EX_OSERR
, "execvp(%s) failed", cmd
);
4058 if ((f
= fdopen(pipedes
[0], "r")) == NULL
) {
4059 int savederrno
= errno
;
4061 kill(preproc
, SIGTERM
);
4063 err(EX_OSERR
, "fdopen()");
4068 while (fgets(buf
, BUFSIZ
, f
)) {
4070 snprintf(linename
, sizeof(linename
), "Line %d", lineno
);
4075 if ((p
= strchr(buf
, '#')) != NULL
)
4079 args
[i
++] = __DECONST(char *, "-q");
4080 for (a
= strtok(buf
, WHITESP
);
4081 a
&& i
< MAX_ARGS
; a
= strtok(NULL
, WHITESP
), i
++)
4083 if (i
== (qflag
? 2: 1))
4086 errx(EX_USAGE
, "%s: too many arguments",
4094 if (waitpid(preproc
, &status
, 0) == -1)
4095 errx(EX_OSERR
, "waitpid()");
4096 if (WIFEXITED(status
) && WEXITSTATUS(status
) != EX_OK
)
4097 errx(EX_UNAVAILABLE
,
4098 "preprocessor exited with status %d",
4099 WEXITSTATUS(status
));
4100 else if (WIFSIGNALED(status
))
4101 errx(EX_UNAVAILABLE
,
4102 "preprocessor exited with signal %d",
4108 main(int ac
, char *av
[])
4110 s
= socket(AF_INET
, SOCK_RAW
, IPPROTO_RAW
);
4112 err(EX_UNAVAILABLE
, "socket");
4115 * If the last argument is an absolute pathname, interpret it
4116 * as a file to be preprocessed.
4119 if (ac
> 1 && av
[ac
- 1][0] == '/' && access(av
[ac
- 1], R_OK
) == 0)
4120 ipfw_readfile(ac
, av
);