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