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