]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/ipfw/ipfw2.c
MFH @ 186335
[FreeBSD/FreeBSD.git] / sbin / ipfw / ipfw2.c
1 /*
2  * Copyright (c) 2002-2003 Luigi Rizzo
3  * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4  * Copyright (c) 1994 Ugen J.S.Antsilevich
5  *
6  * Idea and grammar partially left from:
7  * Copyright (c) 1993 Daniel Boulet
8  *
9  * Redistribution and use in source forms, with and without modification,
10  * are permitted provided that this entire comment appears intact.
11  *
12  * Redistribution in binary form may occur without any restrictions.
13  * Obviously, it would be nice if you gave credit where credit is due
14  * but requiring it would be too onerous.
15  *
16  * This software is provided ``AS IS'' without any warranties of any kind.
17  *
18  * NEW command line interface for IP firewall facility
19  *
20  * $FreeBSD$
21  */
22
23 #include <sys/param.h>
24 #include <sys/mbuf.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
28 #include <sys/time.h>
29 #include <sys/wait.h>
30 #include <sys/queue.h>
31
32 #include <ctype.h>
33 #include <err.h>
34 #include <errno.h>
35 #include <grp.h>
36 #include <limits.h>
37 #include <netdb.h>
38 #include <pwd.h>
39 #include <signal.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <timeconv.h>   /* XXX do we need this ? */
45 #include <unistd.h>
46 #include <sysexits.h>
47 #include <unistd.h>
48 #include <fcntl.h>
49
50 #define IPFW_INTERNAL   /* Access to protected structures in ip_fw.h. */
51
52 #include <net/ethernet.h>
53 #include <net/if.h>
54 #include <net/if_dl.h>
55 #include <net/pfvar.h>
56 #include <net/route.h> /* def. of struct route */
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_icmp.h>
61 #include <netinet/icmp6.h>
62 #include <netinet/ip_fw.h>
63 #include <netinet/ip_dummynet.h>
64 #include <netinet/tcp.h>
65 #include <arpa/inet.h>
66 #include <alias.h>
67
68 int
69                 do_value_as_ip,         /* show table value as IP */
70                 do_resolv,              /* Would try to resolve all */
71                 do_time,                /* Show time stamps */
72                 do_quiet,               /* Be quiet in add and flush */
73                 do_pipe,                /* this cmd refers to a pipe */
74                 do_nat,                 /* Nat configuration. */
75                 do_sort,                /* field to sort results (0 = no) */
76                 do_dynamic,             /* display dynamic rules */
77                 do_expired,             /* display expired dynamic rules */
78                 do_compact,             /* show rules in compact mode */
79                 do_force,               /* do not ask for confirmation */
80                 use_set,                /* work with specified set number */
81                 show_sets,              /* display rule sets */
82                 test_only,              /* only check syntax */
83                 comment_only,           /* only print action and comment */
84                 verbose;
85
86 #define IP_MASK_ALL     0xffffffff
87 /*
88  * the following macro returns an error message if we run out of
89  * arguments.
90  */
91 #define NEED1(msg)      {if (!ac) errx(EX_USAGE, msg);}
92
93 #define GET_UINT_ARG(arg, min, max, tok, s_x) do {                      \
94         if (!ac)                                                        \
95                 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
96         if (_substrcmp(*av, "tablearg") == 0) {                         \
97                 arg = IP_FW_TABLEARG;                                   \
98                 break;                                                  \
99         }                                                               \
100                                                                         \
101         {                                                               \
102         long val;                                                       \
103         char *end;                                                      \
104                                                                         \
105         val = strtol(*av, &end, 10);                                    \
106                                                                         \
107         if (!isdigit(**av) || *end != '\0' || (val == 0 && errno == EINVAL)) \
108                 errx(EX_DATAERR, "%s: invalid argument: %s",            \
109                     match_value(s_x, tok), *av);                        \
110                                                                         \
111         if (errno == ERANGE || val < min || val > max)                  \
112                 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
113                     match_value(s_x, tok), min, max, *av);              \
114                                                                         \
115         if (val == IP_FW_TABLEARG)                                      \
116                 errx(EX_DATAERR, "%s: illegal argument value: %s",      \
117                     match_value(s_x, tok), *av);                        \
118         arg = val;                                                      \
119         }                                                               \
120 } while (0)
121
122 #define PRINT_UINT_ARG(str, arg) do {                                   \
123         if (str != NULL)                                                \
124                 printf("%s",str);                                       \
125         if (arg == IP_FW_TABLEARG)                                      \
126                 printf("tablearg");                                     \
127         else                                                            \
128                 printf("%u", (uint32_t)arg);                            \
129 } while (0)
130
131 /*
132  * _s_x is a structure that stores a string <-> token pairs, used in
133  * various places in the parser. Entries are stored in arrays,
134  * with an entry with s=NULL as terminator.
135  * The search routines are match_token() and match_value().
136  * Often, an element with x=0 contains an error string.
137  *
138  */
139 struct _s_x {
140         char const *s;
141         int x;
142 };
143
144 static struct _s_x f_tcpflags[] = {
145         { "syn", TH_SYN },
146         { "fin", TH_FIN },
147         { "ack", TH_ACK },
148         { "psh", TH_PUSH },
149         { "rst", TH_RST },
150         { "urg", TH_URG },
151         { "tcp flag", 0 },
152         { NULL, 0 }
153 };
154
155 static struct _s_x f_tcpopts[] = {
156         { "mss",        IP_FW_TCPOPT_MSS },
157         { "maxseg",     IP_FW_TCPOPT_MSS },
158         { "window",     IP_FW_TCPOPT_WINDOW },
159         { "sack",       IP_FW_TCPOPT_SACK },
160         { "ts",         IP_FW_TCPOPT_TS },
161         { "timestamp",  IP_FW_TCPOPT_TS },
162         { "cc",         IP_FW_TCPOPT_CC },
163         { "tcp option", 0 },
164         { NULL, 0 }
165 };
166
167 /*
168  * IP options span the range 0 to 255 so we need to remap them
169  * (though in fact only the low 5 bits are significant).
170  */
171 static struct _s_x f_ipopts[] = {
172         { "ssrr",       IP_FW_IPOPT_SSRR},
173         { "lsrr",       IP_FW_IPOPT_LSRR},
174         { "rr",         IP_FW_IPOPT_RR},
175         { "ts",         IP_FW_IPOPT_TS},
176         { "ip option",  0 },
177         { NULL, 0 }
178 };
179
180 static struct _s_x f_iptos[] = {
181         { "lowdelay",   IPTOS_LOWDELAY},
182         { "throughput", IPTOS_THROUGHPUT},
183         { "reliability", IPTOS_RELIABILITY},
184         { "mincost",    IPTOS_MINCOST},
185         { "congestion", IPTOS_ECN_CE},
186         { "ecntransport", IPTOS_ECN_ECT0},
187         { "ip tos option", 0},
188         { NULL, 0 }
189 };
190
191 static struct _s_x limit_masks[] = {
192         {"all",         DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
193         {"src-addr",    DYN_SRC_ADDR},
194         {"src-port",    DYN_SRC_PORT},
195         {"dst-addr",    DYN_DST_ADDR},
196         {"dst-port",    DYN_DST_PORT},
197         {NULL,          0}
198 };
199
200 /*
201  * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
202  * This is only used in this code.
203  */
204 #define IPPROTO_ETHERTYPE       0x1000
205 static struct _s_x ether_types[] = {
206     /*
207      * Note, we cannot use "-:&/" in the names because they are field
208      * separators in the type specifications. Also, we use s = NULL as
209      * end-delimiter, because a type of 0 can be legal.
210      */
211         { "ip",         0x0800 },
212         { "ipv4",       0x0800 },
213         { "ipv6",       0x86dd },
214         { "arp",        0x0806 },
215         { "rarp",       0x8035 },
216         { "vlan",       0x8100 },
217         { "loop",       0x9000 },
218         { "trail",      0x1000 },
219         { "at",         0x809b },
220         { "atalk",      0x809b },
221         { "aarp",       0x80f3 },
222         { "pppoe_disc", 0x8863 },
223         { "pppoe_sess", 0x8864 },
224         { "ipx_8022",   0x00E0 },
225         { "ipx_8023",   0x0000 },
226         { "ipx_ii",     0x8137 },
227         { "ipx_snap",   0x8137 },
228         { "ipx",        0x8137 },
229         { "ns",         0x0600 },
230         { NULL,         0 }
231 };
232
233 static void show_usage(void);
234
235 enum tokens {
236         TOK_NULL=0,
237
238         TOK_OR,
239         TOK_NOT,
240         TOK_STARTBRACE,
241         TOK_ENDBRACE,
242
243         TOK_ACCEPT,
244         TOK_COUNT,
245         TOK_PIPE,
246         TOK_QUEUE,
247         TOK_DIVERT,
248         TOK_TEE,
249         TOK_NETGRAPH,
250         TOK_NGTEE,
251         TOK_FORWARD,
252         TOK_SKIPTO,
253         TOK_DENY,
254         TOK_REJECT,
255         TOK_RESET,
256         TOK_UNREACH,
257         TOK_CHECKSTATE,
258         TOK_NAT,
259
260         TOK_ALTQ,
261         TOK_LOG,
262         TOK_TAG,
263         TOK_UNTAG,
264
265         TOK_TAGGED,
266         TOK_UID,
267         TOK_GID,
268         TOK_JAIL,
269         TOK_IN,
270         TOK_LIMIT,
271         TOK_KEEPSTATE,
272         TOK_LAYER2,
273         TOK_OUT,
274         TOK_DIVERTED,
275         TOK_DIVERTEDLOOPBACK,
276         TOK_DIVERTEDOUTPUT,
277         TOK_XMIT,
278         TOK_RECV,
279         TOK_VIA,
280         TOK_FRAG,
281         TOK_IPOPTS,
282         TOK_IPLEN,
283         TOK_IPID,
284         TOK_IPPRECEDENCE,
285         TOK_IPTOS,
286         TOK_IPTTL,
287         TOK_IPVER,
288         TOK_ESTAB,
289         TOK_SETUP,
290         TOK_TCPDATALEN,
291         TOK_TCPFLAGS,
292         TOK_TCPOPTS,
293         TOK_TCPSEQ,
294         TOK_TCPACK,
295         TOK_TCPWIN,
296         TOK_ICMPTYPES,
297         TOK_MAC,
298         TOK_MACTYPE,
299         TOK_VERREVPATH,
300         TOK_VERSRCREACH,
301         TOK_ANTISPOOF,
302         TOK_IPSEC,
303         TOK_COMMENT,
304
305         TOK_PLR,
306         TOK_NOERROR,
307         TOK_BUCKETS,
308         TOK_DSTIP,
309         TOK_SRCIP,
310         TOK_DSTPORT,
311         TOK_SRCPORT,
312         TOK_ALL,
313         TOK_MASK,
314         TOK_BW,
315         TOK_DELAY,
316         TOK_RED,
317         TOK_GRED,
318         TOK_DROPTAIL,
319         TOK_PROTO,
320         TOK_WEIGHT,
321         TOK_IP,
322         TOK_IF,
323         TOK_ALOG,
324         TOK_DENY_INC,
325         TOK_SAME_PORTS,
326         TOK_UNREG_ONLY,
327         TOK_RESET_ADDR,
328         TOK_ALIAS_REV,
329         TOK_PROXY_ONLY,
330         TOK_REDIR_ADDR,
331         TOK_REDIR_PORT,
332         TOK_REDIR_PROTO,        
333
334         TOK_IPV6,
335         TOK_FLOWID,
336         TOK_ICMP6TYPES,
337         TOK_EXT6HDR,
338         TOK_DSTIP6,
339         TOK_SRCIP6,
340
341         TOK_IPV4,
342         TOK_UNREACH6,
343         TOK_RESET6,
344
345         TOK_FIB,
346         TOK_SETFIB,
347 };
348
349 struct _s_x dummynet_params[] = {
350         { "plr",                TOK_PLR },
351         { "noerror",            TOK_NOERROR },
352         { "buckets",            TOK_BUCKETS },
353         { "dst-ip",             TOK_DSTIP },
354         { "src-ip",             TOK_SRCIP },
355         { "dst-port",           TOK_DSTPORT },
356         { "src-port",           TOK_SRCPORT },
357         { "proto",              TOK_PROTO },
358         { "weight",             TOK_WEIGHT },
359         { "all",                TOK_ALL },
360         { "mask",               TOK_MASK },
361         { "droptail",           TOK_DROPTAIL },
362         { "red",                TOK_RED },
363         { "gred",               TOK_GRED },
364         { "bw",                 TOK_BW },
365         { "bandwidth",          TOK_BW },
366         { "delay",              TOK_DELAY },
367         { "pipe",               TOK_PIPE },
368         { "queue",              TOK_QUEUE },
369         { "flow-id",            TOK_FLOWID},
370         { "dst-ipv6",           TOK_DSTIP6},
371         { "dst-ip6",            TOK_DSTIP6},
372         { "src-ipv6",           TOK_SRCIP6},
373         { "src-ip6",            TOK_SRCIP6},
374         { "dummynet-params",    TOK_NULL },
375         { NULL, 0 }     /* terminator */
376 };
377
378 struct _s_x nat_params[] = {
379         { "ip",                 TOK_IP },
380         { "if",                 TOK_IF },
381         { "log",                TOK_ALOG },
382         { "deny_in",            TOK_DENY_INC },
383         { "same_ports",         TOK_SAME_PORTS },
384         { "unreg_only",         TOK_UNREG_ONLY },
385         { "reset",              TOK_RESET_ADDR },
386         { "reverse",            TOK_ALIAS_REV },        
387         { "proxy_only",         TOK_PROXY_ONLY },
388         { "redirect_addr",      TOK_REDIR_ADDR },
389         { "redirect_port",      TOK_REDIR_PORT },
390         { "redirect_proto",     TOK_REDIR_PROTO },
391         { NULL, 0 }     /* terminator */
392 };
393
394 struct _s_x rule_actions[] = {
395         { "accept",             TOK_ACCEPT },
396         { "pass",               TOK_ACCEPT },
397         { "allow",              TOK_ACCEPT },
398         { "permit",             TOK_ACCEPT },
399         { "count",              TOK_COUNT },
400         { "pipe",               TOK_PIPE },
401         { "queue",              TOK_QUEUE },
402         { "divert",             TOK_DIVERT },
403         { "tee",                TOK_TEE },
404         { "netgraph",           TOK_NETGRAPH },
405         { "ngtee",              TOK_NGTEE },
406         { "fwd",                TOK_FORWARD },
407         { "forward",            TOK_FORWARD },
408         { "skipto",             TOK_SKIPTO },
409         { "deny",               TOK_DENY },
410         { "drop",               TOK_DENY },
411         { "reject",             TOK_REJECT },
412         { "reset6",             TOK_RESET6 },
413         { "reset",              TOK_RESET },
414         { "unreach6",           TOK_UNREACH6 },
415         { "unreach",            TOK_UNREACH },
416         { "check-state",        TOK_CHECKSTATE },
417         { "//",                 TOK_COMMENT },
418         { "nat",                TOK_NAT },
419         { "setfib",             TOK_SETFIB },
420         { NULL, 0 }     /* terminator */
421 };
422
423 struct _s_x rule_action_params[] = {
424         { "altq",               TOK_ALTQ },
425         { "log",                TOK_LOG },
426         { "tag",                TOK_TAG },
427         { "untag",              TOK_UNTAG },
428         { NULL, 0 }     /* terminator */
429 };
430
431 struct _s_x rule_options[] = {
432         { "tagged",             TOK_TAGGED },
433         { "uid",                TOK_UID },
434         { "gid",                TOK_GID },
435         { "jail",               TOK_JAIL },
436         { "in",                 TOK_IN },
437         { "limit",              TOK_LIMIT },
438         { "keep-state",         TOK_KEEPSTATE },
439         { "bridged",            TOK_LAYER2 },
440         { "layer2",             TOK_LAYER2 },
441         { "out",                TOK_OUT },
442         { "diverted",           TOK_DIVERTED },
443         { "diverted-loopback",  TOK_DIVERTEDLOOPBACK },
444         { "diverted-output",    TOK_DIVERTEDOUTPUT },
445         { "xmit",               TOK_XMIT },
446         { "recv",               TOK_RECV },
447         { "via",                TOK_VIA },
448         { "fragment",           TOK_FRAG },
449         { "frag",               TOK_FRAG },
450         { "fib",                TOK_FIB },
451         { "ipoptions",          TOK_IPOPTS },
452         { "ipopts",             TOK_IPOPTS },
453         { "iplen",              TOK_IPLEN },
454         { "ipid",               TOK_IPID },
455         { "ipprecedence",       TOK_IPPRECEDENCE },
456         { "iptos",              TOK_IPTOS },
457         { "ipttl",              TOK_IPTTL },
458         { "ipversion",          TOK_IPVER },
459         { "ipver",              TOK_IPVER },
460         { "estab",              TOK_ESTAB },
461         { "established",        TOK_ESTAB },
462         { "setup",              TOK_SETUP },
463         { "tcpdatalen",         TOK_TCPDATALEN },
464         { "tcpflags",           TOK_TCPFLAGS },
465         { "tcpflgs",            TOK_TCPFLAGS },
466         { "tcpoptions",         TOK_TCPOPTS },
467         { "tcpopts",            TOK_TCPOPTS },
468         { "tcpseq",             TOK_TCPSEQ },
469         { "tcpack",             TOK_TCPACK },
470         { "tcpwin",             TOK_TCPWIN },
471         { "icmptype",           TOK_ICMPTYPES },
472         { "icmptypes",          TOK_ICMPTYPES },
473         { "dst-ip",             TOK_DSTIP },
474         { "src-ip",             TOK_SRCIP },
475         { "dst-port",           TOK_DSTPORT },
476         { "src-port",           TOK_SRCPORT },
477         { "proto",              TOK_PROTO },
478         { "MAC",                TOK_MAC },
479         { "mac",                TOK_MAC },
480         { "mac-type",           TOK_MACTYPE },
481         { "verrevpath",         TOK_VERREVPATH },
482         { "versrcreach",        TOK_VERSRCREACH },
483         { "antispoof",          TOK_ANTISPOOF },
484         { "ipsec",              TOK_IPSEC },
485         { "icmp6type",          TOK_ICMP6TYPES },
486         { "icmp6types",         TOK_ICMP6TYPES },
487         { "ext6hdr",            TOK_EXT6HDR},
488         { "flow-id",            TOK_FLOWID},
489         { "ipv6",               TOK_IPV6},
490         { "ip6",                TOK_IPV6},
491         { "ipv4",               TOK_IPV4},
492         { "ip4",                TOK_IPV4},
493         { "dst-ipv6",           TOK_DSTIP6},
494         { "dst-ip6",            TOK_DSTIP6},
495         { "src-ipv6",           TOK_SRCIP6},
496         { "src-ip6",            TOK_SRCIP6},
497         { "//",                 TOK_COMMENT },
498
499         { "not",                TOK_NOT },              /* pseudo option */
500         { "!", /* escape ? */   TOK_NOT },              /* pseudo option */
501         { "or",                 TOK_OR },               /* pseudo option */
502         { "|", /* escape */     TOK_OR },               /* pseudo option */
503         { "{",                  TOK_STARTBRACE },       /* pseudo option */
504         { "(",                  TOK_STARTBRACE },       /* pseudo option */
505         { "}",                  TOK_ENDBRACE },         /* pseudo option */
506         { ")",                  TOK_ENDBRACE },         /* pseudo option */
507         { NULL, 0 }     /* terminator */
508 };
509
510 #define TABLEARG        "tablearg"
511
512 static __inline uint64_t
513 align_uint64(uint64_t *pll) {
514         uint64_t ret;
515
516         bcopy (pll, &ret, sizeof(ret));
517         return ret;
518 }
519
520 /*
521  * conditionally runs the command.
522  */
523 static int
524 do_cmd(int optname, void *optval, uintptr_t optlen)
525 {
526         static int s = -1;      /* the socket */
527         int i;
528
529         if (test_only)
530                 return 0;
531
532         if (s == -1)
533                 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
534         if (s < 0)
535                 err(EX_UNAVAILABLE, "socket");
536
537         if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
538             optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
539             optname == IP_FW_TABLE_GETSIZE || 
540             optname == IP_FW_NAT_GET_CONFIG || 
541             optname == IP_FW_NAT_GET_LOG)
542                 i = getsockopt(s, IPPROTO_IP, optname, optval,
543                         (socklen_t *)optlen);
544         else
545                 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
546         return i;
547 }
548
549 /**
550  * match_token takes a table and a string, returns the value associated
551  * with the string (-1 in case of failure).
552  */
553 static int
554 match_token(struct _s_x *table, char *string)
555 {
556         struct _s_x *pt;
557         uint i = strlen(string);
558
559         for (pt = table ; i && pt->s != NULL ; pt++)
560                 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
561                         return pt->x;
562         return -1;
563 }
564
565 /**
566  * match_value takes a table and a value, returns the string associated
567  * with the value (NULL in case of failure).
568  */
569 static char const *
570 match_value(struct _s_x *p, int value)
571 {
572         for (; p->s != NULL; p++)
573                 if (p->x == value)
574                         return p->s;
575         return NULL;
576 }
577
578 /*
579  * _substrcmp takes two strings and returns 1 if they do not match,
580  * and 0 if they match exactly or the first string is a sub-string
581  * of the second.  A warning is printed to stderr in the case that the
582  * first string is a sub-string of the second.
583  *
584  * This function will be removed in the future through the usual
585  * deprecation process.
586  */
587 static int
588 _substrcmp(const char *str1, const char* str2)
589 {
590         
591         if (strncmp(str1, str2, strlen(str1)) != 0)
592                 return 1;
593
594         if (strlen(str1) != strlen(str2))
595                 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
596                     str1, str2);
597         return 0;
598 }
599
600 /*
601  * _substrcmp2 takes three strings and returns 1 if the first two do not match,
602  * and 0 if they match exactly or the second string is a sub-string
603  * of the first.  A warning is printed to stderr in the case that the
604  * first string does not match the third.
605  *
606  * This function exists to warn about the bizzare construction
607  * strncmp(str, "by", 2) which is used to allow people to use a shotcut
608  * for "bytes".  The problem is that in addition to accepting "by",
609  * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
610  * other string beginning with "by".
611  *
612  * This function will be removed in the future through the usual
613  * deprecation process.
614  */
615 static int
616 _substrcmp2(const char *str1, const char* str2, const char* str3)
617 {
618         
619         if (strncmp(str1, str2, strlen(str2)) != 0)
620                 return 1;
621
622         if (strcmp(str1, str3) != 0)
623                 warnx("DEPRECATED: '%s' matched '%s'",
624                     str1, str3);
625         return 0;
626 }
627
628 /*
629  * prints one port, symbolic or numeric
630  */
631 static void
632 print_port(int proto, uint16_t port)
633 {
634
635         if (proto == IPPROTO_ETHERTYPE) {
636                 char const *s;
637
638                 if (do_resolv && (s = match_value(ether_types, port)) )
639                         printf("%s", s);
640                 else
641                         printf("0x%04x", port);
642         } else {
643                 struct servent *se = NULL;
644                 if (do_resolv) {
645                         struct protoent *pe = getprotobynumber(proto);
646
647                         se = getservbyport(htons(port), pe ? pe->p_name : NULL);
648                 }
649                 if (se)
650                         printf("%s", se->s_name);
651                 else
652                         printf("%d", port);
653         }
654 }
655
656 struct _s_x _port_name[] = {
657         {"dst-port",    O_IP_DSTPORT},
658         {"src-port",    O_IP_SRCPORT},
659         {"ipid",        O_IPID},
660         {"iplen",       O_IPLEN},
661         {"ipttl",       O_IPTTL},
662         {"mac-type",    O_MAC_TYPE},
663         {"tcpdatalen",  O_TCPDATALEN},
664         {"tagged",      O_TAGGED},
665         {NULL,          0}
666 };
667
668 /*
669  * Print the values in a list 16-bit items of the types above.
670  * XXX todo: add support for mask.
671  */
672 static void
673 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
674 {
675         uint16_t *p = cmd->ports;
676         int i;
677         char const *sep;
678
679         if (opcode != 0) {
680                 sep = match_value(_port_name, opcode);
681                 if (sep == NULL)
682                         sep = "???";
683                 printf (" %s", sep);
684         }
685         sep = " ";
686         for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
687                 printf(sep);
688                 print_port(proto, p[0]);
689                 if (p[0] != p[1]) {
690                         printf("-");
691                         print_port(proto, p[1]);
692                 }
693                 sep = ",";
694         }
695 }
696
697 /*
698  * Like strtol, but also translates service names into port numbers
699  * for some protocols.
700  * In particular:
701  *      proto == -1 disables the protocol check;
702  *      proto == IPPROTO_ETHERTYPE looks up an internal table
703  *      proto == <some value in /etc/protocols> matches the values there.
704  * Returns *end == s in case the parameter is not found.
705  */
706 static int
707 strtoport(char *s, char **end, int base, int proto)
708 {
709         char *p, *buf;
710         char *s1;
711         int i;
712
713         *end = s;               /* default - not found */
714         if (*s == '\0')
715                 return 0;       /* not found */
716
717         if (isdigit(*s))
718                 return strtol(s, end, base);
719
720         /*
721          * find separator. '\\' escapes the next char.
722          */
723         for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
724                 if (*s1 == '\\' && s1[1] != '\0')
725                         s1++;
726
727         buf = malloc(s1 - s + 1);
728         if (buf == NULL)
729                 return 0;
730
731         /*
732          * copy into a buffer skipping backslashes
733          */
734         for (p = s, i = 0; p != s1 ; p++)
735                 if (*p != '\\')
736                         buf[i++] = *p;
737         buf[i++] = '\0';
738
739         if (proto == IPPROTO_ETHERTYPE) {
740                 i = match_token(ether_types, buf);
741                 free(buf);
742                 if (i != -1) {  /* found */
743                         *end = s1;
744                         return i;
745                 }
746         } else {
747                 struct protoent *pe = NULL;
748                 struct servent *se;
749
750                 if (proto != 0)
751                         pe = getprotobynumber(proto);
752                 setservent(1);
753                 se = getservbyname(buf, pe ? pe->p_name : NULL);
754                 free(buf);
755                 if (se != NULL) {
756                         *end = s1;
757                         return ntohs(se->s_port);
758                 }
759         }
760         return 0;       /* not found */
761 }
762
763 /*
764  * Map between current altq queue id numbers and names.
765  */
766 static int altq_fetched = 0;
767 static TAILQ_HEAD(, pf_altq) altq_entries = 
768         TAILQ_HEAD_INITIALIZER(altq_entries);
769
770 static void
771 altq_set_enabled(int enabled)
772 {
773         int pffd;
774
775         pffd = open("/dev/pf", O_RDWR);
776         if (pffd == -1)
777                 err(EX_UNAVAILABLE,
778                     "altq support opening pf(4) control device");
779         if (enabled) {
780                 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST)
781                         err(EX_UNAVAILABLE, "enabling altq");
782         } else {
783                 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT)
784                         err(EX_UNAVAILABLE, "disabling altq");
785         }
786         close(pffd);
787 }
788
789 static void
790 altq_fetch()
791 {
792         struct pfioc_altq pfioc;
793         struct pf_altq *altq;
794         int pffd, mnr;
795
796         if (altq_fetched)
797                 return;
798         altq_fetched = 1;
799         pffd = open("/dev/pf", O_RDONLY);
800         if (pffd == -1) {
801                 warn("altq support opening pf(4) control device");
802                 return;
803         }
804         bzero(&pfioc, sizeof(pfioc));
805         if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) {
806                 warn("altq support getting queue list");
807                 close(pffd);
808                 return;
809         }
810         mnr = pfioc.nr;
811         for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) {
812                 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) {
813                         if (errno == EBUSY)
814                                 break;
815                         warn("altq support getting queue list");
816                         close(pffd);
817                         return;
818                 }
819                 if (pfioc.altq.qid == 0)
820                         continue;
821                 altq = malloc(sizeof(*altq));
822                 if (altq == NULL)
823                         err(EX_OSERR, "malloc");
824                 *altq = pfioc.altq;
825                 TAILQ_INSERT_TAIL(&altq_entries, altq, entries);
826         }
827         close(pffd);
828 }
829
830 static u_int32_t
831 altq_name_to_qid(const char *name)
832 {
833         struct pf_altq *altq;
834
835         altq_fetch();
836         TAILQ_FOREACH(altq, &altq_entries, entries)
837                 if (strcmp(name, altq->qname) == 0)
838                         break;
839         if (altq == NULL)
840                 errx(EX_DATAERR, "altq has no queue named `%s'", name);
841         return altq->qid;
842 }
843
844 static const char *
845 altq_qid_to_name(u_int32_t qid)
846 {
847         struct pf_altq *altq;
848
849         altq_fetch();
850         TAILQ_FOREACH(altq, &altq_entries, entries)
851                 if (qid == altq->qid)
852                         break;
853         if (altq == NULL)
854                 return NULL;
855         return altq->qname;
856 }
857
858 static void
859 fill_altq_qid(u_int32_t *qid, const char *av)
860 {
861         *qid = altq_name_to_qid(av);
862 }
863
864 /*
865  * Fill the body of the command with the list of port ranges.
866  */
867 static int
868 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
869 {
870         uint16_t a, b, *p = cmd->ports;
871         int i = 0;
872         char *s = av;
873
874         while (*s) {
875                 a = strtoport(av, &s, 0, proto);
876                 if (s == av)                    /* empty or invalid argument */
877                         return (0);
878
879                 switch (*s) {
880                 case '-':                       /* a range */
881                         av = s + 1;
882                         b = strtoport(av, &s, 0, proto);
883                         /* Reject expressions like '1-abc' or '1-2-3'. */
884                         if (s == av || (*s != ',' && *s != '\0'))
885                                 return (0);
886                         p[0] = a;
887                         p[1] = b;
888                         break;
889                 case ',':                       /* comma separated list */
890                 case '\0':
891                         p[0] = p[1] = a;
892                         break;
893                 default:
894                         warnx("port list: invalid separator <%c> in <%s>",
895                                 *s, av);
896                         return (0);
897                 }
898
899                 i++;
900                 p += 2;
901                 av = s + 1;
902         }
903         if (i > 0) {
904                 if (i + 1 > F_LEN_MASK)
905                         errx(EX_DATAERR, "too many ports/ranges\n");
906                 cmd->o.len |= i + 1;    /* leave F_NOT and F_OR untouched */
907         }
908         return (i);
909 }
910
911 static struct _s_x icmpcodes[] = {
912       { "net",                  ICMP_UNREACH_NET },
913       { "host",                 ICMP_UNREACH_HOST },
914       { "protocol",             ICMP_UNREACH_PROTOCOL },
915       { "port",                 ICMP_UNREACH_PORT },
916       { "needfrag",             ICMP_UNREACH_NEEDFRAG },
917       { "srcfail",              ICMP_UNREACH_SRCFAIL },
918       { "net-unknown",          ICMP_UNREACH_NET_UNKNOWN },
919       { "host-unknown",         ICMP_UNREACH_HOST_UNKNOWN },
920       { "isolated",             ICMP_UNREACH_ISOLATED },
921       { "net-prohib",           ICMP_UNREACH_NET_PROHIB },
922       { "host-prohib",          ICMP_UNREACH_HOST_PROHIB },
923       { "tosnet",               ICMP_UNREACH_TOSNET },
924       { "toshost",              ICMP_UNREACH_TOSHOST },
925       { "filter-prohib",        ICMP_UNREACH_FILTER_PROHIB },
926       { "host-precedence",      ICMP_UNREACH_HOST_PRECEDENCE },
927       { "precedence-cutoff",    ICMP_UNREACH_PRECEDENCE_CUTOFF },
928       { NULL, 0 }
929 };
930
931 static void
932 fill_reject_code(u_short *codep, char *str)
933 {
934         int val;
935         char *s;
936
937         val = strtoul(str, &s, 0);
938         if (s == str || *s != '\0' || val >= 0x100)
939                 val = match_token(icmpcodes, str);
940         if (val < 0)
941                 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
942         *codep = val;
943         return;
944 }
945
946 static void
947 print_reject_code(uint16_t code)
948 {
949         char const *s = match_value(icmpcodes, code);
950
951         if (s != NULL)
952                 printf("unreach %s", s);
953         else
954                 printf("unreach %u", code);
955 }
956
957 static struct _s_x icmp6codes[] = {
958       { "no-route",             ICMP6_DST_UNREACH_NOROUTE },
959       { "admin-prohib",         ICMP6_DST_UNREACH_ADMIN },
960       { "address",              ICMP6_DST_UNREACH_ADDR },
961       { "port",                 ICMP6_DST_UNREACH_NOPORT },
962       { NULL, 0 }
963 };
964
965 static void
966 fill_unreach6_code(u_short *codep, char *str)
967 {
968         int val;
969         char *s;
970
971         val = strtoul(str, &s, 0);
972         if (s == str || *s != '\0' || val >= 0x100)
973                 val = match_token(icmp6codes, str);
974         if (val < 0)
975                 errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str);
976         *codep = val;
977         return;
978 }
979
980 static void
981 print_unreach6_code(uint16_t code)
982 {
983         char const *s = match_value(icmp6codes, code);
984
985         if (s != NULL)
986                 printf("unreach6 %s", s);
987         else
988                 printf("unreach6 %u", code);
989 }
990
991 /*
992  * Returns the number of bits set (from left) in a contiguous bitmask,
993  * or -1 if the mask is not contiguous.
994  * XXX this needs a proper fix.
995  * This effectively works on masks in big-endian (network) format.
996  * when compiled on little endian architectures.
997  *
998  * First bit is bit 7 of the first byte -- note, for MAC addresses,
999  * the first bit on the wire is bit 0 of the first byte.
1000  * len is the max length in bits.
1001  */
1002 static int
1003 contigmask(uint8_t *p, int len)
1004 {
1005         int i, n;
1006
1007         for (i=0; i<len ; i++)
1008                 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1009                         break;
1010         for (n=i+1; n < len; n++)
1011                 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1012                         return -1; /* mask not contiguous */
1013         return i;
1014 }
1015
1016 /*
1017  * print flags set/clear in the two bitmasks passed as parameters.
1018  * There is a specialized check for f_tcpflags.
1019  */
1020 static void
1021 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
1022 {
1023         char const *comma = "";
1024         int i;
1025         uint8_t set = cmd->arg1 & 0xff;
1026         uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1027
1028         if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1029                 printf(" setup");
1030                 return;
1031         }
1032
1033         printf(" %s ", name);
1034         for (i=0; list[i].x != 0; i++) {
1035                 if (set & list[i].x) {
1036                         set &= ~list[i].x;
1037                         printf("%s%s", comma, list[i].s);
1038                         comma = ",";
1039                 }
1040                 if (clear & list[i].x) {
1041                         clear &= ~list[i].x;
1042                         printf("%s!%s", comma, list[i].s);
1043                         comma = ",";
1044                 }
1045         }
1046 }
1047
1048 /*
1049  * Print the ip address contained in a command.
1050  */
1051 static void
1052 print_ip(ipfw_insn_ip *cmd, char const *s)
1053 {
1054         struct hostent *he = NULL;
1055         int len = F_LEN((ipfw_insn *)cmd);
1056         uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1057
1058         printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1059
1060         if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1061                 printf("me");
1062                 return;
1063         }
1064         if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1065             cmd->o.opcode == O_IP_DST_LOOKUP) {
1066                 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
1067                 if (len == F_INSN_SIZE(ipfw_insn_u32))
1068                         printf(",%u", *a);
1069                 printf(")");
1070                 return;
1071         }
1072         if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1073                 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1074                 int i, j;
1075                 char comma = '{';
1076
1077                 x = cmd->o.arg1 - 1;
1078                 x = htonl( ~x );
1079                 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1080                 printf("%s/%d", inet_ntoa(cmd->addr),
1081                         contigmask((uint8_t *)&x, 32));
1082                 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1083                 x &= 0xff; /* base */
1084                 /*
1085                  * Print bits and ranges.
1086                  * Locate first bit set (i), then locate first bit unset (j).
1087                  * If we have 3+ consecutive bits set, then print them as a
1088                  * range, otherwise only print the initial bit and rescan.
1089                  */
1090                 for (i=0; i < cmd->o.arg1; i++)
1091                         if (map[i/32] & (1<<(i & 31))) {
1092                                 for (j=i+1; j < cmd->o.arg1; j++)
1093                                         if (!(map[ j/32] & (1<<(j & 31))))
1094                                                 break;
1095                                 printf("%c%d", comma, i+x);
1096                                 if (j>i+2) { /* range has at least 3 elements */
1097                                         printf("-%d", j-1+x);
1098                                         i = j-1;
1099                                 }
1100                                 comma = ',';
1101                         }
1102                 printf("}");
1103                 return;
1104         }
1105         /*
1106          * len == 2 indicates a single IP, whereas lists of 1 or more
1107          * addr/mask pairs have len = (2n+1). We convert len to n so we
1108          * use that to count the number of entries.
1109          */
1110     for (len = len / 2; len > 0; len--, a += 2) {
1111         int mb =        /* mask length */
1112             (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1113                 32 : contigmask((uint8_t *)&(a[1]), 32);
1114         if (mb == 32 && do_resolv)
1115                 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1116         if (he != NULL)         /* resolved to name */
1117                 printf("%s", he->h_name);
1118         else if (mb == 0)       /* any */
1119                 printf("any");
1120         else {          /* numeric IP followed by some kind of mask */
1121                 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
1122                 if (mb < 0)
1123                         printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
1124                 else if (mb < 32)
1125                         printf("/%d", mb);
1126         }
1127         if (len > 1)
1128                 printf(",");
1129     }
1130 }
1131
1132 /*
1133  * prints a MAC address/mask pair
1134  */
1135 static void
1136 print_mac(uint8_t *addr, uint8_t *mask)
1137 {
1138         int l = contigmask(mask, 48);
1139
1140         if (l == 0)
1141                 printf(" any");
1142         else {
1143                 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1144                     addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1145                 if (l == -1)
1146                         printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1147                             mask[0], mask[1], mask[2],
1148                             mask[3], mask[4], mask[5]);
1149                 else if (l < 48)
1150                         printf("/%d", l);
1151         }
1152 }
1153
1154 static void
1155 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1156 {
1157         uint8_t type;
1158
1159         cmd->d[0] = 0;
1160         while (*av) {
1161                 if (*av == ',')
1162                         av++;
1163
1164                 type = strtoul(av, &av, 0);
1165
1166                 if (*av != ',' && *av != '\0')
1167                         errx(EX_DATAERR, "invalid ICMP type");
1168
1169                 if (type > 31)
1170                         errx(EX_DATAERR, "ICMP type out of range");
1171
1172                 cmd->d[0] |= 1 << type;
1173         }
1174         cmd->o.opcode = O_ICMPTYPE;
1175         cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1176 }
1177
1178 static void
1179 print_icmptypes(ipfw_insn_u32 *cmd)
1180 {
1181         int i;
1182         char sep= ' ';
1183
1184         printf(" icmptypes");
1185         for (i = 0; i < 32; i++) {
1186                 if ( (cmd->d[0] & (1 << (i))) == 0)
1187                         continue;
1188                 printf("%c%d", sep, i);
1189                 sep = ',';
1190         }
1191 }
1192
1193 /* 
1194  * Print the ip address contained in a command.
1195  */
1196 static void
1197 print_ip6(ipfw_insn_ip6 *cmd, char const *s)
1198 {
1199        struct hostent *he = NULL;
1200        int len = F_LEN((ipfw_insn *) cmd) - 1;
1201        struct in6_addr *a = &(cmd->addr6);
1202        char trad[255];
1203
1204        printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1205
1206        if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) {
1207                printf("me6");
1208                return;
1209        }
1210        if (cmd->o.opcode == O_IP6) {
1211                printf(" ip6");
1212                return;
1213        }
1214
1215        /*
1216         * len == 4 indicates a single IP, whereas lists of 1 or more
1217         * addr/mask pairs have len = (2n+1). We convert len to n so we
1218         * use that to count the number of entries.
1219         */
1220
1221        for (len = len / 4; len > 0; len -= 2, a += 2) {
1222            int mb =        /* mask length */
1223                (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ?
1224                128 : contigmask((uint8_t *)&(a[1]), 128);
1225
1226            if (mb == 128 && do_resolv)
1227                he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6);
1228            if (he != NULL)             /* resolved to name */
1229                printf("%s", he->h_name);
1230            else if (mb == 0)           /* any */
1231                printf("any");
1232            else {          /* numeric IP followed by some kind of mask */
1233                if (inet_ntop(AF_INET6,  a, trad, sizeof( trad ) ) == NULL)
1234                    printf("Error ntop in print_ip6\n");
1235                printf("%s",  trad );
1236                if (mb < 0)     /* XXX not really legal... */
1237                    printf(":%s",
1238                        inet_ntop(AF_INET6, &a[1], trad, sizeof(trad)));
1239                else if (mb < 128)
1240                    printf("/%d", mb);
1241            }
1242            if (len > 2)
1243                printf(",");
1244        }
1245 }
1246
1247 static void
1248 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av)
1249 {
1250        uint8_t type;
1251
1252        bzero(cmd, sizeof(*cmd));
1253        while (*av) {
1254            if (*av == ',')
1255                av++;
1256            type = strtoul(av, &av, 0);
1257            if (*av != ',' && *av != '\0')
1258                errx(EX_DATAERR, "invalid ICMP6 type");
1259            /*
1260             * XXX: shouldn't this be 0xFF?  I can't see any reason why
1261             * we shouldn't be able to filter all possiable values
1262             * regardless of the ability of the rest of the kernel to do
1263             * anything useful with them.
1264             */
1265            if (type > ICMP6_MAXTYPE)
1266                errx(EX_DATAERR, "ICMP6 type out of range");
1267            cmd->d[type / 32] |= ( 1 << (type % 32));
1268        }
1269        cmd->o.opcode = O_ICMP6TYPE;
1270        cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6);
1271 }
1272
1273
1274 static void
1275 print_icmp6types(ipfw_insn_u32 *cmd)
1276 {
1277        int i, j;
1278        char sep= ' ';
1279
1280        printf(" ip6 icmp6types");
1281        for (i = 0; i < 7; i++)
1282                for (j=0; j < 32; ++j) {
1283                        if ( (cmd->d[i] & (1 << (j))) == 0)
1284                                continue;
1285                        printf("%c%d", sep, (i*32 + j));
1286                        sep = ',';
1287                }
1288 }
1289
1290 static void
1291 print_flow6id( ipfw_insn_u32 *cmd)
1292 {
1293        uint16_t i, limit = cmd->o.arg1;
1294        char sep = ',';
1295
1296        printf(" flow-id ");
1297        for( i=0; i < limit; ++i) {
1298                if (i == limit - 1)
1299                        sep = ' ';
1300                printf("%d%c", cmd->d[i], sep);
1301        }
1302 }
1303
1304 /* structure and define for the extension header in ipv6 */
1305 static struct _s_x ext6hdrcodes[] = {
1306        { "frag",       EXT_FRAGMENT },
1307        { "hopopt",     EXT_HOPOPTS },
1308        { "route",      EXT_ROUTING },
1309        { "dstopt",     EXT_DSTOPTS },
1310        { "ah",         EXT_AH },
1311        { "esp",        EXT_ESP },
1312        { "rthdr0",     EXT_RTHDR0 },
1313        { "rthdr2",     EXT_RTHDR2 },
1314        { NULL,         0 }
1315 };
1316
1317 /* fills command for the extension header filtering */
1318 int
1319 fill_ext6hdr( ipfw_insn *cmd, char *av)
1320 {
1321        int tok;
1322        char *s = av;
1323
1324        cmd->arg1 = 0;
1325
1326        while(s) {
1327            av = strsep( &s, ",") ;
1328            tok = match_token(ext6hdrcodes, av);
1329            switch (tok) {
1330            case EXT_FRAGMENT:
1331                cmd->arg1 |= EXT_FRAGMENT;
1332                break;
1333
1334            case EXT_HOPOPTS:
1335                cmd->arg1 |= EXT_HOPOPTS;
1336                break;
1337
1338            case EXT_ROUTING:
1339                cmd->arg1 |= EXT_ROUTING;
1340                break;
1341
1342            case EXT_DSTOPTS:
1343                cmd->arg1 |= EXT_DSTOPTS;
1344                break;
1345
1346            case EXT_AH:
1347                cmd->arg1 |= EXT_AH;
1348                break;
1349
1350            case EXT_ESP:
1351                cmd->arg1 |= EXT_ESP;
1352                break;
1353
1354            case EXT_RTHDR0:
1355                cmd->arg1 |= EXT_RTHDR0;
1356                break;
1357
1358            case EXT_RTHDR2:
1359                cmd->arg1 |= EXT_RTHDR2;
1360                break;
1361
1362            default:
1363                errx( EX_DATAERR, "invalid option for ipv6 exten header" );
1364                break;
1365            }
1366        }
1367        if (cmd->arg1 == 0 )
1368            return 0;
1369        cmd->opcode = O_EXT_HDR;
1370        cmd->len |= F_INSN_SIZE( ipfw_insn );
1371        return 1;
1372 }
1373
1374 void
1375 print_ext6hdr( ipfw_insn *cmd )
1376 {
1377        char sep = ' ';
1378
1379        printf(" extension header:");
1380        if (cmd->arg1 & EXT_FRAGMENT ) {
1381            printf("%cfragmentation", sep);
1382            sep = ',';
1383        }
1384        if (cmd->arg1 & EXT_HOPOPTS ) {
1385            printf("%chop options", sep);
1386            sep = ',';
1387        }
1388        if (cmd->arg1 & EXT_ROUTING ) {
1389            printf("%crouting options", sep);
1390            sep = ',';
1391        }
1392        if (cmd->arg1 & EXT_RTHDR0 ) {
1393            printf("%crthdr0", sep);
1394            sep = ',';
1395        }
1396        if (cmd->arg1 & EXT_RTHDR2 ) {
1397            printf("%crthdr2", sep);
1398            sep = ',';
1399        }
1400        if (cmd->arg1 & EXT_DSTOPTS ) {
1401            printf("%cdestination options", sep);
1402            sep = ',';
1403        }
1404        if (cmd->arg1 & EXT_AH ) {
1405            printf("%cauthentication header", sep);
1406            sep = ',';
1407        }
1408        if (cmd->arg1 & EXT_ESP ) {
1409            printf("%cencapsulated security payload", sep);
1410        }
1411 }
1412
1413 /*
1414  * show_ipfw() prints the body of an ipfw rule.
1415  * Because the standard rule has at least proto src_ip dst_ip, we use
1416  * a helper function to produce these entries if not provided explicitly.
1417  * The first argument is the list of fields we have, the second is
1418  * the list of fields we want to be printed.
1419  *
1420  * Special cases if we have provided a MAC header:
1421  *   + if the rule does not contain IP addresses/ports, do not print them;
1422  *   + if the rule does not contain an IP proto, print "all" instead of "ip";
1423  *
1424  * Once we have 'have_options', IP header fields are printed as options.
1425  */
1426 #define HAVE_PROTO      0x0001
1427 #define HAVE_SRCIP      0x0002
1428 #define HAVE_DSTIP      0x0004
1429 #define HAVE_PROTO4     0x0008
1430 #define HAVE_PROTO6     0x0010
1431 #define HAVE_OPTIONS    0x8000
1432
1433 #define HAVE_IP         (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
1434 static void
1435 show_prerequisites(int *flags, int want, int cmd)
1436 {
1437         if (comment_only)
1438                 return;
1439         if ( (*flags & HAVE_IP) == HAVE_IP)
1440                 *flags |= HAVE_OPTIONS;
1441
1442         if ( !(*flags & HAVE_OPTIONS)) {
1443                 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
1444                         if ( (*flags & HAVE_PROTO4))
1445                                 printf(" ip4");
1446                         else if ( (*flags & HAVE_PROTO6))
1447                                 printf(" ip6");
1448                         else
1449                                 printf(" ip");
1450
1451                 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1452                         printf(" from any");
1453                 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1454                         printf(" to any");
1455         }
1456         *flags |= want;
1457 }
1458
1459 static void
1460 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1461 {
1462         static int twidth = 0;
1463         int l;
1464         ipfw_insn *cmd, *tagptr = NULL;
1465         char *comment = NULL;   /* ptr to comment if we have one */
1466         int proto = 0;          /* default */
1467         int flags = 0;  /* prerequisites */
1468         ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1469         ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1470         int or_block = 0;       /* we are in an or block */
1471         uint32_t set_disable;
1472
1473         bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1474
1475         if (set_disable & (1 << rule->set)) { /* disabled */
1476                 if (!show_sets)
1477                         return;
1478                 else
1479                         printf("# DISABLED ");
1480         }
1481         printf("%05u ", rule->rulenum);
1482
1483         if (pcwidth>0 || bcwidth>0)
1484                 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
1485                     bcwidth, align_uint64(&rule->bcnt));
1486
1487         if (do_time == 2)
1488                 printf("%10u ", rule->timestamp);
1489         else if (do_time == 1) {
1490                 char timestr[30];
1491                 time_t t = (time_t)0;
1492
1493                 if (twidth == 0) {
1494                         strcpy(timestr, ctime(&t));
1495                         *strchr(timestr, '\n') = '\0';
1496                         twidth = strlen(timestr);
1497                 }
1498                 if (rule->timestamp) {
1499                         t = _long_to_time(rule->timestamp);
1500
1501                         strcpy(timestr, ctime(&t));
1502                         *strchr(timestr, '\n') = '\0';
1503                         printf("%s ", timestr);
1504                 } else {
1505                         printf("%*s", twidth, " ");
1506                 }
1507         }
1508
1509         if (show_sets)
1510                 printf("set %d ", rule->set);
1511
1512         /*
1513          * print the optional "match probability"
1514          */
1515         if (rule->cmd_len > 0) {
1516                 cmd = rule->cmd ;
1517                 if (cmd->opcode == O_PROB) {
1518                         ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1519                         double d = 1.0 * p->d[0];
1520
1521                         d = (d / 0x7fffffff);
1522                         printf("prob %f ", d);
1523                 }
1524         }
1525
1526         /*
1527          * first print actions
1528          */
1529         for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1530                         l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1531                 switch(cmd->opcode) {
1532                 case O_CHECK_STATE:
1533                         printf("check-state");
1534                         flags = HAVE_IP; /* avoid printing anything else */
1535                         break;
1536
1537                 case O_ACCEPT:
1538                         printf("allow");
1539                         break;
1540
1541                 case O_COUNT:
1542                         printf("count");
1543                         break;
1544
1545                 case O_DENY:
1546                         printf("deny");
1547                         break;
1548
1549                 case O_REJECT:
1550                         if (cmd->arg1 == ICMP_REJECT_RST)
1551                                 printf("reset");
1552                         else if (cmd->arg1 == ICMP_UNREACH_HOST)
1553                                 printf("reject");
1554                         else
1555                                 print_reject_code(cmd->arg1);
1556                         break;
1557
1558                 case O_UNREACH6:
1559                         if (cmd->arg1 == ICMP6_UNREACH_RST)
1560                                 printf("reset6");
1561                         else
1562                                 print_unreach6_code(cmd->arg1);
1563                         break;
1564
1565                 case O_SKIPTO:
1566                         PRINT_UINT_ARG("skipto ", cmd->arg1);
1567                         break;
1568
1569                 case O_PIPE:
1570                         PRINT_UINT_ARG("pipe ", cmd->arg1);
1571                         break;
1572
1573                 case O_QUEUE:
1574                         PRINT_UINT_ARG("queue ", cmd->arg1);
1575                         break;
1576
1577                 case O_DIVERT:
1578                         PRINT_UINT_ARG("divert ", cmd->arg1);
1579                         break;
1580
1581                 case O_TEE:
1582                         PRINT_UINT_ARG("tee ", cmd->arg1);
1583                         break;
1584
1585                 case O_NETGRAPH:
1586                         PRINT_UINT_ARG("netgraph ", cmd->arg1);
1587                         break;
1588
1589                 case O_NGTEE:
1590                         PRINT_UINT_ARG("ngtee ", cmd->arg1);
1591                         break;
1592
1593                 case O_FORWARD_IP:
1594                     {
1595                         ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1596
1597                         if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1598                                 printf("fwd tablearg");
1599                         } else {
1600                                 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1601                         }
1602                         if (s->sa.sin_port)
1603                                 printf(",%d", s->sa.sin_port);
1604                     }
1605                         break;
1606
1607                 case O_LOG: /* O_LOG is printed last */
1608                         logptr = (ipfw_insn_log *)cmd;
1609                         break;
1610
1611                 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1612                         altqptr = (ipfw_insn_altq *)cmd;
1613                         break;
1614
1615                 case O_TAG:
1616                         tagptr = cmd;
1617                         break;
1618
1619                 case O_NAT:
1620                         PRINT_UINT_ARG("nat ", cmd->arg1);
1621                         break;
1622                         
1623                 case O_SETFIB:
1624                         PRINT_UINT_ARG("setfib ", cmd->arg1);
1625                         break;
1626                         
1627                 default:
1628                         printf("** unrecognized action %d len %d ",
1629                                 cmd->opcode, cmd->len);
1630                 }
1631         }
1632         if (logptr) {
1633                 if (logptr->max_log > 0)
1634                         printf(" log logamount %d", logptr->max_log);
1635                 else
1636                         printf(" log");
1637         }
1638         if (altqptr) {
1639                 const char *qname;
1640
1641                 qname = altq_qid_to_name(altqptr->qid);
1642                 if (qname == NULL)
1643                         printf(" altq ?<%u>", altqptr->qid);
1644                 else
1645                         printf(" altq %s", qname);
1646         }
1647         if (tagptr) {
1648                 if (tagptr->len & F_NOT)
1649                         PRINT_UINT_ARG(" untag ", tagptr->arg1);
1650                 else
1651                         PRINT_UINT_ARG(" tag ", tagptr->arg1);
1652         }
1653
1654         /*
1655          * then print the body.
1656          */
1657         for (l = rule->act_ofs, cmd = rule->cmd ;
1658                         l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1659                 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1660                         continue;
1661                 if (cmd->opcode == O_IP4) {
1662                         flags |= HAVE_PROTO4;
1663                         break;
1664                 } else if (cmd->opcode == O_IP6) {
1665                         flags |= HAVE_PROTO6;
1666                         break;
1667                 }                       
1668         }
1669         if (rule->_pad & 1) {   /* empty rules before options */
1670                 if (!do_compact) {
1671                         show_prerequisites(&flags, HAVE_PROTO, 0);
1672                         printf(" from any to any");
1673                 }
1674                 flags |= HAVE_IP | HAVE_OPTIONS;
1675         }
1676
1677         if (comment_only)
1678                 comment = "...";
1679
1680         for (l = rule->act_ofs, cmd = rule->cmd ;
1681                         l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1682                 /* useful alias */
1683                 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1684
1685                 if (comment_only) {
1686                         if (cmd->opcode != O_NOP)
1687                                 continue;
1688                         printf(" // %s\n", (char *)(cmd + 1));
1689                         return;
1690                 }
1691
1692                 show_prerequisites(&flags, 0, cmd->opcode);
1693
1694                 switch(cmd->opcode) {
1695                 case O_PROB:
1696                         break;  /* done already */
1697
1698                 case O_PROBE_STATE:
1699                         break; /* no need to print anything here */
1700
1701                 case O_IP_SRC:
1702                 case O_IP_SRC_LOOKUP:
1703                 case O_IP_SRC_MASK:
1704                 case O_IP_SRC_ME:
1705                 case O_IP_SRC_SET:
1706                         show_prerequisites(&flags, HAVE_PROTO, 0);
1707                         if (!(flags & HAVE_SRCIP))
1708                                 printf(" from");
1709                         if ((cmd->len & F_OR) && !or_block)
1710                                 printf(" {");
1711                         print_ip((ipfw_insn_ip *)cmd,
1712                                 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1713                         flags |= HAVE_SRCIP;
1714                         break;
1715
1716                 case O_IP_DST:
1717                 case O_IP_DST_LOOKUP:
1718                 case O_IP_DST_MASK:
1719                 case O_IP_DST_ME:
1720                 case O_IP_DST_SET:
1721                         show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1722                         if (!(flags & HAVE_DSTIP))
1723                                 printf(" to");
1724                         if ((cmd->len & F_OR) && !or_block)
1725                                 printf(" {");
1726                         print_ip((ipfw_insn_ip *)cmd,
1727                                 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1728                         flags |= HAVE_DSTIP;
1729                         break;
1730
1731                 case O_IP6_SRC:
1732                 case O_IP6_SRC_MASK:
1733                 case O_IP6_SRC_ME:
1734                         show_prerequisites(&flags, HAVE_PROTO, 0);
1735                         if (!(flags & HAVE_SRCIP))
1736                                 printf(" from");
1737                         if ((cmd->len & F_OR) && !or_block)
1738                                 printf(" {");
1739                         print_ip6((ipfw_insn_ip6 *)cmd,
1740                             (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1741                         flags |= HAVE_SRCIP | HAVE_PROTO;
1742                         break;
1743
1744                 case O_IP6_DST:
1745                 case O_IP6_DST_MASK:
1746                 case O_IP6_DST_ME:
1747                         show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1748                         if (!(flags & HAVE_DSTIP))
1749                                 printf(" to");
1750                         if ((cmd->len & F_OR) && !or_block)
1751                                 printf(" {");
1752                         print_ip6((ipfw_insn_ip6 *)cmd,
1753                             (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1754                         flags |= HAVE_DSTIP;
1755                         break;
1756
1757                 case O_FLOW6ID:
1758                 print_flow6id( (ipfw_insn_u32 *) cmd );
1759                 flags |= HAVE_OPTIONS;
1760                 break;
1761
1762                 case O_IP_DSTPORT:
1763                         show_prerequisites(&flags, HAVE_IP, 0);
1764                 case O_IP_SRCPORT:
1765                         show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1766                         if ((cmd->len & F_OR) && !or_block)
1767                                 printf(" {");
1768                         if (cmd->len & F_NOT)
1769                                 printf(" not");
1770                         print_newports((ipfw_insn_u16 *)cmd, proto,
1771                                 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1772                         break;
1773
1774                 case O_PROTO: {
1775                         struct protoent *pe = NULL;
1776
1777                         if ((cmd->len & F_OR) && !or_block)
1778                                 printf(" {");
1779                         if (cmd->len & F_NOT)
1780                                 printf(" not");
1781                         proto = cmd->arg1;
1782                         pe = getprotobynumber(cmd->arg1);
1783                         if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1784                             !(flags & HAVE_PROTO))
1785                                 show_prerequisites(&flags,
1786                                     HAVE_IP | HAVE_OPTIONS, 0);
1787                         if (flags & HAVE_OPTIONS)
1788                                 printf(" proto");
1789                         if (pe)
1790                                 printf(" %s", pe->p_name);
1791                         else
1792                                 printf(" %u", cmd->arg1);
1793                         }
1794                         flags |= HAVE_PROTO;
1795                         break;
1796
1797                 default: /*options ... */
1798                         if (!(cmd->len & (F_OR|F_NOT)))
1799                                 if (((cmd->opcode == O_IP6) &&
1800                                     (flags & HAVE_PROTO6)) ||
1801                                     ((cmd->opcode == O_IP4) &&
1802                                     (flags & HAVE_PROTO4)))
1803                                         break;
1804                         show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1805                         if ((cmd->len & F_OR) && !or_block)
1806                                 printf(" {");
1807                         if (cmd->len & F_NOT && cmd->opcode != O_IN)
1808                                 printf(" not");
1809                         switch(cmd->opcode) {
1810                         case O_MACADDR2: {
1811                                 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1812
1813                                 printf(" MAC");
1814                                 print_mac(m->addr, m->mask);
1815                                 print_mac(m->addr + 6, m->mask + 6);
1816                                 }
1817                                 break;
1818
1819                         case O_MAC_TYPE:
1820                                 print_newports((ipfw_insn_u16 *)cmd,
1821                                                 IPPROTO_ETHERTYPE, cmd->opcode);
1822                                 break;
1823
1824
1825                         case O_FRAG:
1826                                 printf(" frag");
1827                                 break;
1828
1829                         case O_FIB:
1830                                 printf(" fib %u", cmd->arg1 );
1831                                 break;
1832
1833                         case O_IN:
1834                                 printf(cmd->len & F_NOT ? " out" : " in");
1835                                 break;
1836
1837                         case O_DIVERTED:
1838                                 switch (cmd->arg1) {
1839                                 case 3:
1840                                         printf(" diverted");
1841                                         break;
1842                                 case 1:
1843                                         printf(" diverted-loopback");
1844                                         break;
1845                                 case 2:
1846                                         printf(" diverted-output");
1847                                         break;
1848                                 default:
1849                                         printf(" diverted-?<%u>", cmd->arg1);
1850                                         break;
1851                                 }
1852                                 break;
1853
1854                         case O_LAYER2:
1855                                 printf(" layer2");
1856                                 break;
1857                         case O_XMIT:
1858                         case O_RECV:
1859                         case O_VIA:
1860                             {
1861                                 char const *s;
1862                                 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1863
1864                                 if (cmd->opcode == O_XMIT)
1865                                         s = "xmit";
1866                                 else if (cmd->opcode == O_RECV)
1867                                         s = "recv";
1868                                 else /* if (cmd->opcode == O_VIA) */
1869                                         s = "via";
1870                                 if (cmdif->name[0] == '\0')
1871                                         printf(" %s %s", s,
1872                                             inet_ntoa(cmdif->p.ip));
1873                                 else
1874                                         printf(" %s %s", s, cmdif->name);
1875
1876                                 break;
1877                             }
1878                         case O_IPID:
1879                                 if (F_LEN(cmd) == 1)
1880                                     printf(" ipid %u", cmd->arg1 );
1881                                 else
1882                                     print_newports((ipfw_insn_u16 *)cmd, 0,
1883                                         O_IPID);
1884                                 break;
1885
1886                         case O_IPTTL:
1887                                 if (F_LEN(cmd) == 1)
1888                                     printf(" ipttl %u", cmd->arg1 );
1889                                 else
1890                                     print_newports((ipfw_insn_u16 *)cmd, 0,
1891                                         O_IPTTL);
1892                                 break;
1893
1894                         case O_IPVER:
1895                                 printf(" ipver %u", cmd->arg1 );
1896                                 break;
1897
1898                         case O_IPPRECEDENCE:
1899                                 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1900                                 break;
1901
1902                         case O_IPLEN:
1903                                 if (F_LEN(cmd) == 1)
1904                                     printf(" iplen %u", cmd->arg1 );
1905                                 else
1906                                     print_newports((ipfw_insn_u16 *)cmd, 0,
1907                                         O_IPLEN);
1908                                 break;
1909
1910                         case O_IPOPT:
1911                                 print_flags("ipoptions", cmd, f_ipopts);
1912                                 break;
1913
1914                         case O_IPTOS:
1915                                 print_flags("iptos", cmd, f_iptos);
1916                                 break;
1917
1918                         case O_ICMPTYPE:
1919                                 print_icmptypes((ipfw_insn_u32 *)cmd);
1920                                 break;
1921
1922                         case O_ESTAB:
1923                                 printf(" established");
1924                                 break;
1925
1926                         case O_TCPDATALEN:
1927                                 if (F_LEN(cmd) == 1)
1928                                     printf(" tcpdatalen %u", cmd->arg1 );
1929                                 else
1930                                     print_newports((ipfw_insn_u16 *)cmd, 0,
1931                                         O_TCPDATALEN);
1932                                 break;
1933
1934                         case O_TCPFLAGS:
1935                                 print_flags("tcpflags", cmd, f_tcpflags);
1936                                 break;
1937
1938                         case O_TCPOPTS:
1939                                 print_flags("tcpoptions", cmd, f_tcpopts);
1940                                 break;
1941
1942                         case O_TCPWIN:
1943                                 printf(" tcpwin %d", ntohs(cmd->arg1));
1944                                 break;
1945
1946                         case O_TCPACK:
1947                                 printf(" tcpack %d", ntohl(cmd32->d[0]));
1948                                 break;
1949
1950                         case O_TCPSEQ:
1951                                 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1952                                 break;
1953
1954                         case O_UID:
1955                             {
1956                                 struct passwd *pwd = getpwuid(cmd32->d[0]);
1957
1958                                 if (pwd)
1959                                         printf(" uid %s", pwd->pw_name);
1960                                 else
1961                                         printf(" uid %u", cmd32->d[0]);
1962                             }
1963                                 break;
1964
1965                         case O_GID:
1966                             {
1967                                 struct group *grp = getgrgid(cmd32->d[0]);
1968
1969                                 if (grp)
1970                                         printf(" gid %s", grp->gr_name);
1971                                 else
1972                                         printf(" gid %u", cmd32->d[0]);
1973                             }
1974                                 break;
1975
1976                         case O_JAIL:
1977                                 printf(" jail %d", cmd32->d[0]);
1978                                 break;
1979
1980                         case O_VERREVPATH:
1981                                 printf(" verrevpath");
1982                                 break;
1983
1984                         case O_VERSRCREACH:
1985                                 printf(" versrcreach");
1986                                 break;
1987
1988                         case O_ANTISPOOF:
1989                                 printf(" antispoof");
1990                                 break;
1991
1992                         case O_IPSEC:
1993                                 printf(" ipsec");
1994                                 break;
1995
1996                         case O_NOP:
1997                                 comment = (char *)(cmd + 1);
1998                                 break;
1999
2000                         case O_KEEP_STATE:
2001                                 printf(" keep-state");
2002                                 break;
2003
2004                         case O_LIMIT: {
2005                                 struct _s_x *p = limit_masks;
2006                                 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2007                                 uint8_t x = c->limit_mask;
2008                                 char const *comma = " ";
2009
2010                                 printf(" limit");
2011                                 for (; p->x != 0 ; p++)
2012                                         if ((x & p->x) == p->x) {
2013                                                 x &= ~p->x;
2014                                                 printf("%s%s", comma, p->s);
2015                                                 comma = ",";
2016                                         }
2017                                 PRINT_UINT_ARG(" ", c->conn_limit);
2018                                 break;
2019                         }
2020
2021                         case O_IP6:
2022                                 printf(" ip6");
2023                                 break;
2024
2025                         case O_IP4:
2026                                 printf(" ip4");
2027                                 break;
2028
2029                         case O_ICMP6TYPE:
2030                                 print_icmp6types((ipfw_insn_u32 *)cmd);
2031                                 break;
2032
2033                         case O_EXT_HDR:
2034                                 print_ext6hdr( (ipfw_insn *) cmd );
2035                                 break;
2036
2037                         case O_TAGGED:
2038                                 if (F_LEN(cmd) == 1)
2039                                         PRINT_UINT_ARG(" tagged ", cmd->arg1);
2040                                 else
2041                                         print_newports((ipfw_insn_u16 *)cmd, 0,
2042                                             O_TAGGED);
2043                                 break;
2044
2045                         default:
2046                                 printf(" [opcode %d len %d]",
2047                                     cmd->opcode, cmd->len);
2048                         }
2049                 }
2050                 if (cmd->len & F_OR) {
2051                         printf(" or");
2052                         or_block = 1;
2053                 } else if (or_block) {
2054                         printf(" }");
2055                         or_block = 0;
2056                 }
2057         }
2058         show_prerequisites(&flags, HAVE_IP, 0);
2059         if (comment)
2060                 printf(" // %s", comment);
2061         printf("\n");
2062 }
2063
2064 static void
2065 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
2066 {
2067         struct protoent *pe;
2068         struct in_addr a;
2069         uint16_t rulenum;
2070         char buf[INET6_ADDRSTRLEN];
2071
2072         if (!do_expired) {
2073                 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2074                         return;
2075         }
2076         bcopy(&d->rule, &rulenum, sizeof(rulenum));
2077         printf("%05d", rulenum);
2078         if (pcwidth>0 || bcwidth>0)
2079             printf(" %*llu %*llu (%ds)", pcwidth,
2080                 align_uint64(&d->pcnt), bcwidth,
2081                 align_uint64(&d->bcnt), d->expire);
2082         switch (d->dyn_type) {
2083         case O_LIMIT_PARENT:
2084                 printf(" PARENT %d", d->count);
2085                 break;
2086         case O_LIMIT:
2087                 printf(" LIMIT");
2088                 break;
2089         case O_KEEP_STATE: /* bidir, no mask */
2090                 printf(" STATE");
2091                 break;
2092         }
2093
2094         if ((pe = getprotobynumber(d->id.proto)) != NULL)
2095                 printf(" %s", pe->p_name);
2096         else
2097                 printf(" proto %u", d->id.proto);
2098
2099         if (d->id.addr_type == 4) {
2100                 a.s_addr = htonl(d->id.src_ip);
2101                 printf(" %s %d", inet_ntoa(a), d->id.src_port);
2102
2103                 a.s_addr = htonl(d->id.dst_ip);
2104                 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
2105         } else if (d->id.addr_type == 6) {
2106                 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2107                     sizeof(buf)), d->id.src_port);
2108                 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
2109                     sizeof(buf)), d->id.dst_port);
2110         } else
2111                 printf(" UNKNOWN <-> UNKNOWN\n");
2112         
2113         printf("\n");
2114 }
2115
2116 static int
2117 sort_q(const void *pa, const void *pb)
2118 {
2119         int rev = (do_sort < 0);
2120         int field = rev ? -do_sort : do_sort;
2121         long long res = 0;
2122         const struct dn_flow_queue *a = pa;
2123         const struct dn_flow_queue *b = pb;
2124
2125         switch (field) {
2126         case 1: /* pkts */
2127                 res = a->len - b->len;
2128                 break;
2129         case 2: /* bytes */
2130                 res = a->len_bytes - b->len_bytes;
2131                 break;
2132
2133         case 3: /* tot pkts */
2134                 res = a->tot_pkts - b->tot_pkts;
2135                 break;
2136
2137         case 4: /* tot bytes */
2138                 res = a->tot_bytes - b->tot_bytes;
2139                 break;
2140         }
2141         if (res < 0)
2142                 res = -1;
2143         if (res > 0)
2144                 res = 1;
2145         return (int)(rev ? res : -res);
2146 }
2147
2148 static void
2149 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
2150 {
2151         int l;
2152         int index_printed, indexes = 0;
2153         char buff[255];
2154         struct protoent *pe;
2155
2156         if (fs->rq_elements == 0)
2157                 return;
2158
2159         if (do_sort != 0)
2160                 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
2161
2162         /* Print IPv4 flows */
2163         index_printed = 0;
2164         for (l = 0; l < fs->rq_elements; l++) {
2165                 struct in_addr ina;
2166
2167                 /* XXX: Should check for IPv4 flows */
2168                 if (IS_IP6_FLOW_ID(&(q[l].id)))
2169                         continue;
2170
2171                 if (!index_printed) {
2172                         index_printed = 1;
2173                         if (indexes > 0)        /* currently a no-op */
2174                                 printf("\n");
2175                         indexes++;
2176                         printf("    "
2177                             "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
2178                             fs->flow_mask.proto,
2179                             fs->flow_mask.src_ip, fs->flow_mask.src_port,
2180                             fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
2181
2182                         printf("BKT Prot ___Source IP/port____ "
2183                             "____Dest. IP/port____ "
2184                             "Tot_pkt/bytes Pkt/Byte Drp\n");
2185                 }
2186
2187                 printf("%3d ", q[l].hash_slot);
2188                 pe = getprotobynumber(q[l].id.proto);
2189                 if (pe)
2190                         printf("%-4s ", pe->p_name);
2191                 else
2192                         printf("%4u ", q[l].id.proto);
2193                 ina.s_addr = htonl(q[l].id.src_ip);
2194                 printf("%15s/%-5d ",
2195                     inet_ntoa(ina), q[l].id.src_port);
2196                 ina.s_addr = htonl(q[l].id.dst_ip);
2197                 printf("%15s/%-5d ",
2198                     inet_ntoa(ina), q[l].id.dst_port);
2199                 printf("%4qu %8qu %2u %4u %3u\n",
2200                     q[l].tot_pkts, q[l].tot_bytes,
2201                     q[l].len, q[l].len_bytes, q[l].drops);
2202                 if (verbose)
2203                         printf("   S %20qd  F %20qd\n",
2204                             q[l].S, q[l].F);
2205         }
2206
2207         /* Print IPv6 flows */
2208         index_printed = 0;
2209         for (l = 0; l < fs->rq_elements; l++) {
2210                 if (!IS_IP6_FLOW_ID(&(q[l].id)))
2211                         continue;
2212
2213                 if (!index_printed) {
2214                         index_printed = 1;
2215                         if (indexes > 0)
2216                                 printf("\n");
2217                         indexes++;
2218                         printf("\n        mask: proto: 0x%02x, flow_id: 0x%08x,  ",
2219                             fs->flow_mask.proto, fs->flow_mask.flow_id6);
2220                         inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
2221                             buff, sizeof(buff));
2222                         printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
2223                         inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
2224                             buff, sizeof(buff) );
2225                         printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
2226
2227                         printf("BKT ___Prot___ _flow-id_ "
2228                             "______________Source IPv6/port_______________ "
2229                             "_______________Dest. IPv6/port_______________ "
2230                             "Tot_pkt/bytes Pkt/Byte Drp\n");
2231                 }
2232                 printf("%3d ", q[l].hash_slot);
2233                 pe = getprotobynumber(q[l].id.proto);
2234                 if (pe != NULL)
2235                         printf("%9s ", pe->p_name);
2236                 else
2237                         printf("%9u ", q[l].id.proto);
2238                 printf("%7d  %39s/%-5d ", q[l].id.flow_id6,
2239                     inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
2240                     q[l].id.src_port);
2241                 printf(" %39s/%-5d ",
2242                     inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
2243                     q[l].id.dst_port);
2244                 printf(" %4qu %8qu %2u %4u %3u\n",
2245                     q[l].tot_pkts, q[l].tot_bytes,
2246                     q[l].len, q[l].len_bytes, q[l].drops);
2247                 if (verbose)
2248                         printf("   S %20qd  F %20qd\n", q[l].S, q[l].F);
2249         }
2250 }
2251
2252 static void
2253 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
2254 {
2255         int l;
2256         char qs[30];
2257         char plr[30];
2258         char red[90];   /* Display RED parameters */
2259
2260         l = fs->qsize;
2261         if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
2262                 if (l >= 8192)
2263                         sprintf(qs, "%d KB", l / 1024);
2264                 else
2265                         sprintf(qs, "%d B", l);
2266         } else
2267                 sprintf(qs, "%3d sl.", l);
2268         if (fs->plr)
2269                 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
2270         else
2271                 plr[0] = '\0';
2272         if (fs->flags_fs & DN_IS_RED)   /* RED parameters */
2273                 sprintf(red,
2274                     "\n\t  %cRED w_q %f min_th %d max_th %d max_p %f",
2275                     (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
2276                     1.0 * fs->w_q / (double)(1 << SCALE_RED),
2277                     SCALE_VAL(fs->min_th),
2278                     SCALE_VAL(fs->max_th),
2279                     1.0 * fs->max_p / (double)(1 << SCALE_RED));
2280         else
2281                 sprintf(red, "droptail");
2282
2283         printf("%s %s%s %d queues (%d buckets) %s\n",
2284             prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
2285 }
2286
2287 static void
2288 list_pipes(void *data, uint nbytes, int ac, char *av[])
2289 {
2290         int rulenum;
2291         void *next = data;
2292         struct dn_pipe *p = (struct dn_pipe *) data;
2293         struct dn_flow_set *fs;
2294         struct dn_flow_queue *q;
2295         int l;
2296
2297         if (ac > 0)
2298                 rulenum = strtoul(*av++, NULL, 10);
2299         else
2300                 rulenum = 0;
2301         for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
2302                 double b = p->bandwidth;
2303                 char buf[30];
2304                 char prefix[80];
2305
2306                 if (SLIST_NEXT(p, next) != (struct dn_pipe *)DN_IS_PIPE)
2307                         break;  /* done with pipes, now queues */
2308
2309                 /*
2310                  * compute length, as pipe have variable size
2311                  */
2312                 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
2313                 next = (char *)p + l;
2314                 nbytes -= l;
2315
2316                 if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2)
2317                         continue;
2318
2319                 /*
2320                  * Print rate (or clocking interface)
2321                  */
2322                 if (p->if_name[0] != '\0')
2323                         sprintf(buf, "%s", p->if_name);
2324                 else if (b == 0)
2325                         sprintf(buf, "unlimited");
2326                 else if (b >= 1000000)
2327                         sprintf(buf, "%7.3f Mbit/s", b/1000000);
2328                 else if (b >= 1000)
2329                         sprintf(buf, "%7.3f Kbit/s", b/1000);
2330                 else
2331                         sprintf(buf, "%7.3f bit/s ", b);
2332
2333                 sprintf(prefix, "%05d: %s %4d ms ",
2334                     p->pipe_nr, buf, p->delay);
2335                 print_flowset_parms(&(p->fs), prefix);
2336                 if (verbose)
2337                         printf("   V %20qd\n", p->V >> MY_M);
2338
2339                 q = (struct dn_flow_queue *)(p+1);
2340                 list_queues(&(p->fs), q);
2341         }
2342         for (fs = next; nbytes >= sizeof *fs; fs = next) {
2343                 char prefix[80];
2344
2345                 if (SLIST_NEXT(fs, next) != (struct dn_flow_set *)DN_IS_QUEUE)
2346                         break;
2347                 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
2348                 next = (char *)fs + l;
2349                 nbytes -= l;
2350
2351                 if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) ||
2352                     (rulenum != fs->parent_nr && do_pipe == 1))) {
2353                         continue;
2354                 }
2355
2356                 q = (struct dn_flow_queue *)(fs+1);
2357                 sprintf(prefix, "q%05d: weight %d pipe %d ",
2358                     fs->fs_nr, fs->weight, fs->parent_nr);
2359                 print_flowset_parms(fs, prefix);
2360                 list_queues(fs, q);
2361         }
2362 }
2363
2364 /*
2365  * This one handles all set-related commands
2366  *      ipfw set { show | enable | disable }
2367  *      ipfw set swap X Y
2368  *      ipfw set move X to Y
2369  *      ipfw set move rule X to Y
2370  */
2371 static void
2372 sets_handler(int ac, char *av[])
2373 {
2374         uint32_t set_disable, masks[2];
2375         int i, nbytes;
2376         uint16_t rulenum;
2377         uint8_t cmd, new_set;
2378
2379         ac--;
2380         av++;
2381
2382         if (!ac)
2383                 errx(EX_USAGE, "set needs command");
2384         if (_substrcmp(*av, "show") == 0) {
2385                 void *data;
2386                 char const *msg;
2387
2388                 nbytes = sizeof(struct ip_fw);
2389                 if ((data = calloc(1, nbytes)) == NULL)
2390                         err(EX_OSERR, "calloc");
2391                 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2392                         err(EX_OSERR, "getsockopt(IP_FW_GET)");
2393                 bcopy(&((struct ip_fw *)data)->next_rule,
2394                         &set_disable, sizeof(set_disable));
2395
2396                 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2397                         if ((set_disable & (1<<i))) {
2398                                 printf("%s %d", msg, i);
2399                                 msg = "";
2400                         }
2401                 msg = (set_disable) ? " enable" : "enable";
2402                 for (i = 0; i < RESVD_SET; i++)
2403                         if (!(set_disable & (1<<i))) {
2404                                 printf("%s %d", msg, i);
2405                                 msg = "";
2406                         }
2407                 printf("\n");
2408         } else if (_substrcmp(*av, "swap") == 0) {
2409                 ac--; av++;
2410                 if (ac != 2)
2411                         errx(EX_USAGE, "set swap needs 2 set numbers\n");
2412                 rulenum = atoi(av[0]);
2413                 new_set = atoi(av[1]);
2414                 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2415                         errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2416                 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2417                         errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2418                 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2419                 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2420         } else if (_substrcmp(*av, "move") == 0) {
2421                 ac--; av++;
2422                 if (ac && _substrcmp(*av, "rule") == 0) {
2423                         cmd = 2;
2424                         ac--; av++;
2425                 } else
2426                         cmd = 3;
2427                 if (ac != 3 || _substrcmp(av[1], "to") != 0)
2428                         errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2429                 rulenum = atoi(av[0]);
2430                 new_set = atoi(av[2]);
2431                 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2432                         (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
2433                         errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2434                 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2435                         errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2436                 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2437                 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2438         } else if (_substrcmp(*av, "disable") == 0 ||
2439                    _substrcmp(*av, "enable") == 0 ) {
2440                 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2441
2442                 ac--; av++;
2443                 masks[0] = masks[1] = 0;
2444
2445                 while (ac) {
2446                         if (isdigit(**av)) {
2447                                 i = atoi(*av);
2448                                 if (i < 0 || i > RESVD_SET)
2449                                         errx(EX_DATAERR,
2450                                             "invalid set number %d\n", i);
2451                                 masks[which] |= (1<<i);
2452                         } else if (_substrcmp(*av, "disable") == 0)
2453                                 which = 0;
2454                         else if (_substrcmp(*av, "enable") == 0)
2455                                 which = 1;
2456                         else
2457                                 errx(EX_DATAERR,
2458                                         "invalid set command %s\n", *av);
2459                         av++; ac--;
2460                 }
2461                 if ( (masks[0] & masks[1]) != 0 )
2462                         errx(EX_DATAERR,
2463                             "cannot enable and disable the same set\n");
2464
2465                 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2466                 if (i)
2467                         warn("set enable/disable: setsockopt(IP_FW_DEL)");
2468         } else
2469                 errx(EX_USAGE, "invalid set command %s\n", *av);
2470 }
2471
2472 static void
2473 sysctl_handler(int ac, char *av[], int which)
2474 {
2475         ac--;
2476         av++;
2477
2478         if (ac == 0) {
2479                 warnx("missing keyword to enable/disable\n");
2480         } else if (_substrcmp(*av, "firewall") == 0) {
2481                 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2482                     &which, sizeof(which));
2483         } else if (_substrcmp(*av, "one_pass") == 0) {
2484                 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2485                     &which, sizeof(which));
2486         } else if (_substrcmp(*av, "debug") == 0) {
2487                 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2488                     &which, sizeof(which));
2489         } else if (_substrcmp(*av, "verbose") == 0) {
2490                 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2491                     &which, sizeof(which));
2492         } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2493                 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2494                     &which, sizeof(which));
2495         } else if (_substrcmp(*av, "altq") == 0) {
2496                 altq_set_enabled(which);
2497         } else {
2498                 warnx("unrecognize enable/disable keyword: %s\n", *av);
2499         }
2500 }
2501
2502 static void
2503 list(int ac, char *av[], int show_counters)
2504 {
2505         struct ip_fw *r;
2506         ipfw_dyn_rule *dynrules, *d;
2507
2508 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
2509         char *lim;
2510         void *data = NULL;
2511         int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2512         int exitval = EX_OK;
2513         int lac;
2514         char **lav;
2515         u_long rnum, last;
2516         char *endptr;
2517         int seen = 0;
2518         uint8_t set;
2519
2520         const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2521         int nalloc = 1024;      /* start somewhere... */
2522
2523         last = 0;
2524
2525         if (test_only) {
2526                 fprintf(stderr, "Testing only, list disabled\n");
2527                 return;
2528         }
2529
2530         ac--;
2531         av++;
2532
2533         /* get rules or pipes from kernel, resizing array as necessary */
2534         nbytes = nalloc;
2535
2536         while (nbytes >= nalloc) {
2537                 nalloc = nalloc * 2 + 200;
2538                 nbytes = nalloc;
2539                 if ((data = realloc(data, nbytes)) == NULL)
2540                         err(EX_OSERR, "realloc");
2541                 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2542                         err(EX_OSERR, "getsockopt(IP_%s_GET)",
2543                                 do_pipe ? "DUMMYNET" : "FW");
2544         }
2545
2546         if (do_pipe) {
2547                 list_pipes(data, nbytes, ac, av);
2548                 goto done;
2549         }
2550
2551         /*
2552          * Count static rules. They have variable size so we
2553          * need to scan the list to count them.
2554          */
2555         for (nstat = 1, r = data, lim = (char *)data + nbytes;
2556                     r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
2557                     ++nstat, r = NEXT(r) )
2558                 ; /* nothing */
2559
2560         /*
2561          * Count dynamic rules. This is easier as they have
2562          * fixed size.
2563          */
2564         r = NEXT(r);
2565         dynrules = (ipfw_dyn_rule *)r ;
2566         n = (char *)r - (char *)data;
2567         ndyn = (nbytes - n) / sizeof *dynrules;
2568
2569         /* if showing stats, figure out column widths ahead of time */
2570         bcwidth = pcwidth = 0;
2571         if (show_counters) {
2572                 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2573                         /* skip rules from another set */
2574                         if (use_set && r->set != use_set - 1)
2575                                 continue;
2576
2577                         /* packet counter */
2578                         width = snprintf(NULL, 0, "%llu",
2579                             align_uint64(&r->pcnt));
2580                         if (width > pcwidth)
2581                                 pcwidth = width;
2582
2583                         /* byte counter */
2584                         width = snprintf(NULL, 0, "%llu",
2585                             align_uint64(&r->bcnt));
2586                         if (width > bcwidth)
2587                                 bcwidth = width;
2588                 }
2589         }
2590         if (do_dynamic && ndyn) {
2591                 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2592                         if (use_set) {
2593                                 /* skip rules from another set */
2594                                 bcopy((char *)&d->rule + sizeof(uint16_t),
2595                                       &set, sizeof(uint8_t));
2596                                 if (set != use_set - 1)
2597                                         continue;
2598                         }
2599                         width = snprintf(NULL, 0, "%llu",
2600                             align_uint64(&d->pcnt));
2601                         if (width > pcwidth)
2602                                 pcwidth = width;
2603
2604                         width = snprintf(NULL, 0, "%llu",
2605                             align_uint64(&d->bcnt));
2606                         if (width > bcwidth)
2607                                 bcwidth = width;
2608                 }
2609         }
2610         /* if no rule numbers were specified, list all rules */
2611         if (ac == 0) {
2612                 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2613                         if (use_set && r->set != use_set - 1)
2614                                 continue;
2615                         show_ipfw(r, pcwidth, bcwidth);
2616                 }
2617
2618                 if (do_dynamic && ndyn) {
2619                         printf("## Dynamic rules (%d):\n", ndyn);
2620                         for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2621                                 if (use_set) {
2622                                         bcopy((char *)&d->rule + sizeof(uint16_t),
2623                                               &set, sizeof(uint8_t));
2624                                         if (set != use_set - 1)
2625                                                 continue;
2626                                 }
2627                                 show_dyn_ipfw(d, pcwidth, bcwidth);
2628                 }
2629                 }
2630                 goto done;
2631         }
2632
2633         /* display specific rules requested on command line */
2634
2635         for (lac = ac, lav = av; lac != 0; lac--) {
2636                 /* convert command line rule # */
2637                 last = rnum = strtoul(*lav++, &endptr, 10);
2638                 if (*endptr == '-')
2639                         last = strtoul(endptr+1, &endptr, 10);
2640                 if (*endptr) {
2641                         exitval = EX_USAGE;
2642                         warnx("invalid rule number: %s", *(lav - 1));
2643                         continue;
2644                 }
2645                 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2646                         if (r->rulenum > last)
2647                                 break;
2648                         if (use_set && r->set != use_set - 1)
2649                                 continue;
2650                         if (r->rulenum >= rnum && r->rulenum <= last) {
2651                                 show_ipfw(r, pcwidth, bcwidth);
2652                                 seen = 1;
2653                         }
2654                 }
2655                 if (!seen) {
2656                         /* give precedence to other error(s) */
2657                         if (exitval == EX_OK)
2658                                 exitval = EX_UNAVAILABLE;
2659                         warnx("rule %lu does not exist", rnum);
2660                 }
2661         }
2662
2663         if (do_dynamic && ndyn) {
2664                 printf("## Dynamic rules:\n");
2665                 for (lac = ac, lav = av; lac != 0; lac--) {
2666                         last = rnum = strtoul(*lav++, &endptr, 10);
2667                         if (*endptr == '-')
2668                                 last = strtoul(endptr+1, &endptr, 10);
2669                         if (*endptr)
2670                                 /* already warned */
2671                                 continue;
2672                         for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2673                                 uint16_t rulenum;
2674
2675                                 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2676                                 if (rulenum > rnum)
2677                                         break;
2678                                 if (use_set) {
2679                                         bcopy((char *)&d->rule + sizeof(uint16_t),
2680                                               &set, sizeof(uint8_t));
2681                                         if (set != use_set - 1)
2682                                                 continue;
2683                                 }
2684                                 if (r->rulenum >= rnum && r->rulenum <= last)
2685                                         show_dyn_ipfw(d, pcwidth, bcwidth);
2686                         }
2687                 }
2688         }
2689
2690         ac = 0;
2691
2692 done:
2693         free(data);
2694
2695         if (exitval != EX_OK)
2696                 exit(exitval);
2697 #undef NEXT
2698 }
2699
2700 static void
2701 show_usage(void)
2702 {
2703         fprintf(stderr, "usage: ipfw [options]\n"
2704 "do \"ipfw -h\" or see ipfw manpage for details\n"
2705 );
2706         exit(EX_USAGE);
2707 }
2708
2709 static void
2710 help(void)
2711 {
2712         fprintf(stderr,
2713 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n"
2714 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n"
2715 "add [num] [set N] [prob x] RULE-BODY\n"
2716 "{pipe|queue} N config PIPE-BODY\n"
2717 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
2718 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|reset|\n"
2719 "               reverse|proxy_only|redirect_addr linkspec|\n"
2720 "               redirect_port linkspec|redirect_proto linkspec}\n"
2721 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
2722 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n"
2723 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
2724 "table all {flush | list}\n"
2725 "\n"
2726 "RULE-BODY:     check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
2727 "ACTION:        check-state | allow | count | deny | unreach{,6} CODE |\n"
2728 "               skipto N | {divert|tee} PORT | forward ADDR |\n"
2729 "               pipe N | queue N | nat N | setfib FIB\n"
2730 "PARAMS:        [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
2731 "ADDR:          [ MAC dst src ether_type ] \n"
2732 "               [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
2733 "               [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
2734 "IPADDR:        [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
2735 "IP6ADDR:       [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
2736 "IP6LIST:       { ip6 | ip6/bits }[,IP6LIST]\n"
2737 "IPLIST:        { ip | ip/bits | ip:mask }[,IPLIST]\n"
2738 "OPTION_LIST:   OPTION [OPTION_LIST]\n"
2739 "OPTION:        bridged | diverted | diverted-loopback | diverted-output |\n"
2740 "       {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
2741 "       {dst-port|src-port} LIST |\n"
2742 "       estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
2743 "       iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
2744 "       ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
2745 "       icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n"
2746 "       mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
2747 "       setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
2748 "       tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
2749 );
2750 exit(0);
2751 }
2752
2753
2754 static int
2755 lookup_host (char *host, struct in_addr *ipaddr)
2756 {
2757         struct hostent *he;
2758
2759         if (!inet_aton(host, ipaddr)) {
2760                 if ((he = gethostbyname(host)) == NULL)
2761                         return(-1);
2762                 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2763         }
2764         return(0);
2765 }
2766
2767 /*
2768  * fills the addr and mask fields in the instruction as appropriate from av.
2769  * Update length as appropriate.
2770  * The following formats are allowed:
2771  *      me      returns O_IP_*_ME
2772  *      1.2.3.4         single IP address
2773  *      1.2.3.4:5.6.7.8 address:mask
2774  *      1.2.3.4/24      address/mask
2775  *      1.2.3.4/26{1,6,5,4,23}  set of addresses in a subnet
2776  * We can have multiple comma-separated address/mask entries.
2777  */
2778 static void
2779 fill_ip(ipfw_insn_ip *cmd, char *av)
2780 {
2781         int len = 0;
2782         uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2783
2784         cmd->o.len &= ~F_LEN_MASK;      /* zero len */
2785
2786         if (_substrcmp(av, "any") == 0)
2787                 return;
2788
2789         if (_substrcmp(av, "me") == 0) {
2790                 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2791                 return;
2792         }
2793
2794         if (strncmp(av, "table(", 6) == 0) {
2795                 char *p = strchr(av + 6, ',');
2796
2797                 if (p)
2798                         *p++ = '\0';
2799                 cmd->o.opcode = O_IP_DST_LOOKUP;
2800                 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2801                 if (p) {
2802                         cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2803                         d[0] = strtoul(p, NULL, 0);
2804                 } else
2805                         cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2806                 return;
2807         }
2808
2809     while (av) {
2810         /*
2811          * After the address we can have '/' or ':' indicating a mask,
2812          * ',' indicating another address follows, '{' indicating a
2813          * set of addresses of unspecified size.
2814          */
2815         char *t = NULL, *p = strpbrk(av, "/:,{");
2816         int masklen;
2817         char md, nd;
2818
2819         if (p) {
2820                 md = *p;
2821                 *p++ = '\0';
2822                 if ((t = strpbrk(p, ",{")) != NULL) {
2823                         nd = *t;
2824                         *t = '\0';
2825                 }
2826         } else
2827                 md = '\0';
2828
2829         if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2830                 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2831         switch (md) {
2832         case ':':
2833                 if (!inet_aton(p, (struct in_addr *)&d[1]))
2834                         errx(EX_DATAERR, "bad netmask ``%s''", p);
2835                 break;
2836         case '/':
2837                 masklen = atoi(p);
2838                 if (masklen == 0)
2839                         d[1] = htonl(0);        /* mask */
2840                 else if (masklen > 32)
2841                         errx(EX_DATAERR, "bad width ``%s''", p);
2842                 else
2843                         d[1] = htonl(~0 << (32 - masklen));
2844                 break;
2845         case '{':       /* no mask, assume /24 and put back the '{' */
2846                 d[1] = htonl(~0 << (32 - 24));
2847                 *(--p) = md;
2848                 break;
2849
2850         case ',':       /* single address plus continuation */
2851                 *(--p) = md;
2852                 /* FALLTHROUGH */
2853         case 0:         /* initialization value */
2854         default:
2855                 d[1] = htonl(~0);       /* force /32 */
2856                 break;
2857         }
2858         d[0] &= d[1];           /* mask base address with mask */
2859         if (t)
2860                 *t = nd;
2861         /* find next separator */
2862         if (p)
2863                 p = strpbrk(p, ",{");
2864         if (p && *p == '{') {
2865                 /*
2866                  * We have a set of addresses. They are stored as follows:
2867                  *   arg1       is the set size (powers of 2, 2..256)
2868                  *   addr       is the base address IN HOST FORMAT
2869                  *   mask..     is an array of arg1 bits (rounded up to
2870                  *              the next multiple of 32) with bits set
2871                  *              for each host in the map.
2872                  */
2873                 uint32_t *map = (uint32_t *)&cmd->mask;
2874                 int low, high;
2875                 int i = contigmask((uint8_t *)&(d[1]), 32);
2876
2877                 if (len > 0)
2878                         errx(EX_DATAERR, "address set cannot be in a list");
2879                 if (i < 24 || i > 31)
2880                         errx(EX_DATAERR, "invalid set with mask %d\n", i);
2881                 cmd->o.arg1 = 1<<(32-i);        /* map length           */
2882                 d[0] = ntohl(d[0]);             /* base addr in host format */
2883                 cmd->o.opcode = O_IP_DST_SET;   /* default */
2884                 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2885                 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2886                         map[i] = 0;     /* clear map */
2887
2888                 av = p + 1;
2889                 low = d[0] & 0xff;
2890                 high = low + cmd->o.arg1 - 1;
2891                 /*
2892                  * Here, i stores the previous value when we specify a range
2893                  * of addresses within a mask, e.g. 45-63. i = -1 means we
2894                  * have no previous value.
2895                  */
2896                 i = -1; /* previous value in a range */
2897                 while (isdigit(*av)) {
2898                         char *s;
2899                         int a = strtol(av, &s, 0);
2900
2901                         if (s == av) { /* no parameter */
2902                             if (*av != '}')
2903                                 errx(EX_DATAERR, "set not closed\n");
2904                             if (i != -1)
2905                                 errx(EX_DATAERR, "incomplete range %d-", i);
2906                             break;
2907                         }
2908                         if (a < low || a > high)
2909                             errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2910                                 a, low, high);
2911                         a -= low;
2912                         if (i == -1)    /* no previous in range */
2913                             i = a;
2914                         else {          /* check that range is valid */
2915                             if (i > a)
2916                                 errx(EX_DATAERR, "invalid range %d-%d",
2917                                         i+low, a+low);
2918                             if (*s == '-')
2919                                 errx(EX_DATAERR, "double '-' in range");
2920                         }
2921                         for (; i <= a; i++)
2922                             map[i/32] |= 1<<(i & 31);
2923                         i = -1;
2924                         if (*s == '-')
2925                             i = a;
2926                         else if (*s == '}')
2927                             break;
2928                         av = s+1;
2929                 }
2930                 return;
2931         }
2932         av = p;
2933         if (av)                 /* then *av must be a ',' */
2934                 av++;
2935
2936         /* Check this entry */
2937         if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2938                 /*
2939                  * 'any' turns the entire list into a NOP.
2940                  * 'not any' never matches, so it is removed from the
2941                  * list unless it is the only item, in which case we
2942                  * report an error.
2943                  */
2944                 if (cmd->o.len & F_NOT) {       /* "not any" never matches */
2945                         if (av == NULL && len == 0) /* only this entry */
2946                                 errx(EX_DATAERR, "not any never matches");
2947                 }
2948                 /* else do nothing and skip this entry */
2949                 return;
2950         }
2951         /* A single IP can be stored in an optimized format */
2952         if (d[1] == IP_MASK_ALL && av == NULL && len == 0) {
2953                 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2954                 return;
2955         }
2956         len += 2;       /* two words... */
2957         d += 2;
2958     } /* end while */
2959     if (len + 1 > F_LEN_MASK)
2960         errx(EX_DATAERR, "address list too long");
2961     cmd->o.len |= len+1;
2962 }
2963
2964
2965 /* Try to find ipv6 address by hostname */
2966 static int
2967 lookup_host6 (char *host, struct in6_addr *ip6addr)
2968 {
2969         struct hostent *he;
2970
2971         if (!inet_pton(AF_INET6, host, ip6addr)) {
2972                 if ((he = gethostbyname2(host, AF_INET6)) == NULL)
2973                         return(-1);
2974                 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr));
2975         }
2976         return(0);
2977 }
2978
2979
2980 /* n2mask sets n bits of the mask */
2981 static void
2982 n2mask(struct in6_addr *mask, int n)
2983 {
2984         static int      minimask[9] =
2985             { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2986         u_char          *p;
2987
2988         memset(mask, 0, sizeof(struct in6_addr));
2989         p = (u_char *) mask;
2990         for (; n > 0; p++, n -= 8) {
2991                 if (n >= 8)
2992                         *p = 0xff;
2993                 else
2994                         *p = minimask[n];
2995         }
2996         return;
2997 }
2998  
2999
3000 /*
3001  * fill the addr and mask fields in the instruction as appropriate from av.
3002  * Update length as appropriate.
3003  * The following formats are allowed:
3004  *     any     matches any IP6. Actually returns an empty instruction.
3005  *     me      returns O_IP6_*_ME
3006  *
3007  *     03f1::234:123:0342                single IP6 addres
3008  *     03f1::234:123:0342/24            address/mask
3009  *     03f1::234:123:0342/24,03f1::234:123:0343/               List of address
3010  *
3011  * Set of address (as in ipv6) not supported because ipv6 address
3012  * are typically random past the initial prefix.
3013  * Return 1 on success, 0 on failure.
3014  */
3015 static int
3016 fill_ip6(ipfw_insn_ip6 *cmd, char *av)
3017 {
3018         int len = 0;
3019         struct in6_addr *d = &(cmd->addr6);
3020         /*
3021          * Needed for multiple address.
3022          * Note d[1] points to struct in6_add r mask6 of cmd
3023          */
3024
3025        cmd->o.len &= ~F_LEN_MASK;       /* zero len */
3026
3027        if (strcmp(av, "any") == 0)
3028                return (1);
3029
3030
3031        if (strcmp(av, "me") == 0) {     /* Set the data for "me" opt*/
3032                cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3033                return (1);
3034        }
3035
3036        if (strcmp(av, "me6") == 0) {    /* Set the data for "me" opt*/
3037                cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3038                return (1);
3039        }
3040
3041        av = strdup(av);
3042        while (av) {
3043                 /*
3044                  * After the address we can have '/' indicating a mask,
3045                  * or ',' indicating another address follows.
3046                  */
3047
3048                 char *p;
3049                 int masklen;
3050                 char md = '\0';
3051
3052                 if ((p = strpbrk(av, "/,")) ) {
3053                         md = *p;        /* save the separator */
3054                         *p = '\0';      /* terminate address string */
3055                         p++;            /* and skip past it */
3056                 }
3057                 /* now p points to NULL, mask or next entry */
3058
3059                 /* lookup stores address in *d as a side effect */
3060                 if (lookup_host6(av, d) != 0) {
3061                         /* XXX: failed. Free memory and go */
3062                         errx(EX_DATAERR, "bad address \"%s\"", av);
3063                 }
3064                 /* next, look at the mask, if any */
3065                 masklen = (md == '/') ? atoi(p) : 128;
3066                 if (masklen > 128 || masklen < 0)
3067                         errx(EX_DATAERR, "bad width \"%s\''", p);
3068                 else
3069                         n2mask(&d[1], masklen);
3070
3071                 APPLY_MASK(d, &d[1])   /* mask base address with mask */
3072
3073                 /* find next separator */
3074
3075                 if (md == '/') {        /* find separator past the mask */
3076                         p = strpbrk(p, ",");
3077                         if (p != NULL)
3078                                 p++;
3079                 }
3080                 av = p;
3081
3082                 /* Check this entry */
3083                 if (masklen == 0) {
3084                         /*
3085                          * 'any' turns the entire list into a NOP.
3086                          * 'not any' never matches, so it is removed from the
3087                          * list unless it is the only item, in which case we
3088                          * report an error.
3089                          */
3090                         if (cmd->o.len & F_NOT && av == NULL && len == 0)
3091                                 errx(EX_DATAERR, "not any never matches");
3092                         continue;
3093                 }
3094
3095                 /*
3096                  * A single IP can be stored alone
3097                  */
3098                 if (masklen == 128 && av == NULL && len == 0) {
3099                         len = F_INSN_SIZE(struct in6_addr);
3100                         break;
3101                 }
3102
3103                 /* Update length and pointer to arguments */
3104                 len += F_INSN_SIZE(struct in6_addr)*2;
3105                 d += 2;
3106         } /* end while */
3107
3108         /*
3109          * Total length of the command, remember that 1 is the size of
3110          * the base command.
3111          */
3112         if (len + 1 > F_LEN_MASK)
3113                 errx(EX_DATAERR, "address list too long");
3114         cmd->o.len |= len+1;
3115         free(av);
3116         return (1);
3117 }
3118
3119 /*
3120  * fills command for ipv6 flow-id filtering
3121  * note that the 20 bit flow number is stored in a array of u_int32_t
3122  * it's supported lists of flow-id, so in the o.arg1 we store how many
3123  * additional flow-id we want to filter, the basic is 1
3124  */
3125 void
3126 fill_flow6( ipfw_insn_u32 *cmd, char *av )
3127 {
3128         u_int32_t type;  /* Current flow number */
3129         u_int16_t nflow = 0;    /* Current flow index */
3130         char *s = av;
3131         cmd->d[0] = 0;    /* Initializing the base number*/
3132
3133         while (s) {
3134                 av = strsep( &s, ",") ;
3135                 type = strtoul(av, &av, 0);
3136                 if (*av != ',' && *av != '\0')
3137                         errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
3138                 if (type > 0xfffff)
3139                         errx(EX_DATAERR, "flow number out of range %s", av);
3140                 cmd->d[nflow] |= type;
3141                 nflow++;
3142         }
3143         if( nflow > 0 ) {
3144                 cmd->o.opcode = O_FLOW6ID;
3145                 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow;
3146                 cmd->o.arg1 = nflow;
3147         }
3148         else {
3149                 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
3150         }
3151 }
3152
3153 static ipfw_insn *
3154 add_srcip6(ipfw_insn *cmd, char *av)
3155 {
3156
3157         fill_ip6((ipfw_insn_ip6 *)cmd, av);
3158         if (F_LEN(cmd) == 0)                            /* any */
3159                 ;
3160         if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) {     /* "me" */
3161                 cmd->opcode = O_IP6_SRC_ME;
3162         } else if (F_LEN(cmd) ==
3163             (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
3164                 /* single IP, no mask*/
3165                 cmd->opcode = O_IP6_SRC;
3166         } else {                                        /* addr/mask opt */
3167                 cmd->opcode = O_IP6_SRC_MASK;
3168         }
3169         return cmd;
3170 }
3171
3172 static ipfw_insn *
3173 add_dstip6(ipfw_insn *cmd, char *av)
3174 {
3175
3176         fill_ip6((ipfw_insn_ip6 *)cmd, av);
3177         if (F_LEN(cmd) == 0)                            /* any */
3178                 ;
3179         if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) {     /* "me" */
3180                 cmd->opcode = O_IP6_DST_ME;
3181         } else if (F_LEN(cmd) ==
3182             (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
3183                 /* single IP, no mask*/
3184                 cmd->opcode = O_IP6_DST;
3185         } else {                                        /* addr/mask opt */
3186                 cmd->opcode = O_IP6_DST_MASK;
3187         }
3188         return cmd;
3189 }
3190
3191
3192 /*
3193  * helper function to process a set of flags and set bits in the
3194  * appropriate masks.
3195  */
3196 static void
3197 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3198         struct _s_x *flags, char *p)
3199 {
3200         uint8_t set=0, clear=0;
3201
3202         while (p && *p) {
3203                 char *q;        /* points to the separator */
3204                 int val;
3205                 uint8_t *which; /* mask we are working on */
3206
3207                 if (*p == '!') {
3208                         p++;
3209                         which = &clear;
3210                 } else
3211                         which = &set;
3212                 q = strchr(p, ',');
3213                 if (q)
3214                         *q++ = '\0';
3215                 val = match_token(flags, p);
3216                 if (val <= 0)
3217                         errx(EX_DATAERR, "invalid flag %s", p);
3218                 *which |= (uint8_t)val;
3219                 p = q;
3220         }
3221         cmd->opcode = opcode;
3222         cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
3223         cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3224 }
3225
3226
3227 static void
3228 delete(int ac, char *av[])
3229 {
3230         uint32_t rulenum;
3231         struct dn_pipe p;
3232         int i;
3233         int exitval = EX_OK;
3234         int do_set = 0;
3235
3236         memset(&p, 0, sizeof p);
3237
3238         av++; ac--;
3239         NEED1("missing rule specification");
3240         if (ac > 0 && _substrcmp(*av, "set") == 0) {
3241                 /* Do not allow using the following syntax:
3242                  *      ipfw set N delete set M
3243                  */
3244                 if (use_set)
3245                         errx(EX_DATAERR, "invalid syntax");
3246                 do_set = 1;     /* delete set */
3247                 ac--; av++;
3248         }
3249
3250         /* Rule number */
3251         while (ac && isdigit(**av)) {
3252                 i = atoi(*av); av++; ac--;
3253                 if (do_nat) {
3254                         exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3255                         if (exitval) {
3256                                 exitval = EX_UNAVAILABLE;
3257                                 warn("rule %u not available", i);
3258                         }
3259                 } else if (do_pipe) {
3260                         if (do_pipe == 1)
3261                                 p.pipe_nr = i;
3262                         else
3263                                 p.fs.fs_nr = i;
3264                         i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
3265                         if (i) {
3266                                 exitval = 1;
3267                                 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
3268                                     do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
3269                         }
3270                 } else {
3271                         if (use_set)
3272                                 rulenum = (i & 0xffff) | (5 << 24) |
3273                                     ((use_set - 1) << 16);
3274                         else
3275                         rulenum =  (i & 0xffff) | (do_set << 24);
3276                         i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
3277                         if (i) {
3278                                 exitval = EX_UNAVAILABLE;
3279                                 warn("rule %u: setsockopt(IP_FW_DEL)",
3280                                     rulenum);
3281                         }
3282                 }
3283         }
3284         if (exitval != EX_OK)
3285                 exit(exitval);
3286 }
3287
3288
3289 /*
3290  * fill the interface structure. We do not check the name as we can
3291  * create interfaces dynamically, so checking them at insert time
3292  * makes relatively little sense.
3293  * Interface names containing '*', '?', or '[' are assumed to be shell 
3294  * patterns which match interfaces.
3295  */
3296 static void
3297 fill_iface(ipfw_insn_if *cmd, char *arg)
3298 {
3299         cmd->name[0] = '\0';
3300         cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3301
3302         /* Parse the interface or address */
3303         if (strcmp(arg, "any") == 0)
3304                 cmd->o.len = 0;         /* effectively ignore this command */
3305         else if (!isdigit(*arg)) {
3306                 strlcpy(cmd->name, arg, sizeof(cmd->name));
3307                 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3308         } else if (!inet_aton(arg, &cmd->p.ip))
3309                 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3310 }
3311
3312 /* 
3313  * Search for interface with name "ifn", and fill n accordingly:
3314  *
3315  * n->ip        ip address of interface "ifn"
3316  * n->if_name   copy of interface name "ifn"
3317  */
3318 static void
3319 set_addr_dynamic(const char *ifn, struct cfg_nat *n)
3320 {
3321         size_t needed;
3322         int mib[6];
3323         char *buf, *lim, *next;
3324         struct if_msghdr *ifm;
3325         struct ifa_msghdr *ifam;
3326         struct sockaddr_dl *sdl;
3327         struct sockaddr_in *sin;
3328         int ifIndex, ifMTU;
3329
3330         mib[0] = CTL_NET;
3331         mib[1] = PF_ROUTE;
3332         mib[2] = 0;
3333         mib[3] = AF_INET;       
3334         mib[4] = NET_RT_IFLIST;
3335         mib[5] = 0;             
3336 /*
3337  * Get interface data.
3338  */
3339         if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
3340                 err(1, "iflist-sysctl-estimate");
3341         if ((buf = malloc(needed)) == NULL)
3342                 errx(1, "malloc failed");
3343         if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
3344                 err(1, "iflist-sysctl-get");
3345         lim = buf + needed;
3346 /*
3347  * Loop through interfaces until one with
3348  * given name is found. This is done to
3349  * find correct interface index for routing
3350  * message processing.
3351  */
3352         ifIndex = 0;
3353         next = buf;
3354         while (next < lim) {
3355                 ifm = (struct if_msghdr *)next;
3356                 next += ifm->ifm_msglen;
3357                 if (ifm->ifm_version != RTM_VERSION) {
3358                         if (verbose)
3359                                 warnx("routing message version %d "
3360                                     "not understood", ifm->ifm_version);
3361                         continue;
3362                 }
3363                 if (ifm->ifm_type == RTM_IFINFO) {
3364                         sdl = (struct sockaddr_dl *)(ifm + 1);
3365                         if (strlen(ifn) == sdl->sdl_nlen &&
3366                             strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
3367                                 ifIndex = ifm->ifm_index;
3368                                 ifMTU = ifm->ifm_data.ifi_mtu;
3369                                 break;
3370                         }
3371                 }
3372         }
3373         if (!ifIndex)
3374                 errx(1, "unknown interface name %s", ifn);
3375 /*
3376  * Get interface address.
3377  */
3378         sin = NULL;
3379         while (next < lim) {
3380                 ifam = (struct ifa_msghdr *)next;
3381                 next += ifam->ifam_msglen;
3382                 if (ifam->ifam_version != RTM_VERSION) {
3383                         if (verbose)
3384                                 warnx("routing message version %d "
3385                                     "not understood", ifam->ifam_version);
3386                         continue;
3387                 }
3388                 if (ifam->ifam_type != RTM_NEWADDR)
3389                         break;
3390                 if (ifam->ifam_addrs & RTA_IFA) {
3391                         int i;
3392                         char *cp = (char *)(ifam + 1);
3393
3394                         for (i = 1; i < RTA_IFA; i <<= 1) {
3395                                 if (ifam->ifam_addrs & i)
3396                                         cp += SA_SIZE((struct sockaddr *)cp);
3397                         }
3398                         if (((struct sockaddr *)cp)->sa_family == AF_INET) {
3399                                 sin = (struct sockaddr_in *)cp;
3400                                 break;
3401                         }
3402                 }
3403         }
3404         if (sin == NULL)
3405                 errx(1, "%s: cannot get interface address", ifn);
3406
3407         n->ip = sin->sin_addr;
3408         strncpy(n->if_name, ifn, IF_NAMESIZE);
3409
3410         free(buf);
3411 }
3412
3413 /* 
3414  * XXX - The following functions, macros and definitions come from natd.c:
3415  * it would be better to move them outside natd.c, in a file 
3416  * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live 
3417  * with it.
3418  */
3419
3420 /*
3421  * Definition of a port range, and macros to deal with values.
3422  * FORMAT:  HI 16-bits == first port in range, 0 == all ports.
3423  *          LO 16-bits == number of ports in range
3424  * NOTES:   - Port values are not stored in network byte order.
3425  */
3426
3427 #define port_range u_long
3428
3429 #define GETLOPORT(x)     ((x) >> 0x10)
3430 #define GETNUMPORTS(x)   ((x) & 0x0000ffff)
3431 #define GETHIPORT(x)     (GETLOPORT((x)) + GETNUMPORTS((x)))
3432
3433 /* Set y to be the low-port value in port_range variable x. */
3434 #define SETLOPORT(x,y)   ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
3435
3436 /* Set y to be the number of ports in port_range variable x. */
3437 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
3438
3439 static void 
3440 StrToAddr (const char* str, struct in_addr* addr)
3441 {
3442         struct hostent* hp;
3443
3444         if (inet_aton (str, addr))
3445                 return;
3446
3447         hp = gethostbyname (str);
3448         if (!hp)
3449                 errx (1, "unknown host %s", str);
3450
3451         memcpy (addr, hp->h_addr, sizeof (struct in_addr));
3452 }
3453
3454 static int 
3455 StrToPortRange (const char* str, const char* proto, port_range *portRange)
3456 {
3457         char*           sep;
3458         struct servent* sp;
3459         char*           end;
3460         u_short         loPort;
3461         u_short         hiPort;
3462         
3463         /* First see if this is a service, return corresponding port if so. */
3464         sp = getservbyname (str,proto);
3465         if (sp) {
3466                 SETLOPORT(*portRange, ntohs(sp->s_port));
3467                 SETNUMPORTS(*portRange, 1);
3468                 return 0;
3469         }
3470                 
3471         /* Not a service, see if it's a single port or port range. */
3472         sep = strchr (str, '-');
3473         if (sep == NULL) {
3474                 SETLOPORT(*portRange, strtol(str, &end, 10));
3475                 if (end != str) {
3476                         /* Single port. */
3477                         SETNUMPORTS(*portRange, 1);
3478                         return 0;
3479                 }
3480
3481                 /* Error in port range field. */
3482                 errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
3483         }
3484
3485         /* Port range, get the values and sanity check. */
3486         sscanf (str, "%hu-%hu", &loPort, &hiPort);
3487         SETLOPORT(*portRange, loPort);
3488         SETNUMPORTS(*portRange, 0);     /* Error by default */
3489         if (loPort <= hiPort)
3490                 SETNUMPORTS(*portRange, hiPort - loPort + 1);
3491
3492         if (GETNUMPORTS(*portRange) == 0)
3493                 errx (EX_DATAERR, "invalid port range %s", str);
3494
3495         return 0;
3496 }
3497
3498 static int 
3499 StrToProto (const char* str)
3500 {
3501         if (!strcmp (str, "tcp"))
3502                 return IPPROTO_TCP;
3503
3504         if (!strcmp (str, "udp"))
3505                 return IPPROTO_UDP;
3506
3507         errx (EX_DATAERR, "unknown protocol %s. Expected tcp or udp", str);
3508 }
3509
3510 static int 
3511 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto, 
3512                        port_range *portRange)
3513 {
3514         char*   ptr;
3515
3516         ptr = strchr (str, ':');
3517         if (!ptr)
3518                 errx (EX_DATAERR, "%s is missing port number", str);
3519
3520         *ptr = '\0';
3521         ++ptr;
3522
3523         StrToAddr (str, addr);
3524         return StrToPortRange (ptr, proto, portRange);
3525 }
3526
3527 /* End of stuff taken from natd.c. */
3528
3529 #define INC_ARGCV() do {        \
3530         (*_av)++;               \
3531         (*_ac)--;               \
3532         av = *_av;              \
3533         ac = *_ac;              \
3534 } while(0)
3535
3536 /* 
3537  * The next 3 functions add support for the addr, port and proto redirect and 
3538  * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect() 
3539  * and SetupProtoRedirect() from natd.c.
3540  *
3541  * Every setup_* function fills at least one redirect entry 
3542  * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool) 
3543  * in buf.
3544  * 
3545  * The format of data in buf is:
3546  * 
3547  *
3548  *     cfg_nat    cfg_redir    cfg_spool    ......  cfg_spool 
3549  *
3550  *    -------------------------------------        ------------
3551  *   |          | .....X ... |          |         |           |  .....
3552  *    ------------------------------------- ...... ------------
3553  *                     ^          
3554  *                spool_cnt       n=0       ......   n=(X-1)
3555  *
3556  * len points to the amount of available space in buf
3557  * space counts the memory consumed by every function
3558  *
3559  * XXX - Every function get all the argv params so it 
3560  * has to check, in optional parameters, that the next
3561  * args is a valid option for the redir entry and not 
3562  * another token. Only redir_port and redir_proto are 
3563  * affected by this.
3564  */
3565
3566 static int
3567 setup_redir_addr(char *spool_buf, int len,
3568                  int *_ac, char ***_av) 
3569 {
3570         char **av, *sep; /* Token separator. */
3571         /* Temporary buffer used to hold server pool ip's. */
3572         char tmp_spool_buf[NAT_BUF_LEN]; 
3573         int ac, space, lsnat;
3574         struct cfg_redir *r;    
3575         struct cfg_spool *tmp;          
3576
3577         av = *_av;
3578         ac = *_ac;
3579         space = 0;
3580         lsnat = 0;
3581         if (len >= SOF_REDIR) {
3582                 r = (struct cfg_redir *)spool_buf;
3583                 /* Skip cfg_redir at beginning of buf. */
3584                 spool_buf = &spool_buf[SOF_REDIR];
3585                 space = SOF_REDIR;
3586                 len -= SOF_REDIR;
3587         } else 
3588                 goto nospace; 
3589         r->mode = REDIR_ADDR;
3590         /* Extract local address. */
3591         if (ac == 0) 
3592                 errx(EX_DATAERR, "redirect_addr: missing local address");
3593         sep = strchr(*av, ',');
3594         if (sep) {              /* LSNAT redirection syntax. */
3595                 r->laddr.s_addr = INADDR_NONE;
3596                 /* Preserve av, copy spool servers to tmp_spool_buf. */
3597                 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
3598                 lsnat = 1;
3599         } else 
3600                 StrToAddr(*av, &r->laddr);              
3601         INC_ARGCV();
3602
3603         /* Extract public address. */
3604         if (ac == 0) 
3605                 errx(EX_DATAERR, "redirect_addr: missing public address");
3606         StrToAddr(*av, &r->paddr);
3607         INC_ARGCV();
3608
3609         /* Setup LSNAT server pool. */
3610         if (sep) {
3611                 sep = strtok(tmp_spool_buf, ",");               
3612                 while (sep != NULL) {
3613                         tmp = (struct cfg_spool *)spool_buf;            
3614                         if (len < SOF_SPOOL)
3615                                 goto nospace;
3616                         len -= SOF_SPOOL;
3617                         space += SOF_SPOOL;                     
3618                         StrToAddr(sep, &tmp->addr);
3619                         tmp->port = ~0;
3620                         r->spool_cnt++;
3621                         /* Point to the next possible cfg_spool. */
3622                         spool_buf = &spool_buf[SOF_SPOOL];
3623                         sep = strtok(NULL, ",");
3624                 }
3625         }
3626         return(space);
3627 nospace:
3628         errx(EX_DATAERR, "redirect_addr: buf is too small\n");
3629 }
3630
3631 static int
3632 setup_redir_port(char *spool_buf, int len,
3633                  int *_ac, char ***_av) 
3634 {
3635         char **av, *sep, *protoName;
3636         char tmp_spool_buf[NAT_BUF_LEN];
3637         int ac, space, lsnat;
3638         struct cfg_redir *r;
3639         struct cfg_spool *tmp;
3640         u_short numLocalPorts;
3641         port_range portRange;   
3642
3643         av = *_av;
3644         ac = *_ac;
3645         space = 0;
3646         lsnat = 0;
3647         numLocalPorts = 0;      
3648
3649         if (len >= SOF_REDIR) {
3650                 r = (struct cfg_redir *)spool_buf;
3651                 /* Skip cfg_redir at beginning of buf. */
3652                 spool_buf = &spool_buf[SOF_REDIR];
3653                 space = SOF_REDIR;
3654                 len -= SOF_REDIR;
3655         } else 
3656                 goto nospace; 
3657         r->mode = REDIR_PORT;
3658         /*
3659          * Extract protocol.
3660          */
3661         if (ac == 0)
3662                 errx (EX_DATAERR, "redirect_port: missing protocol");
3663         r->proto = StrToProto(*av);
3664         protoName = *av;        
3665         INC_ARGCV();
3666
3667         /*
3668          * Extract local address.
3669          */
3670         if (ac == 0)
3671                 errx (EX_DATAERR, "redirect_port: missing local address");
3672
3673         sep = strchr(*av, ',');
3674         /* LSNAT redirection syntax. */
3675         if (sep) {
3676                 r->laddr.s_addr = INADDR_NONE;
3677                 r->lport = ~0;
3678                 numLocalPorts = 1;
3679                 /* Preserve av, copy spool servers to tmp_spool_buf. */
3680                 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
3681                 lsnat = 1;
3682         } else {
3683                 if (StrToAddrAndPortRange (*av, &r->laddr, protoName, 
3684                     &portRange) != 0)
3685                         errx(EX_DATAERR, "redirect_port:"
3686                             "invalid local port range");
3687
3688                 r->lport = GETLOPORT(portRange);
3689                 numLocalPorts = GETNUMPORTS(portRange);
3690         }
3691         INC_ARGCV();    
3692
3693         /*
3694          * Extract public port and optionally address.
3695          */
3696         if (ac == 0)
3697                 errx (EX_DATAERR, "redirect_port: missing public port");
3698
3699         sep = strchr (*av, ':');
3700         if (sep) {
3701                 if (StrToAddrAndPortRange (*av, &r->paddr, protoName, 
3702                     &portRange) != 0)
3703                         errx(EX_DATAERR, "redirect_port:" 
3704                             "invalid public port range");
3705         } else {
3706                 r->paddr.s_addr = INADDR_ANY;
3707                 if (StrToPortRange (*av, protoName, &portRange) != 0)
3708                         errx(EX_DATAERR, "redirect_port:"
3709                             "invalid public port range");
3710         }
3711
3712         r->pport = GETLOPORT(portRange);
3713         r->pport_cnt = GETNUMPORTS(portRange);
3714         INC_ARGCV();
3715
3716         /*
3717          * Extract remote address and optionally port.
3718          */     
3719         /* 
3720          * NB: isalpha(**av) => we've to check that next parameter is really an
3721          * option for this redirect entry, else stop here processing arg[cv].
3722          */
3723         if (ac != 0 && !isalpha(**av)) { 
3724                 sep = strchr (*av, ':');
3725                 if (sep) {
3726                         if (StrToAddrAndPortRange (*av, &r->raddr, protoName, 
3727                             &portRange) != 0)
3728                                 errx(EX_DATAERR, "redirect_port:"
3729                                     "invalid remote port range");
3730                 } else {
3731                         SETLOPORT(portRange, 0);
3732                         SETNUMPORTS(portRange, 1);
3733                         StrToAddr (*av, &r->raddr);
3734                 }
3735                 INC_ARGCV();
3736         } else {
3737                 SETLOPORT(portRange, 0);
3738                 SETNUMPORTS(portRange, 1);
3739                 r->raddr.s_addr = INADDR_ANY;
3740         }
3741         r->rport = GETLOPORT(portRange);
3742         r->rport_cnt = GETNUMPORTS(portRange);
3743
3744         /* 
3745          * Make sure port ranges match up, then add the redirect ports.
3746          */
3747         if (numLocalPorts != r->pport_cnt)
3748                 errx(EX_DATAERR, "redirect_port:"
3749                     "port ranges must be equal in size");
3750
3751         /* Remote port range is allowed to be '0' which means all ports. */
3752         if (r->rport_cnt != numLocalPorts && 
3753             (r->rport_cnt != 1 || r->rport != 0))
3754                 errx(EX_DATAERR, "redirect_port: remote port must"
3755                     "be 0 or equal to local port range in size");
3756
3757         /*
3758          * Setup LSNAT server pool.
3759          */
3760         if (lsnat) {
3761                 sep = strtok(tmp_spool_buf, ",");
3762                 while (sep != NULL) {
3763                         tmp = (struct cfg_spool *)spool_buf;
3764                         if (len < SOF_SPOOL)
3765                                 goto nospace;
3766                         len -= SOF_SPOOL;
3767                         space += SOF_SPOOL;
3768                         if (StrToAddrAndPortRange(sep, &tmp->addr, protoName, 
3769                             &portRange) != 0)
3770                                 errx(EX_DATAERR, "redirect_port:"
3771                                     "invalid local port range");
3772                         if (GETNUMPORTS(portRange) != 1)
3773                                 errx(EX_DATAERR, "redirect_port: local port"
3774                                     "must be single in this context");
3775                         tmp->port = GETLOPORT(portRange);
3776                         r->spool_cnt++; 
3777                         /* Point to the next possible cfg_spool. */
3778                         spool_buf = &spool_buf[SOF_SPOOL];
3779                         sep = strtok(NULL, ",");
3780                 }
3781         }
3782         return (space);
3783 nospace:
3784         errx(EX_DATAERR, "redirect_port: buf is too small\n");
3785 }
3786
3787 static int
3788 setup_redir_proto(char *spool_buf, int len,
3789                  int *_ac, char ***_av) 
3790 {
3791         char **av;
3792         int ac, space;
3793         struct protoent *protoent;
3794         struct cfg_redir *r;
3795         
3796         av = *_av;
3797         ac = *_ac;
3798         if (len >= SOF_REDIR) {
3799                 r = (struct cfg_redir *)spool_buf;
3800                 /* Skip cfg_redir at beginning of buf. */
3801                 spool_buf = &spool_buf[SOF_REDIR];
3802                 space = SOF_REDIR;
3803                 len -= SOF_REDIR;
3804         } else 
3805                 goto nospace;
3806         r->mode = REDIR_PROTO;
3807         /*
3808          * Extract protocol.
3809          */     
3810         if (ac == 0)
3811                 errx(EX_DATAERR, "redirect_proto: missing protocol");
3812
3813         protoent = getprotobyname(*av);
3814         if (protoent == NULL)
3815                 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av);
3816         else
3817                 r->proto = protoent->p_proto;
3818
3819         INC_ARGCV();
3820         
3821         /*
3822          * Extract local address.
3823          */
3824         if (ac == 0)
3825                 errx(EX_DATAERR, "redirect_proto: missing local address");
3826         else
3827                 StrToAddr(*av, &r->laddr);
3828
3829         INC_ARGCV();
3830         
3831         /*
3832          * Extract optional public address.
3833          */
3834         if (ac == 0) {
3835                 r->paddr.s_addr = INADDR_ANY;           
3836                 r->raddr.s_addr = INADDR_ANY;   
3837         } else {
3838                 /* see above in setup_redir_port() */
3839                 if (!isalpha(**av)) {
3840                         StrToAddr(*av, &r->paddr);                      
3841                         INC_ARGCV();
3842                 
3843                         /*
3844                          * Extract optional remote address.
3845                          */     
3846                         /* see above in setup_redir_port() */
3847                         if (ac!=0 && !isalpha(**av)) {
3848                                 StrToAddr(*av, &r->raddr);
3849                                 INC_ARGCV();
3850                         }
3851                 }               
3852         }
3853         return (space);
3854 nospace:
3855         errx(EX_DATAERR, "redirect_proto: buf is too small\n");
3856 }
3857
3858 static void
3859 show_nat(int ac, char **av);
3860
3861 static void
3862 print_nat_config(char *buf) {
3863         struct cfg_nat *n;
3864         int i, cnt, flag, off;
3865         struct cfg_redir *t;
3866         struct cfg_spool *s;
3867         struct protoent *p;
3868
3869         n = (struct cfg_nat *)buf;
3870         flag = 1;
3871         off  = sizeof(*n);
3872         printf("ipfw nat %u config", n->id);
3873         if (strlen(n->if_name) != 0)
3874                 printf(" if %s", n->if_name);
3875         else if (n->ip.s_addr != 0)
3876                 printf(" ip %s", inet_ntoa(n->ip));
3877         while (n->mode != 0) {
3878                 if (n->mode & PKT_ALIAS_LOG) {
3879                         printf(" log");
3880                         n->mode &= ~PKT_ALIAS_LOG;
3881                 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
3882                         printf(" deny_in");
3883                         n->mode &= ~PKT_ALIAS_DENY_INCOMING;
3884                 } else if (n->mode & PKT_ALIAS_SAME_PORTS) {
3885                         printf(" same_ports");
3886                         n->mode &= ~PKT_ALIAS_SAME_PORTS;
3887                 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
3888                         printf(" unreg_only");
3889                         n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
3890                 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
3891                         printf(" reset");
3892                         n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
3893                 } else if (n->mode & PKT_ALIAS_REVERSE) {
3894                         printf(" reverse");
3895                         n->mode &= ~PKT_ALIAS_REVERSE;
3896                 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
3897                         printf(" proxy_only");
3898                         n->mode &= ~PKT_ALIAS_PROXY_ONLY;
3899                 }
3900         }
3901         /* Print all the redirect's data configuration. */
3902         for (cnt = 0; cnt < n->redir_cnt; cnt++) {
3903                 t = (struct cfg_redir *)&buf[off];
3904                 off += SOF_REDIR;
3905                 switch (t->mode) {
3906                 case REDIR_ADDR:
3907                         printf(" redirect_addr");
3908                         if (t->spool_cnt == 0)
3909                                 printf(" %s", inet_ntoa(t->laddr));
3910                         else
3911                                 for (i = 0; i < t->spool_cnt; i++) {
3912                                         s = (struct cfg_spool *)&buf[off];
3913                                         if (i)
3914                                                 printf(",");
3915                                         else 
3916                                                 printf(" ");
3917                                         printf("%s", inet_ntoa(s->addr));
3918                                         off += SOF_SPOOL;
3919                                 }
3920                         printf(" %s", inet_ntoa(t->paddr));
3921                         break;
3922                 case REDIR_PORT:
3923                         p = getprotobynumber(t->proto);
3924                         printf(" redirect_port %s ", p->p_name);
3925                         if (!t->spool_cnt) {
3926                                 printf("%s:%u", inet_ntoa(t->laddr), t->lport);
3927                                 if (t->pport_cnt > 1)
3928                                         printf("-%u", t->lport + 
3929                                             t->pport_cnt - 1);
3930                         } else
3931                                 for (i=0; i < t->spool_cnt; i++) {
3932                                         s = (struct cfg_spool *)&buf[off];
3933                                         if (i)
3934                                                 printf(",");
3935                                         printf("%s:%u", inet_ntoa(s->addr), 
3936                                             s->port);
3937                                         off += SOF_SPOOL;
3938                                 }
3939
3940                         printf(" ");
3941                         if (t->paddr.s_addr)
3942                                 printf("%s:", inet_ntoa(t->paddr)); 
3943                         printf("%u", t->pport);
3944                         if (!t->spool_cnt && t->pport_cnt > 1)
3945                                 printf("-%u", t->pport + t->pport_cnt - 1);
3946
3947                         if (t->raddr.s_addr) {
3948                                 printf(" %s", inet_ntoa(t->raddr));
3949                                 if (t->rport) {
3950                                         printf(":%u", t->rport);
3951                                         if (!t->spool_cnt && t->rport_cnt > 1)
3952                                                 printf("-%u", t->rport + 
3953                                                     t->rport_cnt - 1);
3954                                 }
3955                         }
3956                         break;
3957                 case REDIR_PROTO:
3958                         p = getprotobynumber(t->proto);
3959                         printf(" redirect_proto %s %s", p->p_name, 
3960                             inet_ntoa(t->laddr));
3961                         if (t->paddr.s_addr != 0) {
3962                                 printf(" %s", inet_ntoa(t->paddr));
3963                                 if (t->raddr.s_addr)
3964                                         printf(" %s", inet_ntoa(t->raddr));
3965                         }
3966                         break;
3967                 default:
3968                         errx(EX_DATAERR, "unknown redir mode");
3969                         break;
3970                 }
3971         }
3972         printf("\n");
3973 }
3974
3975 static void
3976 config_nat(int ac, char **av)
3977 {
3978         struct cfg_nat *n;              /* Nat instance configuration. */
3979         int i, len, off, tok;
3980         char *id, buf[NAT_BUF_LEN];     /* Buffer for serialized data. */
3981         
3982         len = NAT_BUF_LEN;
3983         /* Offset in buf: save space for n at the beginning. */
3984         off = sizeof(*n);
3985         memset(buf, 0, sizeof(buf));
3986         n = (struct cfg_nat *)buf;
3987
3988         av++; ac--;
3989         /* Nat id. */
3990         if (ac && isdigit(**av)) {
3991                 id = *av;
3992                 i = atoi(*av); 
3993                 ac--; av++;             
3994                 n->id = i;
3995         } else 
3996                 errx(EX_DATAERR, "missing nat id");
3997         if (ac == 0) 
3998                 errx(EX_DATAERR, "missing option");
3999
4000         while (ac > 0) {
4001                 tok = match_token(nat_params, *av);
4002                 ac--; av++;
4003                 switch (tok) {
4004                 case TOK_IP:
4005                         if (ac == 0) 
4006                                 errx(EX_DATAERR, "missing option");
4007                         if (!inet_aton(av[0], &(n->ip)))
4008                                 errx(EX_DATAERR, "bad ip address ``%s''", 
4009                                     av[0]);
4010                         ac--; av++;
4011                         break;      
4012                 case TOK_IF:
4013                         if (ac == 0) 
4014                                 errx(EX_DATAERR, "missing option");
4015                         set_addr_dynamic(av[0], n);
4016                         ac--; av++;
4017                         break;
4018                 case TOK_ALOG:
4019                         n->mode |= PKT_ALIAS_LOG;
4020                         break;
4021                 case TOK_DENY_INC:
4022                         n->mode |= PKT_ALIAS_DENY_INCOMING;
4023                         break;
4024                 case TOK_SAME_PORTS:
4025                         n->mode |= PKT_ALIAS_SAME_PORTS;
4026                         break;
4027                 case TOK_UNREG_ONLY:
4028                         n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
4029                         break;
4030                 case TOK_RESET_ADDR:
4031                         n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
4032                         break;
4033                 case TOK_ALIAS_REV:
4034                         n->mode |= PKT_ALIAS_REVERSE;
4035                         break;
4036                 case TOK_PROXY_ONLY:
4037                         n->mode |= PKT_ALIAS_PROXY_ONLY;
4038                         break;
4039                         /* 
4040                          * All the setup_redir_* functions work directly in the final 
4041                          * buffer, see above for details.
4042                          */
4043                 case TOK_REDIR_ADDR:
4044                 case TOK_REDIR_PORT:
4045                 case TOK_REDIR_PROTO:
4046                         switch (tok) {
4047                         case TOK_REDIR_ADDR:
4048                                 i = setup_redir_addr(&buf[off], len, &ac, &av);
4049                                 break;                    
4050                         case TOK_REDIR_PORT:
4051                                 i = setup_redir_port(&buf[off], len, &ac, &av);
4052                                 break;                    
4053                         case TOK_REDIR_PROTO:
4054                                 i = setup_redir_proto(&buf[off], len, &ac, &av);
4055                                 break;
4056                         }
4057                         n->redir_cnt++;
4058                         off += i;
4059                         len -= i;
4060                         break;
4061                 default:
4062                         errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
4063                 }
4064         }
4065
4066         i = do_cmd(IP_FW_NAT_CFG, buf, off);
4067         if (i)
4068                 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
4069
4070         if (!do_quiet) {
4071                 /* After every modification, we show the resultant rule. */
4072                 int _ac = 3;
4073                 char *_av[] = {"show", "config", id};
4074                 show_nat(_ac, _av);
4075         }
4076 }
4077
4078 static void
4079 config_pipe(int ac, char **av)
4080 {
4081         struct dn_pipe p;
4082         int i;
4083         char *end;
4084         void *par = NULL;
4085
4086         memset(&p, 0, sizeof p);
4087
4088         av++; ac--;
4089         /* Pipe number */
4090         if (ac && isdigit(**av)) {
4091                 i = atoi(*av); av++; ac--;
4092                 if (do_pipe == 1)
4093                         p.pipe_nr = i;
4094                 else
4095                         p.fs.fs_nr = i;
4096         }
4097         while (ac > 0) {
4098                 double d;
4099                 int tok = match_token(dummynet_params, *av);
4100                 ac--; av++;
4101
4102                 switch(tok) {
4103                 case TOK_NOERROR:
4104                         p.fs.flags_fs |= DN_NOERROR;
4105                         break;
4106
4107                 case TOK_PLR:
4108                         NEED1("plr needs argument 0..1\n");
4109                         d = strtod(av[0], NULL);
4110                         if (d > 1)
4111                                 d = 1;
4112                         else if (d < 0)
4113                                 d = 0;
4114                         p.fs.plr = (int)(d*0x7fffffff);
4115                         ac--; av++;
4116                         break;
4117
4118                 case TOK_QUEUE:
4119                         NEED1("queue needs queue size\n");
4120                         end = NULL;
4121                         p.fs.qsize = strtoul(av[0], &end, 0);
4122                         if (*end == 'K' || *end == 'k') {
4123                                 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
4124                                 p.fs.qsize *= 1024;
4125                         } else if (*end == 'B' ||
4126                             _substrcmp2(end, "by", "bytes") == 0) {
4127                                 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
4128                         }
4129                         ac--; av++;
4130                         break;
4131
4132                 case TOK_BUCKETS:
4133                         NEED1("buckets needs argument\n");
4134                         p.fs.rq_size = strtoul(av[0], NULL, 0);
4135                         ac--; av++;
4136                         break;
4137
4138                 case TOK_MASK:
4139                         NEED1("mask needs mask specifier\n");
4140                         /*
4141                          * per-flow queue, mask is dst_ip, dst_port,
4142                          * src_ip, src_port, proto measured in bits
4143                          */
4144                         par = NULL;
4145
4146                         bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
4147                         end = NULL;
4148
4149                         while (ac >= 1) {
4150                             uint32_t *p32 = NULL;
4151                             uint16_t *p16 = NULL;
4152                             uint32_t *p20 = NULL;
4153                             struct in6_addr *pa6 = NULL;
4154                             uint32_t a;
4155
4156                             tok = match_token(dummynet_params, *av);
4157                             ac--; av++;
4158                             switch(tok) {
4159                             case TOK_ALL:
4160                                     /*
4161                                      * special case, all bits significant
4162                                      */
4163                                     p.fs.flow_mask.dst_ip = ~0;
4164                                     p.fs.flow_mask.src_ip = ~0;
4165                                     p.fs.flow_mask.dst_port = ~0;
4166                                     p.fs.flow_mask.src_port = ~0;
4167                                     p.fs.flow_mask.proto = ~0;
4168                                     n2mask(&(p.fs.flow_mask.dst_ip6), 128);
4169                                     n2mask(&(p.fs.flow_mask.src_ip6), 128);
4170                                     p.fs.flow_mask.flow_id6 = ~0;
4171                                     p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
4172                                     goto end_mask;
4173
4174                             case TOK_DSTIP:
4175                                     p32 = &p.fs.flow_mask.dst_ip;
4176                                     break;
4177
4178                             case TOK_SRCIP:
4179                                     p32 = &p.fs.flow_mask.src_ip;
4180                                     break;
4181
4182                             case TOK_DSTIP6:
4183                                     pa6 = &(p.fs.flow_mask.dst_ip6);
4184                                     break;
4185                             
4186                             case TOK_SRCIP6:
4187                                     pa6 = &(p.fs.flow_mask.src_ip6);
4188                                     break;
4189
4190                             case TOK_FLOWID:
4191                                     p20 = &p.fs.flow_mask.flow_id6;
4192                                     break;
4193
4194                             case TOK_DSTPORT:
4195                                     p16 = &p.fs.flow_mask.dst_port;
4196                                     break;
4197
4198                             case TOK_SRCPORT:
4199                                     p16 = &p.fs.flow_mask.src_port;
4200                                     break;
4201
4202                             case TOK_PROTO:
4203                                     break;
4204
4205                             default:
4206                                     ac++; av--; /* backtrack */
4207                                     goto end_mask;
4208                             }
4209                             if (ac < 1)
4210                                     errx(EX_USAGE, "mask: value missing");
4211                             if (*av[0] == '/') {
4212                                     a = strtoul(av[0]+1, &end, 0);
4213                                     if (pa6 == NULL)
4214                                             a = (a == 32) ? ~0 : (1 << a) - 1;
4215                             } else
4216                                     a = strtoul(av[0], &end, 0);
4217                             if (p32 != NULL)
4218                                     *p32 = a;
4219                             else if (p16 != NULL) {
4220                                     if (a > 0xFFFF)
4221                                             errx(EX_DATAERR,
4222                                                 "port mask must be 16 bit");
4223                                     *p16 = (uint16_t)a;
4224                             } else if (p20 != NULL) {
4225                                     if (a > 0xfffff)
4226                                         errx(EX_DATAERR,
4227                                             "flow_id mask must be 20 bit");
4228                                     *p20 = (uint32_t)a;
4229                             } else if (pa6 != NULL) {
4230                                     if (a < 0 || a > 128)
4231                                         errx(EX_DATAERR,
4232                                             "in6addr invalid mask len");
4233                                     else
4234                                         n2mask(pa6, a);
4235                             } else {
4236                                     if (a > 0xFF)
4237                                             errx(EX_DATAERR,
4238                                                 "proto mask must be 8 bit");
4239                                     p.fs.flow_mask.proto = (uint8_t)a;
4240                             }
4241                             if (a != 0)
4242                                     p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
4243                             ac--; av++;
4244                         } /* end while, config masks */
4245 end_mask:
4246                         break;
4247
4248                 case TOK_RED:
4249                 case TOK_GRED:
4250                         NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
4251                         p.fs.flags_fs |= DN_IS_RED;
4252                         if (tok == TOK_GRED)
4253                                 p.fs.flags_fs |= DN_IS_GENTLE_RED;
4254                         /*
4255                          * the format for parameters is w_q/min_th/max_th/max_p
4256                          */
4257                         if ((end = strsep(&av[0], "/"))) {
4258                             double w_q = strtod(end, NULL);
4259                             if (w_q > 1 || w_q <= 0)
4260                                 errx(EX_DATAERR, "0 < w_q <= 1");
4261                             p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
4262                         }
4263                         if ((end = strsep(&av[0], "/"))) {
4264                             p.fs.min_th = strtoul(end, &end, 0);
4265                             if (*end == 'K' || *end == 'k')
4266                                 p.fs.min_th *= 1024;
4267                         }
4268                         if ((end = strsep(&av[0], "/"))) {
4269                             p.fs.max_th = strtoul(end, &end, 0);
4270                             if (*end == 'K' || *end == 'k')
4271                                 p.fs.max_th *= 1024;
4272                         }
4273                         if ((end = strsep(&av[0], "/"))) {
4274                             double max_p = strtod(end, NULL);
4275                             if (max_p > 1 || max_p <= 0)
4276                                 errx(EX_DATAERR, "0 < max_p <= 1");
4277                             p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
4278                         }
4279                         ac--; av++;
4280                         break;
4281
4282                 case TOK_DROPTAIL:
4283                         p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
4284                         break;
4285
4286                 case TOK_BW:
4287                         NEED1("bw needs bandwidth or interface\n");
4288                         if (do_pipe != 1)
4289                             errx(EX_DATAERR, "bandwidth only valid for pipes");
4290                         /*
4291                          * set clocking interface or bandwidth value
4292                          */
4293                         if (av[0][0] >= 'a' && av[0][0] <= 'z') {
4294                             int l = sizeof(p.if_name)-1;
4295                             /* interface name */
4296                             strncpy(p.if_name, av[0], l);
4297                             p.if_name[l] = '\0';
4298                             p.bandwidth = 0;
4299                         } else {
4300                             p.if_name[0] = '\0';
4301                             p.bandwidth = strtoul(av[0], &end, 0);
4302                             if (*end == 'K' || *end == 'k') {
4303                                 end++;
4304                                 p.bandwidth *= 1000;
4305                             } else if (*end == 'M') {
4306                                 end++;
4307                                 p.bandwidth *= 1000000;
4308                             }
4309                             if ((*end == 'B' &&
4310                                   _substrcmp2(end, "Bi", "Bit/s") != 0) ||
4311                                 _substrcmp2(end, "by", "bytes") == 0)
4312                                 p.bandwidth *= 8;
4313                             if (p.bandwidth < 0)
4314                                 errx(EX_DATAERR, "bandwidth too large");
4315                         }
4316                         ac--; av++;
4317                         break;
4318
4319                 case TOK_DELAY:
4320                         if (do_pipe != 1)
4321                                 errx(EX_DATAERR, "delay only valid for pipes");
4322                         NEED1("delay needs argument 0..10000ms\n");
4323                         p.delay = strtoul(av[0], NULL, 0);
4324                         ac--; av++;
4325                         break;
4326
4327                 case TOK_WEIGHT:
4328                         if (do_pipe == 1)
4329                                 errx(EX_DATAERR,"weight only valid for queues");
4330                         NEED1("weight needs argument 0..100\n");
4331                         p.fs.weight = strtoul(av[0], &end, 0);
4332                         ac--; av++;
4333                         break;
4334
4335                 case TOK_PIPE:
4336                         if (do_pipe == 1)
4337                                 errx(EX_DATAERR,"pipe only valid for queues");
4338                         NEED1("pipe needs pipe_number\n");
4339                         p.fs.parent_nr = strtoul(av[0], &end, 0);
4340                         ac--; av++;
4341                         break;
4342
4343                 default:
4344                         errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
4345                 }
4346         }
4347         if (do_pipe == 1) {
4348                 if (p.pipe_nr == 0)
4349                         errx(EX_DATAERR, "pipe_nr must be > 0");
4350                 if (p.delay > 10000)
4351                         errx(EX_DATAERR, "delay must be < 10000");
4352         } else { /* do_pipe == 2, queue */
4353                 if (p.fs.parent_nr == 0)
4354                         errx(EX_DATAERR, "pipe must be > 0");
4355                 if (p.fs.weight >100)
4356                         errx(EX_DATAERR, "weight must be <= 100");
4357         }
4358         if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
4359                 size_t len;
4360                 long limit;
4361
4362                 len = sizeof(limit);
4363                 if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
4364                         &limit, &len, NULL, 0) == -1)
4365                         limit = 1024*1024;
4366                 if (p.fs.qsize > limit)
4367                         errx(EX_DATAERR, "queue size must be < %ldB", limit);
4368         } else {
4369                 size_t len;
4370                 long limit;
4371
4372                 len = sizeof(limit);
4373                 if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
4374                         &limit, &len, NULL, 0) == -1)
4375                         limit = 100;
4376                 if (p.fs.qsize > limit)
4377                         errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
4378         }
4379         if (p.fs.flags_fs & DN_IS_RED) {
4380                 size_t len;
4381                 int lookup_depth, avg_pkt_size;
4382                 double s, idle, weight, w_q;
4383                 struct clockinfo ck;
4384                 int t;
4385
4386                 if (p.fs.min_th >= p.fs.max_th)
4387                     errx(EX_DATAERR, "min_th %d must be < than max_th %d",
4388                         p.fs.min_th, p.fs.max_th);
4389                 if (p.fs.max_th == 0)
4390                     errx(EX_DATAERR, "max_th must be > 0");
4391
4392                 len = sizeof(int);
4393                 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
4394                         &lookup_depth, &len, NULL, 0) == -1)
4395                     errx(1, "sysctlbyname(\"%s\")",
4396                         "net.inet.ip.dummynet.red_lookup_depth");
4397                 if (lookup_depth == 0)
4398                     errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
4399                         " must be greater than zero");
4400
4401                 len = sizeof(int);
4402                 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
4403                         &avg_pkt_size, &len, NULL, 0) == -1)
4404
4405                     errx(1, "sysctlbyname(\"%s\")",
4406                         "net.inet.ip.dummynet.red_avg_pkt_size");
4407                 if (avg_pkt_size == 0)
4408                         errx(EX_DATAERR,
4409                             "net.inet.ip.dummynet.red_avg_pkt_size must"
4410                             " be greater than zero");
4411
4412                 len = sizeof(struct clockinfo);
4413                 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
4414                         errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
4415
4416                 /*
4417                  * Ticks needed for sending a medium-sized packet.
4418                  * Unfortunately, when we are configuring a WF2Q+ queue, we
4419                  * do not have bandwidth information, because that is stored
4420                  * in the parent pipe, and also we have multiple queues
4421                  * competing for it. So we set s=0, which is not very
4422                  * correct. But on the other hand, why do we want RED with
4423                  * WF2Q+ ?
4424                  */
4425                 if (p.bandwidth==0) /* this is a WF2Q+ queue */
4426                         s = 0;
4427                 else
4428                         s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
4429
4430                 /*
4431                  * max idle time (in ticks) before avg queue size becomes 0.
4432                  * NOTA:  (3/w_q) is approx the value x so that
4433                  * (1-w_q)^x < 10^-3.
4434                  */
4435                 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
4436                 idle = s * 3. / w_q;
4437                 p.fs.lookup_step = (int)idle / lookup_depth;
4438                 if (!p.fs.lookup_step)
4439                         p.fs.lookup_step = 1;
4440                 weight = 1 - w_q;
4441                 for (t = p.fs.lookup_step; t > 1; --t)
4442                         weight *= 1 - w_q;
4443                 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
4444         }
4445         i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
4446         if (i)
4447                 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
4448 }
4449
4450 static void
4451 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
4452 {
4453         int i, l;
4454         char *ap, *ptr, *optr;
4455         struct ether_addr *mac;
4456         const char *macset = "0123456789abcdefABCDEF:";
4457
4458         if (strcmp(p, "any") == 0) {
4459                 for (i = 0; i < ETHER_ADDR_LEN; i++)
4460                         addr[i] = mask[i] = 0;
4461                 return;
4462         }
4463
4464         optr = ptr = strdup(p);
4465         if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
4466                 l = strlen(ap);
4467                 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
4468                         errx(EX_DATAERR, "Incorrect MAC address");
4469                 bcopy(mac, addr, ETHER_ADDR_LEN);
4470         } else
4471                 errx(EX_DATAERR, "Incorrect MAC address");
4472
4473         if (ptr != NULL) { /* we have mask? */
4474                 if (p[ptr - optr - 1] == '/') { /* mask len */
4475                         l = strtol(ptr, &ap, 10);
4476                         if (*ap != 0 || l > ETHER_ADDR_LEN * 8 || l < 0)
4477                                 errx(EX_DATAERR, "Incorrect mask length");
4478                         for (i = 0; l > 0 && i < ETHER_ADDR_LEN; l -= 8, i++)
4479                                 mask[i] = (l >= 8) ? 0xff: (~0) << (8 - l);
4480                 } else { /* mask */
4481                         l = strlen(ptr);
4482                         if (strspn(ptr, macset) != l ||
4483                             (mac = ether_aton(ptr)) == NULL)
4484                                 errx(EX_DATAERR, "Incorrect mask");
4485                         bcopy(mac, mask, ETHER_ADDR_LEN);
4486                 }
4487         } else { /* default mask: ff:ff:ff:ff:ff:ff */
4488                 for (i = 0; i < ETHER_ADDR_LEN; i++)
4489                         mask[i] = 0xff;
4490         }
4491         for (i = 0; i < ETHER_ADDR_LEN; i++)
4492                 addr[i] &= mask[i];
4493
4494         free(optr);
4495 }
4496
4497 /*
4498  * helper function, updates the pointer to cmd with the length
4499  * of the current command, and also cleans up the first word of
4500  * the new command in case it has been clobbered before.
4501  */
4502 static ipfw_insn *
4503 next_cmd(ipfw_insn *cmd)
4504 {
4505         cmd += F_LEN(cmd);
4506         bzero(cmd, sizeof(*cmd));
4507         return cmd;
4508 }
4509
4510 /*
4511  * Takes arguments and copies them into a comment
4512  */
4513 static void
4514 fill_comment(ipfw_insn *cmd, int ac, char **av)
4515 {
4516         int i, l;
4517         char *p = (char *)(cmd + 1);
4518
4519         cmd->opcode = O_NOP;
4520         cmd->len =  (cmd->len & (F_NOT | F_OR));
4521
4522         /* Compute length of comment string. */
4523         for (i = 0, l = 0; i < ac; i++)
4524                 l += strlen(av[i]) + 1;
4525         if (l == 0)
4526                 return;
4527         if (l > 84)
4528                 errx(EX_DATAERR,
4529                     "comment too long (max 80 chars)");
4530         l = 1 + (l+3)/4;
4531         cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
4532         for (i = 0; i < ac; i++) {
4533                 strcpy(p, av[i]);
4534                 p += strlen(av[i]);
4535                 *p++ = ' ';
4536         }
4537         *(--p) = '\0';
4538 }
4539
4540 /*
4541  * A function to fill simple commands of size 1.
4542  * Existing flags are preserved.
4543  */
4544 static void
4545 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
4546 {
4547         cmd->opcode = opcode;
4548         cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
4549         cmd->arg1 = arg;
4550 }
4551
4552 /*
4553  * Fetch and add the MAC address and type, with masks. This generates one or
4554  * two microinstructions, and returns the pointer to the last one.
4555  */
4556 static ipfw_insn *
4557 add_mac(ipfw_insn *cmd, int ac, char *av[])
4558 {
4559         ipfw_insn_mac *mac;
4560
4561         if (ac < 2)
4562                 errx(EX_DATAERR, "MAC dst src");
4563
4564         cmd->opcode = O_MACADDR2;
4565         cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
4566
4567         mac = (ipfw_insn_mac *)cmd;
4568         get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
4569         get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
4570             &(mac->mask[ETHER_ADDR_LEN])); /* src */
4571         return cmd;
4572 }
4573
4574 static ipfw_insn *
4575 add_mactype(ipfw_insn *cmd, int ac, char *av)
4576 {
4577         if (ac < 1)
4578                 errx(EX_DATAERR, "missing MAC type");
4579         if (strcmp(av, "any") != 0) { /* we have a non-null type */
4580                 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
4581                 cmd->opcode = O_MAC_TYPE;
4582                 return cmd;
4583         } else
4584                 return NULL;
4585 }
4586
4587 static ipfw_insn *
4588 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
4589 {
4590         struct protoent *pe;
4591         char *ep;
4592         int proto;
4593
4594         proto = strtol(av, &ep, 10);
4595         if (*ep != '\0' || proto <= 0) {
4596                 if ((pe = getprotobyname(av)) == NULL)
4597                         return NULL;
4598                 proto = pe->p_proto;
4599         }
4600
4601         fill_cmd(cmd, O_PROTO, 0, proto);
4602         *protop = proto;
4603         return cmd;
4604 }
4605
4606 static ipfw_insn *
4607 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
4608 {
4609         u_char proto = IPPROTO_IP;
4610
4611         if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
4612                 ; /* do not set O_IP4 nor O_IP6 */
4613         else if (strcmp(av, "ip4") == 0)
4614                 /* explicit "just IPv4" rule */
4615                 fill_cmd(cmd, O_IP4, 0, 0);
4616         else if (strcmp(av, "ip6") == 0) {
4617                 /* explicit "just IPv6" rule */
4618                 proto = IPPROTO_IPV6;
4619                 fill_cmd(cmd, O_IP6, 0, 0);
4620         } else
4621                 return add_proto0(cmd, av, protop);
4622
4623         *protop = proto;
4624         return cmd;
4625 }
4626
4627 static ipfw_insn *
4628 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
4629 {
4630         u_char proto = IPPROTO_IP;
4631
4632         if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
4633                 ; /* do not set O_IP4 nor O_IP6 */
4634         else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
4635                 /* explicit "just IPv4" rule */
4636                 fill_cmd(cmd, O_IP4, 0, 0);
4637         else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
4638                 /* explicit "just IPv6" rule */
4639                 proto = IPPROTO_IPV6;
4640                 fill_cmd(cmd, O_IP6, 0, 0);
4641         } else
4642                 return add_proto0(cmd, av, protop);
4643
4644         *protop = proto;
4645         return cmd;
4646 }
4647
4648 static ipfw_insn *
4649 add_srcip(ipfw_insn *cmd, char *av)
4650 {
4651         fill_ip((ipfw_insn_ip *)cmd, av);
4652         if (cmd->opcode == O_IP_DST_SET)                        /* set */
4653                 cmd->opcode = O_IP_SRC_SET;
4654         else if (cmd->opcode == O_IP_DST_LOOKUP)                /* table */
4655                 cmd->opcode = O_IP_SRC_LOOKUP;
4656         else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))          /* me */
4657                 cmd->opcode = O_IP_SRC_ME;
4658         else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))      /* one IP */
4659                 cmd->opcode = O_IP_SRC;
4660         else                                                    /* addr/mask */
4661                 cmd->opcode = O_IP_SRC_MASK;
4662         return cmd;
4663 }
4664
4665 static ipfw_insn *
4666 add_dstip(ipfw_insn *cmd, char *av)
4667 {
4668         fill_ip((ipfw_insn_ip *)cmd, av);
4669         if (cmd->opcode == O_IP_DST_SET)                        /* set */
4670                 ;
4671         else if (cmd->opcode == O_IP_DST_LOOKUP)                /* table */
4672                 ;
4673         else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))          /* me */
4674                 cmd->opcode = O_IP_DST_ME;
4675         else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))      /* one IP */
4676                 cmd->opcode = O_IP_DST;
4677         else                                                    /* addr/mask */
4678                 cmd->opcode = O_IP_DST_MASK;
4679         return cmd;
4680 }
4681
4682 static ipfw_insn *
4683 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
4684 {
4685         if (_substrcmp(av, "any") == 0) {
4686                 return NULL;
4687         } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
4688                 /* XXX todo: check that we have a protocol with ports */
4689                 cmd->opcode = opcode;
4690                 return cmd;
4691         }
4692         return NULL;
4693 }
4694
4695 static ipfw_insn *
4696 add_src(ipfw_insn *cmd, char *av, u_char proto)
4697 {
4698         struct in6_addr a;
4699         char *host, *ch;
4700         ipfw_insn *ret = NULL;
4701
4702         if ((host = strdup(av)) == NULL)
4703                 return NULL;
4704         if ((ch = strrchr(host, '/')) != NULL)
4705                 *ch = '\0';
4706
4707         if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
4708             inet_pton(AF_INET6, host, &a))
4709                 ret = add_srcip6(cmd, av);
4710         /* XXX: should check for IPv4, not !IPv6 */
4711         if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4712             !inet_pton(AF_INET6, host, &a)))
4713                 ret = add_srcip(cmd, av);
4714         if (ret == NULL && strcmp(av, "any") != 0)
4715                 ret = cmd;
4716
4717         free(host);
4718         return ret;
4719 }
4720
4721 static ipfw_insn *
4722 add_dst(ipfw_insn *cmd, char *av, u_char proto)
4723 {
4724         struct in6_addr a;
4725         char *host, *ch;
4726         ipfw_insn *ret = NULL;
4727
4728         if ((host = strdup(av)) == NULL)
4729                 return NULL;
4730         if ((ch = strrchr(host, '/')) != NULL)
4731                 *ch = '\0';
4732
4733         if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
4734             inet_pton(AF_INET6, host, &a))
4735                 ret = add_dstip6(cmd, av);
4736         /* XXX: should check for IPv4, not !IPv6 */
4737         if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4738             !inet_pton(AF_INET6, host, &a)))
4739                 ret = add_dstip(cmd, av);
4740         if (ret == NULL && strcmp(av, "any") != 0)
4741                 ret = cmd;
4742
4743         free(host);
4744         return ret;
4745 }
4746
4747 /*
4748  * Parse arguments and assemble the microinstructions which make up a rule.
4749  * Rules are added into the 'rulebuf' and then copied in the correct order
4750  * into the actual rule.
4751  *
4752  * The syntax for a rule starts with the action, followed by
4753  * optional action parameters, and the various match patterns.
4754  * In the assembled microcode, the first opcode must be an O_PROBE_STATE
4755  * (generated if the rule includes a keep-state option), then the
4756  * various match patterns, log/altq actions, and the actual action.
4757  *
4758  */
4759 static void
4760 add(int ac, char *av[])
4761 {
4762         /*
4763          * rules are added into the 'rulebuf' and then copied in
4764          * the correct order into the actual rule.
4765          * Some things that need to go out of order (prob, action etc.)
4766          * go into actbuf[].
4767          */
4768         static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
4769
4770         ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4771         ipfw_insn *first_cmd;   /* first match pattern */
4772
4773         struct ip_fw *rule;
4774
4775         /*
4776          * various flags used to record that we entered some fields.
4777          */
4778         ipfw_insn *have_state = NULL;   /* check-state or keep-state */
4779         ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4780         size_t len;
4781
4782         int i;
4783
4784         int open_par = 0;       /* open parenthesis ( */
4785
4786         /* proto is here because it is used to fetch ports */
4787         u_char proto = IPPROTO_IP;      /* default protocol */
4788
4789         double match_prob = 1; /* match probability, default is always match */
4790
4791         bzero(actbuf, sizeof(actbuf));          /* actions go here */
4792         bzero(cmdbuf, sizeof(cmdbuf));
4793         bzero(rulebuf, sizeof(rulebuf));
4794
4795         rule = (struct ip_fw *)rulebuf;
4796         cmd = (ipfw_insn *)cmdbuf;
4797         action = (ipfw_insn *)actbuf;
4798
4799         av++; ac--;
4800
4801         /* [rule N]     -- Rule number optional */
4802         if (ac && isdigit(**av)) {
4803                 rule->rulenum = atoi(*av);
4804                 av++;
4805                 ac--;
4806         }
4807
4808         /* [set N]      -- set number (0..RESVD_SET), optional */
4809         if (ac > 1 && _substrcmp(*av, "set") == 0) {
4810                 int set = strtoul(av[1], NULL, 10);
4811                 if (set < 0 || set > RESVD_SET)
4812                         errx(EX_DATAERR, "illegal set %s", av[1]);
4813                 rule->set = set;
4814                 av += 2; ac -= 2;
4815         }
4816
4817         /* [prob D]     -- match probability, optional */
4818         if (ac > 1 && _substrcmp(*av, "prob") == 0) {
4819                 match_prob = strtod(av[1], NULL);
4820
4821                 if (match_prob <= 0 || match_prob > 1)
4822                         errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4823                 av += 2; ac -= 2;
4824         }
4825
4826         /* action       -- mandatory */
4827         NEED1("missing action");
4828         i = match_token(rule_actions, *av);
4829         ac--; av++;
4830         action->len = 1;        /* default */
4831         switch(i) {
4832         case TOK_CHECKSTATE:
4833                 have_state = action;
4834                 action->opcode = O_CHECK_STATE;
4835                 break;
4836
4837         case TOK_ACCEPT:
4838                 action->opcode = O_ACCEPT;
4839                 break;
4840
4841         case TOK_DENY:
4842                 action->opcode = O_DENY;
4843                 action->arg1 = 0;
4844                 break;
4845
4846         case TOK_REJECT:
4847                 action->opcode = O_REJECT;
4848                 action->arg1 = ICMP_UNREACH_HOST;
4849                 break;
4850
4851         case TOK_RESET:
4852                 action->opcode = O_REJECT;
4853                 action->arg1 = ICMP_REJECT_RST;
4854                 break;
4855
4856         case TOK_RESET6:
4857                 action->opcode = O_UNREACH6;
4858                 action->arg1 = ICMP6_UNREACH_RST;
4859                 break;
4860
4861         case TOK_UNREACH:
4862                 action->opcode = O_REJECT;
4863                 NEED1("missing reject code");
4864                 fill_reject_code(&action->arg1, *av);
4865                 ac--; av++;
4866                 break;
4867
4868         case TOK_UNREACH6:
4869                 action->opcode = O_UNREACH6;
4870                 NEED1("missing unreach code");
4871                 fill_unreach6_code(&action->arg1, *av);
4872                 ac--; av++;
4873                 break;
4874
4875         case TOK_COUNT:
4876                 action->opcode = O_COUNT;
4877                 break;
4878
4879         case TOK_NAT:
4880                 action->opcode = O_NAT;
4881                 action->len = F_INSN_SIZE(ipfw_insn_nat);
4882                 goto chkarg;
4883
4884         case TOK_QUEUE:
4885                 action->opcode = O_QUEUE;
4886                 goto chkarg;
4887         case TOK_PIPE:
4888                 action->opcode = O_PIPE;
4889                 goto chkarg;
4890         case TOK_SKIPTO:
4891                 action->opcode = O_SKIPTO;
4892                 goto chkarg;
4893         case TOK_NETGRAPH:
4894                 action->opcode = O_NETGRAPH;
4895                 goto chkarg;
4896         case TOK_NGTEE:
4897                 action->opcode = O_NGTEE;
4898                 goto chkarg;
4899         case TOK_DIVERT:
4900                 action->opcode = O_DIVERT;
4901                 goto chkarg;
4902         case TOK_TEE:
4903                 action->opcode = O_TEE;
4904 chkarg: 
4905                 if (!ac)
4906                         errx(EX_USAGE, "missing argument for %s", *(av - 1));
4907                 if (isdigit(**av)) {
4908                         action->arg1 = strtoul(*av, NULL, 10);
4909                         if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
4910                                 errx(EX_DATAERR, "illegal argument for %s",
4911                                     *(av - 1));
4912                 } else if (_substrcmp(*av, TABLEARG) == 0) {
4913                         action->arg1 = IP_FW_TABLEARG;
4914                 } else if (i == TOK_DIVERT || i == TOK_TEE) {
4915                         struct servent *s;
4916                         setservent(1);
4917                         s = getservbyname(av[0], "divert");
4918                         if (s != NULL)
4919                                 action->arg1 = ntohs(s->s_port);
4920                         else
4921                                 errx(EX_DATAERR, "illegal divert/tee port");
4922                 } else
4923                         errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
4924                 ac--; av++;
4925                 break;
4926
4927         case TOK_FORWARD: {
4928                 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4929                 char *s, *end;
4930
4931                 NEED1("missing forward address[:port]");
4932
4933                 action->opcode = O_FORWARD_IP;
4934                 action->len = F_INSN_SIZE(ipfw_insn_sa);
4935
4936                 p->sa.sin_len = sizeof(struct sockaddr_in);
4937                 p->sa.sin_family = AF_INET;
4938                 p->sa.sin_port = 0;
4939                 /*
4940                  * locate the address-port separator (':' or ',')
4941                  */
4942                 s = strchr(*av, ':');
4943                 if (s == NULL)
4944                         s = strchr(*av, ',');
4945                 if (s != NULL) {
4946                         *(s++) = '\0';
4947                         i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4948                         if (s == end)
4949                                 errx(EX_DATAERR,
4950                                     "illegal forwarding port ``%s''", s);
4951                         p->sa.sin_port = (u_short)i;
4952                 }
4953                 if (_substrcmp(*av, "tablearg") == 0) 
4954                         p->sa.sin_addr.s_addr = INADDR_ANY;
4955                 else
4956                         lookup_host(*av, &(p->sa.sin_addr));
4957                 ac--; av++;
4958                 break;
4959             }
4960         case TOK_COMMENT:
4961                 /* pretend it is a 'count' rule followed by the comment */
4962                 action->opcode = O_COUNT;
4963                 ac++; av--;     /* go back... */
4964                 break;
4965
4966         case TOK_SETFIB:
4967             {
4968                 int numfibs;
4969                 size_t intsize = sizeof(int);
4970
4971                 action->opcode = O_SETFIB;
4972                 NEED1("missing fib number");
4973                 action->arg1 = strtoul(*av, NULL, 10);
4974                 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
4975                         errx(EX_DATAERR, "fibs not suported.\n");
4976                 if (action->arg1 >= numfibs)  /* Temporary */
4977                         errx(EX_DATAERR, "fib too large.\n");
4978                 ac--; av++;
4979                 break;
4980             }
4981                 
4982         default:
4983                 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
4984         }
4985         action = next_cmd(action);
4986
4987         /*
4988          * [altq queuename] -- altq tag, optional
4989          * [log [logamount N]]  -- log, optional
4990          *
4991          * If they exist, it go first in the cmdbuf, but then it is
4992          * skipped in the copy section to the end of the buffer.
4993          */
4994         while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
4995                 ac--; av++;
4996                 switch (i) {
4997                 case TOK_LOG:
4998                     {
4999                         ipfw_insn_log *c = (ipfw_insn_log *)cmd;
5000                         int l;
5001
5002                         if (have_log)
5003                                 errx(EX_DATAERR,
5004                                     "log cannot be specified more than once");
5005                         have_log = (ipfw_insn *)c;
5006                         cmd->len = F_INSN_SIZE(ipfw_insn_log);
5007                         cmd->opcode = O_LOG;
5008                         if (ac && _substrcmp(*av, "logamount") == 0) {
5009                                 ac--; av++;
5010                                 NEED1("logamount requires argument");
5011                                 l = atoi(*av);
5012                                 if (l < 0)
5013                                         errx(EX_DATAERR,
5014                                             "logamount must be positive");
5015                                 c->max_log = l;
5016                                 ac--; av++;
5017                         } else {
5018                                 len = sizeof(c->max_log);
5019                                 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
5020                                     &c->max_log, &len, NULL, 0) == -1)
5021                                         errx(1, "sysctlbyname(\"%s\")",
5022                                             "net.inet.ip.fw.verbose_limit");
5023                         }
5024                     }
5025                         break;
5026
5027                 case TOK_ALTQ:
5028                     {
5029                         ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
5030
5031                         NEED1("missing altq queue name");
5032                         if (have_altq)
5033                                 errx(EX_DATAERR,
5034                                     "altq cannot be specified more than once");
5035                         have_altq = (ipfw_insn *)a;
5036                         cmd->len = F_INSN_SIZE(ipfw_insn_altq);
5037                         cmd->opcode = O_ALTQ;
5038                         fill_altq_qid(&a->qid, *av);
5039                         ac--; av++;
5040                     }
5041                         break;
5042
5043                 case TOK_TAG:
5044                 case TOK_UNTAG: {
5045                         uint16_t tag;
5046
5047                         if (have_tag)
5048                                 errx(EX_USAGE, "tag and untag cannot be "
5049                                     "specified more than once");
5050                         GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1, i,
5051                            rule_action_params);
5052                         have_tag = cmd;
5053                         fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
5054                         ac--; av++;
5055                         break;
5056                 }
5057
5058                 default:
5059                         abort();
5060                 }
5061                 cmd = next_cmd(cmd);
5062         }
5063
5064         if (have_state) /* must be a check-state, we are done */
5065                 goto done;
5066
5067 #define OR_START(target)                                        \
5068         if (ac && (*av[0] == '(' || *av[0] == '{')) {           \
5069                 if (open_par)                                   \
5070                         errx(EX_USAGE, "nested \"(\" not allowed\n"); \
5071                 prev = NULL;                                    \
5072                 open_par = 1;                                   \
5073                 if ( (av[0])[1] == '\0') {                      \
5074                         ac--; av++;                             \
5075                 } else                                          \
5076                         (*av)++;                                \
5077         }                                                       \
5078         target:                                                 \
5079
5080
5081 #define CLOSE_PAR                                               \
5082         if (open_par) {                                         \
5083                 if (ac && (                                     \
5084                     strcmp(*av, ")") == 0 ||                    \
5085                     strcmp(*av, "}") == 0)) {                   \
5086                         prev = NULL;                            \
5087                         open_par = 0;                           \
5088                         ac--; av++;                             \
5089                 } else                                          \
5090                         errx(EX_USAGE, "missing \")\"\n");      \
5091         }
5092
5093 #define NOT_BLOCK                                               \
5094         if (ac && _substrcmp(*av, "not") == 0) {                \
5095                 if (cmd->len & F_NOT)                           \
5096                         errx(EX_USAGE, "double \"not\" not allowed\n"); \
5097                 cmd->len |= F_NOT;                              \
5098                 ac--; av++;                                     \
5099         }
5100
5101 #define OR_BLOCK(target)                                        \
5102         if (ac && _substrcmp(*av, "or") == 0) {         \
5103                 if (prev == NULL || open_par == 0)              \
5104                         errx(EX_DATAERR, "invalid OR block");   \
5105                 prev->len |= F_OR;                              \
5106                 ac--; av++;                                     \
5107                 goto target;                                    \
5108         }                                                       \
5109         CLOSE_PAR;
5110
5111         first_cmd = cmd;
5112
5113 #if 0
5114         /*
5115          * MAC addresses, optional.
5116          * If we have this, we skip the part "proto from src to dst"
5117          * and jump straight to the option parsing.
5118          */
5119         NOT_BLOCK;
5120         NEED1("missing protocol");
5121         if (_substrcmp(*av, "MAC") == 0 ||
5122             _substrcmp(*av, "mac") == 0) {
5123                 ac--; av++;     /* the "MAC" keyword */
5124                 add_mac(cmd, ac, av); /* exits in case of errors */
5125                 cmd = next_cmd(cmd);
5126                 ac -= 2; av += 2;       /* dst-mac and src-mac */
5127                 NOT_BLOCK;
5128                 NEED1("missing mac type");
5129                 if (add_mactype(cmd, ac, av[0]))
5130                         cmd = next_cmd(cmd);
5131                 ac--; av++;     /* any or mac-type */
5132                 goto read_options;
5133         }
5134 #endif
5135
5136         /*
5137          * protocol, mandatory
5138          */
5139     OR_START(get_proto);
5140         NOT_BLOCK;
5141         NEED1("missing protocol");
5142         if (add_proto_compat(cmd, *av, &proto)) {
5143                 av++; ac--;
5144                 if (F_LEN(cmd) != 0) {
5145                         prev = cmd;
5146                         cmd = next_cmd(cmd);
5147                 }
5148         } else if (first_cmd != cmd) {
5149                 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
5150         } else
5151                 goto read_options;
5152     OR_BLOCK(get_proto);
5153
5154         /*
5155          * "from", mandatory
5156          */
5157         if (!ac || _substrcmp(*av, "from") != 0)
5158                 errx(EX_USAGE, "missing ``from''");
5159         ac--; av++;
5160
5161         /*
5162          * source IP, mandatory
5163          */
5164     OR_START(source_ip);
5165         NOT_BLOCK;      /* optional "not" */
5166         NEED1("missing source address");
5167         if (add_src(cmd, *av, proto)) {
5168                 ac--; av++;
5169                 if (F_LEN(cmd) != 0) {  /* ! any */
5170                         prev = cmd;
5171                         cmd = next_cmd(cmd);
5172                 }
5173         } else
5174                 errx(EX_USAGE, "bad source address %s", *av);
5175     OR_BLOCK(source_ip);
5176
5177         /*
5178          * source ports, optional
5179          */
5180         NOT_BLOCK;      /* optional "not" */
5181         if (ac) {
5182                 if (_substrcmp(*av, "any") == 0 ||
5183                     add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
5184                         ac--; av++;
5185                         if (F_LEN(cmd) != 0)
5186                                 cmd = next_cmd(cmd);
5187                 }
5188         }
5189
5190         /*
5191          * "to", mandatory
5192          */
5193         if (!ac || _substrcmp(*av, "to") != 0)
5194                 errx(EX_USAGE, "missing ``to''");
5195         av++; ac--;
5196
5197         /*
5198          * destination, mandatory
5199          */
5200     OR_START(dest_ip);
5201         NOT_BLOCK;      /* optional "not" */
5202         NEED1("missing dst address");
5203         if (add_dst(cmd, *av, proto)) {
5204                 ac--; av++;
5205                 if (F_LEN(cmd) != 0) {  /* ! any */
5206                         prev = cmd;
5207                         cmd = next_cmd(cmd);
5208                 }
5209         } else
5210                 errx( EX_USAGE, "bad destination address %s", *av);
5211     OR_BLOCK(dest_ip);
5212
5213         /*
5214          * dest. ports, optional
5215          */
5216         NOT_BLOCK;      /* optional "not" */
5217         if (ac) {
5218                 if (_substrcmp(*av, "any") == 0 ||
5219                     add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
5220                         ac--; av++;
5221                         if (F_LEN(cmd) != 0)
5222                                 cmd = next_cmd(cmd);
5223                 }
5224         }
5225
5226 read_options:
5227         if (ac && first_cmd == cmd) {
5228                 /*
5229                  * nothing specified so far, store in the rule to ease
5230                  * printout later.
5231                  */
5232                  rule->_pad = 1;
5233         }
5234         prev = NULL;
5235         while (ac) {
5236                 char *s;
5237                 ipfw_insn_u32 *cmd32;   /* alias for cmd */
5238
5239                 s = *av;
5240                 cmd32 = (ipfw_insn_u32 *)cmd;
5241
5242                 if (*s == '!') {        /* alternate syntax for NOT */
5243                         if (cmd->len & F_NOT)
5244                                 errx(EX_USAGE, "double \"not\" not allowed\n");
5245                         cmd->len = F_NOT;
5246                         s++;
5247                 }
5248                 i = match_token(rule_options, s);
5249                 ac--; av++;
5250                 switch(i) {
5251                 case TOK_NOT:
5252                         if (cmd->len & F_NOT)
5253                                 errx(EX_USAGE, "double \"not\" not allowed\n");
5254                         cmd->len = F_NOT;
5255                         break;
5256
5257                 case TOK_OR:
5258                         if (open_par == 0 || prev == NULL)
5259                                 errx(EX_USAGE, "invalid \"or\" block\n");
5260                         prev->len |= F_OR;
5261                         break;
5262
5263                 case TOK_STARTBRACE:
5264                         if (open_par)
5265                                 errx(EX_USAGE, "+nested \"(\" not allowed\n");
5266                         open_par = 1;
5267                         break;
5268
5269                 case TOK_ENDBRACE:
5270                         if (!open_par)
5271                                 errx(EX_USAGE, "+missing \")\"\n");
5272                         open_par = 0;
5273                         prev = NULL;
5274                         break;
5275
5276                 case TOK_IN:
5277                         fill_cmd(cmd, O_IN, 0, 0);
5278                         break;
5279
5280                 case TOK_OUT:
5281                         cmd->len ^= F_NOT; /* toggle F_NOT */
5282                         fill_cmd(cmd, O_IN, 0, 0);
5283                         break;
5284
5285                 case TOK_DIVERTED:
5286                         fill_cmd(cmd, O_DIVERTED, 0, 3);
5287                         break;
5288
5289                 case TOK_DIVERTEDLOOPBACK:
5290                         fill_cmd(cmd, O_DIVERTED, 0, 1);
5291                         break;
5292
5293                 case TOK_DIVERTEDOUTPUT:
5294                         fill_cmd(cmd, O_DIVERTED, 0, 2);
5295                         break;
5296
5297                 case TOK_FRAG:
5298                         fill_cmd(cmd, O_FRAG, 0, 0);
5299                         break;
5300
5301                 case TOK_LAYER2:
5302                         fill_cmd(cmd, O_LAYER2, 0, 0);
5303                         break;
5304
5305                 case TOK_XMIT:
5306                 case TOK_RECV:
5307                 case TOK_VIA:
5308                         NEED1("recv, xmit, via require interface name"
5309                                 " or address");
5310                         fill_iface((ipfw_insn_if *)cmd, av[0]);
5311                         ac--; av++;
5312                         if (F_LEN(cmd) == 0)    /* not a valid address */
5313                                 break;
5314                         if (i == TOK_XMIT)
5315                                 cmd->opcode = O_XMIT;
5316                         else if (i == TOK_RECV)
5317                                 cmd->opcode = O_RECV;
5318                         else if (i == TOK_VIA)
5319                                 cmd->opcode = O_VIA;
5320                         break;
5321
5322                 case TOK_ICMPTYPES:
5323                         NEED1("icmptypes requires list of types");
5324                         fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
5325                         av++; ac--;
5326                         break;
5327                 
5328                 case TOK_ICMP6TYPES:
5329                         NEED1("icmptypes requires list of types");
5330                         fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
5331                         av++; ac--;
5332                         break;
5333
5334                 case TOK_IPTTL:
5335                         NEED1("ipttl requires TTL");
5336                         if (strpbrk(*av, "-,")) {
5337                             if (!add_ports(cmd, *av, 0, O_IPTTL))
5338                                 errx(EX_DATAERR, "invalid ipttl %s", *av);
5339                         } else
5340                             fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
5341                         ac--; av++;
5342                         break;
5343
5344                 case TOK_IPID:
5345                         NEED1("ipid requires id");
5346                         if (strpbrk(*av, "-,")) {
5347                             if (!add_ports(cmd, *av, 0, O_IPID))
5348                                 errx(EX_DATAERR, "invalid ipid %s", *av);
5349                         } else
5350                             fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
5351                         ac--; av++;
5352                         break;
5353
5354                 case TOK_IPLEN:
5355                         NEED1("iplen requires length");
5356                         if (strpbrk(*av, "-,")) {
5357                             if (!add_ports(cmd, *av, 0, O_IPLEN))
5358                                 errx(EX_DATAERR, "invalid ip len %s", *av);
5359                         } else
5360                             fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
5361                         ac--; av++;
5362                         break;
5363
5364                 case TOK_IPVER:
5365                         NEED1("ipver requires version");
5366                         fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
5367                         ac--; av++;
5368                         break;
5369
5370                 case TOK_IPPRECEDENCE:
5371                         NEED1("ipprecedence requires value");
5372                         fill_cmd(cmd, O_IPPRECEDENCE, 0,
5373                             (strtoul(*av, NULL, 0) & 7) << 5);
5374                         ac--; av++;
5375                         break;
5376
5377                 case TOK_IPOPTS:
5378                         NEED1("missing argument for ipoptions");
5379                         fill_flags(cmd, O_IPOPT, f_ipopts, *av);
5380                         ac--; av++;
5381                         break;
5382
5383                 case TOK_IPTOS:
5384                         NEED1("missing argument for iptos");
5385                         fill_flags(cmd, O_IPTOS, f_iptos, *av);
5386                         ac--; av++;
5387                         break;
5388
5389                 case TOK_UID:
5390                         NEED1("uid requires argument");
5391                     {
5392                         char *end;
5393                         uid_t uid;
5394                         struct passwd *pwd;
5395
5396                         cmd->opcode = O_UID;
5397                         uid = strtoul(*av, &end, 0);
5398                         pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
5399                         if (pwd == NULL)
5400                                 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
5401                         cmd32->d[0] = pwd->pw_uid;
5402                         cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5403                         ac--; av++;
5404                     }
5405                         break;
5406
5407                 case TOK_GID:
5408                         NEED1("gid requires argument");
5409                     {
5410                         char *end;
5411                         gid_t gid;
5412                         struct group *grp;
5413
5414                         cmd->opcode = O_GID;
5415                         gid = strtoul(*av, &end, 0);
5416                         grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
5417                         if (grp == NULL)
5418                                 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
5419                         cmd32->d[0] = grp->gr_gid;
5420                         cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5421                         ac--; av++;
5422                     }
5423                         break;
5424
5425                 case TOK_JAIL:
5426                         NEED1("jail requires argument");
5427                     {
5428                         char *end;
5429                         int jid;
5430
5431                         cmd->opcode = O_JAIL;
5432                         jid = (int)strtol(*av, &end, 0);
5433                         if (jid < 0 || *end != '\0')
5434                                 errx(EX_DATAERR, "jail requires prison ID");
5435                         cmd32->d[0] = (uint32_t)jid;
5436                         cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5437                         ac--; av++;
5438                     }
5439                         break;
5440
5441                 case TOK_ESTAB:
5442                         fill_cmd(cmd, O_ESTAB, 0, 0);
5443                         break;
5444
5445                 case TOK_SETUP:
5446                         fill_cmd(cmd, O_TCPFLAGS, 0,
5447                                 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
5448                         break;
5449
5450                 case TOK_TCPDATALEN:
5451                         NEED1("tcpdatalen requires length");
5452                         if (strpbrk(*av, "-,")) {
5453                             if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
5454                                 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
5455                         } else
5456                             fill_cmd(cmd, O_TCPDATALEN, 0,
5457                                     strtoul(*av, NULL, 0));
5458                         ac--; av++;
5459                         break;
5460
5461                 case TOK_TCPOPTS:
5462                         NEED1("missing argument for tcpoptions");
5463                         fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
5464                         ac--; av++;
5465                         break;
5466
5467                 case TOK_TCPSEQ:
5468                 case TOK_TCPACK:
5469                         NEED1("tcpseq/tcpack requires argument");
5470                         cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5471                         cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5472                         cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5473                         ac--; av++;
5474                         break;
5475
5476                 case TOK_TCPWIN:
5477                         NEED1("tcpwin requires length");
5478                         fill_cmd(cmd, O_TCPWIN, 0,
5479                             htons(strtoul(*av, NULL, 0)));
5480                         ac--; av++;
5481                         break;
5482
5483                 case TOK_TCPFLAGS:
5484                         NEED1("missing argument for tcpflags");
5485                         cmd->opcode = O_TCPFLAGS;
5486                         fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
5487                         ac--; av++;
5488                         break;
5489
5490                 case TOK_KEEPSTATE:
5491                         if (open_par)
5492                                 errx(EX_USAGE, "keep-state cannot be part "
5493                                     "of an or block");
5494                         if (have_state)
5495                                 errx(EX_USAGE, "only one of keep-state "
5496                                         "and limit is allowed");
5497                         have_state = cmd;
5498                         fill_cmd(cmd, O_KEEP_STATE, 0, 0);
5499                         break;
5500
5501                 case TOK_LIMIT: {
5502                         ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
5503                         int val;
5504
5505                         if (open_par)
5506                                 errx(EX_USAGE,
5507                                     "limit cannot be part of an or block");
5508                         if (have_state)
5509                                 errx(EX_USAGE, "only one of keep-state and "
5510                                     "limit is allowed");
5511                         have_state = cmd;
5512
5513                         cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5514                         cmd->opcode = O_LIMIT;
5515                         c->limit_mask = c->conn_limit = 0;
5516
5517                         while (ac > 0) {
5518                                 if ((val = match_token(limit_masks, *av)) <= 0)
5519                                         break;
5520                                 c->limit_mask |= val;
5521                                 ac--; av++;
5522                         }
5523
5524                         if (c->limit_mask == 0)
5525                                 errx(EX_USAGE, "limit: missing limit mask");
5526
5527                         GET_UINT_ARG(c->conn_limit, 1, IPFW_DEFAULT_RULE - 1,
5528                             TOK_LIMIT, rule_options);
5529
5530                         ac--; av++;
5531                         break;
5532                 }
5533
5534                 case TOK_PROTO:
5535                         NEED1("missing protocol");
5536                         if (add_proto(cmd, *av, &proto)) {
5537                                 ac--; av++;
5538                         } else
5539                                 errx(EX_DATAERR, "invalid protocol ``%s''",
5540                                     *av);
5541                         break;
5542
5543                 case TOK_SRCIP:
5544                         NEED1("missing source IP");
5545                         if (add_srcip(cmd, *av)) {
5546                                 ac--; av++;
5547                         }
5548                         break;
5549
5550                 case TOK_DSTIP:
5551                         NEED1("missing destination IP");
5552                         if (add_dstip(cmd, *av)) {
5553                                 ac--; av++;
5554                         }
5555                         break;
5556
5557                 case TOK_SRCIP6:
5558                         NEED1("missing source IP6");
5559                         if (add_srcip6(cmd, *av)) {
5560                                 ac--; av++;
5561                         }
5562                         break;
5563                                 
5564                 case TOK_DSTIP6:
5565                         NEED1("missing destination IP6");
5566                         if (add_dstip6(cmd, *av)) {
5567                                 ac--; av++;
5568                         }
5569                         break;
5570
5571                 case TOK_SRCPORT:
5572                         NEED1("missing source port");
5573                         if (_substrcmp(*av, "any") == 0 ||
5574                             add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
5575                                 ac--; av++;
5576                         } else
5577                                 errx(EX_DATAERR, "invalid source port %s", *av);
5578                         break;
5579
5580                 case TOK_DSTPORT:
5581                         NEED1("missing destination port");
5582                         if (_substrcmp(*av, "any") == 0 ||
5583                             add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
5584                                 ac--; av++;
5585                         } else
5586                                 errx(EX_DATAERR, "invalid destination port %s",
5587                                     *av);
5588                         break;
5589
5590                 case TOK_MAC:
5591                         if (add_mac(cmd, ac, av)) {
5592                                 ac -= 2; av += 2;
5593                         }
5594                         break;
5595
5596                 case TOK_MACTYPE:
5597                         NEED1("missing mac type");
5598                         if (!add_mactype(cmd, ac, *av))
5599                                 errx(EX_DATAERR, "invalid mac type %s", *av);
5600                         ac--; av++;
5601                         break;
5602
5603                 case TOK_VERREVPATH:
5604                         fill_cmd(cmd, O_VERREVPATH, 0, 0);
5605                         break;
5606
5607                 case TOK_VERSRCREACH:
5608                         fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5609                         break;
5610
5611                 case TOK_ANTISPOOF:
5612                         fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5613                         break;
5614
5615                 case TOK_IPSEC:
5616                         fill_cmd(cmd, O_IPSEC, 0, 0);
5617                         break;
5618
5619                 case TOK_IPV6:
5620                         fill_cmd(cmd, O_IP6, 0, 0);
5621                         break;
5622
5623                 case TOK_IPV4:
5624                         fill_cmd(cmd, O_IP4, 0, 0);
5625                         break;
5626
5627                 case TOK_EXT6HDR:
5628                         fill_ext6hdr( cmd, *av );
5629                         ac--; av++;
5630                         break;
5631
5632                 case TOK_FLOWID:
5633                         if (proto != IPPROTO_IPV6 )
5634                                 errx( EX_USAGE, "flow-id filter is active "
5635                                     "only for ipv6 protocol\n");
5636                         fill_flow6( (ipfw_insn_u32 *) cmd, *av );
5637                         ac--; av++;
5638                         break;
5639
5640                 case TOK_COMMENT:
5641                         fill_comment(cmd, ac, av);
5642                         av += ac;
5643                         ac = 0;
5644                         break;
5645
5646                 case TOK_TAGGED:
5647                         if (ac > 0 && strpbrk(*av, "-,")) {
5648                                 if (!add_ports(cmd, *av, 0, O_TAGGED))
5649                                         errx(EX_DATAERR, "tagged: invalid tag"
5650                                             " list: %s", *av);
5651                         }
5652                         else {
5653                                 uint16_t tag;
5654
5655                                 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1,
5656                                     TOK_TAGGED, rule_options);
5657                                 fill_cmd(cmd, O_TAGGED, 0, tag);
5658                         }
5659                         ac--; av++;
5660                         break;
5661
5662                 case TOK_FIB:
5663                         NEED1("fib requires fib number");
5664                         fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5665                         ac--; av++;
5666                         break;
5667
5668                 default:
5669                         errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5670                 }
5671                 if (F_LEN(cmd) > 0) {   /* prepare to advance */
5672                         prev = cmd;
5673                         cmd = next_cmd(cmd);
5674                 }
5675         }
5676
5677 done:
5678         /*
5679          * Now copy stuff into the rule.
5680          * If we have a keep-state option, the first instruction
5681          * must be a PROBE_STATE (which is generated here).
5682          * If we have a LOG option, it was stored as the first command,
5683          * and now must be moved to the top of the action part.
5684          */
5685         dst = (ipfw_insn *)rule->cmd;
5686
5687         /*
5688          * First thing to write into the command stream is the match probability.
5689          */
5690         if (match_prob != 1) { /* 1 means always match */
5691                 dst->opcode = O_PROB;
5692                 dst->len = 2;
5693                 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5694                 dst += dst->len;
5695         }
5696
5697         /*
5698          * generate O_PROBE_STATE if necessary
5699          */
5700         if (have_state && have_state->opcode != O_CHECK_STATE) {
5701                 fill_cmd(dst, O_PROBE_STATE, 0, 0);
5702                 dst = next_cmd(dst);
5703         }
5704
5705         /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
5706         for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5707                 i = F_LEN(src);
5708
5709                 switch (src->opcode) {
5710                 case O_LOG:
5711                 case O_KEEP_STATE:
5712                 case O_LIMIT:
5713                 case O_ALTQ:
5714                 case O_TAG:
5715                         break;
5716                 default:
5717                         bcopy(src, dst, i * sizeof(uint32_t));
5718                         dst += i;
5719                 }
5720         }
5721
5722         /*
5723          * put back the have_state command as last opcode
5724          */
5725         if (have_state && have_state->opcode != O_CHECK_STATE) {
5726                 i = F_LEN(have_state);
5727                 bcopy(have_state, dst, i * sizeof(uint32_t));
5728                 dst += i;
5729         }
5730         /*
5731          * start action section
5732          */
5733         rule->act_ofs = dst - rule->cmd;
5734
5735         /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5736         if (have_log) {
5737                 i = F_LEN(have_log);
5738                 bcopy(have_log, dst, i * sizeof(uint32_t));
5739                 dst += i;
5740         }
5741         if (have_altq) {
5742                 i = F_LEN(have_altq);
5743                 bcopy(have_altq, dst, i * sizeof(uint32_t));
5744                 dst += i;
5745         }
5746         if (have_tag) {
5747                 i = F_LEN(have_tag);
5748                 bcopy(have_tag, dst, i * sizeof(uint32_t));
5749                 dst += i;
5750         }
5751         /*
5752          * copy all other actions
5753          */
5754         for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5755                 i = F_LEN(src);
5756                 bcopy(src, dst, i * sizeof(uint32_t));
5757                 dst += i;
5758         }
5759
5760         rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5761         i = (char *)dst - (char *)rule;
5762         if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
5763                 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
5764         if (!do_quiet)
5765                 show_ipfw(rule, 0, 0);
5766 }
5767
5768 static void
5769 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */)
5770 {
5771         uint32_t arg, saved_arg;
5772         int failed = EX_OK;
5773         char const *name = optname == IP_FW_ZERO ?  "ZERO" : "RESETLOG";
5774         char const *errstr;
5775
5776         av++; ac--;
5777
5778         if (!ac) {
5779                 /* clear all entries */
5780                 if (do_cmd(optname, NULL, 0) < 0)
5781                         err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
5782                 if (!do_quiet)
5783                         printf("%s.\n", optname == IP_FW_ZERO ?
5784                             "Accounting cleared":"Logging counts reset");
5785
5786                 return;
5787         }
5788
5789         while (ac) {
5790                 /* Rule number */
5791                 if (isdigit(**av)) {
5792                         arg = strtonum(*av, 0, 0xffff, &errstr);
5793                         if (errstr)
5794                                 errx(EX_DATAERR,
5795                                     "invalid rule number %s\n", *av);
5796                         saved_arg = arg;
5797                         if (use_set)
5798                                 arg |= (1 << 24) | ((use_set - 1) << 16);
5799                         av++;
5800                         ac--;
5801                         if (do_cmd(optname, &arg, sizeof(arg))) {
5802                                 warn("rule %u: setsockopt(IP_FW_%s)",
5803                                     saved_arg, name);
5804                                 failed = EX_UNAVAILABLE;
5805                         } else if (!do_quiet)
5806                                 printf("Entry %d %s.\n", saved_arg,
5807                                     optname == IP_FW_ZERO ?
5808                                         "cleared" : "logging count reset");
5809                 } else {
5810                         errx(EX_USAGE, "invalid rule number ``%s''", *av);
5811                 }
5812         }
5813         if (failed != EX_OK)
5814                 exit(failed);
5815 }
5816
5817 static void
5818 flush(int force)
5819 {
5820         int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
5821
5822         if (!force && !do_quiet) { /* need to ask user */
5823                 int c;
5824
5825                 printf("Are you sure? [yn] ");
5826                 fflush(stdout);
5827                 do {
5828                         c = toupper(getc(stdin));
5829                         while (c != '\n' && getc(stdin) != '\n')
5830                                 if (feof(stdin))
5831                                         return; /* and do not flush */
5832                 } while (c != 'Y' && c != 'N');
5833                 printf("\n");
5834                 if (c == 'N')   /* user said no */
5835                         return;
5836         }
5837         /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5838         if (use_set) {
5839                 uint32_t arg = ((use_set - 1) & 0xffff) | (1 << 24);
5840                 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
5841                         err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
5842         } else if (do_cmd(cmd, NULL, 0) < 0)
5843                 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
5844                     do_pipe ? "DUMMYNET" : "FW");
5845         if (!do_quiet)
5846                 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
5847 }
5848
5849 /*
5850  * Free a the (locally allocated) copy of command line arguments.
5851  */
5852 static void
5853 free_args(int ac, char **av)
5854 {
5855         int i;
5856
5857         for (i=0; i < ac; i++)
5858                 free(av[i]);
5859         free(av);
5860 }
5861
5862 static void table_list(ipfw_table_entry ent, int need_header);
5863
5864 /*
5865  * This one handles all table-related commands
5866  *      ipfw table N add addr[/masklen] [value]
5867  *      ipfw table N delete addr[/masklen]
5868  *      ipfw table {N | all} flush
5869  *      ipfw table {N | all} list
5870  */
5871 static void
5872 table_handler(int ac, char *av[])
5873 {
5874         ipfw_table_entry ent;
5875         int do_add;
5876         int is_all;
5877         size_t len;
5878         char *p;
5879         uint32_t a;
5880         uint32_t tables_max;
5881
5882         len = sizeof(tables_max);
5883         if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
5884                 NULL, 0) == -1) {
5885 #ifdef IPFW_TABLES_MAX
5886                 warn("Warn: Failed to get the max tables number via sysctl. "
5887                      "Using the compiled in defaults. \nThe reason was");
5888                 tables_max = IPFW_TABLES_MAX;
5889 #else
5890                 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
5891 #endif
5892         }
5893
5894         ac--; av++;
5895         if (ac && isdigit(**av)) {
5896                 ent.tbl = atoi(*av);
5897                 is_all = 0;
5898                 ac--; av++;
5899         } else if (ac && _substrcmp(*av, "all") == 0) {
5900                 ent.tbl = 0;
5901                 is_all = 1;
5902                 ac--; av++;
5903         } else
5904                 errx(EX_USAGE, "table number or 'all' keyword required");
5905         if (ent.tbl >= tables_max)
5906                 errx(EX_USAGE, "The table number exceeds the maximum allowed "
5907                         "value (%d)", tables_max - 1);
5908         NEED1("table needs command");
5909         if (is_all && _substrcmp(*av, "list") != 0
5910                    && _substrcmp(*av, "flush") != 0)
5911                 errx(EX_USAGE, "table number required");
5912
5913         if (_substrcmp(*av, "add") == 0 ||
5914             _substrcmp(*av, "delete") == 0) {
5915                 do_add = **av == 'a';
5916                 ac--; av++;
5917                 if (!ac)
5918                         errx(EX_USAGE, "IP address required");
5919                 p = strchr(*av, '/');
5920                 if (p) {
5921                         *p++ = '\0';
5922                         ent.masklen = atoi(p);
5923                         if (ent.masklen > 32)
5924                                 errx(EX_DATAERR, "bad width ``%s''", p);
5925                 } else
5926                         ent.masklen = 32;
5927                 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
5928                         errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
5929                 ac--; av++;
5930                 if (do_add && ac) {
5931                         unsigned int tval;
5932                         /* isdigit is a bit of a hack here.. */
5933                         if (strchr(*av, (int)'.') == NULL && isdigit(**av))  {
5934                                 ent.value = strtoul(*av, NULL, 0);
5935                         } else {
5936                                 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
5937                                         /* The value must be stored in host order        *
5938                                          * so that the values < 65k can be distinguished */
5939                                         ent.value = ntohl(tval); 
5940                                 } else {
5941                                         errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
5942                                 }
5943                         }
5944                 } else
5945                         ent.value = 0;
5946                 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
5947                     &ent, sizeof(ent)) < 0) {
5948                         /* If running silent, don't bomb out on these errors. */
5949                         if (!(do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
5950                                 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
5951                                     do_add ? "ADD" : "DEL");
5952                         /* In silent mode, react to a failed add by deleting */
5953                         if (do_add) {
5954                                 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
5955                                 if (do_cmd(IP_FW_TABLE_ADD,
5956                                     &ent, sizeof(ent)) < 0)
5957                                         err(EX_OSERR,
5958                                             "setsockopt(IP_FW_TABLE_ADD)");
5959                         }
5960                 }
5961         } else if (_substrcmp(*av, "flush") == 0) {
5962                 a = is_all ? tables_max : (ent.tbl + 1);
5963                 do {
5964                         if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
5965                             sizeof(ent.tbl)) < 0)
5966                                 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
5967                 } while (++ent.tbl < a);
5968         } else if (_substrcmp(*av, "list") == 0) {
5969                 a = is_all ? tables_max : (ent.tbl + 1);
5970                 do {
5971                         table_list(ent, is_all);
5972                 } while (++ent.tbl < a);
5973         } else
5974                 errx(EX_USAGE, "invalid table command %s", *av);
5975 }
5976
5977 static void
5978 table_list(ipfw_table_entry ent, int need_header)
5979 {
5980         ipfw_table *tbl;
5981         socklen_t l;
5982         uint32_t a;
5983
5984         a = ent.tbl;
5985         l = sizeof(a);
5986         if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
5987                 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
5988
5989         /* If a is zero we have nothing to do, the table is empty. */
5990         if (a == 0)
5991                 return;
5992
5993         l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
5994         tbl = malloc(l);
5995         if (tbl == NULL)
5996                 err(EX_OSERR, "malloc");
5997         tbl->tbl = ent.tbl;
5998         if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
5999                 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
6000         if (tbl->cnt && need_header)
6001                 printf("---table(%d)---\n", tbl->tbl);
6002         for (a = 0; a < tbl->cnt; a++) {
6003                 unsigned int tval;
6004                 tval = tbl->ent[a].value;
6005                 if (do_value_as_ip) {
6006                         char tbuf[128];
6007                         strncpy(tbuf, inet_ntoa(*(struct in_addr *)
6008                                 &tbl->ent[a].addr), 127);
6009                         /* inet_ntoa expects network order */
6010                         tval = htonl(tval);
6011                         printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
6012                                 inet_ntoa(*(struct in_addr *)&tval));
6013                 } else {
6014                         printf("%s/%u %u\n",
6015                                 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
6016                                 tbl->ent[a].masklen, tval);
6017                 }
6018         }
6019         free(tbl);
6020 }
6021
6022 static void
6023 show_nat(int ac, char **av)
6024 {
6025         struct cfg_nat *n;
6026         struct cfg_redir *e;
6027         int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
6028         int nat_cnt, redir_cnt, r;
6029         uint8_t *data, *p;
6030         char *endptr;
6031
6032         do_rule = 0;
6033         nalloc = 1024;
6034         size = 0;
6035         data = NULL;
6036         frule = 0;
6037         lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */
6038         ac--; av++;
6039
6040         if (test_only)
6041                 return;
6042
6043         /* Parse parameters. */
6044         for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
6045                 if (!strncmp(av[0], "config", strlen(av[0]))) {
6046                         cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1; 
6047                         continue;
6048                 }
6049                 /* Convert command line rule #. */
6050                 frule = lrule = strtoul(av[0], &endptr, 10);
6051                 if (*endptr == '-')
6052                         lrule = strtoul(endptr+1, &endptr, 10);
6053                 if (lrule == 0)                 
6054                         err(EX_USAGE, "invalid rule number: %s", av[0]);
6055                 do_rule = 1;
6056         }
6057
6058         nbytes = nalloc;
6059         while (nbytes >= nalloc) {
6060                 nalloc = nalloc * 2;
6061                 nbytes = nalloc;
6062                 if ((data = realloc(data, nbytes)) == NULL)
6063                         err(EX_OSERR, "realloc");
6064                 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
6065                         err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
6066                             (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
6067         }
6068         if (nbytes == 0)
6069                 exit(0);
6070         if (do_cfg) {
6071                 nat_cnt = *((int *)data);
6072                 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
6073                         n = (struct cfg_nat *)&data[i];
6074                         if (frule <= n->id && lrule >= n->id)
6075                                 print_nat_config(&data[i]);
6076                         i += sizeof(struct cfg_nat);
6077                         for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
6078                                 e = (struct cfg_redir *)&data[i];
6079                                 i += sizeof(struct cfg_redir) + e->spool_cnt * 
6080                                     sizeof(struct cfg_spool);
6081                         }
6082                 }
6083         } else {
6084                 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
6085                         p = &data[i];
6086                         if (p == data + nbytes)
6087                                 break;
6088                         bcopy(p, &r, sizeof(int));
6089                         if (do_rule) {
6090                                 if (!(frule <= r && lrule >= r))
6091                                         continue;
6092                         }
6093                         printf("nat %u: %s\n", r, p+sizeof(int));
6094                 }
6095         }
6096 }
6097
6098 /*
6099  * Called with the arguments (excluding program name).
6100  * Returns 0 if successful, 1 if empty command, errx() in case of errors.
6101  */
6102 static int
6103 ipfw_main(int oldac, char **oldav)
6104 {
6105         int ch, ac, save_ac;
6106         const char *errstr;
6107         char **av, **save_av;
6108         int do_acct = 0;                /* Show packet/byte count */
6109
6110 #define WHITESP         " \t\f\v\n\r"
6111         if (oldac == 0)
6112                 return 1;
6113         else if (oldac == 1) {
6114                 /*
6115                  * If we are called with a single string, try to split it into
6116                  * arguments for subsequent parsing.
6117                  * But first, remove spaces after a ',', by copying the string
6118                  * in-place.
6119                  */
6120                 char *arg = oldav[0];   /* The string... */
6121                 int l = strlen(arg);
6122                 int copy = 0;           /* 1 if we need to copy, 0 otherwise */
6123                 int i, j;
6124                 for (i = j = 0; i < l; i++) {
6125                         if (arg[i] == '#')      /* comment marker */
6126                                 break;
6127                         if (copy) {
6128                                 arg[j++] = arg[i];
6129                                 copy = !index("," WHITESP, arg[i]);
6130                         } else {
6131                                 copy = !index(WHITESP, arg[i]);
6132                                 if (copy)
6133                                         arg[j++] = arg[i];
6134                         }
6135                 }
6136                 if (!copy && j > 0)     /* last char was a 'blank', remove it */
6137                         j--;
6138                 l = j;                  /* the new argument length */
6139                 arg[j++] = '\0';
6140                 if (l == 0)             /* empty string! */
6141                         return 1;
6142
6143                 /*
6144                  * First, count number of arguments. Because of the previous
6145                  * processing, this is just the number of blanks plus 1.
6146                  */
6147                 for (i = 0, ac = 1; i < l; i++)
6148                         if (index(WHITESP, arg[i]) != NULL)
6149                                 ac++;
6150
6151                 av = calloc(ac, sizeof(char *));
6152
6153                 /*
6154                  * Second, copy arguments from cmd[] to av[]. For each one,
6155                  * j is the initial character, i is the one past the end.
6156                  */
6157                 for (ac = 0, i = j = 0; i < l; i++)
6158                         if (index(WHITESP, arg[i]) != NULL || i == l-1) {
6159                                 if (i == l-1)
6160                                         i++;
6161                                 av[ac] = calloc(i-j+1, 1);
6162                                 bcopy(arg+j, av[ac], i-j);
6163                                 ac++;
6164                                 j = i + 1;
6165                         }
6166         } else {
6167                 /*
6168                  * If an argument ends with ',' join with the next one.
6169                  */
6170                 int first, i, l;
6171
6172                 av = calloc(oldac, sizeof(char *));
6173                 for (first = i = ac = 0, l = 0; i < oldac; i++) {
6174                         char *arg = oldav[i];
6175                         int k = strlen(arg);
6176
6177                         l += k;
6178                         if (arg[k-1] != ',' || i == oldac-1) {
6179                                 /* Time to copy. */
6180                                 av[ac] = calloc(l+1, 1);
6181                                 for (l=0; first <= i; first++) {
6182                                         strcat(av[ac]+l, oldav[first]);
6183                                         l += strlen(oldav[first]);
6184                                 }
6185                                 ac++;
6186                                 l = 0;
6187                                 first = i+1;
6188                         }
6189                 }
6190         }
6191
6192         /* Set the force flag for non-interactive processes */
6193         if (!do_force)
6194                 do_force = !isatty(STDIN_FILENO);
6195
6196         /* Save arguments for final freeing of memory. */
6197         save_ac = ac;
6198         save_av = av;
6199
6200         optind = optreset = 0;
6201         while ((ch = getopt(ac, av, "abcdefhinNqs:STtv")) != -1)
6202                 switch (ch) {
6203                 case 'a':
6204                         do_acct = 1;
6205                         break;
6206
6207                 case 'b':
6208                         comment_only = 1;
6209                         do_compact = 1;
6210                         break;
6211
6212                 case 'c':
6213                         do_compact = 1;
6214                         break;
6215
6216                 case 'd':
6217                         do_dynamic = 1;
6218                         break;
6219
6220                 case 'e':
6221                         do_expired = 1;
6222                         break;
6223
6224                 case 'f':
6225                         do_force = 1;
6226                         break;
6227
6228                 case 'h': /* help */
6229                         free_args(save_ac, save_av);
6230                         help();
6231                         break;  /* NOTREACHED */
6232
6233                 case 'i':
6234                         do_value_as_ip = 1;
6235                         break;
6236
6237                 case 'n':
6238                         test_only = 1;
6239                         break;
6240
6241                 case 'N':
6242                         do_resolv = 1;
6243                         break;
6244
6245                 case 'q':
6246                         do_quiet = 1;
6247                         break;
6248
6249                 case 's': /* sort */
6250                         do_sort = atoi(optarg);
6251                         break;
6252
6253                 case 'S':
6254                         show_sets = 1;
6255                         break;
6256
6257                 case 't':
6258                         do_time = 1;
6259                         break;
6260
6261                 case 'T':
6262                         do_time = 2;    /* numeric timestamp */
6263                         break;
6264
6265                 case 'v': /* verbose */
6266                         verbose = 1;
6267                         break;
6268
6269                 default:
6270                         free_args(save_ac, save_av);
6271                         return 1;
6272                 }
6273
6274         ac -= optind;
6275         av += optind;
6276         NEED1("bad arguments, for usage summary ``ipfw''");
6277
6278         /*
6279          * An undocumented behaviour of ipfw1 was to allow rule numbers first,
6280          * e.g. "100 add allow ..." instead of "add 100 allow ...".
6281          * In case, swap first and second argument to get the normal form.
6282          */
6283         if (ac > 1 && isdigit(*av[0])) {
6284                 char *p = av[0];
6285
6286                 av[0] = av[1];
6287                 av[1] = p;
6288         }
6289
6290         /*
6291          * Optional: pipe, queue or nat.
6292          */
6293         do_nat = 0;
6294         do_pipe = 0;
6295         if (!strncmp(*av, "nat", strlen(*av)))
6296                 do_nat = 1;
6297         else if (!strncmp(*av, "pipe", strlen(*av)))
6298                 do_pipe = 1;
6299         else if (_substrcmp(*av, "queue") == 0)
6300                 do_pipe = 2;
6301         else if (!strncmp(*av, "set", strlen(*av))) {
6302                 if (ac > 1 && isdigit(av[1][0])) {
6303                         use_set = strtonum(av[1], 0, RESVD_SET, &errstr);
6304                         if (errstr)
6305                                 errx(EX_DATAERR,
6306                                     "invalid set number %s\n", av[1]);
6307                         ac -= 2; av += 2; use_set++;
6308                 }
6309         }
6310
6311         if (do_pipe || do_nat) {
6312                 ac--;
6313                 av++;
6314         }
6315         NEED1("missing command");
6316
6317         /*
6318          * For pipes, queues and nats we normally say 'nat|pipe NN config'
6319          * but the code is easier to parse as 'nat|pipe config NN'
6320          * so we swap the two arguments.
6321          */
6322         if ((do_pipe || do_nat) && ac > 1 && isdigit(*av[0])) {
6323                 char *p = av[0];
6324
6325                 av[0] = av[1];
6326                 av[1] = p;
6327         }
6328
6329         int try_next = 0;
6330         if (use_set == 0) {
6331                 if (_substrcmp(*av, "add") == 0)
6332                         add(ac, av);
6333                 else if (do_nat && _substrcmp(*av, "show") == 0)
6334                         show_nat(ac, av);
6335                 else if (do_pipe && _substrcmp(*av, "config") == 0)
6336                         config_pipe(ac, av);
6337                 else if (do_nat && _substrcmp(*av, "config") == 0)
6338                         config_nat(ac, av);
6339                 else if (_substrcmp(*av, "set") == 0)
6340                         sets_handler(ac, av);
6341                 else if (_substrcmp(*av, "table") == 0)
6342                         table_handler(ac, av);
6343                 else if (_substrcmp(*av, "enable") == 0)
6344                         sysctl_handler(ac, av, 1);
6345                 else if (_substrcmp(*av, "disable") == 0)
6346                         sysctl_handler(ac, av, 0);
6347                 else
6348                         try_next = 1;
6349         }
6350
6351         if (use_set || try_next) {
6352                 if (_substrcmp(*av, "delete") == 0)
6353                         delete(ac, av);
6354                 else if (_substrcmp(*av, "flush") == 0)
6355                         flush(do_force);
6356                 else if (_substrcmp(*av, "zero") == 0)
6357                         zero(ac, av, IP_FW_ZERO);
6358                 else if (_substrcmp(*av, "resetlog") == 0)
6359                         zero(ac, av, IP_FW_RESETLOG);
6360                 else if (_substrcmp(*av, "print") == 0 ||
6361                          _substrcmp(*av, "list") == 0)
6362                         list(ac, av, do_acct);
6363                 else if (_substrcmp(*av, "show") == 0)
6364                         list(ac, av, 1 /* show counters */);
6365                 else
6366                         errx(EX_USAGE, "bad command `%s'", *av);
6367         }
6368
6369         /* Free memory allocated in the argument parsing. */
6370         free_args(save_ac, save_av);
6371         return 0;
6372 }
6373
6374
6375 static void
6376 ipfw_readfile(int ac, char *av[])
6377 {
6378 #define MAX_ARGS        32
6379         char    buf[BUFSIZ];
6380         char    *cmd = NULL, *filename = av[ac-1];
6381         int     c, lineno=0;
6382         FILE    *f = NULL;
6383         pid_t   preproc = 0;
6384
6385         filename = av[ac-1];
6386
6387         while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
6388                 switch(c) {
6389                 case 'c':
6390                         do_compact = 1;
6391                         break;
6392
6393                 case 'f':
6394                         do_force = 1;
6395                         break;
6396
6397                 case 'N':
6398                         do_resolv = 1;
6399                         break;
6400
6401                 case 'n':
6402                         test_only = 1;
6403                         break;
6404
6405                 case 'p':
6406                         cmd = optarg;
6407                         /*
6408                          * Skip previous args and delete last one, so we
6409                          * pass all but the last argument to the preprocessor
6410                          * via av[optind-1]
6411                          */
6412                         av += optind - 1;
6413                         ac -= optind - 1;
6414                         if (ac < 2)
6415                                 errx(EX_USAGE, "no filename argument");
6416                         av[ac-1] = NULL;
6417                         fprintf(stderr, "command is %s\n", av[0]);
6418                         break;
6419
6420                 case 'q':
6421                         do_quiet = 1;
6422                         break;
6423
6424                 case 'S':
6425                         show_sets = 1;
6426                         break;
6427
6428                 default:
6429                         errx(EX_USAGE, "bad arguments, for usage"
6430                              " summary ``ipfw''");
6431                 }
6432
6433                 if (cmd != NULL)
6434                         break;
6435         }
6436
6437         if (cmd == NULL && ac != optind + 1) {
6438                 fprintf(stderr, "ac %d, optind %d\n", ac, optind);
6439                 errx(EX_USAGE, "extraneous filename arguments");
6440         }
6441
6442         if ((f = fopen(filename, "r")) == NULL)
6443                 err(EX_UNAVAILABLE, "fopen: %s", filename);
6444
6445         if (cmd != NULL) {                      /* pipe through preprocessor */
6446                 int pipedes[2];
6447
6448                 if (pipe(pipedes) == -1)
6449                         err(EX_OSERR, "cannot create pipe");
6450
6451                 preproc = fork();
6452                 if (preproc == -1)
6453                         err(EX_OSERR, "cannot fork");
6454
6455                 if (preproc == 0) {
6456                         /*
6457                          * Child, will run the preprocessor with the
6458                          * file on stdin and the pipe on stdout.
6459                          */
6460                         if (dup2(fileno(f), 0) == -1
6461                             || dup2(pipedes[1], 1) == -1)
6462                                 err(EX_OSERR, "dup2()");
6463                         fclose(f);
6464                         close(pipedes[1]);
6465                         close(pipedes[0]);
6466                         execvp(cmd, av);
6467                         err(EX_OSERR, "execvp(%s) failed", cmd);
6468                 } else { /* parent, will reopen f as the pipe */
6469                         fclose(f);
6470                         close(pipedes[1]);
6471                         if ((f = fdopen(pipedes[0], "r")) == NULL) {
6472                                 int savederrno = errno;
6473
6474                                 (void)kill(preproc, SIGTERM);
6475                                 errno = savederrno;
6476                                 err(EX_OSERR, "fdopen()");
6477                         }
6478                 }
6479         }
6480
6481         while (fgets(buf, BUFSIZ, f)) {         /* read commands */
6482                 char linename[10];
6483                 char *args[1];
6484
6485                 lineno++;
6486                 sprintf(linename, "Line %d", lineno);
6487                 setprogname(linename); /* XXX */
6488                 args[0] = buf;
6489                 ipfw_main(1, args);
6490         }
6491         fclose(f);
6492         if (cmd != NULL) {
6493                 int status;
6494
6495                 if (waitpid(preproc, &status, 0) == -1)
6496                         errx(EX_OSERR, "waitpid()");
6497                 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
6498                         errx(EX_UNAVAILABLE,
6499                             "preprocessor exited with status %d",
6500                             WEXITSTATUS(status));
6501                 else if (WIFSIGNALED(status))
6502                         errx(EX_UNAVAILABLE,
6503                             "preprocessor exited with signal %d",
6504                             WTERMSIG(status));
6505         }
6506 }
6507
6508 int
6509 main(int ac, char *av[])
6510 {
6511         /*
6512          * If the last argument is an absolute pathname, interpret it
6513          * as a file to be preprocessed.
6514          */
6515
6516         if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
6517                 ipfw_readfile(ac, av);
6518         else {
6519                 if (ipfw_main(ac-1, av+1))
6520                         show_usage();
6521         }
6522         return EX_OK;
6523 }