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