]> git.saurik.com Git - apple/network_cmds.git/blame_incremental - ipfw.tproj/ipfw2.c
network_cmds-480.tar.gz
[apple/network_cmds.git] / ipfw.tproj / ipfw2.c
... / ...
CommitLineData
1/*
2 * Copyright (c) 2002-2009 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29/*
30 * Copyright (c) 2002-2003 Luigi Rizzo
31 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
32 * Copyright (c) 1994 Ugen J.S.Antsilevich
33 *
34 * Idea and grammar partially left from:
35 * Copyright (c) 1993 Daniel Boulet
36 *
37 * Redistribution and use in source forms, with and without modification,
38 * are permitted provided that this entire comment appears intact.
39 *
40 * Redistribution in binary form may occur without any restrictions.
41 * Obviously, it would be nice if you gave credit where credit is due
42 * but requiring it would be too onerous.
43 *
44 * This software is provided ``AS IS'' without any warranties of any kind.
45 *
46 * NEW command line interface for IP firewall facility
47 *
48 * $FreeBSD: /repoman/r/ncvs/src/sbin/ipfw/ipfw2.c,v 1.4.2.18 2003/09/15 10:27:03 luigi Exp $
49 */
50
51#include <sys/param.h>
52#include <sys/mbuf.h>
53#include <sys/socket.h>
54#include <sys/sockio.h>
55#include <sys/sysctl.h>
56#include <sys/time.h>
57#include <sys/wait.h>
58
59#include <ctype.h>
60#include <err.h>
61#include <errno.h>
62#include <grp.h>
63#include <limits.h>
64#include <netdb.h>
65#include <pwd.h>
66#include <signal.h>
67#include <stdio.h>
68#include <stdlib.h>
69#include <stdarg.h>
70#include <string.h>
71#include <unistd.h>
72#include <sysexits.h>
73
74#include <net/if.h>
75#include <netinet/in.h>
76#include <netinet/in_systm.h>
77#include <netinet/ip.h>
78#include <netinet/ip_icmp.h>
79#define IPFW2
80#include <netinet/ip_fw.h>
81#undef IPFW2
82#include <net/route.h> /* def. of struct route */
83#include <netinet/ip_dummynet.h>
84#include <netinet/tcp.h>
85#include <arpa/inet.h>
86
87int
88 do_resolv, /* Would try to resolve all */
89 do_time, /* Show time stamps */
90 do_quiet, /* Be quiet in add and flush */
91 do_pipe, /* this cmd refers to a pipe */
92 do_sort, /* field to sort results (0 = no) */
93 do_dynamic, /* display dynamic rules */
94 do_expired, /* display expired dynamic rules */
95 do_compact, /* show rules in compact mode */
96 show_sets, /* display rule sets */
97 test_only, /* only check syntax */
98 verbose;
99
100#define IP_MASK_ALL 0xffffffff
101
102/*
103 * _s_x is a structure that stores a string <-> token pairs, used in
104 * various places in the parser. Entries are stored in arrays,
105 * with an entry with s=NULL as terminator.
106 * The search routines are match_token() and match_value().
107 * Often, an element with x=0 contains an error string.
108 *
109 */
110struct _s_x {
111 char const *s;
112 int x;
113};
114
115static struct _s_x f_tcpflags[] = {
116 { "syn", TH_SYN },
117 { "fin", TH_FIN },
118 { "ack", TH_ACK },
119 { "psh", TH_PUSH },
120 { "rst", TH_RST },
121 { "urg", TH_URG },
122 { "tcp flag", 0 },
123 { NULL, 0 }
124};
125
126static struct _s_x f_tcpopts[] = {
127 { "mss", IP_FW_TCPOPT_MSS },
128 { "maxseg", IP_FW_TCPOPT_MSS },
129 { "window", IP_FW_TCPOPT_WINDOW },
130 { "sack", IP_FW_TCPOPT_SACK },
131 { "ts", IP_FW_TCPOPT_TS },
132 { "timestamp", IP_FW_TCPOPT_TS },
133 { "cc", IP_FW_TCPOPT_CC },
134 { "tcp option", 0 },
135 { NULL, 0 }
136};
137
138/*
139 * IP options span the range 0 to 255 so we need to remap them
140 * (though in fact only the low 5 bits are significant).
141 */
142static struct _s_x f_ipopts[] = {
143 { "ssrr", IP_FW_IPOPT_SSRR},
144 { "lsrr", IP_FW_IPOPT_LSRR},
145 { "rr", IP_FW_IPOPT_RR},
146 { "ts", IP_FW_IPOPT_TS},
147 { "ip option", 0 },
148 { NULL, 0 }
149};
150
151static struct _s_x f_iptos[] = {
152 { "lowdelay", IPTOS_LOWDELAY},
153 { "throughput", IPTOS_THROUGHPUT},
154 { "reliability", IPTOS_RELIABILITY},
155 { "mincost", IPTOS_MINCOST},
156 { "congestion", IPTOS_CE},
157 { "ecntransport", IPTOS_ECT},
158 { "ip tos option", 0},
159 { NULL, 0 }
160};
161
162static struct _s_x limit_masks[] = {
163 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
164 {"src-addr", DYN_SRC_ADDR},
165 {"src-port", DYN_SRC_PORT},
166 {"dst-addr", DYN_DST_ADDR},
167 {"dst-port", DYN_DST_PORT},
168 {NULL, 0}
169};
170
171/*
172 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
173 * This is only used in this code.
174 */
175#define IPPROTO_ETHERTYPE 0x1000
176static struct _s_x ether_types[] = {
177 /*
178 * Note, we cannot use "-:&/" in the names because they are field
179 * separators in the type specifications. Also, we use s = NULL as
180 * end-delimiter, because a type of 0 can be legal.
181 */
182 { "ip", 0x0800 },
183 { "ipv4", 0x0800 },
184 { "ipv6", 0x86dd },
185 { "arp", 0x0806 },
186 { "rarp", 0x8035 },
187 { "vlan", 0x8100 },
188 { "loop", 0x9000 },
189 { "trail", 0x1000 },
190 { "at", 0x809b },
191 { "atalk", 0x809b },
192 { "aarp", 0x80f3 },
193 { "pppoe_disc", 0x8863 },
194 { "pppoe_sess", 0x8864 },
195 { "ipx_8022", 0x00E0 },
196 { "ipx_8023", 0x0000 },
197 { "ipx_ii", 0x8137 },
198 { "ipx_snap", 0x8137 },
199 { "ipx", 0x8137 },
200 { "ns", 0x0600 },
201 { NULL, 0 }
202};
203
204static struct _s_x exception_types[] = {
205 { "to", 1},
206 { "dst", 2},
207 { "in", 3},
208 { "out", 4},
209 { "xmit", 5},
210 { "recv", 6},
211 { "via", 7},
212 { "src", 8},
213 { NULL, 0}
214};
215
216static void show_usage(void);
217
218enum tokens {
219 TOK_NULL=0,
220
221 TOK_OR,
222 TOK_NOT,
223 TOK_STARTBRACE,
224 TOK_ENDBRACE,
225
226 TOK_ACCEPT,
227 TOK_COUNT,
228 TOK_PIPE,
229 TOK_QUEUE,
230 TOK_DIVERT,
231 TOK_TEE,
232 TOK_FORWARD,
233 TOK_SKIPTO,
234 TOK_DENY,
235 TOK_REJECT,
236 TOK_RESET,
237 TOK_UNREACH,
238 TOK_CHECKSTATE,
239
240 TOK_UID,
241 TOK_GID,
242 TOK_IN,
243 TOK_LIMIT,
244 TOK_KEEPSTATE,
245 TOK_LAYER2,
246 TOK_OUT,
247 TOK_XMIT,
248 TOK_RECV,
249 TOK_VIA,
250 TOK_FRAG,
251 TOK_IPOPTS,
252 TOK_IPLEN,
253 TOK_IPID,
254 TOK_IPPRECEDENCE,
255 TOK_IPTOS,
256 TOK_IPTTL,
257 TOK_IPVER,
258 TOK_ESTAB,
259 TOK_SETUP,
260 TOK_TCPFLAGS,
261 TOK_TCPOPTS,
262 TOK_TCPSEQ,
263 TOK_TCPACK,
264 TOK_TCPWIN,
265 TOK_ICMPTYPES,
266 TOK_MAC,
267 TOK_MACTYPE,
268 TOK_VERREVPATH,
269 TOK_IPSEC,
270 TOK_COMMENT,
271
272 TOK_PLR,
273 TOK_NOERROR,
274 TOK_BUCKETS,
275 TOK_DSTIP,
276 TOK_SRCIP,
277 TOK_DSTPORT,
278 TOK_SRCPORT,
279 TOK_ALL,
280 TOK_MASK,
281 TOK_BW,
282 TOK_DELAY,
283 TOK_RED,
284 TOK_GRED,
285 TOK_DROPTAIL,
286 TOK_PROTO,
287 TOK_WEIGHT,
288};
289
290struct _s_x dummynet_params[] = {
291 { "plr", TOK_PLR },
292 { "noerror", TOK_NOERROR },
293 { "buckets", TOK_BUCKETS },
294 { "dst-ip", TOK_DSTIP },
295 { "src-ip", TOK_SRCIP },
296 { "dst-port", TOK_DSTPORT },
297 { "src-port", TOK_SRCPORT },
298 { "proto", TOK_PROTO },
299 { "weight", TOK_WEIGHT },
300 { "all", TOK_ALL },
301 { "mask", TOK_MASK },
302 { "droptail", TOK_DROPTAIL },
303 { "red", TOK_RED },
304 { "gred", TOK_GRED },
305 { "bw", TOK_BW },
306 { "bandwidth", TOK_BW },
307 { "delay", TOK_DELAY },
308 { "pipe", TOK_PIPE },
309 { "queue", TOK_QUEUE },
310 { "dummynet-params", TOK_NULL },
311 { NULL, 0 } /* terminator */
312};
313
314struct _s_x rule_actions[] = {
315 { "accept", TOK_ACCEPT },
316 { "pass", TOK_ACCEPT },
317 { "allow", TOK_ACCEPT },
318 { "permit", TOK_ACCEPT },
319 { "count", TOK_COUNT },
320 { "pipe", TOK_PIPE },
321 { "queue", TOK_QUEUE },
322 { "divert", TOK_DIVERT },
323 { "tee", TOK_TEE },
324 { "fwd", TOK_FORWARD },
325 { "forward", TOK_FORWARD },
326 { "skipto", TOK_SKIPTO },
327 { "deny", TOK_DENY },
328 { "drop", TOK_DENY },
329 { "reject", TOK_REJECT },
330 { "reset", TOK_RESET },
331 { "unreach", TOK_UNREACH },
332 { "check-state", TOK_CHECKSTATE },
333 { "//", TOK_COMMENT },
334 { NULL, 0 } /* terminator */
335};
336
337struct _s_x rule_options[] = {
338 { "uid", TOK_UID },
339 { "gid", TOK_GID },
340 { "in", TOK_IN },
341 { "limit", TOK_LIMIT },
342 { "keep-state", TOK_KEEPSTATE },
343 { "bridged", TOK_LAYER2 },
344 { "layer2", TOK_LAYER2 },
345 { "out", TOK_OUT },
346 { "xmit", TOK_XMIT },
347 { "recv", TOK_RECV },
348 { "via", TOK_VIA },
349 { "fragment", TOK_FRAG },
350 { "frag", TOK_FRAG },
351 { "ipoptions", TOK_IPOPTS },
352 { "ipopts", TOK_IPOPTS },
353 { "iplen", TOK_IPLEN },
354 { "ipid", TOK_IPID },
355 { "ipprecedence", TOK_IPPRECEDENCE },
356 { "iptos", TOK_IPTOS },
357 { "ipttl", TOK_IPTTL },
358 { "ipversion", TOK_IPVER },
359 { "ipver", TOK_IPVER },
360 { "estab", TOK_ESTAB },
361 { "established", TOK_ESTAB },
362 { "setup", TOK_SETUP },
363 { "tcpflags", TOK_TCPFLAGS },
364 { "tcpflgs", TOK_TCPFLAGS },
365 { "tcpoptions", TOK_TCPOPTS },
366 { "tcpopts", TOK_TCPOPTS },
367 { "tcpseq", TOK_TCPSEQ },
368 { "tcpack", TOK_TCPACK },
369 { "tcpwin", TOK_TCPWIN },
370 { "icmptype", TOK_ICMPTYPES },
371 { "icmptypes", TOK_ICMPTYPES },
372 { "dst-ip", TOK_DSTIP },
373 { "src-ip", TOK_SRCIP },
374 { "dst-port", TOK_DSTPORT },
375 { "src-port", TOK_SRCPORT },
376 { "proto", TOK_PROTO },
377 { "MAC", TOK_MAC },
378 { "mac", TOK_MAC },
379 { "mac-type", TOK_MACTYPE },
380 { "verrevpath", TOK_VERREVPATH },
381 { "ipsec", TOK_IPSEC },
382 { "//", TOK_COMMENT },
383
384 { "not", TOK_NOT }, /* pseudo option */
385 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
386 { "or", TOK_OR }, /* pseudo option */
387 { "|", /* escape */ TOK_OR }, /* pseudo option */
388 { "{", TOK_STARTBRACE }, /* pseudo option */
389 { "(", TOK_STARTBRACE }, /* pseudo option */
390 { "}", TOK_ENDBRACE }, /* pseudo option */
391 { ")", TOK_ENDBRACE }, /* pseudo option */
392 { NULL, 0 } /* terminator */
393};
394
395static __inline uint64_t
396align_uint64(uint64_t *pll) {
397 uint64_t ret;
398
399 bcopy (pll, &ret, sizeof(ret));
400 return ret;
401};
402
403/*
404 * conditionally runs the command.
405 */
406static int
407do_cmd(int optname, void *optval, uintptr_t optlen)
408{
409 static int s = -1; /* the socket */
410 int i;
411
412 if (test_only)
413 return 0;
414
415 if (s == -1)
416 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
417 if (s < 0)
418 err(EX_UNAVAILABLE, "socket");
419
420 switch (optname) {
421 case IP_FW_GET:
422 case IP_FW_FLUSH:
423 case IP_FW_ADD:
424 case IP_FW_DEL:
425 case IP_FW_ZERO:
426 case IP_FW_RESETLOG:
427 ((struct ip_fw *)optval)->version = IP_FW_CURRENT_API_VERSION;
428 default:
429 break;
430 }
431
432 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
433 optname == IP_FW_ADD)
434 i = getsockopt(s, IPPROTO_IP, optname, optval,
435 (socklen_t *)optlen);
436 else
437 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
438 return i;
439}
440
441/**
442 * match_token takes a table and a string, returns the value associated
443 * with the string (-1 in case of failure).
444 */
445static int
446match_token(struct _s_x *table, char *string)
447{
448 struct _s_x *pt;
449 uint i = strlen(string);
450
451 for (pt = table ; i && pt->s != NULL ; pt++)
452 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
453 return pt->x;
454 return -1;
455};
456
457/**
458 * match_value takes a table and a value, returns the string associated
459 * with the value (NULL in case of failure).
460 */
461static char const *
462match_value(struct _s_x *p, int value)
463{
464 for (; p->s != NULL; p++)
465 if (p->x == value)
466 return p->s;
467 return NULL;
468}
469
470/*
471 * prints one port, symbolic or numeric
472 */
473static void
474print_port(int proto, uint16_t port)
475{
476
477 if (proto == IPPROTO_ETHERTYPE) {
478 char const *s;
479
480 if (do_resolv && (s = match_value(ether_types, port)) )
481 printf("%s", s);
482 else
483 printf("0x%04x", port);
484 } else {
485 struct servent *se = NULL;
486 if (do_resolv) {
487 struct protoent *pe = getprotobynumber(proto);
488
489 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
490 }
491 if (se)
492 printf("%s", se->s_name);
493 else
494 printf("%d", port);
495 }
496}
497
498struct _s_x _port_name[] = {
499 {"dst-port", O_IP_DSTPORT},
500 {"src-port", O_IP_SRCPORT},
501 {"ipid", O_IPID},
502 {"iplen", O_IPLEN},
503 {"ipttl", O_IPTTL},
504 {"mac-type", O_MAC_TYPE},
505 {NULL, 0}
506};
507
508/*
509 * Print the values in a list 16-bit items of the types above.
510 * XXX todo: add support for mask.
511 */
512static void
513print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
514{
515 uint16_t *p = cmd->ports;
516 int i;
517 char const *sep;
518
519 if (cmd->o.len & F_NOT)
520 printf(" not");
521 if (opcode != 0) {
522 sep = match_value(_port_name, opcode);
523 if (sep == NULL)
524 sep = "???";
525 printf (" %s", sep);
526 }
527 sep = " ";
528 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
529 printf("%s", sep);
530 print_port(proto, p[0]);
531 if (p[0] != p[1]) {
532 printf("-");
533 print_port(proto, p[1]);
534 }
535 sep = ",";
536 }
537}
538
539/*
540 * Like strtol, but also translates service names into port numbers
541 * for some protocols.
542 * In particular:
543 * proto == -1 disables the protocol check;
544 * proto == IPPROTO_ETHERTYPE looks up an internal table
545 * proto == <some value in /etc/protocols> matches the values there.
546 * Returns *end == s in case the parameter is not found.
547 */
548static int
549strtoport(char *s, char **end, int base, int proto)
550{
551 char *p, *buf;
552 char *s1;
553 int i;
554
555 *end = s; /* default - not found */
556 if (*s == '\0')
557 return 0; /* not found */
558
559 if (isdigit(*s))
560 return strtol(s, end, base);
561
562 /*
563 * find separator. '\\' escapes the next char.
564 */
565 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
566 if (*s1 == '\\' && s1[1] != '\0')
567 s1++;
568
569 buf = malloc(s1 - s + 1);
570 if (buf == NULL)
571 return 0;
572
573 /*
574 * copy into a buffer skipping backslashes
575 */
576 for (p = s, i = 0; p != s1 ; p++)
577 if (*p != '\\')
578 buf[i++] = *p;
579 buf[i++] = '\0';
580
581 if ( match_token( exception_types, buf) != -1 ){
582 free(buf);
583 return 0;
584 }
585
586 if (proto == IPPROTO_ETHERTYPE) {
587 i = match_token(ether_types, buf);
588 free(buf);
589 if (i != -1) { /* found */
590 *end = s1;
591 return i;
592 }
593 } else {
594 struct protoent *pe = NULL;
595 struct servent *se;
596
597 if (proto != 0)
598 pe = getprotobynumber(proto);
599 setservent(1);
600 se = getservbyname(buf, pe ? pe->p_name : NULL);
601 free(buf);
602 if (se != NULL) {
603 *end = s1;
604 return ntohs(se->s_port);
605 }
606 }
607 return 0; /* not found */
608}
609
610/*
611 * Fill the body of the command with the list of port ranges.
612 */
613static int
614fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
615{
616 uint16_t a, b, *p = cmd->ports;
617 int i = 0;
618 char *s = av;
619
620 while (*s) {
621 a = strtoport(av, &s, 0, proto);
622 if (s == av) /* no parameter */
623 break;
624 if (*s == '-') { /* a range */
625 av = s+1;
626 b = strtoport(av, &s, 0, proto);
627 if (s == av) /* no parameter */
628 break;
629 p[0] = a;
630 p[1] = b;
631 } else if (*s == ',' || *s == '\0' )
632 p[0] = p[1] = a;
633 else /* invalid separator */
634 errx(EX_DATAERR, "invalid separator <%c> in <%s>",
635 *s, av);
636 i++;
637 p += 2;
638 av = s+1;
639 }
640 if (i > 0) {
641 if (i+1 > F_LEN_MASK)
642 errx(EX_DATAERR, "too many ports/ranges");
643 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
644 }
645 return i;
646}
647
648static struct _s_x icmpcodes[] = {
649 { "net", ICMP_UNREACH_NET },
650 { "host", ICMP_UNREACH_HOST },
651 { "protocol", ICMP_UNREACH_PROTOCOL },
652 { "port", ICMP_UNREACH_PORT },
653 { "needfrag", ICMP_UNREACH_NEEDFRAG },
654 { "srcfail", ICMP_UNREACH_SRCFAIL },
655 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
656 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
657 { "isolated", ICMP_UNREACH_ISOLATED },
658 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
659 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
660 { "tosnet", ICMP_UNREACH_TOSNET },
661 { "toshost", ICMP_UNREACH_TOSHOST },
662 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
663 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
664 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
665 { NULL, 0 }
666};
667
668static void
669fill_reject_code(u_short *codep, char *str)
670{
671 int val;
672 char *s;
673
674 val = strtoul(str, &s, 0);
675 if (s == str || *s != '\0' || val >= 0x100)
676 val = match_token(icmpcodes, str);
677 if (val < 0)
678 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
679 *codep = val;
680 return;
681}
682
683static void
684print_reject_code(uint16_t code)
685{
686 char const *s = match_value(icmpcodes, code);
687
688 if (s != NULL)
689 printf("unreach %s", s);
690 else
691 printf("unreach %u", code);
692}
693
694/*
695 * Returns the number of bits set (from left) in a contiguous bitmask,
696 * or -1 if the mask is not contiguous.
697 * XXX this needs a proper fix.
698 * This effectively works on masks in big-endian (network) format.
699 * when compiled on little endian architectures.
700 *
701 * First bit is bit 7 of the first byte -- note, for MAC addresses,
702 * the first bit on the wire is bit 0 of the first byte.
703 * len is the max length in bits.
704 */
705static int
706contigmask(uint8_t *p, int len)
707{
708 int i, n;
709
710 for (i=0; i<len ; i++)
711 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
712 break;
713 for (n=i+1; n < len; n++)
714 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
715 return -1; /* mask not contiguous */
716 return i;
717}
718
719/*
720 * print flags set/clear in the two bitmasks passed as parameters.
721 * There is a specialized check for f_tcpflags.
722 */
723static void
724print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
725{
726 char const *comma = "";
727 int i;
728 uint8_t set = cmd->arg1 & 0xff;
729 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
730
731 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
732 printf(" setup");
733 return;
734 }
735
736 printf(" %s ", name);
737 for (i=0; list[i].x != 0; i++) {
738 if (set & list[i].x) {
739 set &= ~list[i].x;
740 printf("%s%s", comma, list[i].s);
741 comma = ",";
742 }
743 if (clear & list[i].x) {
744 clear &= ~list[i].x;
745 printf("%s!%s", comma, list[i].s);
746 comma = ",";
747 }
748 }
749}
750
751/*
752 * Print the ip address contained in a command.
753 */
754static void
755print_ip(ipfw_insn_ip *cmd, char const *s)
756{
757 struct hostent *he = NULL;
758 int len = F_LEN((ipfw_insn *)cmd);
759 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
760
761 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
762
763 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
764 printf("me");
765 return;
766 }
767 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
768 uint32_t x, *map = (uint32_t *)&(cmd->mask);
769 int i, j;
770 char comma = '{';
771
772 x = cmd->o.arg1 - 1;
773 x = htonl( ~x );
774 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
775 printf("%s/%d", inet_ntoa(cmd->addr),
776 contigmask((uint8_t *)&x, 32));
777 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
778 x &= 0xff; /* base */
779 /*
780 * Print bits and ranges.
781 * Locate first bit set (i), then locate first bit unset (j).
782 * If we have 3+ consecutive bits set, then print them as a
783 * range, otherwise only print the initial bit and rescan.
784 */
785 for (i=0; i < cmd->o.arg1; i++)
786 if (map[i/32] & (1<<(i & 31))) {
787 for (j=i+1; j < cmd->o.arg1; j++)
788 if (!(map[ j/32] & (1<<(j & 31))))
789 break;
790 printf("%c%d", comma, i+x);
791 if (j>i+2) { /* range has at least 3 elements */
792 printf("-%d", j-1+x);
793 i = j-1;
794 }
795 comma = ',';
796 }
797 printf("}");
798 return;
799 }
800 /*
801 * len == 2 indicates a single IP, whereas lists of 1 or more
802 * addr/mask pairs have len = (2n+1). We convert len to n so we
803 * use that to count the number of entries.
804 */
805 for (len = len / 2; len > 0; len--, a += 2) {
806 int mb = /* mask length */
807 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
808 32 : contigmask((uint8_t *)&(a[1]), 32);
809 if (mb == 32 && do_resolv)
810 he = gethostbyaddr((char *)&(a[0]), sizeof(in_addr_t), AF_INET);
811 if (he != NULL) /* resolved to name */
812 printf("%s", he->h_name);
813 else if (mb == 0) /* any */
814 printf("any");
815 else { /* numeric IP followed by some kind of mask */
816 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
817 if (mb < 0)
818 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
819 else if (mb < 32)
820 printf("/%d", mb);
821 }
822 if (len > 1)
823 printf(",");
824 }
825}
826
827/*
828 * prints a MAC address/mask pair
829 */
830static void
831print_mac(uint8_t *addr, uint8_t *mask)
832{
833 int l = contigmask(mask, 48);
834
835 if (l == 0)
836 printf(" any");
837 else {
838 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
839 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
840 if (l == -1)
841 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
842 mask[0], mask[1], mask[2],
843 mask[3], mask[4], mask[5]);
844 else if (l < 48)
845 printf("/%d", l);
846 }
847}
848
849static void
850fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
851{
852 uint8_t type;
853
854 cmd->d[0] = 0;
855 while (*av) {
856 if (*av == ',')
857 av++;
858
859 type = strtoul(av, &av, 0);
860
861 if (*av != ',' && *av != '\0')
862 errx(EX_DATAERR, "invalid ICMP type");
863
864 if (type > 31)
865 errx(EX_DATAERR, "ICMP type out of range");
866
867 cmd->d[0] |= 1 << type;
868 }
869 cmd->o.opcode = O_ICMPTYPE;
870 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
871}
872
873static void
874print_icmptypes(ipfw_insn_u32 *cmd)
875{
876 int i;
877 char sep= ' ';
878
879 printf(" icmptypes");
880 for (i = 0; i < 32; i++) {
881 if ( (cmd->d[0] & (1 << (i))) == 0)
882 continue;
883 printf("%c%d", sep, i);
884 sep = ',';
885 }
886}
887
888/*
889 * show_ipfw() prints the body of an ipfw rule.
890 * Because the standard rule has at least proto src_ip dst_ip, we use
891 * a helper function to produce these entries if not provided explicitly.
892 * The first argument is the list of fields we have, the second is
893 * the list of fields we want to be printed.
894 *
895 * Special cases if we have provided a MAC header:
896 * + if the rule does not contain IP addresses/ports, do not print them;
897 * + if the rule does not contain an IP proto, print "all" instead of "ip";
898 *
899 * Once we have 'have_options', IP header fields are printed as options.
900 */
901#define HAVE_PROTO 0x0001
902#define HAVE_SRCIP 0x0002
903#define HAVE_DSTIP 0x0004
904#define HAVE_MAC 0x0008
905#define HAVE_MACTYPE 0x0010
906#define HAVE_OPTIONS 0x8000
907
908#define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
909static void
910show_prerequisites(int *flags, int want, int cmd)
911{
912 if ( (*flags & HAVE_IP) == HAVE_IP)
913 *flags |= HAVE_OPTIONS;
914
915 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC &&
916 cmd != O_MAC_TYPE) {
917 /*
918 * mac-type was optimized out by the compiler,
919 * restore it
920 */
921 printf(" any");
922 *flags |= HAVE_MACTYPE | HAVE_OPTIONS;
923 return;
924 }
925 if ( !(*flags & HAVE_OPTIONS)) {
926 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
927 printf(" ip");
928 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
929 printf(" from any");
930 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
931 printf(" to any");
932 }
933 *flags |= want;
934}
935
936static void
937show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
938{
939 static int twidth = 0;
940 int l;
941 ipfw_insn *cmd;
942 char *comment = NULL; /* ptr to comment if we have one */
943 int proto = 0; /* default */
944 int flags = 0; /* prerequisites */
945 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
946 int or_block = 0; /* we are in an or block */
947 uint32_t set_disable;
948
949 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
950
951 if (set_disable & (1 << rule->set)) { /* disabled */
952 if (!show_sets)
953 return;
954 else
955 printf("# DISABLED ");
956 }
957 printf("%05u ", rule->rulenum);
958
959 if (pcwidth>0 || bcwidth>0)
960 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
961 bcwidth, align_uint64(&rule->bcnt));
962
963 if (do_time == 2)
964 printf("%10u ", rule->timestamp);
965 else if (do_time == 1) {
966 char timestr[30];
967 time_t t = (time_t)0;
968
969 if (twidth == 0) {
970 strlcpy(timestr, ctime(&t), sizeof(timestr));
971 *strchr(timestr, '\n') = '\0';
972 twidth = strlen(timestr);
973 }
974 if (rule->timestamp) {
975#if _FreeBSD_version < 500000 /* XXX check */
976#define _long_to_time(x) (time_t)(x)
977#endif
978 t = _long_to_time(rule->timestamp);
979
980 strlcpy(timestr, ctime(&t), sizeof(timestr));
981 *strchr(timestr, '\n') = '\0';
982 printf("%s ", timestr);
983 } else {
984 printf("%*s", twidth, " ");
985 }
986 }
987
988 if (show_sets)
989 printf("set %d ", rule->set);
990
991 /*
992 * print the optional "match probability"
993 */
994 if (rule->cmd_len > 0) {
995 cmd = rule->cmd ;
996 if (cmd->opcode == O_PROB) {
997 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
998 double d = 1.0 * p->d[0];
999
1000 d = (d / 0x7fffffff);
1001 printf("prob %f ", d);
1002 }
1003 }
1004
1005 /*
1006 * first print actions
1007 */
1008 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1009 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1010 switch(cmd->opcode) {
1011 case O_CHECK_STATE:
1012 printf("check-state");
1013 flags = HAVE_IP; /* avoid printing anything else */
1014 break;
1015
1016 case O_ACCEPT:
1017 printf("allow");
1018 break;
1019
1020 case O_COUNT:
1021 printf("count");
1022 break;
1023
1024 case O_DENY:
1025 printf("deny");
1026 break;
1027
1028 case O_REJECT:
1029 if (cmd->arg1 == ICMP_REJECT_RST)
1030 printf("reset");
1031 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1032 printf("reject");
1033 else
1034 print_reject_code(cmd->arg1);
1035 break;
1036
1037 case O_SKIPTO:
1038 printf("skipto %u", cmd->arg1);
1039 break;
1040
1041 case O_PIPE:
1042 printf("pipe %u", cmd->arg1);
1043 break;
1044
1045 case O_QUEUE:
1046 printf("queue %u", cmd->arg1);
1047 break;
1048
1049 case O_DIVERT:
1050 printf("divert %u", cmd->arg1);
1051 break;
1052
1053 case O_TEE:
1054 printf("tee %u", cmd->arg1);
1055 break;
1056
1057 case O_FORWARD_IP:
1058 {
1059 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1060
1061 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1062 if (s->sa.sin_port)
1063 printf(",%d", s->sa.sin_port);
1064 }
1065 break;
1066
1067 case O_LOG: /* O_LOG is printed last */
1068 logptr = (ipfw_insn_log *)cmd;
1069 break;
1070
1071 default:
1072 printf("** unrecognized action %d len %d",
1073 cmd->opcode, cmd->len);
1074 }
1075 }
1076 if (logptr) {
1077 if (logptr->max_log > 0)
1078 printf(" log logamount %d", logptr->max_log);
1079 else
1080 printf(" log");
1081 }
1082
1083 /*
1084 * then print the body.
1085 */
1086 if (rule->_pad & 1) { /* empty rules before options */
1087 if (!do_compact)
1088 printf(" ip from any to any");
1089 flags |= HAVE_IP | HAVE_OPTIONS;
1090 }
1091
1092 for (l = rule->act_ofs, cmd = rule->cmd ;
1093 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1094 /* useful alias */
1095 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1096
1097 show_prerequisites(&flags, 0, cmd->opcode);
1098
1099 switch(cmd->opcode) {
1100 case O_PROB:
1101 break; /* done already */
1102
1103 case O_PROBE_STATE:
1104 break; /* no need to print anything here */
1105
1106 case O_MACADDR2: {
1107 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1108
1109 if ((cmd->len & F_OR) && !or_block)
1110 printf(" {");
1111 if (cmd->len & F_NOT)
1112 printf(" not");
1113 printf(" MAC");
1114 flags |= HAVE_MAC;
1115 print_mac(m->addr, m->mask);
1116 print_mac(m->addr + 6, m->mask + 6);
1117 }
1118 break;
1119
1120 case O_MAC_TYPE:
1121 if ((cmd->len & F_OR) && !or_block)
1122 printf(" {");
1123 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE,
1124 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1125 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS;
1126 break;
1127
1128 case O_IP_SRC:
1129 case O_IP_SRC_MASK:
1130 case O_IP_SRC_ME:
1131 case O_IP_SRC_SET:
1132 show_prerequisites(&flags, HAVE_PROTO, 0);
1133 if (!(flags & HAVE_SRCIP))
1134 printf(" from");
1135 if ((cmd->len & F_OR) && !or_block)
1136 printf(" {");
1137 print_ip((ipfw_insn_ip *)cmd,
1138 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1139 flags |= HAVE_SRCIP;
1140 break;
1141
1142 case O_IP_DST:
1143 case O_IP_DST_MASK:
1144 case O_IP_DST_ME:
1145 case O_IP_DST_SET:
1146 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1147 if (!(flags & HAVE_DSTIP))
1148 printf(" to");
1149 if ((cmd->len & F_OR) && !or_block)
1150 printf(" {");
1151 print_ip((ipfw_insn_ip *)cmd,
1152 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1153 flags |= HAVE_DSTIP;
1154 break;
1155
1156 case O_IP_DSTPORT:
1157 show_prerequisites(&flags, HAVE_IP, 0);
1158 case O_IP_SRCPORT:
1159 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1160 if ((cmd->len & F_OR) && !or_block)
1161 printf(" {");
1162 print_newports((ipfw_insn_u16 *)cmd, proto,
1163 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1164 break;
1165
1166 case O_PROTO: {
1167 struct protoent *pe;
1168
1169 if ((cmd->len & F_OR) && !or_block)
1170 printf(" {");
1171 if (cmd->len & F_NOT)
1172 printf(" not");
1173 proto = cmd->arg1;
1174 pe = getprotobynumber(cmd->arg1);
1175 if (flags & HAVE_OPTIONS)
1176 printf(" proto");
1177 if (pe)
1178 printf(" %s", pe->p_name);
1179 else
1180 printf(" %u", cmd->arg1);
1181 }
1182 flags |= HAVE_PROTO;
1183 break;
1184
1185 default: /*options ... */
1186 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1187 if ((cmd->len & F_OR) && !or_block)
1188 printf(" {");
1189 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1190 printf(" not");
1191 switch(cmd->opcode) {
1192 case O_FRAG:
1193 printf(" frag");
1194 break;
1195
1196 case O_IN:
1197 printf(cmd->len & F_NOT ? " out" : " in");
1198 break;
1199
1200 case O_LAYER2:
1201 printf(" layer2");
1202 break;
1203 case O_XMIT:
1204 case O_RECV:
1205 case O_VIA: {
1206 char const *s;
1207 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1208
1209 if (cmd->opcode == O_XMIT)
1210 s = "xmit";
1211 else if (cmd->opcode == O_RECV)
1212 s = "recv";
1213 else /* if (cmd->opcode == O_VIA) */
1214 s = "via";
1215 if (cmdif->name[0] == '\0')
1216 printf(" %s %s", s,
1217 inet_ntoa(cmdif->p.ip));
1218 else if (cmdif->p.unit == -1)
1219 printf(" %s %s*", s, cmdif->name);
1220 else
1221 printf(" %s %s%d", s, cmdif->name,
1222 cmdif->p.unit);
1223 }
1224 break;
1225
1226 case O_IPID:
1227 if (F_LEN(cmd) == 1)
1228 printf(" ipid %u", cmd->arg1 );
1229 else
1230 print_newports((ipfw_insn_u16 *)cmd, 0,
1231 O_IPID);
1232 break;
1233
1234 case O_IPTTL:
1235 if (F_LEN(cmd) == 1)
1236 printf(" ipttl %u", cmd->arg1 );
1237 else
1238 print_newports((ipfw_insn_u16 *)cmd, 0,
1239 O_IPTTL);
1240 break;
1241
1242 case O_IPVER:
1243 printf(" ipver %u", cmd->arg1 );
1244 break;
1245
1246 case O_IPPRECEDENCE:
1247 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1248 break;
1249
1250 case O_IPLEN:
1251 if (F_LEN(cmd) == 1)
1252 printf(" iplen %u", cmd->arg1 );
1253 else
1254 print_newports((ipfw_insn_u16 *)cmd, 0,
1255 O_IPLEN);
1256 break;
1257
1258 case O_IPOPT:
1259 print_flags("ipoptions", cmd, f_ipopts);
1260 break;
1261
1262 case O_IPTOS:
1263 print_flags("iptos", cmd, f_iptos);
1264 break;
1265
1266 case O_ICMPTYPE:
1267 print_icmptypes((ipfw_insn_u32 *)cmd);
1268 break;
1269
1270 case O_ESTAB:
1271 printf(" established");
1272 break;
1273
1274 case O_TCPFLAGS:
1275 print_flags("tcpflags", cmd, f_tcpflags);
1276 break;
1277
1278 case O_TCPOPTS:
1279 print_flags("tcpoptions", cmd, f_tcpopts);
1280 break;
1281
1282 case O_TCPWIN:
1283 printf(" tcpwin %d", ntohs(cmd->arg1));
1284 break;
1285
1286 case O_TCPACK:
1287 printf(" tcpack %d", ntohl(cmd32->d[0]));
1288 break;
1289
1290 case O_TCPSEQ:
1291 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1292 break;
1293
1294 case O_UID:
1295 {
1296 struct passwd *pwd = getpwuid(cmd32->d[0]);
1297
1298 if (pwd)
1299 printf(" uid %s", pwd->pw_name);
1300 else
1301 printf(" uid %u", cmd32->d[0]);
1302 }
1303 break;
1304
1305 case O_GID:
1306 {
1307 struct group *grp = getgrgid(cmd32->d[0]);
1308
1309 if (grp)
1310 printf(" gid %s", grp->gr_name);
1311 else
1312 printf(" gid %u", cmd32->d[0]);
1313 }
1314 break;
1315
1316 case O_VERREVPATH:
1317 printf(" verrevpath");
1318 break;
1319
1320 case O_IPSEC:
1321 printf(" ipsec");
1322 break;
1323
1324 case O_NOP:
1325 comment = (char *)(cmd + 1);
1326 break;
1327
1328 case O_KEEP_STATE:
1329 printf(" keep-state");
1330 break;
1331
1332 case O_LIMIT:
1333 {
1334 struct _s_x *p = limit_masks;
1335 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1336 uint8_t x = c->limit_mask;
1337 char const *comma = " ";
1338
1339 printf(" limit");
1340 for (; p->x != 0 ; p++)
1341 if ((x & p->x) == p->x) {
1342 x &= ~p->x;
1343 printf("%s%s", comma, p->s);
1344 comma = ",";
1345 }
1346 printf(" %d", c->conn_limit);
1347 }
1348 break;
1349
1350 default:
1351 printf(" [opcode %d len %d]",
1352 cmd->opcode, cmd->len);
1353 }
1354 }
1355 if (cmd->len & F_OR) {
1356 printf(" or");
1357 or_block = 1;
1358 } else if (or_block) {
1359 printf(" }");
1360 or_block = 0;
1361 }
1362 }
1363 show_prerequisites(&flags, HAVE_IP, 0);
1364 if (comment)
1365 printf(" // %s", comment);
1366 printf("\n");
1367}
1368
1369static void
1370show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1371{
1372 struct protoent *pe;
1373 struct in_addr a;
1374 uint16_t rulenum;
1375
1376 if (!do_expired) {
1377 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1378 return;
1379 }
1380 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1381 printf("%05d", rulenum);
1382 if (pcwidth>0 || bcwidth>0)
1383 printf(" %*llu %*llu (%ds)", pcwidth,
1384 align_uint64(&d->pcnt), bcwidth,
1385 align_uint64(&d->bcnt), d->expire);
1386 switch (d->dyn_type) {
1387 case O_LIMIT_PARENT:
1388 printf(" PARENT %d", d->count);
1389 break;
1390 case O_LIMIT:
1391 printf(" LIMIT");
1392 break;
1393 case O_KEEP_STATE: /* bidir, no mask */
1394 printf(" STATE");
1395 break;
1396 }
1397
1398 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1399 printf(" %s", pe->p_name);
1400 else
1401 printf(" proto %u", d->id.proto);
1402
1403 a.s_addr = htonl(d->id.src_ip);
1404 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1405
1406 a.s_addr = htonl(d->id.dst_ip);
1407 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1408 printf("\n");
1409}
1410
1411static int
1412sort_q(const void *pa, const void *pb)
1413{
1414 int rev = (do_sort < 0);
1415 int field = rev ? -do_sort : do_sort;
1416 long long res = 0;
1417 const struct dn_flow_queue *a = pa;
1418 const struct dn_flow_queue *b = pb;
1419
1420 switch (field) {
1421 case 1: /* pkts */
1422 res = a->len - b->len;
1423 break;
1424 case 2: /* bytes */
1425 res = a->len_bytes - b->len_bytes;
1426 break;
1427
1428 case 3: /* tot pkts */
1429 res = a->tot_pkts - b->tot_pkts;
1430 break;
1431
1432 case 4: /* tot bytes */
1433 res = a->tot_bytes - b->tot_bytes;
1434 break;
1435 }
1436 if (res < 0)
1437 res = -1;
1438 if (res > 0)
1439 res = 1;
1440 return (int)(rev ? res : -res);
1441}
1442
1443static void
1444list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
1445{
1446 int l;
1447
1448 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1449 fs->flow_mask.proto,
1450 fs->flow_mask.src_ip, fs->flow_mask.src_port,
1451 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
1452 if (fs->rq_elements == 0)
1453 return;
1454
1455 printf("BKT Prot ___Source IP/port____ "
1456 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1457 if (do_sort != 0)
1458 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
1459 for (l = 0; l < fs->rq_elements; l++) {
1460 struct in_addr ina;
1461 struct protoent *pe;
1462
1463 ina.s_addr = htonl(q[l].id.src_ip);
1464 printf("%3d ", q[l].hash_slot);
1465 pe = getprotobynumber(q[l].id.proto);
1466 if (pe)
1467 printf("%-4s ", pe->p_name);
1468 else
1469 printf("%4u ", q[l].id.proto);
1470 printf("%15s/%-5d ",
1471 inet_ntoa(ina), q[l].id.src_port);
1472 ina.s_addr = htonl(q[l].id.dst_ip);
1473 printf("%15s/%-5d ",
1474 inet_ntoa(ina), q[l].id.dst_port);
1475 printf("%4qu %8qu %2u %4u %3u\n",
1476 q[l].tot_pkts, q[l].tot_bytes,
1477 q[l].len, q[l].len_bytes, q[l].drops);
1478 if (verbose)
1479 printf(" S %20qd F %20qd\n",
1480 q[l].S, q[l].F);
1481 }
1482}
1483
1484static void
1485print_flowset_parms(struct dn_flow_set *fs, char *prefix)
1486{
1487 int l;
1488 char qs[30];
1489 char plr[30];
1490 char red[90]; /* Display RED parameters */
1491
1492 l = fs->qsize;
1493 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1494 if (l >= 8192)
1495 snprintf(qs, sizeof(qs), "%d KB", l / 1024);
1496 else
1497 snprintf(qs, sizeof(qs), "%d B", l);
1498 } else
1499 snprintf(qs, sizeof(qs), "%3d sl.", l);
1500 if (fs->plr)
1501 snprintf(plr, sizeof(plr), "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
1502 else
1503 plr[0] = '\0';
1504 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
1505 snprintf(red, sizeof(red),
1506 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
1507 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
1508 1.0 * fs->w_q / (double)(1 << SCALE_RED),
1509 SCALE_VAL(fs->min_th),
1510 SCALE_VAL(fs->max_th),
1511 1.0 * fs->max_p / (double)(1 << SCALE_RED));
1512 else
1513 snprintf(red, sizeof(red), "droptail");
1514
1515 printf("%s %s%s %d queues (%d buckets) %s\n",
1516 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
1517}
1518
1519static void
1520list_pipes(void *data, uint nbytes, int ac, char *av[])
1521{
1522 int rulenum;
1523 void *next = data;
1524 struct dn_pipe *p = (struct dn_pipe *) data;
1525 struct dn_flow_set *fs;
1526 struct dn_flow_queue *q;
1527 int l;
1528
1529 if (ac > 0)
1530 rulenum = strtoul(*av++, NULL, 10);
1531 else
1532 rulenum = 0;
1533 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
1534 double b = p->bandwidth;
1535 char buf[30];
1536 char prefix[80];
1537
1538 if (p->next.sle_next != (struct dn_pipe *)DN_IS_PIPE)
1539 break; /* done with pipes, now queues */
1540
1541 /*
1542 * compute length, as pipe have variable size
1543 */
1544 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
1545 next = (char *)p + l;
1546 nbytes -= l;
1547
1548 if (rulenum != 0 && rulenum != p->pipe_nr)
1549 continue;
1550
1551 /*
1552 * Print rate (or clocking interface)
1553 */
1554 if (p->if_name[0] != '\0')
1555 snprintf(buf, sizeof(buf), "%s", p->if_name);
1556 else if (b == 0)
1557 snprintf(buf, sizeof(buf), "unlimited");
1558 else if (b >= 1000000)
1559 snprintf(buf, sizeof(buf), "%7.3f Mbit/s", b/1000000);
1560 else if (b >= 1000)
1561 snprintf(buf, sizeof(buf), "%7.3f Kbit/s", b/1000);
1562 else
1563 snprintf(buf, sizeof(buf), "%7.3f bit/s ", b);
1564
1565 snprintf(prefix, sizeof(prefix), "%05d: %s %4d ms ",
1566 p->pipe_nr, buf, p->delay);
1567 print_flowset_parms(&(p->fs), prefix);
1568 if (verbose)
1569 printf(" V %20qd\n", p->V >> MY_M);
1570
1571 q = (struct dn_flow_queue *)(p+1);
1572 list_queues(&(p->fs), q);
1573 }
1574 for (fs = next; nbytes >= sizeof *fs; fs = next) {
1575 char prefix[80];
1576
1577 if (fs->next.sle_next != (struct dn_flow_set *)DN_IS_QUEUE)
1578 break;
1579 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
1580 next = (char *)fs + l;
1581 nbytes -= l;
1582 q = (struct dn_flow_queue *)(fs+1);
1583 snprintf(prefix, sizeof(prefix), "q%05d: weight %d pipe %d ",
1584 fs->fs_nr, fs->weight, fs->parent_nr);
1585 print_flowset_parms(fs, prefix);
1586 list_queues(fs, q);
1587 }
1588}
1589
1590/*
1591 * This one handles all set-related commands
1592 * ipfw set { show | enable | disable }
1593 * ipfw set swap X Y
1594 * ipfw set move X to Y
1595 * ipfw set move rule X to Y
1596 */
1597static void
1598sets_handler(int ac, char *av[])
1599{
1600 uint32_t set_disable, masks[2];
1601 int i, nbytes;
1602 uint16_t rulenum;
1603 uint8_t cmd, new_set;
1604
1605 ac--;
1606 av++;
1607
1608 if (!ac)
1609 errx(EX_USAGE, "set needs command");
1610 if (!strncmp(*av, "show", strlen(*av)) ) {
1611 void *data;
1612 char const *msg;
1613
1614 nbytes = sizeof(struct ip_fw);
1615 if ((data = calloc(1, nbytes)) == NULL)
1616 err(EX_OSERR, "calloc");
1617
1618 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1619 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1620 bcopy(&((struct ip_fw *)data)->next_rule,
1621 &set_disable, sizeof(set_disable));
1622
1623 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1624 if ((set_disable & (1<<i))) {
1625 printf("%s %d", msg, i);
1626 msg = "";
1627 }
1628 msg = (set_disable) ? " enable" : "enable";
1629 for (i = 0; i < RESVD_SET; i++)
1630 if (!(set_disable & (1<<i))) {
1631 printf("%s %d", msg, i);
1632 msg = "";
1633 }
1634 printf("\n");
1635 } else if (!strncmp(*av, "swap", strlen(*av))) {
1636 struct ip_fw rule;
1637 ac--; av++;
1638 if (ac != 2)
1639 errx(EX_USAGE, "set swap needs 2 set numbers");
1640 rulenum = atoi(av[0]);
1641 new_set = atoi(av[1]);
1642 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1643 errx(EX_DATAERR, "invalid set number %s", av[0]);
1644 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1645 errx(EX_DATAERR, "invalid set number %s", av[1]);
1646 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1647
1648 bzero(&rule, sizeof(rule));
1649 rule.set_masks[0] = masks[0];
1650
1651 i = do_cmd(IP_FW_DEL, &rule, sizeof(rule));
1652 } else if (!strncmp(*av, "move", strlen(*av))) {
1653 struct ip_fw rule;
1654 ac--; av++;
1655 if (ac && !strncmp(*av, "rule", strlen(*av))) {
1656 cmd = 2;
1657 ac--; av++;
1658 } else
1659 cmd = 3;
1660 if (ac != 3 || strncmp(av[1], "to", strlen(*av)))
1661 errx(EX_USAGE, "syntax: set move [rule] X to Y");
1662 rulenum = atoi(av[0]);
1663 new_set = atoi(av[2]);
1664 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1665 (cmd == 2 && rulenum == 65535) )
1666 errx(EX_DATAERR, "invalid source number %s", av[0]);
1667 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1668 errx(EX_DATAERR, "invalid dest. set %s", av[1]);
1669 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1670
1671 bzero(&rule, sizeof(rule));
1672 rule.set_masks[0] = masks[0];
1673
1674 i = do_cmd(IP_FW_DEL, &rule, sizeof(rule));
1675 } else if (!strncmp(*av, "disable", strlen(*av)) ||
1676 !strncmp(*av, "enable", strlen(*av)) ) {
1677 int which = !strncmp(*av, "enable", strlen(*av)) ? 1 : 0;
1678 struct ip_fw rule;
1679
1680 ac--; av++;
1681 masks[0] = masks[1] = 0;
1682
1683 while (ac) {
1684 if (isdigit(**av)) {
1685 i = atoi(*av);
1686 if (i < 0 || i > RESVD_SET)
1687 errx(EX_DATAERR,
1688 "invalid set number %d", i);
1689 masks[which] |= (1<<i);
1690 } else if (!strncmp(*av, "disable", strlen(*av)))
1691 which = 0;
1692 else if (!strncmp(*av, "enable", strlen(*av)))
1693 which = 1;
1694 else
1695 errx(EX_DATAERR,
1696 "invalid set command %s", *av);
1697 av++; ac--;
1698 }
1699 if ( (masks[0] & masks[1]) != 0 )
1700 errx(EX_DATAERR,
1701 "cannot enable and disable the same set");
1702
1703 bzero(&rule, sizeof(rule));
1704 rule.set_masks[0] = masks[0];
1705 rule.set_masks[1] = masks[1];
1706
1707 i = do_cmd(IP_FW_DEL, &rule, sizeof(rule));
1708 if (i)
1709 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1710 } else
1711 errx(EX_USAGE, "invalid set command %s", *av);
1712}
1713
1714static void
1715sysctl_handler(int ac, char *av[], int which)
1716{
1717 ac--;
1718 av++;
1719
1720 if (ac == 0) {
1721 warnx("missing keyword to enable/disable");
1722 } else if (strncmp(*av, "firewall", strlen(*av)) == 0) {
1723 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1724 &which, sizeof(which));
1725 } else if (strncmp(*av, "one_pass", strlen(*av)) == 0) {
1726 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1727 &which, sizeof(which));
1728 } else if (strncmp(*av, "debug", strlen(*av)) == 0) {
1729 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1730 &which, sizeof(which));
1731 } else if (strncmp(*av, "verbose", strlen(*av)) == 0) {
1732 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1733 &which, sizeof(which));
1734 } else if (strncmp(*av, "dyn_keepalive", strlen(*av)) == 0) {
1735 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1736 &which, sizeof(which));
1737 } else {
1738 warnx("unrecognize enable/disable keyword: %s", *av);
1739 }
1740}
1741
1742static void
1743list(int ac, char *av[], int show_counters)
1744{
1745 struct ip_fw *r;
1746 ipfw_dyn_rule *dynrules, *d;
1747
1748#define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1749 char *lim;
1750 void *data = NULL;
1751 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1752 int exitval = EX_OK;
1753 int lac;
1754 char **lav;
1755 u_long rnum, last;
1756 char *endptr;
1757 int seen = 0;
1758
1759 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1760 int nalloc = 1024; /* start somewhere... */
1761
1762 if (test_only) {
1763 fprintf(stderr, "Testing only, list disabled\n");
1764 return;
1765 }
1766
1767 ac--;
1768 av++;
1769
1770 /* get rules or pipes from kernel, resizing array as necessary */
1771 nbytes = nalloc;
1772
1773 while (nbytes >= nalloc) {
1774 nalloc = nalloc * 2 + 200;
1775 nbytes = nalloc;
1776 if ((data = realloc(data, nbytes)) == NULL)
1777 err(EX_OSERR, "realloc");
1778
1779 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
1780 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1781 do_pipe ? "DUMMYNET" : "FW");
1782 }
1783
1784 if (do_pipe) {
1785 list_pipes(data, nbytes, ac, av);
1786 goto done;
1787 }
1788
1789 /*
1790 * Count static rules. They have variable size so we
1791 * need to scan the list to count them.
1792 */
1793 for (nstat = 1, r = data, lim = (char *)data + nbytes;
1794 r->rulenum < 65535 && (char *)r < lim;
1795 ++nstat, r = NEXT(r) )
1796 ; /* nothing */
1797
1798 /*
1799 * Count dynamic rules. This is easier as they have
1800 * fixed size.
1801 */
1802 r = NEXT(r);
1803 dynrules = (ipfw_dyn_rule *)r ;
1804 n = (char *)r - (char *)data;
1805 ndyn = (nbytes - n) / sizeof *dynrules;
1806
1807 /* if showing stats, figure out column widths ahead of time */
1808 bcwidth = pcwidth = 0;
1809 if (show_counters) {
1810 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1811 /* packet counter */
1812 width = snprintf(NULL, 0, "%llu",
1813 align_uint64(&r->pcnt));
1814 if (width > pcwidth)
1815 pcwidth = width;
1816
1817 /* byte counter */
1818 width = snprintf(NULL, 0, "%llu",
1819 align_uint64(&r->bcnt));
1820 if (width > bcwidth)
1821 bcwidth = width;
1822 }
1823 }
1824 if (do_dynamic && ndyn) {
1825 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1826 width = snprintf(NULL, 0, "%llu",
1827 align_uint64(&d->pcnt));
1828 if (width > pcwidth)
1829 pcwidth = width;
1830
1831 width = snprintf(NULL, 0, "%llu",
1832 align_uint64(&d->bcnt));
1833 if (width > bcwidth)
1834 bcwidth = width;
1835 }
1836 }
1837 /* if no rule numbers were specified, list all rules */
1838 if (ac == 0) {
1839 for (n = 0, r = data; n < nstat; n++, r = NEXT(r) )
1840 show_ipfw(r, pcwidth, bcwidth);
1841
1842 if (do_dynamic && ndyn) {
1843 printf("## Dynamic rules (%d):\n", ndyn);
1844 for (n = 0, d = dynrules; n < ndyn; n++, d++)
1845 show_dyn_ipfw(d, pcwidth, bcwidth);
1846 }
1847 goto done;
1848 }
1849
1850 /* display specific rules requested on command line */
1851
1852 for (lac = ac, lav = av; lac != 0; lac--) {
1853 /* convert command line rule # */
1854 last = rnum = strtoul(*lav++, &endptr, 10);
1855 if (*endptr == '-')
1856 last = strtoul(endptr+1, &endptr, 10);
1857 if (*endptr) {
1858 exitval = EX_USAGE;
1859 warnx("invalid rule number: %s", *(lav - 1));
1860 continue;
1861 }
1862 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
1863 if (r->rulenum > last)
1864 break;
1865 if (r->rulenum >= rnum && r->rulenum <= last) {
1866 show_ipfw(r, pcwidth, bcwidth);
1867 seen = 1;
1868 }
1869 }
1870 if (!seen) {
1871 /* give precedence to other error(s) */
1872 if (exitval == EX_OK)
1873 exitval = EX_UNAVAILABLE;
1874 warnx("rule %lu does not exist", rnum);
1875 }
1876 }
1877
1878 if (do_dynamic && ndyn) {
1879 printf("## Dynamic rules:\n");
1880 for (lac = ac, lav = av; lac != 0; lac--) {
1881 rnum = strtoul(*lav++, &endptr, 10);
1882 if (*endptr == '-')
1883 last = strtoul(endptr+1, &endptr, 10);
1884 if (*endptr)
1885 /* already warned */
1886 continue;
1887 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1888 uint16_t rulenum;
1889
1890 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1891 if (rulenum > rnum)
1892 break;
1893 if (r->rulenum >= rnum && r->rulenum <= last)
1894 show_dyn_ipfw(d, pcwidth, bcwidth);
1895 }
1896 }
1897 }
1898
1899 ac = 0;
1900
1901done:
1902 free(data);
1903
1904 if (exitval != EX_OK)
1905 exit(exitval);
1906#undef NEXT
1907}
1908
1909static void
1910show_usage(void)
1911{
1912 fprintf(stderr, "usage: ipfw [options]\n"
1913"do \"ipfw -h\" or see ipfw manpage for details\n"
1914);
1915 exit(EX_USAGE);
1916}
1917
1918static void
1919help(void)
1920{
1921 fprintf(stderr,
1922"ipfw syntax summary (but please do read the ipfw(8) manpage):\n"
1923"ipfw [-acdeftTnNpqS] <command> where <command> is one of:\n"
1924"add [num] [set N] [prob x] RULE-BODY\n"
1925"{pipe|queue} N config PIPE-BODY\n"
1926"[pipe|queue] {zero|delete|show} [N{,N}]\n"
1927"set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
1928"\n"
1929"RULE-BODY: check-state [LOG] | ACTION [LOG] ADDR [OPTION_LIST]\n"
1930"ACTION: check-state | allow | count | deny | reject | skipto N |\n"
1931" {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1932"ADDR: [ MAC dst src ether_type ] \n"
1933" [ from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
1934"IPADDR: [not] { any | me | ip/bits{x,y,z} | IPLIST }\n"
1935"IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
1936"OPTION_LIST: OPTION [OPTION_LIST]\n"
1937"OPTION: bridged | {dst-ip|src-ip} ADDR | {dst-port|src-port} LIST |\n"
1938" estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
1939" iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
1940" ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
1941" mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
1942" setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
1943" verrevpath\n"
1944);
1945exit(0);
1946}
1947
1948
1949static int
1950lookup_host (char *host, struct in_addr *ipaddr)
1951{
1952 struct hostent *he;
1953
1954 if (!inet_aton(host, ipaddr)) {
1955 if ((he = gethostbyname(host)) == NULL)
1956 return(-1);
1957 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1958 }
1959 return(0);
1960}
1961
1962/*
1963 * fills the addr and mask fields in the instruction as appropriate from av.
1964 * Update length as appropriate.
1965 * The following formats are allowed:
1966 * any matches any IP. Actually returns an empty instruction.
1967 * me returns O_IP_*_ME
1968 * 1.2.3.4 single IP address
1969 * 1.2.3.4:5.6.7.8 address:mask
1970 * 1.2.3.4/24 address/mask
1971 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1972 * We can have multiple comma-separated address/mask entries.
1973 */
1974static void
1975fill_ip(ipfw_insn_ip *cmd, char *av)
1976{
1977 int len = 0;
1978 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
1979
1980 cmd->o.len &= ~F_LEN_MASK; /* zero len */
1981
1982 if (!strncmp(av, "any", strlen(av)))
1983 return;
1984
1985 if (!strncmp(av, "me", strlen(av))) {
1986 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1987 return;
1988 }
1989
1990 while (av) {
1991 /*
1992 * After the address we can have '/' or ':' indicating a mask,
1993 * ',' indicating another address follows, '{' indicating a
1994 * set of addresses of unspecified size.
1995 */
1996 char *p = strpbrk(av, "/:,{");
1997 int masklen;
1998 char md;
1999
2000 if (p) {
2001 md = *p;
2002 *p++ = '\0';
2003 } else
2004 md = '\0';
2005
2006 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2007 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2008 switch (md) {
2009 case ':':
2010 if (!inet_aton(p, (struct in_addr *)&d[1]))
2011 errx(EX_DATAERR, "bad netmask ``%s''", p);
2012 break;
2013 case '/':
2014 masklen = atoi(p);
2015 if (masklen == 0)
2016 d[1] = htonl(0); /* mask */
2017 else if (masklen > 32)
2018 errx(EX_DATAERR, "bad width ``%s''", p);
2019 else
2020 d[1] = htonl(~0 << (32 - masklen));
2021 break;
2022 case '{': /* no mask, assume /24 and put back the '{' */
2023 d[1] = htonl(~0 << (32 - 24));
2024 *(--p) = md;
2025 break;
2026
2027 case ',': /* single address plus continuation */
2028 *(--p) = md;
2029 /* FALLTHROUGH */
2030 case 0: /* initialization value */
2031 default:
2032 d[1] = htonl(~0); /* force /32 */
2033 break;
2034 }
2035 d[0] &= d[1]; /* mask base address with mask */
2036 /* find next separator */
2037 if (p)
2038 p = strpbrk(p, ",{");
2039 if (p && *p == '{') {
2040 /*
2041 * We have a set of addresses. They are stored as follows:
2042 * arg1 is the set size (powers of 2, 2..256)
2043 * addr is the base address IN HOST FORMAT
2044 * mask.. is an array of arg1 bits (rounded up to
2045 * the next multiple of 32) with bits set
2046 * for each host in the map.
2047 */
2048 uint32_t *map = (uint32_t *)&cmd->mask;
2049 int low, high;
2050 int i = contigmask((uint8_t *)&(d[1]), 32);
2051
2052 if (len > 0)
2053 errx(EX_DATAERR, "address set cannot be in a list");
2054 if (i < 24 || i > 31)
2055 errx(EX_DATAERR, "invalid set with mask %d", i);
2056 cmd->o.arg1 = 1<<(32-i); /* map length */
2057 d[0] = ntohl(d[0]); /* base addr in host format */
2058 cmd->o.opcode = O_IP_DST_SET; /* default */
2059 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2060 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2061 map[i] = 0; /* clear map */
2062
2063 av = p + 1;
2064 low = d[0] & 0xff;
2065 high = low + cmd->o.arg1 - 1;
2066 /*
2067 * Here, i stores the previous value when we specify a range
2068 * of addresses within a mask, e.g. 45-63. i = -1 means we
2069 * have no previous value.
2070 */
2071 i = -1; /* previous value in a range */
2072 while (isdigit(*av)) {
2073 char *s;
2074 int a = strtol(av, &s, 0);
2075
2076 if (s == av) { /* no parameter */
2077 if (*av != '}')
2078 errx(EX_DATAERR, "set not closed");
2079 if (i != -1)
2080 errx(EX_DATAERR, "incomplete range %d-", i);
2081 break;
2082 }
2083 if (a < low || a > high)
2084 errx(EX_DATAERR, "addr %d out of range [%d-%d]",
2085 a, low, high);
2086 a -= low;
2087 if (i == -1) /* no previous in range */
2088 i = a;
2089 else { /* check that range is valid */
2090 if (i > a)
2091 errx(EX_DATAERR, "invalid range %d-%d",
2092 i+low, a+low);
2093 if (*s == '-')
2094 errx(EX_DATAERR, "double '-' in range");
2095 }
2096 for (; i <= a; i++)
2097 map[i/32] |= 1<<(i & 31);
2098 i = -1;
2099 if (*s == '-')
2100 i = a;
2101 else if (*s == '}')
2102 break;
2103 av = s+1;
2104 }
2105 return;
2106 }
2107 av = p;
2108 if (av) /* then *av must be a ',' */
2109 av++;
2110
2111 /* Check this entry */
2112 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2113 /*
2114 * 'any' turns the entire list into a NOP.
2115 * 'not any' never matches, so it is removed from the
2116 * list unless it is the only item, in which case we
2117 * report an error.
2118 */
2119 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2120 if (av == NULL && len == 0) /* only this entry */
2121 errx(EX_DATAERR, "not any never matches");
2122 }
2123 /* else do nothing and return */
2124 return;
2125 }
2126 /* A single IP can be stored in an optimized format */
2127 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) {
2128 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2129 return;
2130 }
2131 len += 2; /* two words... */
2132 d += 2;
2133 } /* end while */
2134 cmd->o.len |= len+1;
2135}
2136
2137
2138/*
2139 * helper function to process a set of flags and set bits in the
2140 * appropriate masks.
2141 */
2142static void
2143fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2144 struct _s_x *flags, char *p)
2145{
2146 uint8_t set=0, clear=0;
2147
2148 while (p && *p) {
2149 char *q; /* points to the separator */
2150 int val;
2151 uint8_t *which; /* mask we are working on */
2152
2153 if (*p == '!') {
2154 p++;
2155 which = &clear;
2156 } else
2157 which = &set;
2158 q = strchr(p, ',');
2159 if (q)
2160 *q++ = '\0';
2161 val = match_token(flags, p);
2162 if (val <= 0)
2163 errx(EX_DATAERR, "invalid flag %s", p);
2164 *which |= (uint8_t)val;
2165 p = q;
2166 }
2167 cmd->opcode = opcode;
2168 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2169 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2170}
2171
2172
2173static void
2174delete(int ac, char *av[])
2175{
2176 struct ip_fw rule;
2177 struct dn_pipe p;
2178 int i;
2179 int exitval = EX_OK;
2180 int do_set = 0;
2181
2182 memset(&p, 0, sizeof p);
2183
2184 av++; ac--;
2185 if (ac > 0 && !strncmp(*av, "set", strlen(*av))) {
2186 do_set = 1; /* delete set */
2187 ac--; av++;
2188 }
2189
2190 /* Rule number */
2191 while (ac && isdigit(**av)) {
2192 i = atoi(*av); av++; ac--;
2193 if (do_pipe) {
2194 if (do_pipe == 1)
2195 p.pipe_nr = i;
2196 else
2197 p.fs.fs_nr = i;
2198 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
2199 if (i) {
2200 exitval = 1;
2201 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
2202 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
2203 }
2204 } else {
2205 bzero(&rule, sizeof(rule));
2206 if (do_set) {
2207 rule.set_masks[0] = (i & 0xffff) | (do_set << 24);
2208 }
2209 else {
2210 rule.rulenum = i;
2211 }
2212 i = do_cmd(IP_FW_DEL, &rule, sizeof(rule));
2213 if (i) {
2214 exitval = EX_UNAVAILABLE;
2215 warn("rule %u: setsockopt(IP_FW_DEL)",
2216 rule.rulenum);
2217 }
2218 }
2219 }
2220 if (exitval != EX_OK)
2221 exit(exitval);
2222}
2223
2224
2225/*
2226 * fill the interface structure. We do not check the name as we can
2227 * create interfaces dynamically, so checking them at insert time
2228 * makes relatively little sense.
2229 * A '*' following the name means any unit.
2230 */
2231static void
2232fill_iface(ipfw_insn_if *cmd, char *arg)
2233{
2234 cmd->name[0] = '\0';
2235 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2236
2237 /* Parse the interface or address */
2238 if (!strcmp(arg, "any"))
2239 cmd->o.len = 0; /* effectively ignore this command */
2240 else if (!isdigit(*arg)) {
2241 char *q;
2242
2243 strncpy(cmd->name, arg, sizeof(cmd->name));
2244 cmd->name[sizeof(cmd->name) - 1] = '\0';
2245 /* find first digit or wildcard */
2246 for (q = cmd->name; *q && !isdigit(*q) && *q != '*'; q++)
2247 continue;
2248 cmd->p.unit = (*q == '*') ? -1 : atoi(q);
2249 *q = '\0';
2250 } else if (!inet_aton(arg, &cmd->p.ip))
2251 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2252}
2253
2254/*
2255 * the following macro returns an error message if we run out of
2256 * arguments.
2257 */
2258#define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
2259
2260static void
2261config_pipe(int ac, char **av)
2262{
2263 struct dn_pipe p;
2264 int i;
2265 char *end;
2266 uint32_t a;
2267 void *par = NULL;
2268
2269 memset(&p, 0, sizeof p);
2270
2271 av++; ac--;
2272 /* Pipe number */
2273 if (ac && isdigit(**av)) {
2274 i = atoi(*av); av++; ac--;
2275 if (do_pipe == 1)
2276 p.pipe_nr = i;
2277 else
2278 p.fs.fs_nr = i;
2279 }
2280 while (ac > 0) {
2281 double d;
2282 int tok = match_token(dummynet_params, *av);
2283 ac--; av++;
2284
2285 switch(tok) {
2286 case TOK_NOERROR:
2287 p.fs.flags_fs |= DN_NOERROR;
2288 break;
2289
2290 case TOK_PLR:
2291 NEED1("plr needs argument 0..1\n");
2292 d = strtod(av[0], NULL);
2293 if (d > 1)
2294 d = 1;
2295 else if (d < 0)
2296 d = 0;
2297 p.fs.plr = (int)(d*0x7fffffff);
2298 ac--; av++;
2299 break;
2300
2301 case TOK_QUEUE:
2302 NEED1("queue needs queue size\n");
2303 end = NULL;
2304 p.fs.qsize = strtoul(av[0], &end, 0);
2305 if (*end == 'K' || *end == 'k') {
2306 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
2307 p.fs.qsize *= 1024;
2308 } else if (*end == 'B' || !strncmp(end, "by", 2)) {
2309 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
2310 }
2311 ac--; av++;
2312 break;
2313
2314 case TOK_BUCKETS:
2315 NEED1("buckets needs argument\n");
2316 p.fs.rq_size = strtoul(av[0], NULL, 0);
2317 ac--; av++;
2318 break;
2319
2320 case TOK_MASK:
2321 NEED1("mask needs mask specifier\n");
2322 /*
2323 * per-flow queue, mask is dst_ip, dst_port,
2324 * src_ip, src_port, proto measured in bits
2325 */
2326 par = NULL;
2327
2328 p.fs.flow_mask.dst_ip = 0;
2329 p.fs.flow_mask.src_ip = 0;
2330 p.fs.flow_mask.dst_port = 0;
2331 p.fs.flow_mask.src_port = 0;
2332 p.fs.flow_mask.proto = 0;
2333 end = NULL;
2334
2335 while (ac >= 1) {
2336 uint32_t *p32 = NULL;
2337 uint16_t *p16 = NULL;
2338
2339 tok = match_token(dummynet_params, *av);
2340 ac--; av++;
2341 switch(tok) {
2342 case TOK_ALL:
2343 /*
2344 * special case, all bits significant
2345 */
2346 p.fs.flow_mask.dst_ip = ~0;
2347 p.fs.flow_mask.src_ip = ~0;
2348 p.fs.flow_mask.dst_port = ~0;
2349 p.fs.flow_mask.src_port = ~0;
2350 p.fs.flow_mask.proto = ~0;
2351 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2352 goto end_mask;
2353
2354 case TOK_DSTIP:
2355 p32 = &p.fs.flow_mask.dst_ip;
2356 break;
2357
2358 case TOK_SRCIP:
2359 p32 = &p.fs.flow_mask.src_ip;
2360 break;
2361
2362 case TOK_DSTPORT:
2363 p16 = &p.fs.flow_mask.dst_port;
2364 break;
2365
2366 case TOK_SRCPORT:
2367 p16 = &p.fs.flow_mask.src_port;
2368 break;
2369
2370 case TOK_PROTO:
2371 break;
2372
2373 default:
2374 ac++; av--; /* backtrack */
2375 goto end_mask;
2376 }
2377 if (ac < 1)
2378 errx(EX_USAGE, "mask: value missing");
2379 if (*av[0] == '/') {
2380 a = strtoul(av[0]+1, &end, 0);
2381 a = (a == 32) ? ~0 : (1 << a) - 1;
2382 } else
2383 a = strtoul(av[0], &end, 0);
2384 if (p32 != NULL)
2385 *p32 = a;
2386 else if (p16 != NULL) {
2387 if (a > 65535)
2388 errx(EX_DATAERR,
2389 "mask: must be 16 bit");
2390 *p16 = (uint16_t)a;
2391 } else {
2392 if (a > 255)
2393 errx(EX_DATAERR,
2394 "mask: must be 8 bit");
2395 p.fs.flow_mask.proto = (uint8_t)a;
2396 }
2397 if (a != 0)
2398 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2399 ac--; av++;
2400 } /* end while, config masks */
2401end_mask:
2402 break;
2403
2404 case TOK_RED:
2405 case TOK_GRED:
2406 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
2407 p.fs.flags_fs |= DN_IS_RED;
2408 if (tok == TOK_GRED)
2409 p.fs.flags_fs |= DN_IS_GENTLE_RED;
2410 /*
2411 * the format for parameters is w_q/min_th/max_th/max_p
2412 */
2413 if ((end = strsep(&av[0], "/"))) {
2414 double w_q = strtod(end, NULL);
2415 if (w_q > 1 || w_q <= 0)
2416 errx(EX_DATAERR, "0 < w_q <= 1");
2417 p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
2418 }
2419 if ((end = strsep(&av[0], "/"))) {
2420 p.fs.min_th = strtoul(end, &end, 0);
2421 if (*end == 'K' || *end == 'k')
2422 p.fs.min_th *= 1024;
2423 }
2424 if ((end = strsep(&av[0], "/"))) {
2425 p.fs.max_th = strtoul(end, &end, 0);
2426 if (*end == 'K' || *end == 'k')
2427 p.fs.max_th *= 1024;
2428 }
2429 if ((end = strsep(&av[0], "/"))) {
2430 double max_p = strtod(end, NULL);
2431 if (max_p > 1 || max_p <= 0)
2432 errx(EX_DATAERR, "0 < max_p <= 1");
2433 p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
2434 }
2435 ac--; av++;
2436 break;
2437
2438 case TOK_DROPTAIL:
2439 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
2440 break;
2441
2442 case TOK_BW:
2443 NEED1("bw needs bandwidth or interface\n");
2444 if (do_pipe != 1)
2445 errx(EX_DATAERR, "bandwidth only valid for pipes");
2446 /*
2447 * set clocking interface or bandwidth value
2448 */
2449 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
2450 int l = sizeof(p.if_name)-1;
2451 /* interface name */
2452 strncpy(p.if_name, av[0], l);
2453 p.if_name[l] = '\0';
2454 p.bandwidth = 0;
2455 } else {
2456 p.if_name[0] = '\0';
2457 p.bandwidth = strtoul(av[0], &end, 0);
2458 if (*end == 'K' || *end == 'k') {
2459 end++;
2460 p.bandwidth *= 1000;
2461 } else if (*end == 'M') {
2462 end++;
2463 p.bandwidth *= 1000000;
2464 }
2465 if (*end == 'B' || !strncmp(end, "by", 2))
2466 p.bandwidth *= 8;
2467 if (p.bandwidth < 0)
2468 errx(EX_DATAERR, "bandwidth too large");
2469 }
2470 ac--; av++;
2471 break;
2472
2473 case TOK_DELAY:
2474 if (do_pipe != 1)
2475 errx(EX_DATAERR, "delay only valid for pipes");
2476 NEED1("delay needs argument 0..10000ms\n");
2477 p.delay = strtoul(av[0], NULL, 0);
2478 ac--; av++;
2479 break;
2480
2481 case TOK_WEIGHT:
2482 if (do_pipe == 1)
2483 errx(EX_DATAERR,"weight only valid for queues");
2484 NEED1("weight needs argument 0..100\n");
2485 p.fs.weight = strtoul(av[0], &end, 0);
2486 ac--; av++;
2487 break;
2488
2489 case TOK_PIPE:
2490 if (do_pipe == 1)
2491 errx(EX_DATAERR,"pipe only valid for queues");
2492 NEED1("pipe needs pipe_number\n");
2493 p.fs.parent_nr = strtoul(av[0], &end, 0);
2494 ac--; av++;
2495 break;
2496
2497 default:
2498 errx(EX_DATAERR, "unrecognised option ``%s''", *(--av));
2499 }
2500 }
2501 if (do_pipe == 1) {
2502 if (p.pipe_nr == 0)
2503 errx(EX_DATAERR, "pipe_nr must be > 0");
2504 if (p.delay > 10000)
2505 errx(EX_DATAERR, "delay must be < 10000");
2506 } else { /* do_pipe == 2, queue */
2507 if (p.fs.parent_nr == 0)
2508 errx(EX_DATAERR, "pipe must be > 0");
2509 if (p.fs.weight >100)
2510 errx(EX_DATAERR, "weight must be <= 100");
2511 }
2512 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
2513 if (p.fs.qsize > 1024*1024)
2514 errx(EX_DATAERR, "queue size must be < 1MB");
2515 } else {
2516 if (p.fs.qsize > 100)
2517 errx(EX_DATAERR, "2 <= queue size <= 100");
2518 }
2519 if (p.fs.flags_fs & DN_IS_RED) {
2520 size_t len;
2521 int lookup_depth, avg_pkt_size;
2522 double s, idle, weight, w_q;
2523 struct clockinfo ck;
2524 int t;
2525
2526 if (p.fs.min_th >= p.fs.max_th)
2527 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
2528 p.fs.min_th, p.fs.max_th);
2529 if (p.fs.max_th == 0)
2530 errx(EX_DATAERR, "max_th must be > 0");
2531
2532 len = sizeof(int);
2533 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
2534 &lookup_depth, &len, NULL, 0) == -1)
2535
2536 errx(1, "sysctlbyname(\"%s\")",
2537 "net.inet.ip.dummynet.red_lookup_depth");
2538 if (lookup_depth == 0)
2539 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
2540 " must be greater than zero");
2541
2542 len = sizeof(int);
2543 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2544 &avg_pkt_size, &len, NULL, 0) == -1)
2545
2546 errx(1, "sysctlbyname(\"%s\")",
2547 "net.inet.ip.dummynet.red_avg_pkt_size");
2548 if (avg_pkt_size == 0)
2549 errx(EX_DATAERR,
2550 "net.inet.ip.dummynet.red_avg_pkt_size must"
2551 " be greater than zero");
2552
2553 len = sizeof(struct clockinfo);
2554 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
2555 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
2556
2557 /*
2558 * Ticks needed for sending a medium-sized packet.
2559 * Unfortunately, when we are configuring a WF2Q+ queue, we
2560 * do not have bandwidth information, because that is stored
2561 * in the parent pipe, and also we have multiple queues
2562 * competing for it. So we set s=0, which is not very
2563 * correct. But on the other hand, why do we want RED with
2564 * WF2Q+ ?
2565 */
2566 if (p.bandwidth==0) /* this is a WF2Q+ queue */
2567 s = 0;
2568 else
2569 s = ck.hz * avg_pkt_size * 8 / p.bandwidth;
2570
2571 /*
2572 * max idle time (in ticks) before avg queue size becomes 0.
2573 * NOTA: (3/w_q) is approx the value x so that
2574 * (1-w_q)^x < 10^-3.
2575 */
2576 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
2577 idle = s * 3. / w_q;
2578 p.fs.lookup_step = (int)idle / lookup_depth;
2579 if (!p.fs.lookup_step)
2580 p.fs.lookup_step = 1;
2581 weight = 1 - w_q;
2582 for (t = p.fs.lookup_step; t > 0; --t)
2583 weight *= weight;
2584 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2585 }
2586 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
2587 if (i)
2588 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2589}
2590
2591static void
2592get_mac_addr_mask(char *p, uint8_t *addr, uint8_t *mask)
2593{
2594 int i, l;
2595
2596 for (i=0; i<6; i++)
2597 addr[i] = mask[i] = 0;
2598 if (!strcmp(p, "any"))
2599 return;
2600
2601 for (i=0; *p && i<6;i++, p++) {
2602 addr[i] = strtol(p, &p, 16);
2603 if (*p != ':') /* we start with the mask */
2604 break;
2605 }
2606 if (*p == '/') { /* mask len */
2607 l = strtol(p+1, &p, 0);
2608 for (i=0; l>0; l -=8, i++)
2609 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2610 } else if (*p == '&') { /* mask */
2611 for (i=0, p++; *p && i<6;i++, p++) {
2612 mask[i] = strtol(p, &p, 16);
2613 if (*p != ':')
2614 break;
2615 }
2616 } else if (*p == '\0') {
2617 for (i=0; i<6; i++)
2618 mask[i] = 0xff;
2619 }
2620 for (i=0; i<6; i++)
2621 addr[i] &= mask[i];
2622}
2623
2624/*
2625 * helper function, updates the pointer to cmd with the length
2626 * of the current command, and also cleans up the first word of
2627 * the new command in case it has been clobbered before.
2628 */
2629static ipfw_insn *
2630next_cmd(ipfw_insn *cmd)
2631{
2632 cmd += F_LEN(cmd);
2633 bzero(cmd, sizeof(*cmd));
2634 return cmd;
2635}
2636
2637/*
2638 * Takes arguments and copies them into a comment
2639 */
2640static void
2641fill_comment(ipfw_insn *cmd, int ac, char **av)
2642{
2643 int i, l;
2644 char *p = (char *)(cmd + 1);
2645
2646 cmd->opcode = O_NOP;
2647 cmd->len = (cmd->len & (F_NOT | F_OR));
2648
2649 /* Compute length of comment string. */
2650 for (i = 0, l = 0; i < ac; i++)
2651 l += strlen(av[i]) + 1;
2652 if (l == 0)
2653 return;
2654 if (l > 84)
2655 errx(EX_DATAERR,
2656 "comment too long (max 80 chars)");
2657 l = 1 + (l+3)/4;
2658 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2659 for (i = 0; i < ac; i++) {
2660 /* length being checked above (max 80 chars) */
2661 strlcpy(p, av[i], 80);
2662 p += strlen(av[i]);
2663 *p++ = ' ';
2664 }
2665 *(--p) = '\0';
2666}
2667
2668/*
2669 * A function to fill simple commands of size 1.
2670 * Existing flags are preserved.
2671 */
2672static void
2673fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2674{
2675 cmd->opcode = opcode;
2676 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2677 cmd->arg1 = arg;
2678}
2679
2680/*
2681 * Fetch and add the MAC address and type, with masks. This generates one or
2682 * two microinstructions, and returns the pointer to the last one.
2683 */
2684static ipfw_insn *
2685add_mac(ipfw_insn *cmd, int ac, char *av[])
2686{
2687 ipfw_insn_mac *mac;
2688
2689 if (ac < 2)
2690 errx(EX_DATAERR, "MAC dst src");
2691
2692 cmd->opcode = O_MACADDR2;
2693 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2694
2695 mac = (ipfw_insn_mac *)cmd;
2696 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2697 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2698 return cmd;
2699}
2700
2701static ipfw_insn *
2702add_mactype(ipfw_insn *cmd, int ac, char *av)
2703{
2704 if (ac < 1)
2705 errx(EX_DATAERR, "missing MAC type");
2706 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2707 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2708 cmd->opcode = O_MAC_TYPE;
2709 return cmd;
2710 } else
2711 return NULL;
2712}
2713
2714static ipfw_insn *
2715add_proto(ipfw_insn *cmd, char *av)
2716{
2717 struct protoent *pe;
2718 u_char proto = 0;
2719
2720 if (!strncmp(av, "all", strlen(av)))
2721 ; /* same as "ip" */
2722 else if ((proto = atoi(av)) > 0)
2723 ; /* all done! */
2724 else if ((pe = getprotobyname(av)) != NULL)
2725 proto = pe->p_proto;
2726 else
2727 return NULL;
2728 if (proto != IPPROTO_IP)
2729 fill_cmd(cmd, O_PROTO, 0, proto);
2730 return cmd;
2731}
2732
2733static ipfw_insn *
2734add_srcip(ipfw_insn *cmd, char *av)
2735{
2736 fill_ip((ipfw_insn_ip *)cmd, av);
2737 if (cmd->opcode == O_IP_DST_SET) /* set */
2738 cmd->opcode = O_IP_SRC_SET;
2739 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2740 cmd->opcode = O_IP_SRC_ME;
2741 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2742 cmd->opcode = O_IP_SRC;
2743 else /* addr/mask */
2744 cmd->opcode = O_IP_SRC_MASK;
2745 return cmd;
2746}
2747
2748static ipfw_insn *
2749add_dstip(ipfw_insn *cmd, char *av)
2750{
2751 fill_ip((ipfw_insn_ip *)cmd, av);
2752 if (cmd->opcode == O_IP_DST_SET) /* set */
2753 ;
2754 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2755 cmd->opcode = O_IP_DST_ME;
2756 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2757 cmd->opcode = O_IP_DST;
2758 else /* addr/mask */
2759 cmd->opcode = O_IP_DST_MASK;
2760 return cmd;
2761}
2762
2763static ipfw_insn *
2764add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2765{
2766 if (!strncmp(av, "any", strlen(av))) {
2767 return NULL;
2768 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2769 /* XXX todo: check that we have a protocol with ports */
2770 cmd->opcode = opcode;
2771 return cmd;
2772 }
2773 return NULL;
2774}
2775
2776/*
2777 * Parse arguments and assemble the microinstructions which make up a rule.
2778 * Rules are added into the 'rulebuf' and then copied in the correct order
2779 * into the actual rule.
2780 *
2781 * The syntax for a rule starts with the action, followed by an
2782 * optional log action, and the various match patterns.
2783 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2784 * (generated if the rule includes a keep-state option), then the
2785 * various match patterns, the "log" action, and the actual action.
2786 *
2787 */
2788static void
2789add(int ac, char *av[])
2790{
2791 /*
2792 * rules are added into the 'rulebuf' and then copied in
2793 * the correct order into the actual rule.
2794 * Some things that need to go out of order (prob, action etc.)
2795 * go into actbuf[].
2796 */
2797 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2798
2799 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2800 ipfw_insn *first_cmd; /* first match pattern */
2801
2802 struct ip_fw *rule;
2803
2804 /*
2805 * various flags used to record that we entered some fields.
2806 */
2807 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2808
2809 int i;
2810
2811 int open_par = 0; /* open parenthesis ( */
2812
2813 /* proto is here because it is used to fetch ports */
2814 u_char proto = IPPROTO_IP; /* default protocol */
2815
2816 double match_prob = 1; /* match probability, default is always match */
2817
2818 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2819 bzero(cmdbuf, sizeof(cmdbuf));
2820 bzero(rulebuf, sizeof(rulebuf));
2821
2822 rule = (struct ip_fw *)rulebuf;
2823 cmd = (ipfw_insn *)cmdbuf;
2824 action = (ipfw_insn *)actbuf;
2825
2826 av++; ac--;
2827
2828 /* [rule N] -- Rule number optional */
2829 if (ac && isdigit(**av)) {
2830 rule->rulenum = atoi(*av);
2831 av++;
2832 ac--;
2833 }
2834
2835 /* [set N] -- set number (0..RESVD_SET), optional */
2836 if (ac > 1 && !strncmp(*av, "set", strlen(*av))) {
2837 int set = strtoul(av[1], NULL, 10);
2838 if (set < 0 || set > RESVD_SET)
2839 errx(EX_DATAERR, "illegal set %s", av[1]);
2840 rule->set = set;
2841 av += 2; ac -= 2;
2842 }
2843
2844 /* [prob D] -- match probability, optional */
2845 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2846 match_prob = strtod(av[1], NULL);
2847
2848 if (match_prob <= 0 || match_prob > 1)
2849 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2850 av += 2; ac -= 2;
2851 }
2852
2853 /* action -- mandatory */
2854 NEED1("missing action");
2855 i = match_token(rule_actions, *av);
2856 ac--; av++;
2857 action->len = 1; /* default */
2858 switch(i) {
2859 case TOK_CHECKSTATE:
2860 have_state = action;
2861 action->opcode = O_CHECK_STATE;
2862 break;
2863
2864 case TOK_ACCEPT:
2865 action->opcode = O_ACCEPT;
2866 break;
2867
2868 case TOK_DENY:
2869 action->opcode = O_DENY;
2870 action->arg1 = 0;
2871 break;
2872
2873 case TOK_REJECT:
2874 action->opcode = O_REJECT;
2875 action->arg1 = ICMP_UNREACH_HOST;
2876 break;
2877
2878 case TOK_RESET:
2879 action->opcode = O_REJECT;
2880 action->arg1 = ICMP_REJECT_RST;
2881 break;
2882
2883 case TOK_UNREACH:
2884 action->opcode = O_REJECT;
2885 NEED1("missing reject code");
2886 fill_reject_code(&action->arg1, *av);
2887 ac--; av++;
2888 break;
2889
2890 case TOK_COUNT:
2891 action->opcode = O_COUNT;
2892 break;
2893
2894 case TOK_QUEUE:
2895 case TOK_PIPE:
2896 action->len = F_INSN_SIZE(ipfw_insn_pipe);
2897 case TOK_SKIPTO:
2898 if (i == TOK_QUEUE)
2899 action->opcode = O_QUEUE;
2900 else if (i == TOK_PIPE)
2901 action->opcode = O_PIPE;
2902 else if (i == TOK_SKIPTO)
2903 action->opcode = O_SKIPTO;
2904 NEED1("missing skipto/pipe/queue number");
2905 action->arg1 = strtoul(*av, NULL, 10);
2906 av++; ac--;
2907 break;
2908
2909 case TOK_DIVERT:
2910 case TOK_TEE:
2911 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2912 NEED1("missing divert/tee port");
2913 action->arg1 = strtoul(*av, NULL, 0);
2914 if (action->arg1 == 0) {
2915 struct servent *s;
2916 setservent(1);
2917 s = getservbyname(av[0], "divert");
2918 if (s != NULL)
2919 action->arg1 = ntohs(s->s_port);
2920 else
2921 errx(EX_DATAERR, "illegal divert/tee port");
2922 }
2923 ac--; av++;
2924 break;
2925
2926 case TOK_FORWARD: {
2927 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2928 char *s, *end;
2929
2930 NEED1("missing forward address[:port]");
2931
2932 action->opcode = O_FORWARD_IP;
2933 action->len = F_INSN_SIZE(ipfw_insn_sa);
2934
2935 p->sa.sin_len = sizeof(struct sockaddr_in);
2936 p->sa.sin_family = AF_INET;
2937 p->sa.sin_port = 0;
2938 /*
2939 * locate the address-port separator (':' or ',')
2940 */
2941 s = strchr(*av, ':');
2942 if (s == NULL)
2943 s = strchr(*av, ',');
2944 if (s != NULL) {
2945 *(s++) = '\0';
2946 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2947 if (s == end)
2948 errx(EX_DATAERR,
2949 "illegal forwarding port ``%s''", s);
2950 p->sa.sin_port = (u_short)i;
2951 }
2952 lookup_host(*av, &(p->sa.sin_addr));
2953 }
2954 ac--; av++;
2955 break;
2956
2957 case TOK_COMMENT:
2958 /* pretend it is a 'count' rule followed by the comment */
2959 action->opcode = O_COUNT;
2960 ac++; av--; /* go back... */
2961 break;
2962
2963 default:
2964 errx(EX_DATAERR, "invalid action %s", av[-1]);
2965 }
2966 action = next_cmd(action);
2967
2968 /*
2969 * [log [logamount N]] -- log, optional
2970 *
2971 * If exists, it goes first in the cmdbuf, but then it is
2972 * skipped in the copy section to the end of the buffer.
2973 */
2974 if (ac && !strncmp(*av, "log", strlen(*av))) {
2975 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2976 int l;
2977
2978 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2979 cmd->opcode = O_LOG;
2980 av++; ac--;
2981 if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2982 ac--; av++;
2983 NEED1("logamount requires argument");
2984 l = atoi(*av);
2985 if (l < 0)
2986 errx(EX_DATAERR, "logamount must be positive");
2987 c->max_log = l;
2988 ac--; av++;
2989 }
2990 cmd = next_cmd(cmd);
2991 }
2992
2993 if (have_state) /* must be a check-state, we are done */
2994 goto done;
2995
2996#define OR_START(target) \
2997 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2998 if (open_par) \
2999 errx(EX_USAGE, "nested \"(\" not allowed"); \
3000 prev = NULL; \
3001 open_par = 1; \
3002 if ( (av[0])[1] == '\0') { \
3003 ac--; av++; \
3004 } else \
3005 (*av)++; \
3006 } \
3007 target: \
3008
3009
3010#define CLOSE_PAR \
3011 if (open_par) { \
3012 if (ac && ( \
3013 !strncmp(*av, ")", strlen(*av)) || \
3014 !strncmp(*av, "}", strlen(*av)) )) { \
3015 prev = NULL; \
3016 open_par = 0; \
3017 ac--; av++; \
3018 } else \
3019 errx(EX_USAGE, "missing \")\""); \
3020 }
3021
3022#define NOT_BLOCK \
3023 if (ac && !strncmp(*av, "not", strlen(*av))) { \
3024 if (cmd->len & F_NOT) \
3025 errx(EX_USAGE, "double \"not\" not allowed"); \
3026 cmd->len |= F_NOT; \
3027 ac--; av++; \
3028 }
3029
3030#define OR_BLOCK(target) \
3031 if (ac && !strncmp(*av, "or", strlen(*av))) { \
3032 if (prev == NULL || open_par == 0) \
3033 errx(EX_DATAERR, "invalid OR block"); \
3034 prev->len |= F_OR; \
3035 ac--; av++; \
3036 goto target; \
3037 } \
3038 CLOSE_PAR;
3039
3040 first_cmd = cmd;
3041
3042#if 0
3043 /*
3044 * MAC addresses, optional.
3045 * If we have this, we skip the part "proto from src to dst"
3046 * and jump straight to the option parsing.
3047 */
3048 NOT_BLOCK;
3049 NEED1("missing protocol");
3050 if (!strncmp(*av, "MAC", strlen(*av)) ||
3051 !strncmp(*av, "mac", strlen(*av))) {
3052 ac--; av++; /* the "MAC" keyword */
3053 add_mac(cmd, ac, av); /* exits in case of errors */
3054 cmd = next_cmd(cmd);
3055 ac -= 2; av += 2; /* dst-mac and src-mac */
3056 NOT_BLOCK;
3057 NEED1("missing mac type");
3058 if (add_mactype(cmd, ac, av[0]))
3059 cmd = next_cmd(cmd);
3060 ac--; av++; /* any or mac-type */
3061 goto read_options;
3062 }
3063#endif
3064
3065 /*
3066 * protocol, mandatory
3067 */
3068 OR_START(get_proto);
3069 NOT_BLOCK;
3070 NEED1("missing protocol");
3071 if (add_proto(cmd, *av)) {
3072 av++; ac--;
3073 if (F_LEN(cmd) == 0) /* plain IP */
3074 proto = 0;
3075 else {
3076 proto = cmd->arg1;
3077 prev = cmd;
3078 cmd = next_cmd(cmd);
3079 }
3080 } else if (first_cmd != cmd) {
3081 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3082 } else
3083 goto read_options;
3084 OR_BLOCK(get_proto);
3085
3086 /*
3087 * "from", mandatory
3088 */
3089 if (!ac || strncmp(*av, "from", strlen(*av)))
3090 errx(EX_USAGE, "missing ``from''");
3091 ac--; av++;
3092
3093 /*
3094 * source IP, mandatory
3095 */
3096 OR_START(source_ip);
3097 NOT_BLOCK; /* optional "not" */
3098 NEED1("missing source address");
3099 if (add_srcip(cmd, *av)) {
3100 ac--; av++;
3101 if (F_LEN(cmd) != 0) { /* ! any */
3102 prev = cmd;
3103 cmd = next_cmd(cmd);
3104 }
3105 }
3106 OR_BLOCK(source_ip);
3107
3108 /*
3109 * source ports, optional
3110 */
3111 NOT_BLOCK; /* optional "not" */
3112 if (ac) {
3113 if (!strncmp(*av, "any", strlen(*av)) ||
3114 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3115 ac--; av++;
3116 if (F_LEN(cmd) != 0)
3117 cmd = next_cmd(cmd);
3118 }
3119 }
3120
3121 /*
3122 * "to", mandatory
3123 */
3124 if (!ac || strncmp(*av, "to", strlen(*av)))
3125 errx(EX_USAGE, "missing ``to''");
3126 av++; ac--;
3127
3128 /*
3129 * destination, mandatory
3130 */
3131 OR_START(dest_ip);
3132 NOT_BLOCK; /* optional "not" */
3133 NEED1("missing dst address");
3134 if (add_dstip(cmd, *av)) {
3135 ac--; av++;
3136 if (F_LEN(cmd) != 0) { /* ! any */
3137 prev = cmd;
3138 cmd = next_cmd(cmd);
3139 }
3140 }
3141 OR_BLOCK(dest_ip);
3142
3143 /*
3144 * dest. ports, optional
3145 */
3146 NOT_BLOCK; /* optional "not" */
3147 if (ac) {
3148 if (!strncmp(*av, "any", strlen(*av)) ||
3149 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3150 ac--; av++;
3151 if (F_LEN(cmd) != 0)
3152 cmd = next_cmd(cmd);
3153 }
3154 }
3155
3156read_options:
3157 if (ac && first_cmd == cmd) {
3158 /*
3159 * nothing specified so far, store in the rule to ease
3160 * printout later.
3161 */
3162 rule->_pad = 1;
3163 }
3164 prev = NULL;
3165 while (ac) {
3166 char *s;
3167 ipfw_insn_u32 *cmd32; /* alias for cmd */
3168
3169 s = *av;
3170 cmd32 = (ipfw_insn_u32 *)cmd;
3171
3172 if (*s == '!') { /* alternate syntax for NOT */
3173 if (cmd->len & F_NOT)
3174 errx(EX_USAGE, "double \"not\" not allowed");
3175 cmd->len = F_NOT;
3176 s++;
3177 }
3178 i = match_token(rule_options, s);
3179 ac--; av++;
3180 switch(i) {
3181 case TOK_NOT:
3182 if (cmd->len & F_NOT)
3183 errx(EX_USAGE, "double \"not\" not allowed");
3184 cmd->len = F_NOT;
3185 break;
3186
3187 case TOK_OR:
3188 if (open_par == 0 || prev == NULL)
3189 errx(EX_USAGE, "invalid \"or\" block");
3190 prev->len |= F_OR;
3191 break;
3192
3193 case TOK_STARTBRACE:
3194 if (open_par)
3195 errx(EX_USAGE, "+nested \"(\" not allowed");
3196 open_par = 1;
3197 break;
3198
3199 case TOK_ENDBRACE:
3200 if (!open_par)
3201 errx(EX_USAGE, "+missing \")\"");
3202 open_par = 0;
3203 prev = NULL;
3204 break;
3205
3206 case TOK_IN:
3207 fill_cmd(cmd, O_IN, 0, 0);
3208 break;
3209
3210 case TOK_OUT:
3211 cmd->len ^= F_NOT; /* toggle F_NOT */
3212 fill_cmd(cmd, O_IN, 0, 0);
3213 break;
3214
3215 case TOK_FRAG:
3216 fill_cmd(cmd, O_FRAG, 0, 0);
3217 break;
3218
3219 case TOK_LAYER2:
3220 fill_cmd(cmd, O_LAYER2, 0, 0);
3221 break;
3222
3223 case TOK_XMIT:
3224 case TOK_RECV:
3225 case TOK_VIA:
3226 NEED1("recv, xmit, via require interface name"
3227 " or address");
3228 fill_iface((ipfw_insn_if *)cmd, av[0]);
3229 ac--; av++;
3230 if (F_LEN(cmd) == 0) /* not a valid address */
3231 break;
3232 if (i == TOK_XMIT)
3233 cmd->opcode = O_XMIT;
3234 else if (i == TOK_RECV)
3235 cmd->opcode = O_RECV;
3236 else if (i == TOK_VIA)
3237 cmd->opcode = O_VIA;
3238 break;
3239
3240 case TOK_ICMPTYPES:
3241 NEED1("icmptypes requires list of types");
3242 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3243 av++; ac--;
3244 break;
3245
3246 case TOK_IPTTL:
3247 NEED1("ipttl requires TTL");
3248 if (strpbrk(*av, "-,")) {
3249 if (!add_ports(cmd, *av, 0, O_IPTTL))
3250 errx(EX_DATAERR, "invalid ipttl %s", *av);
3251 } else
3252 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3253 ac--; av++;
3254 break;
3255
3256 case TOK_IPID:
3257 NEED1("ipid requires id");
3258 if (strpbrk(*av, "-,")) {
3259 if (!add_ports(cmd, *av, 0, O_IPID))
3260 errx(EX_DATAERR, "invalid ipid %s", *av);
3261 } else
3262 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3263 ac--; av++;
3264 break;
3265
3266 case TOK_IPLEN:
3267 NEED1("iplen requires length");
3268 if (strpbrk(*av, "-,")) {
3269 if (!add_ports(cmd, *av, 0, O_IPLEN))
3270 errx(EX_DATAERR, "invalid ip len %s", *av);
3271 } else
3272 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3273 ac--; av++;
3274 break;
3275
3276 case TOK_IPVER:
3277 NEED1("ipver requires version");
3278 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3279 ac--; av++;
3280 break;
3281
3282 case TOK_IPPRECEDENCE:
3283 NEED1("ipprecedence requires value");
3284 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3285 (strtoul(*av, NULL, 0) & 7) << 5);
3286 ac--; av++;
3287 break;
3288
3289 case TOK_IPOPTS:
3290 NEED1("missing argument for ipoptions");
3291 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3292 ac--; av++;
3293 break;
3294
3295 case TOK_IPTOS:
3296 NEED1("missing argument for iptos");
3297 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3298 ac--; av++;
3299 break;
3300
3301 case TOK_UID:
3302 NEED1("uid requires argument");
3303 {
3304 char *end;
3305 uid_t uid;
3306 struct passwd *pwd;
3307
3308 cmd->opcode = O_UID;
3309 uid = strtoul(*av, &end, 0);
3310 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3311 if (pwd == NULL)
3312 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3313 cmd32->d[0] = pwd->pw_uid;
3314 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3315 ac--; av++;
3316 }
3317 break;
3318
3319 case TOK_GID:
3320 NEED1("gid requires argument");
3321 {
3322 char *end;
3323 gid_t gid;
3324 struct group *grp;
3325
3326 cmd->opcode = O_GID;
3327 gid = strtoul(*av, &end, 0);
3328 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3329 if (grp == NULL)
3330 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3331 cmd32->d[0] = grp->gr_gid;
3332 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3333 ac--; av++;
3334 }
3335 break;
3336
3337 case TOK_ESTAB:
3338 fill_cmd(cmd, O_ESTAB, 0, 0);
3339 break;
3340
3341 case TOK_SETUP:
3342 fill_cmd(cmd, O_TCPFLAGS, 0,
3343 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3344 break;
3345
3346 case TOK_TCPOPTS:
3347 NEED1("missing argument for tcpoptions");
3348 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3349 ac--; av++;
3350 break;
3351
3352 case TOK_TCPSEQ:
3353 case TOK_TCPACK:
3354 NEED1("tcpseq/tcpack requires argument");
3355 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3356 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3357 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3358 ac--; av++;
3359 break;
3360
3361 case TOK_TCPWIN:
3362 NEED1("tcpwin requires length");
3363 fill_cmd(cmd, O_TCPWIN, 0,
3364 htons(strtoul(*av, NULL, 0)));
3365 ac--; av++;
3366 break;
3367
3368 case TOK_TCPFLAGS:
3369 NEED1("missing argument for tcpflags");
3370 cmd->opcode = O_TCPFLAGS;
3371 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3372 ac--; av++;
3373 break;
3374
3375 case TOK_KEEPSTATE:
3376 if (open_par)
3377 errx(EX_USAGE, "keep-state cannot be part "
3378 "of an or block");
3379 if (have_state)
3380 errx(EX_USAGE, "only one of keep-state "
3381 "and limit is allowed");
3382 have_state = cmd;
3383 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3384 break;
3385
3386 case TOK_LIMIT:
3387 if (open_par)
3388 errx(EX_USAGE, "limit cannot be part "
3389 "of an or block");
3390 if (have_state)
3391 errx(EX_USAGE, "only one of keep-state "
3392 "and limit is allowed");
3393 NEED1("limit needs mask and # of connections");
3394 have_state = cmd;
3395 {
3396 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3397
3398 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3399 cmd->opcode = O_LIMIT;
3400 c->limit_mask = 0;
3401 c->conn_limit = 0;
3402 for (; ac >1 ;) {
3403 int val;
3404
3405 val = match_token(limit_masks, *av);
3406 if (val <= 0)
3407 break;
3408 c->limit_mask |= val;
3409 ac--; av++;
3410 }
3411 c->conn_limit = atoi(*av);
3412 if (c->conn_limit == 0)
3413 errx(EX_USAGE, "limit: limit must be >0");
3414 if (c->limit_mask == 0)
3415 errx(EX_USAGE, "missing limit mask");
3416 ac--; av++;
3417 }
3418 break;
3419
3420 case TOK_PROTO:
3421 NEED1("missing protocol");
3422 if (add_proto(cmd, *av)) {
3423 proto = cmd->arg1;
3424 ac--; av++;
3425 } else
3426 errx(EX_DATAERR, "invalid protocol ``%s''",
3427 *av);
3428 break;
3429
3430 case TOK_SRCIP:
3431 NEED1("missing source IP");
3432 if (add_srcip(cmd, *av)) {
3433 ac--; av++;
3434 }
3435 break;
3436
3437 case TOK_DSTIP:
3438 NEED1("missing destination IP");
3439 if (add_dstip(cmd, *av)) {
3440 ac--; av++;
3441 }
3442 break;
3443
3444 case TOK_SRCPORT:
3445 NEED1("missing source port");
3446 if (!strncmp(*av, "any", strlen(*av)) ||
3447 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3448 ac--; av++;
3449 } else
3450 errx(EX_DATAERR, "invalid source port %s", *av);
3451 break;
3452
3453 case TOK_DSTPORT:
3454 NEED1("missing destination port");
3455 if (!strncmp(*av, "any", strlen(*av)) ||
3456 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3457 ac--; av++;
3458 } else
3459 errx(EX_DATAERR, "invalid destination port %s",
3460 *av);
3461 break;
3462
3463 case TOK_MAC:
3464 if (ac < 2)
3465 errx(EX_USAGE, "MAC dst-mac src-mac");
3466 if (add_mac(cmd, ac, av)) {
3467 ac -= 2; av += 2;
3468 }
3469 break;
3470
3471 case TOK_MACTYPE:
3472 NEED1("missing mac type");
3473 if (!add_mactype(cmd, ac, *av))
3474 errx(EX_DATAERR, "invalid mac type %s", *av);
3475 ac--; av++;
3476 break;
3477
3478 case TOK_VERREVPATH:
3479 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3480 break;
3481
3482 case TOK_IPSEC:
3483 fill_cmd(cmd, O_IPSEC, 0, 0);
3484 break;
3485
3486 case TOK_COMMENT:
3487 fill_comment(cmd, ac, av);
3488 av += ac;
3489 ac = 0;
3490 break;
3491
3492 default:
3493 errx(EX_USAGE, "unrecognised option [%d] %s", i, s);
3494 }
3495 if (F_LEN(cmd) > 0) { /* prepare to advance */
3496 prev = cmd;
3497 cmd = next_cmd(cmd);
3498 }
3499 }
3500
3501done:
3502 /*
3503 * Now copy stuff into the rule.
3504 * If we have a keep-state option, the first instruction
3505 * must be a PROBE_STATE (which is generated here).
3506 * If we have a LOG option, it was stored as the first command,
3507 * and now must be moved to the top of the action part.
3508 */
3509 dst = (ipfw_insn *)rule->cmd;
3510
3511 /*
3512 * First thing to write into the command stream is the match probability.
3513 */
3514 if (match_prob != 1) { /* 1 means always match */
3515 dst->opcode = O_PROB;
3516 dst->len = 2;
3517 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3518 dst += dst->len;
3519 }
3520
3521 /*
3522 * generate O_PROBE_STATE if necessary
3523 */
3524 if (have_state && have_state->opcode != O_CHECK_STATE) {
3525 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3526 dst = next_cmd(dst);
3527 }
3528 /*
3529 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT
3530 */
3531 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3532 i = F_LEN(src);
3533
3534 switch (src->opcode) {
3535 case O_LOG:
3536 case O_KEEP_STATE:
3537 case O_LIMIT:
3538 break;
3539 default:
3540 bcopy(src, dst, i * sizeof(uint32_t));
3541 dst += i;
3542 }
3543 }
3544
3545 /*
3546 * put back the have_state command as last opcode
3547 */
3548 if (have_state && have_state->opcode != O_CHECK_STATE) {
3549 i = F_LEN(have_state);
3550 bcopy(have_state, dst, i * sizeof(uint32_t));
3551 dst += i;
3552 }
3553 /*
3554 * start action section
3555 */
3556 rule->act_ofs = dst - rule->cmd;
3557
3558 /*
3559 * put back O_LOG if necessary
3560 */
3561 src = (ipfw_insn *)cmdbuf;
3562 if (src->opcode == O_LOG) {
3563 i = F_LEN(src);
3564 bcopy(src, dst, i * sizeof(uint32_t));
3565 dst += i;
3566 }
3567 /*
3568 * copy all other actions
3569 */
3570 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3571 i = F_LEN(src);
3572 bcopy(src, dst, i * sizeof(uint32_t));
3573 dst += i;
3574 }
3575
3576 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
3577 i = (char *)dst - (char *)rule;
3578
3579 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
3580 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3581 if (!do_quiet)
3582 show_ipfw(rule, 0, 0);
3583}
3584
3585static void
3586zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */)
3587{
3588 struct ip_fw rule;
3589 int rulenum;
3590 int failed = EX_OK;
3591 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG";
3592
3593 av++; ac--;
3594 bzero(&rule, sizeof(rule));
3595
3596 if (!ac) {
3597 /* clear all entries - send empty rule */
3598 if (do_cmd(optname, &rule, sizeof(rule)) < 0)
3599 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
3600 if (!do_quiet)
3601 printf("%s.\n", optname == IP_FW_ZERO ?
3602 "Accounting cleared":"Logging counts reset");
3603
3604 return;
3605 }
3606
3607 while (ac) {
3608 /* Rule number */
3609 if (isdigit(**av)) {
3610 rulenum = atoi(*av);
3611 av++;
3612 ac--;
3613 rule.rulenum = rulenum;
3614 if (do_cmd(optname, &rule, sizeof(rule))) {
3615 warn("rule %u: setsockopt(IP_FW_%s)",
3616 rulenum, name);
3617 failed = EX_UNAVAILABLE;
3618 } else if (!do_quiet)
3619 printf("Entry %d %s.\n", rulenum,
3620 optname == IP_FW_ZERO ?
3621 "cleared" : "logging count reset");
3622 } else {
3623 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3624 }
3625 }
3626 if (failed != EX_OK)
3627 exit(failed);
3628}
3629
3630static void
3631flush(int force)
3632{
3633 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3634 struct ip_fw rule;
3635
3636 if (!force && !do_quiet) { /* need to ask user */
3637 int c;
3638
3639 printf("Are you sure? [yn] ");
3640 fflush(stdout);
3641 do {
3642 c = toupper(getc(stdin));
3643 while (c != '\n' && getc(stdin) != '\n')
3644 if (feof(stdin))
3645 return; /* and do not flush */
3646 } while (c != 'Y' && c != 'N');
3647 printf("\n");
3648 if (c == 'N') /* user said no */
3649 return;
3650 }
3651
3652 if (cmd == IP_FW_FLUSH) {
3653 /* send empty rule */
3654 bzero(&rule, sizeof(rule));
3655 if (do_cmd(cmd, &rule, sizeof(rule)) < 0)
3656 err(EX_UNAVAILABLE, "setsockopt(IP_FW_FLUSH)");
3657 }
3658 else {
3659 if (do_cmd(cmd, NULL, 0) < 0)
3660 err(EX_UNAVAILABLE, "setsockopt(IP_DUMMYNET_FLUSH)");
3661 }
3662 if (!do_quiet)
3663 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
3664}
3665
3666/*
3667 * Free a the (locally allocated) copy of command line arguments.
3668 */
3669static void
3670free_args(int ac, char **av)
3671{
3672 int i;
3673
3674 for (i=0; i < ac; i++)
3675 free(av[i]);
3676 free(av);
3677}
3678
3679/*
3680 * Called with the arguments (excluding program name).
3681 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
3682 */
3683static int
3684ipfw_main(int oldac, char **oldav)
3685{
3686 int ch, ac, save_ac;
3687 char **av, **save_av;
3688 int do_acct = 0; /* Show packet/byte count */
3689 int do_force = 0; /* Don't ask for confirmation */
3690
3691#define WHITESP " \t\f\v\n\r"
3692 if (oldac == 0)
3693 return 1;
3694 else if (oldac == 1) {
3695 /*
3696 * If we are called with a single string, try to split it into
3697 * arguments for subsequent parsing.
3698 * But first, remove spaces after a ',', by copying the string
3699 * in-place.
3700 */
3701 char *arg = oldav[0]; /* The string... */
3702 int l = strlen(arg);
3703 int copy = 0; /* 1 if we need to copy, 0 otherwise */
3704 int i, j;
3705 for (i = j = 0; i < l; i++) {
3706 if (arg[i] == '#') /* comment marker */
3707 break;
3708 if (copy) {
3709 arg[j++] = arg[i];
3710 copy = !index("," WHITESP, arg[i]);
3711 } else {
3712 copy = !index(WHITESP, arg[i]);
3713 if (copy)
3714 arg[j++] = arg[i];
3715 }
3716 }
3717 if (!copy && j > 0) /* last char was a 'blank', remove it */
3718 j--;
3719 l = j; /* the new argument length */
3720 arg[j++] = '\0';
3721 if (l == 0) /* empty string! */
3722 return 1;
3723
3724 /*
3725 * First, count number of arguments. Because of the previous
3726 * processing, this is just the number of blanks plus 1.
3727 */
3728 for (i = 0, ac = 1; i < l; i++)
3729 if (index(WHITESP, arg[i]) != NULL)
3730 ac++;
3731
3732 av = calloc(ac, sizeof(char *));
3733
3734 /*
3735 * Second, copy arguments from cmd[] to av[]. For each one,
3736 * j is the initial character, i is the one past the end.
3737 */
3738 for (ac = 0, i = j = 0; i < l; i++)
3739 if (index(WHITESP, arg[i]) != NULL || i == l-1) {
3740 if (i == l-1)
3741 i++;
3742 av[ac] = calloc(i-j+1, 1);
3743 bcopy(arg+j, av[ac], i-j);
3744 ac++;
3745 j = i + 1;
3746 }
3747 } else {
3748 /*
3749 * If an argument ends with ',' join with the next one.
3750 * Just add its length to 'l' and continue. When we have a string
3751 * without a ',' ending, we'll have the combined length in 'l'
3752 */
3753 int first, i, l;
3754
3755 av = calloc(oldac, sizeof(char *));
3756 for (first = i = ac = 0, l = 0; i < oldac; i++) {
3757 char *arg = oldav[i];
3758 int k = strlen(arg);
3759
3760 l += k;
3761 if (arg[k-1] != ',' || i == oldac-1) {
3762 int buflen = l+1;
3763 /* Time to copy. */
3764 av[ac] = calloc(l+1, 1);
3765 for (l=0; first <= i; first++) {
3766 strlcat(av[ac]+l, oldav[first], buflen-l);
3767 l += strlen(oldav[first]);
3768 }
3769 ac++;
3770 l = 0;
3771 first = i+1;
3772 }
3773 }
3774 }
3775
3776 /* Set the force flag for non-interactive processes */
3777 do_force = !isatty(STDIN_FILENO);
3778
3779 /* Save arguments for final freeing of memory. */
3780 save_ac = ac;
3781 save_av = av;
3782
3783 optind = optreset = 0;
3784 while ((ch = getopt(ac, av, "acdefhnNqs:STtv")) != -1)
3785 switch (ch) {
3786 case 'a':
3787 do_acct = 1;
3788 break;
3789
3790 case 'c':
3791 do_compact = 1;
3792 break;
3793
3794 case 'd':
3795 do_dynamic = 1;
3796 break;
3797
3798 case 'e':
3799 do_expired = 1;
3800 break;
3801
3802 case 'f':
3803 do_force = 1;
3804 break;
3805
3806 case 'h': /* help */
3807 free_args(save_ac, save_av);
3808 help();
3809 break; /* NOTREACHED */
3810
3811 case 'n':
3812 test_only = 1;
3813 break;
3814
3815 case 'N':
3816 do_resolv = 1;
3817 break;
3818
3819 case 'q':
3820 do_quiet = 1;
3821 break;
3822
3823 case 's': /* sort */
3824 do_sort = atoi(optarg);
3825 break;
3826
3827 case 'S':
3828 show_sets = 1;
3829 break;
3830
3831 case 't':
3832 do_time = 1;
3833 break;
3834
3835 case 'T':
3836 do_time = 2; /* numeric timestamp */
3837 break;
3838
3839 case 'v': /* verbose */
3840 verbose = 1;
3841 break;
3842
3843 default:
3844 free_args(save_ac, save_av);
3845 return 1;
3846 }
3847
3848 ac -= optind;
3849 av += optind;
3850 NEED1("bad arguments, for usage summary ``ipfw''");
3851
3852 /*
3853 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
3854 * e.g. "100 add allow ..." instead of "add 100 allow ...".
3855 * In case, swap first and second argument to get the normal form.
3856 */
3857 if (ac > 1 && isdigit(*av[0])) {
3858 char *p = av[0];
3859
3860 av[0] = av[1];
3861 av[1] = p;
3862 }
3863
3864 /*
3865 * optional: pipe or queue
3866 */
3867 do_pipe = 0;
3868 if (!strncmp(*av, "pipe", strlen(*av)))
3869 do_pipe = 1;
3870 else if (!strncmp(*av, "queue", strlen(*av)))
3871 do_pipe = 2;
3872 if (do_pipe) {
3873 ac--;
3874 av++;
3875 }
3876 NEED1("missing command");
3877
3878 /*
3879 * For pipes and queues we normally say 'pipe NN config'
3880 * but the code is easier to parse as 'pipe config NN'
3881 * so we swap the two arguments.
3882 */
3883 if (do_pipe > 0 && ac > 1 && isdigit(*av[0])) {
3884 char *p = av[0];
3885
3886 av[0] = av[1];
3887 av[1] = p;
3888 }
3889
3890 if (!strncmp(*av, "add", strlen(*av)))
3891 add(ac, av);
3892 else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
3893 config_pipe(ac, av);
3894 else if (!strncmp(*av, "delete", strlen(*av)))
3895 delete(ac, av);
3896 else if (!strncmp(*av, "flush", strlen(*av)))
3897 flush(do_force);
3898 else if (!strncmp(*av, "zero", strlen(*av)))
3899 zero(ac, av, IP_FW_ZERO);
3900 else if (!strncmp(*av, "resetlog", strlen(*av)))
3901 zero(ac, av, IP_FW_RESETLOG);
3902 else if (!strncmp(*av, "print", strlen(*av)) ||
3903 !strncmp(*av, "list", strlen(*av)))
3904 list(ac, av, do_acct);
3905 else if (!strncmp(*av, "set", strlen(*av)))
3906 sets_handler(ac, av);
3907 else if (!strncmp(*av, "enable", strlen(*av)))
3908 sysctl_handler(ac, av, 1);
3909 else if (!strncmp(*av, "disable", strlen(*av)))
3910 sysctl_handler(ac, av, 0);
3911 else if (!strncmp(*av, "show", strlen(*av)))
3912 list(ac, av, 1 /* show counters */);
3913 else
3914 errx(EX_USAGE, "bad command `%s'", *av);
3915
3916 /* Free memory allocated in the argument parsing. */
3917 free_args(save_ac, save_av);
3918 return 0;
3919}
3920
3921
3922static void
3923ipfw_readfile(int ac, char *av[])
3924{
3925#define MAX_ARGS 32
3926 char buf[BUFSIZ];
3927 char *cmd = NULL, *filename = av[ac-1];
3928 int c, lineno=0;
3929 FILE *f = NULL;
3930 pid_t preproc = 0;
3931
3932 filename = av[ac-1];
3933
3934 while ((c = getopt(ac, av, "cNnp:qS")) != -1) {
3935 switch(c) {
3936 case 'c':
3937 do_compact = 1;
3938 break;
3939
3940 case 'N':
3941 do_resolv = 1;
3942 break;
3943
3944 case 'n':
3945 test_only = 1;
3946 break;
3947
3948 case 'p':
3949 cmd = optarg;
3950 /*
3951 * Skip previous args and delete last one, so we
3952 * pass all but the last argument to the preprocessor
3953 * via av[optind-1]
3954 */
3955 av += optind - 1;
3956 ac -= optind - 1;
3957 av[ac-1] = NULL;
3958 fprintf(stderr, "command is %s\n", av[0]);
3959 break;
3960
3961 case 'q':
3962 do_quiet = 1;
3963 break;
3964
3965 case 'S':
3966 show_sets = 1;
3967 break;
3968
3969 default:
3970 errx(EX_USAGE, "bad arguments, for usage"
3971 " summary ``ipfw''");
3972 }
3973
3974 if (cmd != NULL)
3975 break;
3976 }
3977
3978 if (cmd == NULL && ac != optind + 1) {
3979 fprintf(stderr, "ac %d, optind %d\n", ac, optind);
3980 errx(EX_USAGE, "extraneous filename arguments");
3981 }
3982
3983 if ((f = fopen(filename, "r")) == NULL)
3984 err(EX_UNAVAILABLE, "fopen: %s", filename);
3985
3986 if (cmd != NULL) { /* pipe through preprocessor */
3987 int pipedes[2];
3988
3989 if (pipe(pipedes) == -1)
3990 err(EX_OSERR, "cannot create pipe");
3991
3992 preproc = fork();
3993 if (preproc == -1)
3994 err(EX_OSERR, "cannot fork");
3995
3996 if (preproc == 0) {
3997 /*
3998 * Child, will run the preprocessor with the
3999 * file on stdin and the pipe on stdout.
4000 */
4001 if (dup2(fileno(f), 0) == -1
4002 || dup2(pipedes[1], 1) == -1)
4003 err(EX_OSERR, "dup2()");
4004 fclose(f);
4005 close(pipedes[1]);
4006 close(pipedes[0]);
4007 execvp(cmd, av);
4008 err(EX_OSERR, "execvp(%s) failed", cmd);
4009 } else { /* parent, will reopen f as the pipe */
4010 fclose(f);
4011 close(pipedes[1]);
4012 if ((f = fdopen(pipedes[0], "r")) == NULL) {
4013 int savederrno = errno;
4014
4015 (void)kill(preproc, SIGTERM);
4016 errno = savederrno;
4017 err(EX_OSERR, "fdopen()");
4018 }
4019 }
4020 }
4021
4022 while (fgets(buf, BUFSIZ, f)) { /* read commands */
4023 char linename[16];
4024 char *args[1];
4025
4026 lineno++;
4027 snprintf(linename, sizeof(linename), "Line %d", lineno);
4028 setprogname(linename); /* XXX */
4029 args[0] = buf;
4030 ipfw_main(1, args);
4031 }
4032 fclose(f);
4033 if (cmd != NULL) {
4034 int status;
4035
4036 if (waitpid(preproc, &status, 0) == -1)
4037 errx(EX_OSERR, "waitpid()");
4038 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
4039 errx(EX_UNAVAILABLE,
4040 "preprocessor exited with status %d",
4041 WEXITSTATUS(status));
4042 else if (WIFSIGNALED(status))
4043 errx(EX_UNAVAILABLE,
4044 "preprocessor exited with signal %d",
4045 WTERMSIG(status));
4046 }
4047}
4048
4049int
4050main(int ac, char *av[])
4051{
4052 /*
4053 * If the last argument is an absolute pathname, interpret it
4054 * as a file to be preprocessed.
4055 */
4056
4057 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
4058 ipfw_readfile(ac, av);
4059 else {
4060 if (ipfw_main(ac-1, av+1))
4061 show_usage();
4062 }
4063 return EX_OK;
4064}