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