parse.y revision 1.588
1/*	$OpenBSD: parse.y,v 1.588 2010/01/13 05:20:10 deraadt Exp $	*/
2
3/*
4 * Copyright (c) 2001 Markus Friedl.  All rights reserved.
5 * Copyright (c) 2001 Daniel Hartmeier.  All rights reserved.
6 * Copyright (c) 2001 Theo de Raadt.  All rights reserved.
7 * Copyright (c) 2002,2003 Henning Brauer. All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29%{
30#include <sys/types.h>
31#include <sys/socket.h>
32#include <sys/stat.h>
33#include <net/if.h>
34#include <netinet/in.h>
35#include <netinet/in_systm.h>
36#include <netinet/ip.h>
37#include <netinet/ip_icmp.h>
38#include <netinet/icmp6.h>
39#include <net/pfvar.h>
40#include <arpa/inet.h>
41#include <altq/altq.h>
42#include <altq/altq_cbq.h>
43#include <altq/altq_priq.h>
44#include <altq/altq_hfsc.h>
45
46#include <stdio.h>
47#include <unistd.h>
48#include <stdlib.h>
49#include <netdb.h>
50#include <stdarg.h>
51#include <errno.h>
52#include <string.h>
53#include <ctype.h>
54#include <math.h>
55#include <err.h>
56#include <limits.h>
57#include <pwd.h>
58#include <grp.h>
59#include <md5.h>
60
61#include "pfctl_parser.h"
62#include "pfctl.h"
63
64static struct pfctl	*pf = NULL;
65static int		 debug = 0;
66static int		 rulestate = 0;
67static u_int16_t	 returnicmpdefault =
68			    (ICMP_UNREACH << 8) | ICMP_UNREACH_PORT;
69static u_int16_t	 returnicmp6default =
70			    (ICMP6_DST_UNREACH << 8) | ICMP6_DST_UNREACH_NOPORT;
71static int		 blockpolicy = PFRULE_DROP;
72static int		 require_order = 0;
73static int		 default_statelock;
74
75TAILQ_HEAD(files, file)		 files = TAILQ_HEAD_INITIALIZER(files);
76static struct file {
77	TAILQ_ENTRY(file)	 entry;
78	FILE			*stream;
79	char			*name;
80	int			 lineno;
81	int			 errors;
82} *file;
83struct file	*pushfile(const char *, int);
84int		 popfile(void);
85int		 check_file_secrecy(int, const char *);
86int		 yyparse(void);
87int		 yylex(void);
88int		 yyerror(const char *, ...);
89int		 kw_cmp(const void *, const void *);
90int		 lookup(char *);
91int		 lgetc(int);
92int		 lungetc(int);
93int		 findeol(void);
94
95TAILQ_HEAD(symhead, sym)	 symhead = TAILQ_HEAD_INITIALIZER(symhead);
96struct sym {
97	TAILQ_ENTRY(sym)	 entry;
98	int			 used;
99	int			 persist;
100	char			*nam;
101	char			*val;
102};
103int		 symset(const char *, const char *, int);
104char		*symget(const char *);
105
106int		 atoul(char *, u_long *);
107
108enum {
109	PFCTL_STATE_NONE,
110	PFCTL_STATE_OPTION,
111	PFCTL_STATE_QUEUE,
112	PFCTL_STATE_NAT,
113	PFCTL_STATE_FILTER
114};
115
116struct node_proto {
117	u_int8_t		 proto;
118	struct node_proto	*next;
119	struct node_proto	*tail;
120};
121
122struct node_port {
123	u_int16_t		 port[2];
124	u_int8_t		 op;
125	struct node_port	*next;
126	struct node_port	*tail;
127};
128
129struct node_uid {
130	uid_t			 uid[2];
131	u_int8_t		 op;
132	struct node_uid		*next;
133	struct node_uid		*tail;
134};
135
136struct node_gid {
137	gid_t			 gid[2];
138	u_int8_t		 op;
139	struct node_gid		*next;
140	struct node_gid		*tail;
141};
142
143struct node_icmp {
144	u_int8_t		 code;
145	u_int8_t		 type;
146	u_int8_t		 proto;
147	struct node_icmp	*next;
148	struct node_icmp	*tail;
149};
150
151enum	{ PF_STATE_OPT_MAX, PF_STATE_OPT_NOSYNC, PF_STATE_OPT_SRCTRACK,
152	    PF_STATE_OPT_MAX_SRC_STATES, PF_STATE_OPT_MAX_SRC_CONN,
153	    PF_STATE_OPT_MAX_SRC_CONN_RATE, PF_STATE_OPT_MAX_SRC_NODES,
154	    PF_STATE_OPT_OVERLOAD, PF_STATE_OPT_STATELOCK,
155	    PF_STATE_OPT_TIMEOUT, PF_STATE_OPT_SLOPPY,
156	    PF_STATE_OPT_PFLOW };
157
158enum	{ PF_SRCTRACK_NONE, PF_SRCTRACK, PF_SRCTRACK_GLOBAL, PF_SRCTRACK_RULE };
159
160struct node_state_opt {
161	int			 type;
162	union {
163		u_int32_t	 max_states;
164		u_int32_t	 max_src_states;
165		u_int32_t	 max_src_conn;
166		struct {
167			u_int32_t	limit;
168			u_int32_t	seconds;
169		}		 max_src_conn_rate;
170		struct {
171			u_int8_t	flush;
172			char		tblname[PF_TABLE_NAME_SIZE];
173		}		 overload;
174		u_int32_t	 max_src_nodes;
175		u_int8_t	 src_track;
176		u_int32_t	 statelock;
177		struct {
178			int		number;
179			u_int32_t	seconds;
180		}		 timeout;
181	}			 data;
182	struct node_state_opt	*next;
183	struct node_state_opt	*tail;
184};
185
186struct peer {
187	struct node_host	*host;
188	struct node_port	*port;
189};
190
191struct node_queue {
192	char			 queue[PF_QNAME_SIZE];
193	char			 parent[PF_QNAME_SIZE];
194	char			 ifname[IFNAMSIZ];
195	int			 scheduler;
196	struct node_queue	*next;
197	struct node_queue	*tail;
198}	*queues = NULL;
199
200struct node_qassign {
201	char		*qname;
202	char		*pqname;
203};
204
205struct range {
206	int		 a;
207	int		 b;
208	int		 t;
209};
210struct redirection {
211	struct node_host	*host;
212	struct range		 rport;
213};
214
215struct pool_opts {
216	int			 marker;
217#define POM_TYPE		0x01
218#define POM_STICKYADDRESS	0x02
219	u_int8_t		 opts;
220	int			 type;
221	int			 staticport;
222	struct pf_poolhashkey	*key;
223
224} pool_opts;
225
226struct redirspec {
227	struct redirection      *rdr;
228	struct pool_opts         pool_opts;
229	int			 binat;
230};
231
232struct filter_opts {
233	int			 marker;
234#define FOM_FLAGS	0x0001
235#define FOM_ICMP	0x0002
236#define FOM_TOS		0x0004
237#define FOM_KEEP	0x0008
238#define FOM_SRCTRACK	0x0010
239#define FOM_MINTTL	0x0020
240#define FOM_MAXMSS	0x0040
241#define FOM_SETTOS	0x0100
242#define FOM_SCRUB_TCP	0x0200
243	struct node_uid		*uid;
244	struct node_gid		*gid;
245	struct node_if		*rcv;
246	struct {
247		u_int8_t	 b1;
248		u_int8_t	 b2;
249		u_int16_t	 w;
250		u_int16_t	 w2;
251	} flags;
252	struct node_icmp	*icmpspec;
253	u_int32_t		 tos;
254	u_int32_t		 prob;
255	struct {
256		int			 action;
257		struct node_state_opt	*options;
258	} keep;
259	int			 fragment;
260	int			 allowopts;
261	char			*label;
262	struct node_qassign	 queues;
263	char			*tag;
264	char			*match_tag;
265	u_int8_t		 match_tag_not;
266	u_int			 rtableid;
267	struct {
268		struct node_host	*addr;
269		u_int16_t		port;
270	}			 divert, divert_packet;
271	struct redirspec	 nat;
272	struct redirspec	 rdr;
273	struct redirspec	 rroute;
274
275	/* scrub opts */
276	int			 nodf;
277	int			 minttl;
278	int			 settos;
279	int			 randomid;
280	int			 max_mss;
281
282	/* route opts */
283	struct {
284		struct node_host	*host;
285		u_int8_t		 rt;
286		u_int8_t		 pool_opts;
287		sa_family_t		 af;
288		struct pf_poolhashkey	*key;
289	}			 route;
290} filter_opts;
291
292struct antispoof_opts {
293	char			*label;
294	u_int			 rtableid;
295} antispoof_opts;
296
297struct scrub_opts {
298	int			marker;
299	int			nodf;
300	int			minttl;
301	int			maxmss;
302	int			settos;
303	int			randomid;
304	int			reassemble_tcp;
305} scrub_opts;
306
307struct queue_opts {
308	int			marker;
309#define QOM_BWSPEC	0x01
310#define QOM_SCHEDULER	0x02
311#define QOM_PRIORITY	0x04
312#define QOM_TBRSIZE	0x08
313#define QOM_QLIMIT	0x10
314	struct node_queue_bw	queue_bwspec;
315	struct node_queue_opt	scheduler;
316	int			priority;
317	int			tbrsize;
318	int			qlimit;
319} queue_opts;
320
321struct table_opts {
322	int			flags;
323	int			init_addr;
324	struct node_tinithead	init_nodes;
325} table_opts;
326
327struct node_hfsc_opts	 hfsc_opts;
328struct node_state_opt	*keep_state_defaults = NULL;
329
330int		 disallow_table(struct node_host *, const char *);
331int		 disallow_urpf_failed(struct node_host *, const char *);
332int		 disallow_alias(struct node_host *, const char *);
333int		 rule_consistent(struct pf_rule *, int);
334int		 process_tabledef(char *, struct table_opts *);
335void		 expand_label_str(char *, size_t, const char *, const char *);
336void		 expand_label_if(const char *, char *, size_t, const char *);
337void		 expand_label_addr(const char *, char *, size_t, u_int8_t,
338		    struct node_host *);
339void		 expand_label_port(const char *, char *, size_t,
340		    struct node_port *);
341void		 expand_label_proto(const char *, char *, size_t, u_int8_t);
342void		 expand_label_nr(const char *, char *, size_t);
343void		 expand_label(char *, size_t, const char *, u_int8_t,
344		    struct node_host *, struct node_port *, struct node_host *,
345		    struct node_port *, u_int8_t);
346int		 collapse_redirspec(struct pf_pool *, struct pf_rule *,
347		    struct redirspec *rs, u_int8_t);
348int		 apply_redirspec(struct pf_pool *, struct pf_rule *,
349		    struct redirspec *, int, struct node_port *);
350void		 expand_rule(struct pf_rule *, int, struct node_if *,
351		    struct redirspec *, struct redirspec *, struct redirspec *,
352		    struct node_proto *,
353		    struct node_os *, struct node_host *, struct node_port *,
354		    struct node_host *, struct node_port *, struct node_uid *,
355		    struct node_gid *, struct node_if *, struct node_icmp *,
356		    const char *);
357int		 expand_altq(struct pf_altq *, struct node_if *,
358		    struct node_queue *, struct node_queue_bw bwspec,
359		    struct node_queue_opt *);
360int		 expand_queue(struct pf_altq *, struct node_if *,
361		    struct node_queue *, struct node_queue_bw,
362		    struct node_queue_opt *);
363int		 expand_skip_interface(struct node_if *);
364
365int	 check_rulestate(int);
366int	 getservice(char *);
367int	 rule_label(struct pf_rule *, char *);
368
369void	 mv_rules(struct pf_ruleset *, struct pf_ruleset *);
370void	 decide_address_family(struct node_host *, sa_family_t *);
371int	 invalid_redirect(struct node_host *, sa_family_t);
372u_int16_t parseicmpspec(char *, sa_family_t);
373int	 kw_casecmp(const void *, const void *);
374int	 map_tos(char *string, int *);
375
376TAILQ_HEAD(loadanchorshead, loadanchors)
377    loadanchorshead = TAILQ_HEAD_INITIALIZER(loadanchorshead);
378
379struct loadanchors {
380	TAILQ_ENTRY(loadanchors)	 entries;
381	char				*anchorname;
382	char				*filename;
383};
384
385typedef struct {
386	union {
387		int64_t			 number;
388		double			 probability;
389		int			 i;
390		char			*string;
391		u_int			 rtableid;
392		struct {
393			u_int8_t	 b1;
394			u_int8_t	 b2;
395			u_int16_t	 w;
396			u_int16_t	 w2;
397		}			 b;
398		struct range		 range;
399		struct node_if		*interface;
400		struct node_proto	*proto;
401		struct node_icmp	*icmp;
402		struct node_host	*host;
403		struct node_os		*os;
404		struct node_port	*port;
405		struct node_uid		*uid;
406		struct node_gid		*gid;
407		struct node_state_opt	*state_opt;
408		struct peer		 peer;
409		struct {
410			struct peer	 src, dst;
411			struct node_os	*src_os;
412		}			 fromto;
413		struct redirection	*redirection;
414		struct {
415			int			 action;
416			struct node_state_opt	*options;
417		}			 keep_state;
418		struct {
419			u_int8_t	 log;
420			u_int8_t	 logif;
421			u_int8_t	 quick;
422		}			 logquick;
423		struct {
424			int		 neg;
425			char		*name;
426		}			 tagged;
427		struct pf_poolhashkey	*hashkey;
428		struct node_queue	*queue;
429		struct node_queue_opt	 queue_options;
430		struct node_queue_bw	 queue_bwspec;
431		struct node_qassign	 qassign;
432		struct filter_opts	 filter_opts;
433		struct antispoof_opts	 antispoof_opts;
434		struct queue_opts	 queue_opts;
435		struct scrub_opts	 scrub_opts;
436		struct table_opts	 table_opts;
437		struct pool_opts	 pool_opts;
438		struct node_hfsc_opts	 hfsc_opts;
439	} v;
440	int lineno;
441} YYSTYPE;
442
443#define PPORT_RANGE	1
444#define PPORT_STAR	2
445int	parseport(char *, struct range *r, int);
446
447#define DYNIF_MULTIADDR(addr) ((addr).type == PF_ADDR_DYNIFTL && \
448	(!((addr).iflags & PFI_AFLAG_NOALIAS) ||		 \
449	!isdigit((addr).v.ifname[strlen((addr).v.ifname)-1])))
450
451%}
452
453%token	PASS BLOCK MATCH SCRUB RETURN IN OS OUT LOG QUICK ON FROM TO FLAGS
454%token	RETURNRST RETURNICMP RETURNICMP6 PROTO INET INET6 ALL ANY ICMPTYPE
455%token	ICMP6TYPE CODE KEEP MODULATE STATE PORT RDR NAT BINATTO NODF
456%token	MINTTL ERROR ALLOWOPTS FASTROUTE FILENAME ROUTETO DUPTO REPLYTO NO LABEL
457%token	NOROUTE URPFFAILED FRAGMENT USER GROUP MAXMSS MAXIMUM TTL TOS DROP TABLE
458%token	REASSEMBLE FRAGDROP FRAGCROP ANCHOR NATANCHOR RDRANCHOR BINATANCHOR
459%token	SET OPTIMIZATION TIMEOUT LIMIT LOGINTERFACE BLOCKPOLICY RANDOMID
460%token	REQUIREORDER SYNPROXY FINGERPRINTS NOSYNC DEBUG SKIP HOSTID
461%token	ANTISPOOF FOR INCLUDE
462%token	BITMASK RANDOM SOURCEHASH ROUNDROBIN STATICPORT PROBABILITY
463%token	ALTQ CBQ PRIQ HFSC BANDWIDTH TBRSIZE LINKSHARE REALTIME UPPERLIMIT
464%token	QUEUE PRIORITY QLIMIT RTABLE
465%token	LOAD RULESET_OPTIMIZATION
466%token	STICKYADDRESS MAXSRCSTATES MAXSRCNODES SOURCETRACK GLOBAL RULE
467%token	MAXSRCCONN MAXSRCCONNRATE OVERLOAD FLUSH SLOPPY PFLOW
468%token	TAGGED TAG IFBOUND FLOATING STATEPOLICY STATEDEFAULTS ROUTE SETTOS
469%token	DIVERTTO DIVERTREPLY DIVERTPACKET NATTO RDRTO RECEIVEDON NE LE GE
470%token	<v.string>		STRING
471%token	<v.number>		NUMBER
472%token	<v.i>			PORTBINARY
473%type	<v.interface>		interface if_list if_item_not if_item
474%type	<v.number>		number icmptype icmp6type uid gid
475%type	<v.number>		tos not yesno optnodf
476%type	<v.probability>		probability
477%type	<v.i>			dir af optimizer
478%type	<v.i>			sourcetrack flush unaryop statelock
479%type	<v.b>			action
480%type	<v.b>			flags flag blockspec
481%type	<v.range>		portplain portstar portrange
482%type	<v.hashkey>		hashkey
483%type	<v.proto>		proto proto_list proto_item
484%type	<v.number>		protoval
485%type	<v.icmp>		icmpspec
486%type	<v.icmp>		icmp_list icmp_item
487%type	<v.icmp>		icmp6_list icmp6_item
488%type	<v.number>		reticmpspec reticmp6spec
489%type	<v.fromto>		fromto
490%type	<v.peer>		ipportspec from to
491%type	<v.host>		ipspec xhost host dynaddr host_list
492%type	<v.host>		redir_host_list redirspec
493%type	<v.host>		route_host route_host_list routespec
494%type	<v.os>			os xos os_list
495%type	<v.port>		portspec port_list port_item
496%type	<v.uid>			uids uid_list uid_item
497%type	<v.gid>			gids gid_list gid_item
498%type	<v.redirection>		redirpool
499%type	<v.string>		label stringall anchorname
500%type	<v.string>		string varstring numberstring
501%type	<v.keep_state>		keep
502%type	<v.state_opt>		state_opt_spec state_opt_list state_opt_item
503%type	<v.logquick>		logquick quick log logopts logopt
504%type	<v.interface>		antispoof_ifspc antispoof_iflst antispoof_if
505%type	<v.qassign>		qname
506%type	<v.queue>		qassign qassign_list qassign_item
507%type	<v.queue_options>	scheduler
508%type	<v.number>		cbqflags_list cbqflags_item
509%type	<v.number>		priqflags_list priqflags_item
510%type	<v.hfsc_opts>		hfscopts_list hfscopts_item hfsc_opts
511%type	<v.queue_bwspec>	bandwidth
512%type	<v.filter_opts>		filter_opts filter_opt filter_opts_l
513%type	<v.antispoof_opts>	antispoof_opts antispoof_opt antispoof_opts_l
514%type	<v.queue_opts>		queue_opts queue_opt queue_opts_l
515%type	<v.scrub_opts>		scrub_opts scrub_opt scrub_opts_l
516%type	<v.table_opts>		table_opts table_opt table_opts_l
517%type	<v.pool_opts>		pool_opts pool_opt pool_opts_l
518%%
519
520ruleset		: /* empty */
521		| ruleset include '\n'
522		| ruleset '\n'
523		| ruleset option '\n'
524		| ruleset pfrule '\n'
525		| ruleset anchorrule '\n'
526		| ruleset loadrule '\n'
527		| ruleset altqif '\n'
528		| ruleset queuespec '\n'
529		| ruleset varset '\n'
530		| ruleset antispoof '\n'
531		| ruleset tabledef '\n'
532		| '{' fakeanchor '}' '\n';
533		| ruleset error '\n'		{ file->errors++; }
534		;
535
536include		: INCLUDE STRING		{
537			struct file	*nfile;
538
539			if ((nfile = pushfile($2, 0)) == NULL) {
540				yyerror("failed to include file %s", $2);
541				free($2);
542				YYERROR;
543			}
544			free($2);
545
546			file = nfile;
547			lungetc('\n');
548		}
549		;
550
551/*
552 * apply to previously specified rule: must be careful to note
553 * what that is: pf or nat or binat or rdr
554 */
555fakeanchor	: fakeanchor '\n'
556		| fakeanchor anchorrule '\n'
557		| fakeanchor pfrule '\n'
558		| fakeanchor error '\n'
559		;
560
561optimizer	: string	{
562			if (!strcmp($1, "none"))
563				$$ = 0;
564			else if (!strcmp($1, "basic"))
565				$$ = PF_OPTIMIZE_BASIC;
566			else if (!strcmp($1, "profile"))
567				$$ = PF_OPTIMIZE_BASIC | PF_OPTIMIZE_PROFILE;
568			else {
569				yyerror("unknown ruleset-optimization %s", $1);
570				YYERROR;
571			}
572		}
573		;
574
575optnodf		: /* empty */	{ $$ = 0; }
576		| NODF		{ $$ = 1; }
577		;
578
579option		: SET REASSEMBLE yesno optnodf		{
580			if (check_rulestate(PFCTL_STATE_OPTION))
581				YYERROR;
582			pfctl_set_reassembly(pf, $3, $4);
583		}
584		| SET OPTIMIZATION STRING		{
585			if (check_rulestate(PFCTL_STATE_OPTION)) {
586				free($3);
587				YYERROR;
588			}
589			if (pfctl_set_optimization(pf, $3) != 0) {
590				yyerror("unknown optimization %s", $3);
591				free($3);
592				YYERROR;
593			}
594			free($3);
595		}
596		| SET RULESET_OPTIMIZATION optimizer {
597			if (!(pf->opts & PF_OPT_OPTIMIZE)) {
598				pf->opts |= PF_OPT_OPTIMIZE;
599				pf->optimize = $3;
600			}
601		}
602		| SET TIMEOUT timeout_spec
603		| SET TIMEOUT '{' optnl timeout_list '}'
604		| SET LIMIT limit_spec
605		| SET LIMIT '{' optnl limit_list '}'
606		| SET LOGINTERFACE stringall		{
607			if (check_rulestate(PFCTL_STATE_OPTION)) {
608				free($3);
609				YYERROR;
610			}
611			if (pfctl_set_logif(pf, $3) != 0) {
612				yyerror("error setting loginterface %s", $3);
613				free($3);
614				YYERROR;
615			}
616			free($3);
617		}
618		| SET HOSTID number {
619			if ($3 == 0 || $3 > UINT_MAX) {
620				yyerror("hostid must be non-zero");
621				YYERROR;
622			}
623			if (pfctl_set_hostid(pf, $3) != 0) {
624				yyerror("error setting hostid %08x", $3);
625				YYERROR;
626			}
627		}
628		| SET BLOCKPOLICY DROP	{
629			if (pf->opts & PF_OPT_VERBOSE)
630				printf("set block-policy drop\n");
631			if (check_rulestate(PFCTL_STATE_OPTION))
632				YYERROR;
633			blockpolicy = PFRULE_DROP;
634		}
635		| SET BLOCKPOLICY RETURN {
636			if (pf->opts & PF_OPT_VERBOSE)
637				printf("set block-policy return\n");
638			if (check_rulestate(PFCTL_STATE_OPTION))
639				YYERROR;
640			blockpolicy = PFRULE_RETURN;
641		}
642		| SET REQUIREORDER yesno {
643			if (pf->opts & PF_OPT_VERBOSE)
644				printf("set require-order %s\n",
645				    $3 == 1 ? "yes" : "no");
646			require_order = $3;
647		}
648		| SET FINGERPRINTS STRING {
649			if (pf->opts & PF_OPT_VERBOSE)
650				printf("set fingerprints \"%s\"\n", $3);
651			if (check_rulestate(PFCTL_STATE_OPTION)) {
652				free($3);
653				YYERROR;
654			}
655			if (!pf->anchor->name[0]) {
656				if (pfctl_file_fingerprints(pf->dev,
657				    pf->opts, $3)) {
658					yyerror("error loading "
659					    "fingerprints %s", $3);
660					free($3);
661					YYERROR;
662				}
663			}
664			free($3);
665		}
666		| SET STATEPOLICY statelock {
667			if (pf->opts & PF_OPT_VERBOSE)
668				switch ($3) {
669				case 0:
670					printf("set state-policy floating\n");
671					break;
672				case PFRULE_IFBOUND:
673					printf("set state-policy if-bound\n");
674					break;
675				}
676			default_statelock = $3;
677		}
678		| SET DEBUG STRING {
679			if (check_rulestate(PFCTL_STATE_OPTION)) {
680				free($3);
681				YYERROR;
682			}
683			if (pfctl_set_debug(pf, $3) != 0) {
684				yyerror("error setting debuglevel %s", $3);
685				free($3);
686				YYERROR;
687			}
688			free($3);
689		}
690		| SET SKIP interface {
691			if (expand_skip_interface($3) != 0) {
692				yyerror("error setting skip interface(s)");
693				YYERROR;
694			}
695		}
696		| SET STATEDEFAULTS state_opt_list {
697			if (keep_state_defaults != NULL) {
698				yyerror("cannot redefine state-defaults");
699				YYERROR;
700			}
701			keep_state_defaults = $3;
702		}
703		;
704
705stringall	: STRING	{ $$ = $1; }
706		| ALL		{
707			if (($$ = strdup("all")) == NULL) {
708				err(1, "stringall: strdup");
709			}
710		}
711		;
712
713string		: STRING string				{
714			if (asprintf(&$$, "%s %s", $1, $2) == -1)
715				err(1, "string: asprintf");
716			free($1);
717			free($2);
718		}
719		| STRING
720		;
721
722varstring	: numberstring varstring 		{
723			if (asprintf(&$$, "%s %s", $1, $2) == -1)
724				err(1, "string: asprintf");
725			free($1);
726			free($2);
727		}
728		| numberstring
729		;
730
731numberstring	: NUMBER				{
732			char	*s;
733			if (asprintf(&s, "%lld", $1) == -1) {
734				yyerror("string: asprintf");
735				YYERROR;
736			}
737			$$ = s;
738		}
739		| STRING
740		;
741
742varset		: STRING '=' varstring	{
743			if (pf->opts & PF_OPT_VERBOSE)
744				printf("%s = \"%s\"\n", $1, $3);
745			if (symset($1, $3, 0) == -1)
746				err(1, "cannot store variable %s", $1);
747			free($1);
748			free($3);
749		}
750		;
751
752anchorname	: STRING			{ $$ = $1; }
753		| /* empty */			{ $$ = NULL; }
754		;
755
756pfa_anchorlist	: /* empty */
757		| pfa_anchorlist '\n'
758		| pfa_anchorlist pfrule '\n'
759		| pfa_anchorlist anchorrule '\n'
760		;
761
762pfa_anchor	: '{'
763		{
764			char ta[PF_ANCHOR_NAME_SIZE];
765			struct pf_ruleset *rs;
766
767			/* steping into a brace anchor */
768			pf->asd++;
769			pf->bn++;
770			pf->brace = 1;
771
772			/* create a holding ruleset in the root */
773			snprintf(ta, PF_ANCHOR_NAME_SIZE, "_%d", pf->bn);
774			rs = pf_find_or_create_ruleset(ta);
775			if (rs == NULL)
776				err(1, "pfa_anchor: pf_find_or_create_ruleset");
777			pf->astack[pf->asd] = rs->anchor;
778			pf->anchor = rs->anchor;
779		} '\n' pfa_anchorlist '}'
780		{
781			pf->alast = pf->anchor;
782			pf->asd--;
783			pf->anchor = pf->astack[pf->asd];
784		}
785		| /* empty */
786		;
787
788anchorrule	: ANCHOR anchorname dir quick interface af proto fromto
789		    filter_opts pfa_anchor
790		{
791			struct pf_rule	r;
792			struct node_proto	*proto;
793
794			if (check_rulestate(PFCTL_STATE_FILTER)) {
795				if ($2)
796					free($2);
797				YYERROR;
798			}
799
800			if ($2 && ($2[0] == '_' || strstr($2, "/_") != NULL)) {
801				free($2);
802				yyerror("anchor names beginning with '_' "
803				    "are reserved for internal use");
804				YYERROR;
805			}
806
807			memset(&r, 0, sizeof(r));
808			if (pf->astack[pf->asd + 1]) {
809				/* move inline rules into relative location */
810				pf_anchor_setup(&r,
811				    &pf->astack[pf->asd]->ruleset,
812				    $2 ? $2 : pf->alast->name);
813
814				if (r.anchor == NULL)
815					err(1, "anchorrule: unable to "
816					    "create ruleset");
817
818				if (pf->alast != r.anchor) {
819					if (r.anchor->match) {
820						yyerror("inline anchor '%s' "
821						    "already exists",
822						    r.anchor->name);
823						YYERROR;
824					}
825					mv_rules(&pf->alast->ruleset,
826					    &r.anchor->ruleset);
827				}
828				pf_remove_if_empty_ruleset(&pf->alast->ruleset);
829				pf->alast = r.anchor;
830			} else {
831				if (!$2) {
832					yyerror("anchors without explicit "
833					    "rules must specify a name");
834					YYERROR;
835				}
836			}
837			r.direction = $3;
838			r.quick = $4.quick;
839			r.af = $6;
840			r.prob = $9.prob;
841			r.rtableid = $9.rtableid;
842
843			if ($9.tag)
844				if (strlcpy(r.tagname, $9.tag,
845				    PF_TAG_NAME_SIZE) >= PF_TAG_NAME_SIZE) {
846					yyerror("tag too long, max %u chars",
847					    PF_TAG_NAME_SIZE - 1);
848					YYERROR;
849				}
850			if ($9.match_tag)
851				if (strlcpy(r.match_tagname, $9.match_tag,
852				    PF_TAG_NAME_SIZE) >= PF_TAG_NAME_SIZE) {
853					yyerror("tag too long, max %u chars",
854					    PF_TAG_NAME_SIZE - 1);
855					YYERROR;
856				}
857			r.match_tag_not = $9.match_tag_not;
858			if (rule_label(&r, $9.label))
859				YYERROR;
860			free($9.label);
861			r.flags = $9.flags.b1;
862			r.flagset = $9.flags.b2;
863			if (($9.flags.b1 & $9.flags.b2) != $9.flags.b1) {
864				yyerror("flags always false");
865				YYERROR;
866			}
867			if ($9.flags.b1 || $9.flags.b2 || $8.src_os) {
868				for (proto = $7; proto != NULL &&
869				    proto->proto != IPPROTO_TCP;
870				    proto = proto->next)
871					;	/* nothing */
872				if (proto == NULL && $7 != NULL) {
873					if ($9.flags.b1 || $9.flags.b2)
874						yyerror(
875						    "flags only apply to tcp");
876					if ($8.src_os)
877						yyerror(
878						    "OS fingerprinting only "
879						    "applies to tcp");
880					YYERROR;
881				}
882			}
883
884			r.tos = $9.tos;
885
886			if ($9.keep.action) {
887				yyerror("cannot specify state handling "
888				    "on anchors");
889				YYERROR;
890			}
891
892			if ($9.route.rt) {
893				yyerror("cannot specify route handling "
894				    "on anchors");
895				YYERROR;
896			}
897
898			if ($9.match_tag)
899				if (strlcpy(r.match_tagname, $9.match_tag,
900				    PF_TAG_NAME_SIZE) >= PF_TAG_NAME_SIZE) {
901					yyerror("tag too long, max %u chars",
902					    PF_TAG_NAME_SIZE - 1);
903					YYERROR;
904				}
905			r.match_tag_not = $9.match_tag_not;
906
907			decide_address_family($8.src.host, &r.af);
908			decide_address_family($8.dst.host, &r.af);
909
910			expand_rule(&r, 0, $5, NULL, NULL, NULL, $7, $8.src_os,
911			    $8.src.host, $8.src.port, $8.dst.host, $8.dst.port,
912			    $9.uid, $9.gid, $9.rcv, $9.icmpspec,
913			    pf->astack[pf->asd + 1] ? pf->alast->name : $2);
914			free($2);
915			pf->astack[pf->asd + 1] = NULL;
916		}
917		;
918
919loadrule	: LOAD ANCHOR string FROM string	{
920			struct loadanchors	*loadanchor;
921
922			if (strlen(pf->anchor->name) + 1 +
923			    strlen($3) >= MAXPATHLEN) {
924				yyerror("anchorname %s too long, max %u\n",
925				    $3, MAXPATHLEN - 1);
926				free($3);
927				YYERROR;
928			}
929			loadanchor = calloc(1, sizeof(struct loadanchors));
930			if (loadanchor == NULL)
931				err(1, "loadrule: calloc");
932			if ((loadanchor->anchorname = malloc(MAXPATHLEN)) ==
933			    NULL)
934				err(1, "loadrule: malloc");
935			if (pf->anchor->name[0])
936				snprintf(loadanchor->anchorname, MAXPATHLEN,
937				    "%s/%s", pf->anchor->name, $3);
938			else
939				strlcpy(loadanchor->anchorname, $3, MAXPATHLEN);
940			if ((loadanchor->filename = strdup($5)) == NULL)
941				err(1, "loadrule: strdup");
942
943			TAILQ_INSERT_TAIL(&loadanchorshead, loadanchor,
944			    entries);
945
946			free($3);
947			free($5);
948		};
949
950scrub_opts	:	{
951				bzero(&scrub_opts, sizeof scrub_opts);
952			}
953		    scrub_opts_l
954			{ $$ = scrub_opts; }
955		;
956
957scrub_opts_l	: scrub_opts_l comma scrub_opt
958		| scrub_opt
959		;
960
961scrub_opt	: NODF	{
962			if (scrub_opts.nodf) {
963				yyerror("no-df cannot be respecified");
964				YYERROR;
965			}
966			scrub_opts.nodf = 1;
967		}
968		| MINTTL NUMBER {
969			if (scrub_opts.marker & FOM_MINTTL) {
970				yyerror("min-ttl cannot be respecified");
971				YYERROR;
972			}
973			if ($2 < 0 || $2 > 255) {
974				yyerror("illegal min-ttl value %d", $2);
975				YYERROR;
976			}
977			scrub_opts.marker |= FOM_MINTTL;
978			scrub_opts.minttl = $2;
979		}
980		| MAXMSS NUMBER {
981			if (scrub_opts.marker & FOM_MAXMSS) {
982				yyerror("max-mss cannot be respecified");
983				YYERROR;
984			}
985			if ($2 < 0 || $2 > 65535) {
986				yyerror("illegal max-mss value %d", $2);
987				YYERROR;
988			}
989			scrub_opts.marker |= FOM_MAXMSS;
990			scrub_opts.maxmss = $2;
991		}
992		| SETTOS tos {
993			if (scrub_opts.marker & FOM_SETTOS) {
994				yyerror("set-tos cannot be respecified");
995				YYERROR;
996			}
997			scrub_opts.marker |= FOM_SETTOS;
998			scrub_opts.settos = $2;
999		}
1000		| REASSEMBLE STRING {
1001			if (strcasecmp($2, "tcp") != 0) {
1002				yyerror("scrub reassemble supports only tcp, "
1003				    "not '%s'", $2);
1004				free($2);
1005				YYERROR;
1006			}
1007			free($2);
1008			if (scrub_opts.reassemble_tcp) {
1009				yyerror("reassemble tcp cannot be respecified");
1010				YYERROR;
1011			}
1012			scrub_opts.reassemble_tcp = 1;
1013		}
1014		| RANDOMID {
1015			if (scrub_opts.randomid) {
1016				yyerror("random-id cannot be respecified");
1017				YYERROR;
1018			}
1019			scrub_opts.randomid = 1;
1020		}
1021		;
1022
1023antispoof	: ANTISPOOF logquick antispoof_ifspc af antispoof_opts {
1024			struct pf_rule		 r;
1025			struct node_host	*h = NULL, *hh;
1026			struct node_if		*i, *j;
1027
1028			if (check_rulestate(PFCTL_STATE_FILTER))
1029				YYERROR;
1030
1031			for (i = $3; i; i = i->next) {
1032				bzero(&r, sizeof(r));
1033
1034				r.action = PF_DROP;
1035				r.direction = PF_IN;
1036				r.log = $2.log;
1037				r.logif = $2.logif;
1038				r.quick = $2.quick;
1039				r.af = $4;
1040				if (rule_label(&r, $5.label))
1041					YYERROR;
1042				r.rtableid = $5.rtableid;
1043				j = calloc(1, sizeof(struct node_if));
1044				if (j == NULL)
1045					err(1, "antispoof: calloc");
1046				if (strlcpy(j->ifname, i->ifname,
1047				    sizeof(j->ifname)) >= sizeof(j->ifname)) {
1048					free(j);
1049					yyerror("interface name too long");
1050					YYERROR;
1051				}
1052				j->not = 1;
1053				if (i->dynamic) {
1054					h = calloc(1, sizeof(*h));
1055					if (h == NULL)
1056						err(1, "address: calloc");
1057					h->addr.type = PF_ADDR_DYNIFTL;
1058					set_ipmask(h, 128);
1059					if (strlcpy(h->addr.v.ifname, i->ifname,
1060					    sizeof(h->addr.v.ifname)) >=
1061					    sizeof(h->addr.v.ifname)) {
1062						free(h);
1063						yyerror(
1064						    "interface name too long");
1065						YYERROR;
1066					}
1067					hh = malloc(sizeof(*hh));
1068					if (hh == NULL)
1069						 err(1, "address: malloc");
1070					bcopy(h, hh, sizeof(*hh));
1071					h->addr.iflags = PFI_AFLAG_NETWORK;
1072				} else {
1073					h = ifa_lookup(j->ifname,
1074					    PFI_AFLAG_NETWORK);
1075					hh = NULL;
1076				}
1077
1078				if (h != NULL)
1079					expand_rule(&r, 0, j, NULL, NULL, NULL,
1080					    NULL, NULL, h, NULL, NULL, NULL,
1081					    NULL, NULL, NULL, NULL, "");
1082
1083				if ((i->ifa_flags & IFF_LOOPBACK) == 0) {
1084					bzero(&r, sizeof(r));
1085
1086					r.action = PF_DROP;
1087					r.direction = PF_IN;
1088					r.log = $2.log;
1089					r.logif = $2.logif;
1090					r.quick = $2.quick;
1091					r.af = $4;
1092					if (rule_label(&r, $5.label))
1093						YYERROR;
1094					r.rtableid = $5.rtableid;
1095					if (hh != NULL)
1096						h = hh;
1097					else
1098						h = ifa_lookup(i->ifname, 0);
1099					if (h != NULL)
1100						expand_rule(&r, 0, NULL, NULL,
1101						    NULL, NULL, NULL, NULL, h,
1102						    NULL, NULL, NULL, NULL,
1103						    NULL, NULL, NULL, "");
1104				} else
1105					free(hh);
1106			}
1107			free($5.label);
1108		}
1109		;
1110
1111antispoof_ifspc	: FOR antispoof_if			{ $$ = $2; }
1112		| FOR '{' optnl antispoof_iflst '}'	{ $$ = $4; }
1113		;
1114
1115antispoof_iflst	: antispoof_if optnl			{ $$ = $1; }
1116		| antispoof_iflst comma antispoof_if optnl {
1117			$1->tail->next = $3;
1118			$1->tail = $3;
1119			$$ = $1;
1120		}
1121		;
1122
1123antispoof_if	: if_item				{ $$ = $1; }
1124		| '(' if_item ')'			{
1125			$2->dynamic = 1;
1126			$$ = $2;
1127		}
1128		;
1129
1130antispoof_opts	:	{
1131				bzero(&antispoof_opts, sizeof antispoof_opts);
1132				antispoof_opts.rtableid = -1;
1133			}
1134		    antispoof_opts_l
1135			{ $$ = antispoof_opts; }
1136		| /* empty */	{
1137			bzero(&antispoof_opts, sizeof antispoof_opts);
1138			antispoof_opts.rtableid = -1;
1139			$$ = antispoof_opts;
1140		}
1141		;
1142
1143antispoof_opts_l	: antispoof_opts_l antispoof_opt
1144			| antispoof_opt
1145			;
1146
1147antispoof_opt	: LABEL label	{
1148			if (antispoof_opts.label) {
1149				yyerror("label cannot be redefined");
1150				YYERROR;
1151			}
1152			antispoof_opts.label = $2;
1153		}
1154		| RTABLE NUMBER				{
1155			if ($2 < 0 || $2 > RT_TABLEID_MAX) {
1156				yyerror("invalid rtable id");
1157				YYERROR;
1158			}
1159			antispoof_opts.rtableid = $2;
1160		}
1161		;
1162
1163not		: '!'		{ $$ = 1; }
1164		| /* empty */	{ $$ = 0; }
1165		;
1166
1167tabledef	: TABLE '<' STRING '>' table_opts {
1168			struct node_host	 *h, *nh;
1169			struct node_tinit	 *ti, *nti;
1170
1171			if (strlen($3) >= PF_TABLE_NAME_SIZE) {
1172				yyerror("table name too long, max %d chars",
1173				    PF_TABLE_NAME_SIZE - 1);
1174				free($3);
1175				YYERROR;
1176			}
1177			if (pf->loadopt & PFCTL_FLAG_TABLE)
1178				if (process_tabledef($3, &$5)) {
1179					free($3);
1180					YYERROR;
1181				}
1182			free($3);
1183			for (ti = SIMPLEQ_FIRST(&$5.init_nodes);
1184			    ti != SIMPLEQ_END(&$5.init_nodes); ti = nti) {
1185				if (ti->file)
1186					free(ti->file);
1187				for (h = ti->host; h != NULL; h = nh) {
1188					nh = h->next;
1189					free(h);
1190				}
1191				nti = SIMPLEQ_NEXT(ti, entries);
1192				free(ti);
1193			}
1194		}
1195		;
1196
1197table_opts	:	{
1198			bzero(&table_opts, sizeof table_opts);
1199			SIMPLEQ_INIT(&table_opts.init_nodes);
1200		}
1201		    table_opts_l
1202			{ $$ = table_opts; }
1203		| /* empty */
1204			{
1205			bzero(&table_opts, sizeof table_opts);
1206			SIMPLEQ_INIT(&table_opts.init_nodes);
1207			$$ = table_opts;
1208		}
1209		;
1210
1211table_opts_l	: table_opts_l table_opt
1212		| table_opt
1213		;
1214
1215table_opt	: STRING		{
1216			if (!strcmp($1, "const"))
1217				table_opts.flags |= PFR_TFLAG_CONST;
1218			else if (!strcmp($1, "persist"))
1219				table_opts.flags |= PFR_TFLAG_PERSIST;
1220			else if (!strcmp($1, "counters"))
1221				table_opts.flags |= PFR_TFLAG_COUNTERS;
1222			else {
1223				yyerror("invalid table option '%s'", $1);
1224				free($1);
1225				YYERROR;
1226			}
1227			free($1);
1228		}
1229		| '{' optnl '}'		{ table_opts.init_addr = 1; }
1230		| '{' optnl host_list '}'	{
1231			struct node_host	*n;
1232			struct node_tinit	*ti;
1233
1234			for (n = $3; n != NULL; n = n->next) {
1235				switch (n->addr.type) {
1236				case PF_ADDR_ADDRMASK:
1237					continue; /* ok */
1238				case PF_ADDR_RANGE:
1239					yyerror("address ranges are not "
1240					    "permitted inside tables");
1241					break;
1242				case PF_ADDR_DYNIFTL:
1243					yyerror("dynamic addresses are not "
1244					    "permitted inside tables");
1245					break;
1246				case PF_ADDR_TABLE:
1247					yyerror("tables cannot contain tables");
1248					break;
1249				case PF_ADDR_NOROUTE:
1250					yyerror("\"no-route\" is not permitted "
1251					    "inside tables");
1252					break;
1253				case PF_ADDR_URPFFAILED:
1254					yyerror("\"urpf-failed\" is not "
1255					    "permitted inside tables");
1256					break;
1257				default:
1258					yyerror("unknown address type %d",
1259					    n->addr.type);
1260				}
1261				YYERROR;
1262			}
1263			if (!(ti = calloc(1, sizeof(*ti))))
1264				err(1, "table_opt: calloc");
1265			ti->host = $3;
1266			SIMPLEQ_INSERT_TAIL(&table_opts.init_nodes, ti,
1267			    entries);
1268			table_opts.init_addr = 1;
1269		}
1270		| FILENAME STRING	{
1271			struct node_tinit	*ti;
1272
1273			if (!(ti = calloc(1, sizeof(*ti))))
1274				err(1, "table_opt: calloc");
1275			ti->file = $2;
1276			SIMPLEQ_INSERT_TAIL(&table_opts.init_nodes, ti,
1277			    entries);
1278			table_opts.init_addr = 1;
1279		}
1280		;
1281
1282altqif		: ALTQ interface queue_opts QUEUE qassign {
1283			struct pf_altq	a;
1284
1285			if (check_rulestate(PFCTL_STATE_QUEUE))
1286				YYERROR;
1287
1288			memset(&a, 0, sizeof(a));
1289			if ($3.scheduler.qtype == ALTQT_NONE) {
1290				yyerror("no scheduler specified!");
1291				YYERROR;
1292			}
1293			a.scheduler = $3.scheduler.qtype;
1294			a.qlimit = $3.qlimit;
1295			a.tbrsize = $3.tbrsize;
1296			if ($5 == NULL) {
1297				yyerror("no child queues specified");
1298				YYERROR;
1299			}
1300			if (expand_altq(&a, $2, $5, $3.queue_bwspec,
1301			    &$3.scheduler))
1302				YYERROR;
1303		}
1304		;
1305
1306queuespec	: QUEUE STRING interface queue_opts qassign {
1307			struct pf_altq	a;
1308
1309			if (check_rulestate(PFCTL_STATE_QUEUE)) {
1310				free($2);
1311				YYERROR;
1312			}
1313
1314			memset(&a, 0, sizeof(a));
1315
1316			if (strlcpy(a.qname, $2, sizeof(a.qname)) >=
1317			    sizeof(a.qname)) {
1318				yyerror("queue name too long (max "
1319				    "%d chars)", PF_QNAME_SIZE-1);
1320				free($2);
1321				YYERROR;
1322			}
1323			free($2);
1324			if ($4.tbrsize) {
1325				yyerror("cannot specify tbrsize for queue");
1326				YYERROR;
1327			}
1328			if ($4.priority > 255) {
1329				yyerror("priority out of range: max 255");
1330				YYERROR;
1331			}
1332			a.priority = $4.priority;
1333			a.qlimit = $4.qlimit;
1334			a.scheduler = $4.scheduler.qtype;
1335			if (expand_queue(&a, $3, $5, $4.queue_bwspec,
1336			    &$4.scheduler)) {
1337				yyerror("errors in queue definition");
1338				YYERROR;
1339			}
1340		}
1341		;
1342
1343queue_opts	:	{
1344			bzero(&queue_opts, sizeof queue_opts);
1345			queue_opts.priority = DEFAULT_PRIORITY;
1346			queue_opts.qlimit = DEFAULT_QLIMIT;
1347			queue_opts.scheduler.qtype = ALTQT_NONE;
1348			queue_opts.queue_bwspec.bw_percent = 100;
1349		}
1350		    queue_opts_l
1351			{ $$ = queue_opts; }
1352		| /* empty */ {
1353			bzero(&queue_opts, sizeof queue_opts);
1354			queue_opts.priority = DEFAULT_PRIORITY;
1355			queue_opts.qlimit = DEFAULT_QLIMIT;
1356			queue_opts.scheduler.qtype = ALTQT_NONE;
1357			queue_opts.queue_bwspec.bw_percent = 100;
1358			$$ = queue_opts;
1359		}
1360		;
1361
1362queue_opts_l	: queue_opts_l queue_opt
1363		| queue_opt
1364		;
1365
1366queue_opt	: BANDWIDTH bandwidth	{
1367			if (queue_opts.marker & QOM_BWSPEC) {
1368				yyerror("bandwidth cannot be respecified");
1369				YYERROR;
1370			}
1371			queue_opts.marker |= QOM_BWSPEC;
1372			queue_opts.queue_bwspec = $2;
1373		}
1374		| PRIORITY NUMBER	{
1375			if (queue_opts.marker & QOM_PRIORITY) {
1376				yyerror("priority cannot be respecified");
1377				YYERROR;
1378			}
1379			if ($2 < 0 || $2 > 255) {
1380				yyerror("priority out of range: max 255");
1381				YYERROR;
1382			}
1383			queue_opts.marker |= QOM_PRIORITY;
1384			queue_opts.priority = $2;
1385		}
1386		| QLIMIT NUMBER	{
1387			if (queue_opts.marker & QOM_QLIMIT) {
1388				yyerror("qlimit cannot be respecified");
1389				YYERROR;
1390			}
1391			if ($2 < 0 || $2 > 65535) {
1392				yyerror("qlimit out of range: max 65535");
1393				YYERROR;
1394			}
1395			queue_opts.marker |= QOM_QLIMIT;
1396			queue_opts.qlimit = $2;
1397		}
1398		| scheduler	{
1399			if (queue_opts.marker & QOM_SCHEDULER) {
1400				yyerror("scheduler cannot be respecified");
1401				YYERROR;
1402			}
1403			queue_opts.marker |= QOM_SCHEDULER;
1404			queue_opts.scheduler = $1;
1405		}
1406		| TBRSIZE NUMBER	{
1407			if (queue_opts.marker & QOM_TBRSIZE) {
1408				yyerror("tbrsize cannot be respecified");
1409				YYERROR;
1410			}
1411			if ($2 < 0 || $2 > 65535) {
1412				yyerror("tbrsize too big: max 65535");
1413				YYERROR;
1414			}
1415			queue_opts.marker |= QOM_TBRSIZE;
1416			queue_opts.tbrsize = $2;
1417		}
1418		;
1419
1420bandwidth	: STRING {
1421			double	 bps;
1422			char	*cp;
1423
1424			$$.bw_percent = 0;
1425
1426			bps = strtod($1, &cp);
1427			if (cp != NULL) {
1428				if (!strcmp(cp, "b"))
1429					; /* nothing */
1430				else if (!strcmp(cp, "Kb"))
1431					bps *= 1000;
1432				else if (!strcmp(cp, "Mb"))
1433					bps *= 1000 * 1000;
1434				else if (!strcmp(cp, "Gb"))
1435					bps *= 1000 * 1000 * 1000;
1436				else if (!strcmp(cp, "%")) {
1437					if (bps < 0 || bps > 100) {
1438						yyerror("bandwidth spec "
1439						    "out of range");
1440						free($1);
1441						YYERROR;
1442					}
1443					$$.bw_percent = bps;
1444					bps = 0;
1445				} else {
1446					yyerror("unknown unit %s", cp);
1447					free($1);
1448					YYERROR;
1449				}
1450			}
1451			free($1);
1452			$$.bw_absolute = (u_int32_t)bps;
1453		}
1454		| NUMBER {
1455			if ($1 < 0 || $1 > UINT_MAX) {
1456				yyerror("bandwidth number too big");
1457				YYERROR;
1458			}
1459			$$.bw_percent = 0;
1460			$$.bw_absolute = $1;
1461		}
1462		;
1463
1464scheduler	: CBQ				{
1465			$$.qtype = ALTQT_CBQ;
1466			$$.data.cbq_opts.flags = 0;
1467		}
1468		| CBQ '(' cbqflags_list ')'	{
1469			$$.qtype = ALTQT_CBQ;
1470			$$.data.cbq_opts.flags = $3;
1471		}
1472		| PRIQ				{
1473			$$.qtype = ALTQT_PRIQ;
1474			$$.data.priq_opts.flags = 0;
1475		}
1476		| PRIQ '(' priqflags_list ')'	{
1477			$$.qtype = ALTQT_PRIQ;
1478			$$.data.priq_opts.flags = $3;
1479		}
1480		| HFSC				{
1481			$$.qtype = ALTQT_HFSC;
1482			bzero(&$$.data.hfsc_opts,
1483			    sizeof(struct node_hfsc_opts));
1484		}
1485		| HFSC '(' hfsc_opts ')'	{
1486			$$.qtype = ALTQT_HFSC;
1487			$$.data.hfsc_opts = $3;
1488		}
1489		;
1490
1491cbqflags_list	: cbqflags_item				{ $$ |= $1; }
1492		| cbqflags_list comma cbqflags_item	{ $$ |= $3; }
1493		;
1494
1495cbqflags_item	: STRING	{
1496			if (!strcmp($1, "default"))
1497				$$ = CBQCLF_DEFCLASS;
1498			else if (!strcmp($1, "borrow"))
1499				$$ = CBQCLF_BORROW;
1500			else if (!strcmp($1, "red"))
1501				$$ = CBQCLF_RED;
1502			else if (!strcmp($1, "ecn"))
1503				$$ = CBQCLF_RED|CBQCLF_ECN;
1504			else if (!strcmp($1, "rio"))
1505				$$ = CBQCLF_RIO;
1506			else {
1507				yyerror("unknown cbq flag \"%s\"", $1);
1508				free($1);
1509				YYERROR;
1510			}
1511			free($1);
1512		}
1513		;
1514
1515priqflags_list	: priqflags_item			{ $$ |= $1; }
1516		| priqflags_list comma priqflags_item	{ $$ |= $3; }
1517		;
1518
1519priqflags_item	: STRING	{
1520			if (!strcmp($1, "default"))
1521				$$ = PRCF_DEFAULTCLASS;
1522			else if (!strcmp($1, "red"))
1523				$$ = PRCF_RED;
1524			else if (!strcmp($1, "ecn"))
1525				$$ = PRCF_RED|PRCF_ECN;
1526			else if (!strcmp($1, "rio"))
1527				$$ = PRCF_RIO;
1528			else {
1529				yyerror("unknown priq flag \"%s\"", $1);
1530				free($1);
1531				YYERROR;
1532			}
1533			free($1);
1534		}
1535		;
1536
1537hfsc_opts	:	{
1538				bzero(&hfsc_opts,
1539				    sizeof(struct node_hfsc_opts));
1540			}
1541		    hfscopts_list				{
1542			$$ = hfsc_opts;
1543		}
1544		;
1545
1546hfscopts_list	: hfscopts_item
1547		| hfscopts_list comma hfscopts_item
1548		;
1549
1550hfscopts_item	: LINKSHARE bandwidth				{
1551			if (hfsc_opts.linkshare.used) {
1552				yyerror("linkshare already specified");
1553				YYERROR;
1554			}
1555			hfsc_opts.linkshare.m2 = $2;
1556			hfsc_opts.linkshare.used = 1;
1557		}
1558		| LINKSHARE '(' bandwidth comma NUMBER comma bandwidth ')'
1559		    {
1560			if ($5 < 0 || $5 > INT_MAX) {
1561				yyerror("timing in curve out of range");
1562				YYERROR;
1563			}
1564			if (hfsc_opts.linkshare.used) {
1565				yyerror("linkshare already specified");
1566				YYERROR;
1567			}
1568			hfsc_opts.linkshare.m1 = $3;
1569			hfsc_opts.linkshare.d = $5;
1570			hfsc_opts.linkshare.m2 = $7;
1571			hfsc_opts.linkshare.used = 1;
1572		}
1573		| REALTIME bandwidth				{
1574			if (hfsc_opts.realtime.used) {
1575				yyerror("realtime already specified");
1576				YYERROR;
1577			}
1578			hfsc_opts.realtime.m2 = $2;
1579			hfsc_opts.realtime.used = 1;
1580		}
1581		| REALTIME '(' bandwidth comma NUMBER comma bandwidth ')'
1582		    {
1583			if ($5 < 0 || $5 > INT_MAX) {
1584				yyerror("timing in curve out of range");
1585				YYERROR;
1586			}
1587			if (hfsc_opts.realtime.used) {
1588				yyerror("realtime already specified");
1589				YYERROR;
1590			}
1591			hfsc_opts.realtime.m1 = $3;
1592			hfsc_opts.realtime.d = $5;
1593			hfsc_opts.realtime.m2 = $7;
1594			hfsc_opts.realtime.used = 1;
1595		}
1596		| UPPERLIMIT bandwidth				{
1597			if (hfsc_opts.upperlimit.used) {
1598				yyerror("upperlimit already specified");
1599				YYERROR;
1600			}
1601			hfsc_opts.upperlimit.m2 = $2;
1602			hfsc_opts.upperlimit.used = 1;
1603		}
1604		| UPPERLIMIT '(' bandwidth comma NUMBER comma bandwidth ')'
1605		    {
1606			if ($5 < 0 || $5 > INT_MAX) {
1607				yyerror("timing in curve out of range");
1608				YYERROR;
1609			}
1610			if (hfsc_opts.upperlimit.used) {
1611				yyerror("upperlimit already specified");
1612				YYERROR;
1613			}
1614			hfsc_opts.upperlimit.m1 = $3;
1615			hfsc_opts.upperlimit.d = $5;
1616			hfsc_opts.upperlimit.m2 = $7;
1617			hfsc_opts.upperlimit.used = 1;
1618		}
1619		| STRING	{
1620			if (!strcmp($1, "default"))
1621				hfsc_opts.flags |= HFCF_DEFAULTCLASS;
1622			else if (!strcmp($1, "red"))
1623				hfsc_opts.flags |= HFCF_RED;
1624			else if (!strcmp($1, "ecn"))
1625				hfsc_opts.flags |= HFCF_RED|HFCF_ECN;
1626			else if (!strcmp($1, "rio"))
1627				hfsc_opts.flags |= HFCF_RIO;
1628			else {
1629				yyerror("unknown hfsc flag \"%s\"", $1);
1630				free($1);
1631				YYERROR;
1632			}
1633			free($1);
1634		}
1635		;
1636
1637qassign		: /* empty */		{ $$ = NULL; }
1638		| qassign_item		{ $$ = $1; }
1639		| '{' optnl qassign_list '}'	{ $$ = $3; }
1640		;
1641
1642qassign_list	: qassign_item optnl		{ $$ = $1; }
1643		| qassign_list comma qassign_item optnl	{
1644			$1->tail->next = $3;
1645			$1->tail = $3;
1646			$$ = $1;
1647		}
1648		;
1649
1650qassign_item	: STRING			{
1651			$$ = calloc(1, sizeof(struct node_queue));
1652			if ($$ == NULL)
1653				err(1, "qassign_item: calloc");
1654			if (strlcpy($$->queue, $1, sizeof($$->queue)) >=
1655			    sizeof($$->queue)) {
1656				yyerror("queue name '%s' too long (max "
1657				    "%d chars)", $1, sizeof($$->queue)-1);
1658				free($1);
1659				free($$);
1660				YYERROR;
1661			}
1662			free($1);
1663			$$->next = NULL;
1664			$$->tail = $$;
1665		}
1666		;
1667
1668pfrule		: action dir logquick interface af proto fromto
1669		    filter_opts
1670		{
1671			struct pf_rule		 r;
1672			struct node_state_opt	*o;
1673			struct node_proto	*proto;
1674			int			 srctrack = 0;
1675			int			 statelock = 0;
1676			int			 adaptive = 0;
1677			int			 defaults = 0;
1678
1679			if (check_rulestate(PFCTL_STATE_FILTER))
1680				YYERROR;
1681
1682			memset(&r, 0, sizeof(r));
1683
1684			r.action = $1.b1;
1685			switch ($1.b2) {
1686			case PFRULE_RETURNRST:
1687				r.rule_flag |= PFRULE_RETURNRST;
1688				r.return_ttl = $1.w;
1689				break;
1690			case PFRULE_RETURNICMP:
1691				r.rule_flag |= PFRULE_RETURNICMP;
1692				r.return_icmp = $1.w;
1693				r.return_icmp6 = $1.w2;
1694				break;
1695			case PFRULE_RETURN:
1696				r.rule_flag |= PFRULE_RETURN;
1697				r.return_icmp = $1.w;
1698				r.return_icmp6 = $1.w2;
1699				break;
1700			}
1701			r.direction = $2;
1702			r.log = $3.log;
1703			r.logif = $3.logif;
1704			r.quick = $3.quick;
1705			r.prob = $8.prob;
1706			r.rtableid = $8.rtableid;
1707
1708			if ($8.nodf)
1709				r.scrub_flags |= PFSTATE_NODF;
1710			if ($8.randomid)
1711				r.scrub_flags |= PFSTATE_RANDOMID;
1712			if ($8.minttl)
1713				r.min_ttl = $8.minttl;
1714			if ($8.max_mss)
1715				r.max_mss = $8.max_mss;
1716			if ($8.marker & FOM_SETTOS) {
1717				r.scrub_flags |= PFSTATE_SETTOS;
1718				r.set_tos = $8.settos;
1719			}
1720			if ($8.marker & FOM_SCRUB_TCP)
1721				r.scrub_flags |= PFSTATE_SCRUB_TCP;
1722
1723			r.af = $5;
1724			if ($8.tag)
1725				if (strlcpy(r.tagname, $8.tag,
1726				    PF_TAG_NAME_SIZE) >= PF_TAG_NAME_SIZE) {
1727					yyerror("tag too long, max %u chars",
1728					    PF_TAG_NAME_SIZE - 1);
1729					YYERROR;
1730				}
1731			if ($8.match_tag)
1732				if (strlcpy(r.match_tagname, $8.match_tag,
1733				    PF_TAG_NAME_SIZE) >= PF_TAG_NAME_SIZE) {
1734					yyerror("tag too long, max %u chars",
1735					    PF_TAG_NAME_SIZE - 1);
1736					YYERROR;
1737				}
1738			r.match_tag_not = $8.match_tag_not;
1739			if (rule_label(&r, $8.label))
1740				YYERROR;
1741			free($8.label);
1742			r.flags = $8.flags.b1;
1743			r.flagset = $8.flags.b2;
1744			if (($8.flags.b1 & $8.flags.b2) != $8.flags.b1) {
1745				yyerror("flags always false");
1746				YYERROR;
1747			}
1748			if ($8.flags.b1 || $8.flags.b2 || $7.src_os) {
1749				for (proto = $6; proto != NULL &&
1750				    proto->proto != IPPROTO_TCP;
1751				    proto = proto->next)
1752					;	/* nothing */
1753				if (proto == NULL && $6 != NULL) {
1754					if ($8.flags.b1 || $8.flags.b2)
1755						yyerror(
1756						    "flags only apply to tcp");
1757					if ($7.src_os)
1758						yyerror(
1759						    "OS fingerprinting only "
1760						    "apply to tcp");
1761					YYERROR;
1762				}
1763#if 0
1764				if (($8.flags.b1 & parse_flags("S")) == 0 &&
1765				    $7.src_os) {
1766					yyerror("OS fingerprinting requires "
1767					    "the SYN TCP flag (flags S/SA)");
1768					YYERROR;
1769				}
1770#endif
1771			}
1772
1773			r.tos = $8.tos;
1774			r.keep_state = $8.keep.action;
1775			o = $8.keep.options;
1776
1777			/* 'keep state' by default on pass rules. */
1778			if (!r.keep_state && !r.action &&
1779			    !($8.marker & FOM_KEEP)) {
1780				r.keep_state = PF_STATE_NORMAL;
1781				o = keep_state_defaults;
1782				defaults = 1;
1783			}
1784
1785			while (o) {
1786				struct node_state_opt	*p = o;
1787
1788				switch (o->type) {
1789				case PF_STATE_OPT_MAX:
1790					if (r.max_states) {
1791						yyerror("state option 'max' "
1792						    "multiple definitions");
1793						YYERROR;
1794					}
1795					r.max_states = o->data.max_states;
1796					break;
1797				case PF_STATE_OPT_NOSYNC:
1798					if (r.rule_flag & PFRULE_NOSYNC) {
1799						yyerror("state option 'sync' "
1800						    "multiple definitions");
1801						YYERROR;
1802					}
1803					r.rule_flag |= PFRULE_NOSYNC;
1804					break;
1805				case PF_STATE_OPT_SRCTRACK:
1806					if (srctrack) {
1807						yyerror("state option "
1808						    "'source-track' "
1809						    "multiple definitions");
1810						YYERROR;
1811					}
1812					srctrack =  o->data.src_track;
1813					r.rule_flag |= PFRULE_SRCTRACK;
1814					break;
1815				case PF_STATE_OPT_MAX_SRC_STATES:
1816					if (r.max_src_states) {
1817						yyerror("state option "
1818						    "'max-src-states' "
1819						    "multiple definitions");
1820						YYERROR;
1821					}
1822					if (o->data.max_src_states == 0) {
1823						yyerror("'max-src-states' must "
1824						    "be > 0");
1825						YYERROR;
1826					}
1827					r.max_src_states =
1828					    o->data.max_src_states;
1829					r.rule_flag |= PFRULE_SRCTRACK;
1830					break;
1831				case PF_STATE_OPT_OVERLOAD:
1832					if (r.overload_tblname[0]) {
1833						yyerror("multiple 'overload' "
1834						    "table definitions");
1835						YYERROR;
1836					}
1837					if (strlcpy(r.overload_tblname,
1838					    o->data.overload.tblname,
1839					    PF_TABLE_NAME_SIZE) >=
1840					    PF_TABLE_NAME_SIZE) {
1841						yyerror("state option: "
1842						    "strlcpy");
1843						YYERROR;
1844					}
1845					r.flush = o->data.overload.flush;
1846					break;
1847				case PF_STATE_OPT_MAX_SRC_CONN:
1848					if (r.max_src_conn) {
1849						yyerror("state option "
1850						    "'max-src-conn' "
1851						    "multiple definitions");
1852						YYERROR;
1853					}
1854					if (o->data.max_src_conn == 0) {
1855						yyerror("'max-src-conn' "
1856						    "must be > 0");
1857						YYERROR;
1858					}
1859					r.max_src_conn =
1860					    o->data.max_src_conn;
1861					r.rule_flag |= PFRULE_SRCTRACK |
1862					    PFRULE_RULESRCTRACK;
1863					break;
1864				case PF_STATE_OPT_MAX_SRC_CONN_RATE:
1865					if (r.max_src_conn_rate.limit) {
1866						yyerror("state option "
1867						    "'max-src-conn-rate' "
1868						    "multiple definitions");
1869						YYERROR;
1870					}
1871					if (!o->data.max_src_conn_rate.limit ||
1872					    !o->data.max_src_conn_rate.seconds) {
1873						yyerror("'max-src-conn-rate' "
1874						    "values must be > 0");
1875						YYERROR;
1876					}
1877					if (o->data.max_src_conn_rate.limit >
1878					    PF_THRESHOLD_MAX) {
1879						yyerror("'max-src-conn-rate' "
1880						    "maximum rate must be < %u",
1881						    PF_THRESHOLD_MAX);
1882						YYERROR;
1883					}
1884					r.max_src_conn_rate.limit =
1885					    o->data.max_src_conn_rate.limit;
1886					r.max_src_conn_rate.seconds =
1887					    o->data.max_src_conn_rate.seconds;
1888					r.rule_flag |= PFRULE_SRCTRACK |
1889					    PFRULE_RULESRCTRACK;
1890					break;
1891				case PF_STATE_OPT_MAX_SRC_NODES:
1892					if (r.max_src_nodes) {
1893						yyerror("state option "
1894						    "'max-src-nodes' "
1895						    "multiple definitions");
1896						YYERROR;
1897					}
1898					if (o->data.max_src_nodes == 0) {
1899						yyerror("'max-src-nodes' must "
1900						    "be > 0");
1901						YYERROR;
1902					}
1903					r.max_src_nodes =
1904					    o->data.max_src_nodes;
1905					r.rule_flag |= PFRULE_SRCTRACK |
1906					    PFRULE_RULESRCTRACK;
1907					break;
1908				case PF_STATE_OPT_STATELOCK:
1909					if (statelock) {
1910						yyerror("state locking option: "
1911						    "multiple definitions");
1912						YYERROR;
1913					}
1914					statelock = 1;
1915					r.rule_flag |= o->data.statelock;
1916					break;
1917				case PF_STATE_OPT_SLOPPY:
1918					if (r.rule_flag & PFRULE_STATESLOPPY) {
1919						yyerror("state sloppy option: "
1920						    "multiple definitions");
1921						YYERROR;
1922					}
1923					r.rule_flag |= PFRULE_STATESLOPPY;
1924					break;
1925				case PF_STATE_OPT_PFLOW:
1926					if (r.rule_flag & PFRULE_PFLOW) {
1927						yyerror("state pflow "
1928						    "option: multiple "
1929						    "definitions");
1930						YYERROR;
1931					}
1932					r.rule_flag |= PFRULE_PFLOW;
1933					break;
1934				case PF_STATE_OPT_TIMEOUT:
1935					if (o->data.timeout.number ==
1936					    PFTM_ADAPTIVE_START ||
1937					    o->data.timeout.number ==
1938					    PFTM_ADAPTIVE_END)
1939						adaptive = 1;
1940					if (r.timeout[o->data.timeout.number]) {
1941						yyerror("state timeout %s "
1942						    "multiple definitions",
1943						    pf_timeouts[o->data.
1944						    timeout.number].name);
1945						YYERROR;
1946					}
1947					r.timeout[o->data.timeout.number] =
1948					    o->data.timeout.seconds;
1949				}
1950				o = o->next;
1951				if (!defaults)
1952					free(p);
1953			}
1954
1955			/* 'flags S/SA' by default on stateful rules */
1956			if (!r.action && !r.flags && !r.flagset &&
1957			    !$8.fragment && !($8.marker & FOM_FLAGS) &&
1958			    r.keep_state) {
1959				r.flags = parse_flags("S");
1960				r.flagset =  parse_flags("SA");
1961			}
1962			if (!adaptive && r.max_states) {
1963				r.timeout[PFTM_ADAPTIVE_START] =
1964				    (r.max_states / 10) * 6;
1965				r.timeout[PFTM_ADAPTIVE_END] =
1966				    (r.max_states / 10) * 12;
1967			}
1968			if (r.rule_flag & PFRULE_SRCTRACK) {
1969				if (srctrack == PF_SRCTRACK_GLOBAL &&
1970				    r.max_src_nodes) {
1971					yyerror("'max-src-nodes' is "
1972					    "incompatible with "
1973					    "'source-track global'");
1974					YYERROR;
1975				}
1976				if (srctrack == PF_SRCTRACK_GLOBAL &&
1977				    r.max_src_conn) {
1978					yyerror("'max-src-conn' is "
1979					    "incompatible with "
1980					    "'source-track global'");
1981					YYERROR;
1982				}
1983				if (srctrack == PF_SRCTRACK_GLOBAL &&
1984				    r.max_src_conn_rate.seconds) {
1985					yyerror("'max-src-conn-rate' is "
1986					    "incompatible with "
1987					    "'source-track global'");
1988					YYERROR;
1989				}
1990				if (r.timeout[PFTM_SRC_NODE] <
1991				    r.max_src_conn_rate.seconds)
1992					r.timeout[PFTM_SRC_NODE] =
1993					    r.max_src_conn_rate.seconds;
1994				r.rule_flag |= PFRULE_SRCTRACK;
1995				if (srctrack == PF_SRCTRACK_RULE)
1996					r.rule_flag |= PFRULE_RULESRCTRACK;
1997			}
1998			if (r.keep_state && !statelock)
1999				r.rule_flag |= default_statelock;
2000
2001			if ($8.fragment)
2002				r.rule_flag |= PFRULE_FRAGMENT;
2003			r.allow_opts = $8.allowopts;
2004
2005			decide_address_family($7.src.host, &r.af);
2006			decide_address_family($7.dst.host, &r.af);
2007
2008			if ($8.route.rt) {
2009				if (!r.direction) {
2010					yyerror("direction must be explicit "
2011					    "with rules that specify routing");
2012					YYERROR;
2013				}
2014				r.rt = $8.route.rt;
2015				r.route.opts = $8.route.pool_opts;
2016				if ($8.route.key != NULL)
2017					memcpy(&r.route.key, $8.route.key,
2018					    sizeof(struct pf_poolhashkey));
2019			}
2020			if (r.rt && r.rt != PF_FASTROUTE) {
2021				decide_address_family($8.route.host, &r.af);
2022				if ((r.route.opts & PF_POOL_TYPEMASK) ==
2023				    PF_POOL_NONE && ($8.route.host->next != NULL ||
2024				    $8.route.host->addr.type == PF_ADDR_TABLE ||
2025				    DYNIF_MULTIADDR($8.route.host->addr)))
2026					r.route.opts |= PF_POOL_ROUNDROBIN;
2027				if ((r.route.opts & PF_POOL_TYPEMASK) !=
2028				    PF_POOL_ROUNDROBIN &&
2029				    disallow_table($8.route.host,
2030				    "tables are only "
2031				    "supported in round-robin routing pools"))
2032					YYERROR;
2033				if ((r.route.opts & PF_POOL_TYPEMASK) !=
2034				    PF_POOL_ROUNDROBIN &&
2035				    disallow_alias($8.route.host,
2036				    "interface (%s) "
2037				    "is only supported in round-robin "
2038				    "routing pools"))
2039					YYERROR;
2040				if ($8.route.host->next != NULL) {
2041					if ((r.route.opts & PF_POOL_TYPEMASK) !=
2042					    PF_POOL_ROUNDROBIN) {
2043						yyerror("r.route.opts must "
2044						    "be PF_POOL_ROUNDROBIN");
2045						YYERROR;
2046					}
2047				}
2048				/* fake redirspec */
2049				if (($8.rroute.rdr = calloc(1,
2050				    sizeof(*$8.rroute.rdr))) == NULL)
2051					err(1, "$8.rroute.rdr");
2052				$8.rroute.rdr->host = $8.route.host;
2053			}
2054			if ($8.queues.qname != NULL) {
2055				if (strlcpy(r.qname, $8.queues.qname,
2056				    sizeof(r.qname)) >= sizeof(r.qname)) {
2057					yyerror("rule qname too long (max "
2058					    "%d chars)", sizeof(r.qname)-1);
2059					YYERROR;
2060				}
2061				free($8.queues.qname);
2062			}
2063			if ($8.queues.pqname != NULL) {
2064				if (strlcpy(r.pqname, $8.queues.pqname,
2065				    sizeof(r.pqname)) >= sizeof(r.pqname)) {
2066					yyerror("rule pqname too long (max "
2067					    "%d chars)", sizeof(r.pqname)-1);
2068					YYERROR;
2069				}
2070				free($8.queues.pqname);
2071			}
2072			if ((r.divert.port = $8.divert.port)) {
2073				if (r.direction == PF_OUT) {
2074					if ($8.divert.addr) {
2075						yyerror("address specified "
2076						    "for outgoing divert");
2077						YYERROR;
2078					}
2079					bzero(&r.divert.addr,
2080					    sizeof(r.divert.addr));
2081				} else {
2082					if (!$8.divert.addr) {
2083						yyerror("no address specified "
2084						    "for incoming divert");
2085						YYERROR;
2086					}
2087					if ($8.divert.addr->af != r.af) {
2088						yyerror("address family "
2089						    "mismatch for divert");
2090						YYERROR;
2091					}
2092					r.divert.addr =
2093					    $8.divert.addr->addr.v.a.addr;
2094				}
2095			}
2096			r.divert_packet.port = $8.divert_packet.port;
2097
2098			expand_rule(&r, 0, $4, &$8.nat, &$8.rdr, &$8.rroute, $6,
2099			    $7.src_os,
2100			    $7.src.host, $7.src.port, $7.dst.host, $7.dst.port,
2101			    $8.uid, $8.gid, $8.rcv, $8.icmpspec, "");
2102		}
2103		;
2104
2105filter_opts	:	{
2106				bzero(&filter_opts, sizeof filter_opts);
2107				filter_opts.rtableid = -1;
2108			}
2109		    filter_opts_l
2110			{ $$ = filter_opts; }
2111		| /* empty */	{
2112			bzero(&filter_opts, sizeof filter_opts);
2113			filter_opts.rtableid = -1;
2114			$$ = filter_opts;
2115		}
2116		;
2117
2118filter_opts_l	: filter_opts_l filter_opt
2119		| filter_opt
2120		;
2121
2122filter_opt	: USER uids {
2123			if (filter_opts.uid)
2124				$2->tail->next = filter_opts.uid;
2125			filter_opts.uid = $2;
2126		}
2127		| GROUP gids {
2128			if (filter_opts.gid)
2129				$2->tail->next = filter_opts.gid;
2130			filter_opts.gid = $2;
2131		}
2132		| flags {
2133			if (filter_opts.marker & FOM_FLAGS) {
2134				yyerror("flags cannot be redefined");
2135				YYERROR;
2136			}
2137			filter_opts.marker |= FOM_FLAGS;
2138			filter_opts.flags.b1 |= $1.b1;
2139			filter_opts.flags.b2 |= $1.b2;
2140			filter_opts.flags.w |= $1.w;
2141			filter_opts.flags.w2 |= $1.w2;
2142		}
2143		| icmpspec {
2144			if (filter_opts.marker & FOM_ICMP) {
2145				yyerror("icmp-type cannot be redefined");
2146				YYERROR;
2147			}
2148			filter_opts.marker |= FOM_ICMP;
2149			filter_opts.icmpspec = $1;
2150		}
2151		| TOS tos {
2152			if (filter_opts.marker & FOM_TOS) {
2153				yyerror("tos cannot be redefined");
2154				YYERROR;
2155			}
2156			filter_opts.marker |= FOM_TOS;
2157			filter_opts.tos = $2;
2158		}
2159		| keep {
2160			if (filter_opts.marker & FOM_KEEP) {
2161				yyerror("modulate or keep cannot be redefined");
2162				YYERROR;
2163			}
2164			filter_opts.marker |= FOM_KEEP;
2165			filter_opts.keep.action = $1.action;
2166			filter_opts.keep.options = $1.options;
2167		}
2168		| FRAGMENT {
2169			filter_opts.fragment = 1;
2170		}
2171		| ALLOWOPTS {
2172			filter_opts.allowopts = 1;
2173		}
2174		| LABEL label	{
2175			if (filter_opts.label) {
2176				yyerror("label cannot be redefined");
2177				YYERROR;
2178			}
2179			filter_opts.label = $2;
2180		}
2181		| QUEUE qname	{
2182			if (filter_opts.queues.qname) {
2183				yyerror("queue cannot be redefined");
2184				YYERROR;
2185			}
2186			filter_opts.queues = $2;
2187		}
2188		| TAG string				{
2189			filter_opts.tag = $2;
2190		}
2191		| not TAGGED string			{
2192			filter_opts.match_tag = $3;
2193			filter_opts.match_tag_not = $1;
2194		}
2195		| PROBABILITY probability		{
2196			double	p;
2197
2198			p = floor($2 * UINT_MAX + 0.5);
2199			if (p < 0.0 || p > UINT_MAX) {
2200				yyerror("invalid probability: %lf", p);
2201				YYERROR;
2202			}
2203			filter_opts.prob = (u_int32_t)p;
2204			if (filter_opts.prob == 0)
2205				filter_opts.prob = 1;
2206		}
2207		| RTABLE NUMBER				{
2208			if ($2 < 0 || $2 > RT_TABLEID_MAX) {
2209				yyerror("invalid rtable id");
2210				YYERROR;
2211			}
2212			filter_opts.rtableid = $2;
2213		}
2214		| DIVERTTO STRING PORT portplain {
2215			if ((filter_opts.divert.addr = host($2)) == NULL) {
2216				yyerror("could not parse divert address: %s",
2217				    $2);
2218				free($2);
2219				YYERROR;
2220			}
2221			free($2);
2222			filter_opts.divert.port = $4.a;
2223			if (!filter_opts.divert.port) {
2224				yyerror("invalid divert port: %u", ntohs($4.a));
2225				YYERROR;
2226			}
2227		}
2228		| DIVERTREPLY {
2229			filter_opts.divert.port = 1;	/* some random value */
2230		}
2231		| DIVERTPACKET PORT number {
2232			/*
2233			 * If IP reassembly was not turned off, also
2234			 * forcibly enable TCP reassembly by default.
2235			 */
2236			if (pf->reassemble & PF_REASS_ENABLED)
2237				filter_opts.marker |= FOM_SCRUB_TCP;
2238
2239			if ($3 < 1 || $3 > 65535) {
2240				yyerror("invalid divert port");
2241				YYERROR;
2242			}
2243
2244			filter_opts.divert_packet.port = htons($3);
2245		}
2246		| SCRUB '(' scrub_opts ')' {
2247			filter_opts.nodf = $3.nodf;
2248			filter_opts.minttl = $3.minttl;
2249			filter_opts.settos = $3.settos;
2250			filter_opts.randomid = $3.randomid;
2251			filter_opts.max_mss = $3.maxmss;
2252			if ($3.reassemble_tcp)
2253				filter_opts.marker |= FOM_SCRUB_TCP;
2254			filter_opts.marker |= $3.marker;
2255		}
2256		| NATTO redirpool pool_opts {
2257			if (filter_opts.nat.rdr) {
2258				yyerror("cannot respecify nat-to/binat-to");
2259				YYERROR;
2260			}
2261			filter_opts.nat.rdr = $2;
2262			memcpy(&filter_opts.nat.pool_opts, &$3,
2263			    sizeof(filter_opts.nat.pool_opts));
2264		}
2265		| RDRTO redirpool pool_opts {
2266			if (filter_opts.rdr.rdr) {
2267				yyerror("cannot respecify rdr-to");
2268				YYERROR;
2269			}
2270			filter_opts.rdr.rdr = $2;
2271			memcpy(&filter_opts.rdr.pool_opts, &$3,
2272			    sizeof(filter_opts.rdr.pool_opts));
2273		}
2274		| BINATTO redirpool pool_opts {
2275			if (filter_opts.nat.rdr) {
2276				yyerror("cannot respecify nat-to/binat-to");
2277				YYERROR;
2278			}
2279			filter_opts.nat.rdr = $2;
2280			filter_opts.nat.binat = 1;
2281			memcpy(&filter_opts.nat.pool_opts, &$3,
2282			    sizeof(filter_opts.nat.pool_opts));
2283			filter_opts.nat.pool_opts.staticport = 1;
2284		}
2285		| FASTROUTE {
2286			filter_opts.route.host = NULL;
2287			filter_opts.route.rt = PF_FASTROUTE;
2288			filter_opts.route.pool_opts = 0;
2289		}
2290		| ROUTETO routespec pool_opts {
2291			filter_opts.route.host = $2;
2292			filter_opts.route.rt = PF_ROUTETO;
2293			filter_opts.route.pool_opts = $3.type | $3.opts;
2294			if ($3.key != NULL)
2295				filter_opts.route.key = $3.key;
2296		}
2297		| REPLYTO routespec pool_opts {
2298			filter_opts.route.host = $2;
2299			filter_opts.route.rt = PF_REPLYTO;
2300			filter_opts.route.pool_opts = $3.type | $3.opts;
2301			if ($3.key != NULL)
2302				filter_opts.route.key = $3.key;
2303		}
2304		| DUPTO routespec pool_opts {
2305			filter_opts.route.host = $2;
2306			filter_opts.route.rt = PF_DUPTO;
2307			filter_opts.route.pool_opts = $3.type | $3.opts;
2308			if ($3.key != NULL)
2309				filter_opts.route.key = $3.key;
2310		}
2311		| RECEIVEDON if_item {
2312			if (filter_opts.rcv) {
2313				yyerror("cannot respecify received-on");
2314				YYERROR;
2315			}
2316			filter_opts.rcv = $2;
2317		}
2318		;
2319
2320probability	: STRING				{
2321			char	*e;
2322			double	 p = strtod($1, &e);
2323
2324			if (*e == '%') {
2325				p *= 0.01;
2326				e++;
2327			}
2328			if (*e) {
2329				yyerror("invalid probability: %s", $1);
2330				free($1);
2331				YYERROR;
2332			}
2333			free($1);
2334			$$ = p;
2335		}
2336		| NUMBER				{
2337			$$ = (double)$1;
2338		}
2339		;
2340
2341
2342action		: PASS			{ $$.b1 = PF_PASS; $$.b2 = $$.w = 0; }
2343		| MATCH			{ $$.b1 = PF_MATCH; $$.b2 = $$.w = 0; }
2344		| BLOCK blockspec	{ $$ = $2; $$.b1 = PF_DROP; }
2345		;
2346
2347blockspec	: /* empty */		{
2348			$$.b2 = blockpolicy;
2349			$$.w = returnicmpdefault;
2350			$$.w2 = returnicmp6default;
2351		}
2352		| DROP			{
2353			$$.b2 = PFRULE_DROP;
2354			$$.w = 0;
2355			$$.w2 = 0;
2356		}
2357		| RETURNRST		{
2358			$$.b2 = PFRULE_RETURNRST;
2359			$$.w = 0;
2360			$$.w2 = 0;
2361		}
2362		| RETURNRST '(' TTL NUMBER ')'	{
2363			if ($4 < 0 || $4 > 255) {
2364				yyerror("illegal ttl value %d", $4);
2365				YYERROR;
2366			}
2367			$$.b2 = PFRULE_RETURNRST;
2368			$$.w = $4;
2369			$$.w2 = 0;
2370		}
2371		| RETURNICMP		{
2372			$$.b2 = PFRULE_RETURNICMP;
2373			$$.w = returnicmpdefault;
2374			$$.w2 = returnicmp6default;
2375		}
2376		| RETURNICMP6		{
2377			$$.b2 = PFRULE_RETURNICMP;
2378			$$.w = returnicmpdefault;
2379			$$.w2 = returnicmp6default;
2380		}
2381		| RETURNICMP '(' reticmpspec ')'	{
2382			$$.b2 = PFRULE_RETURNICMP;
2383			$$.w = $3;
2384			$$.w2 = returnicmpdefault;
2385		}
2386		| RETURNICMP6 '(' reticmp6spec ')'	{
2387			$$.b2 = PFRULE_RETURNICMP;
2388			$$.w = returnicmpdefault;
2389			$$.w2 = $3;
2390		}
2391		| RETURNICMP '(' reticmpspec comma reticmp6spec ')' {
2392			$$.b2 = PFRULE_RETURNICMP;
2393			$$.w = $3;
2394			$$.w2 = $5;
2395		}
2396		| RETURN {
2397			$$.b2 = PFRULE_RETURN;
2398			$$.w = returnicmpdefault;
2399			$$.w2 = returnicmp6default;
2400		}
2401		;
2402
2403reticmpspec	: STRING			{
2404			if (!($$ = parseicmpspec($1, AF_INET))) {
2405				free($1);
2406				YYERROR;
2407			}
2408			free($1);
2409		}
2410		| NUMBER			{
2411			u_int8_t		icmptype;
2412
2413			if ($1 < 0 || $1 > 255) {
2414				yyerror("invalid icmp code %lu", $1);
2415				YYERROR;
2416			}
2417			icmptype = returnicmpdefault >> 8;
2418			$$ = (icmptype << 8 | $1);
2419		}
2420		;
2421
2422reticmp6spec	: STRING			{
2423			if (!($$ = parseicmpspec($1, AF_INET6))) {
2424				free($1);
2425				YYERROR;
2426			}
2427			free($1);
2428		}
2429		| NUMBER			{
2430			u_int8_t		icmptype;
2431
2432			if ($1 < 0 || $1 > 255) {
2433				yyerror("invalid icmp code %lu", $1);
2434				YYERROR;
2435			}
2436			icmptype = returnicmp6default >> 8;
2437			$$ = (icmptype << 8 | $1);
2438		}
2439		;
2440
2441dir		: /* empty */			{ $$ = PF_INOUT; }
2442		| IN				{ $$ = PF_IN; }
2443		| OUT				{ $$ = PF_OUT; }
2444		;
2445
2446quick		: /* empty */			{ $$.quick = 0; }
2447		| QUICK				{ $$.quick = 1; }
2448		;
2449
2450logquick	: /* empty */	{ $$.log = 0; $$.quick = 0; $$.logif = 0; }
2451		| log		{ $$ = $1; $$.quick = 0; }
2452		| QUICK		{ $$.quick = 1; $$.log = 0; $$.logif = 0; }
2453		| log QUICK	{ $$ = $1; $$.quick = 1; }
2454		| QUICK log	{ $$ = $2; $$.quick = 1; }
2455		;
2456
2457log		: LOG			{ $$.log = PF_LOG; $$.logif = 0; }
2458		| LOG '(' logopts ')'	{
2459			$$.log = PF_LOG | $3.log;
2460			$$.logif = $3.logif;
2461		}
2462		;
2463
2464logopts		: logopt			{ $$ = $1; }
2465		| logopts comma logopt		{
2466			$$.log = $1.log | $3.log;
2467			$$.logif = $3.logif;
2468			if ($$.logif == 0)
2469				$$.logif = $1.logif;
2470		}
2471		;
2472
2473logopt		: ALL		{ $$.log = PF_LOG_ALL; $$.logif = 0; }
2474		| USER		{ $$.log = PF_LOG_SOCKET_LOOKUP; $$.logif = 0; }
2475		| GROUP		{ $$.log = PF_LOG_SOCKET_LOOKUP; $$.logif = 0; }
2476		| TO string	{
2477			const char	*errstr;
2478			u_int		 i;
2479
2480			$$.log = 0;
2481			if (strncmp($2, "pflog", 5)) {
2482				yyerror("%s: should be a pflog interface", $2);
2483				free($2);
2484				YYERROR;
2485			}
2486			i = strtonum($2 + 5, 0, 255, &errstr);
2487			if (errstr) {
2488				yyerror("%s: %s", $2, errstr);
2489				free($2);
2490				YYERROR;
2491			}
2492			free($2);
2493			$$.logif = i;
2494		}
2495		;
2496
2497interface	: /* empty */			{ $$ = NULL; }
2498		| ON if_item_not		{ $$ = $2; }
2499		| ON '{' optnl if_list '}'	{ $$ = $4; }
2500		;
2501
2502if_list		: if_item_not optnl		{ $$ = $1; }
2503		| if_list comma if_item_not optnl	{
2504			$1->tail->next = $3;
2505			$1->tail = $3;
2506			$$ = $1;
2507		}
2508		;
2509
2510if_item_not	: not if_item			{ $$ = $2; $$->not = $1; }
2511		;
2512
2513if_item		: STRING			{
2514			struct node_host	*n;
2515
2516			$$ = calloc(1, sizeof(struct node_if));
2517			if ($$ == NULL)
2518				err(1, "if_item: calloc");
2519			if (strlcpy($$->ifname, $1, sizeof($$->ifname)) >=
2520			    sizeof($$->ifname)) {
2521				free($1);
2522				free($$);
2523				yyerror("interface name too long");
2524				YYERROR;
2525			}
2526
2527			if ((n = ifa_exists($1)) != NULL)
2528				$$->ifa_flags = n->ifa_flags;
2529
2530			free($1);
2531			$$->not = 0;
2532			$$->next = NULL;
2533			$$->tail = $$;
2534		}
2535		;
2536
2537af		: /* empty */			{ $$ = 0; }
2538		| INET				{ $$ = AF_INET; }
2539		| INET6				{ $$ = AF_INET6; }
2540		;
2541
2542proto		: /* empty */				{ $$ = NULL; }
2543		| PROTO proto_item			{ $$ = $2; }
2544		| PROTO '{' optnl proto_list '}'	{ $$ = $4; }
2545		;
2546
2547proto_list	: proto_item optnl		{ $$ = $1; }
2548		| proto_list comma proto_item optnl	{
2549			$1->tail->next = $3;
2550			$1->tail = $3;
2551			$$ = $1;
2552		}
2553		;
2554
2555proto_item	: protoval			{
2556			u_int8_t	pr;
2557
2558			pr = (u_int8_t)$1;
2559			if (pr == 0) {
2560				yyerror("proto 0 cannot be used");
2561				YYERROR;
2562			}
2563			$$ = calloc(1, sizeof(struct node_proto));
2564			if ($$ == NULL)
2565				err(1, "proto_item: calloc");
2566			$$->proto = pr;
2567			$$->next = NULL;
2568			$$->tail = $$;
2569		}
2570		;
2571
2572protoval	: STRING			{
2573			struct protoent	*p;
2574
2575			p = getprotobyname($1);
2576			if (p == NULL) {
2577				yyerror("unknown protocol %s", $1);
2578				free($1);
2579				YYERROR;
2580			}
2581			$$ = p->p_proto;
2582			free($1);
2583		}
2584		| NUMBER			{
2585			if ($1 < 0 || $1 > 255) {
2586				yyerror("protocol outside range");
2587				YYERROR;
2588			}
2589		}
2590		;
2591
2592fromto		: ALL				{
2593			$$.src.host = NULL;
2594			$$.src.port = NULL;
2595			$$.dst.host = NULL;
2596			$$.dst.port = NULL;
2597			$$.src_os = NULL;
2598		}
2599		| from os to			{
2600			$$.src = $1;
2601			$$.src_os = $2;
2602			$$.dst = $3;
2603		}
2604		;
2605
2606os		: /* empty */			{ $$ = NULL; }
2607		| OS xos			{ $$ = $2; }
2608		| OS '{' optnl os_list '}'	{ $$ = $4; }
2609		;
2610
2611xos		: STRING {
2612			$$ = calloc(1, sizeof(struct node_os));
2613			if ($$ == NULL)
2614				err(1, "os: calloc");
2615			$$->os = $1;
2616			$$->tail = $$;
2617		}
2618		;
2619
2620os_list		: xos optnl 			{ $$ = $1; }
2621		| os_list comma xos optnl	{
2622			$1->tail->next = $3;
2623			$1->tail = $3;
2624			$$ = $1;
2625		}
2626		;
2627
2628from		: /* empty */			{
2629			$$.host = NULL;
2630			$$.port = NULL;
2631		}
2632		| FROM ipportspec		{
2633			$$ = $2;
2634		}
2635		;
2636
2637to		: /* empty */			{
2638			$$.host = NULL;
2639			$$.port = NULL;
2640		}
2641		| TO ipportspec		{
2642			if (disallow_urpf_failed($2.host, "\"urpf-failed\" is "
2643			    "not permitted in a destination address"))
2644				YYERROR;
2645			$$ = $2;
2646		}
2647		;
2648
2649ipportspec	: ipspec			{
2650			$$.host = $1;
2651			$$.port = NULL;
2652		}
2653		| ipspec PORT portspec		{
2654			$$.host = $1;
2655			$$.port = $3;
2656		}
2657		| PORT portspec			{
2658			$$.host = NULL;
2659			$$.port = $2;
2660		}
2661		;
2662
2663optnl		: '\n' optnl
2664		| /* empty */
2665		;
2666
2667ipspec		: ANY				{ $$ = NULL; }
2668		| xhost				{ $$ = $1; }
2669		| '{' optnl host_list '}'	{ $$ = $3; }
2670		;
2671
2672host_list	: ipspec optnl			{ $$ = $1; }
2673		| host_list comma ipspec optnl	{
2674			if ($1 == NULL) {
2675				freehostlist($3);
2676				$$ = $1;
2677			} else if ($3 == NULL) {
2678				freehostlist($1);
2679				$$ = $3;
2680			} else {
2681				$1->tail->next = $3;
2682				$1->tail = $3->tail;
2683				$$ = $1;
2684			}
2685		}
2686		;
2687
2688xhost		: not host			{
2689			struct node_host	*n;
2690
2691			for (n = $2; n != NULL; n = n->next)
2692				n->not = $1;
2693			$$ = $2;
2694		}
2695		| not NOROUTE			{
2696			$$ = calloc(1, sizeof(struct node_host));
2697			if ($$ == NULL)
2698				err(1, "xhost: calloc");
2699			$$->addr.type = PF_ADDR_NOROUTE;
2700			$$->next = NULL;
2701			$$->not = $1;
2702			$$->tail = $$;
2703		}
2704		| not URPFFAILED		{
2705			$$ = calloc(1, sizeof(struct node_host));
2706			if ($$ == NULL)
2707				err(1, "xhost: calloc");
2708			$$->addr.type = PF_ADDR_URPFFAILED;
2709			$$->next = NULL;
2710			$$->not = $1;
2711			$$->tail = $$;
2712		}
2713		;
2714
2715host		: STRING			{
2716			if (($$ = host($1)) == NULL)	{
2717				/* error. "any" is handled elsewhere */
2718				free($1);
2719				yyerror("could not parse host specification");
2720				YYERROR;
2721			}
2722			free($1);
2723
2724		}
2725		| STRING '-' STRING		{
2726			struct node_host *b, *e;
2727
2728			if ((b = host($1)) == NULL || (e = host($3)) == NULL) {
2729				free($1);
2730				free($3);
2731				yyerror("could not parse host specification");
2732				YYERROR;
2733			}
2734			if (b->af != e->af ||
2735			    b->addr.type != PF_ADDR_ADDRMASK ||
2736			    e->addr.type != PF_ADDR_ADDRMASK ||
2737			    unmask(&b->addr.v.a.mask, b->af) !=
2738			    (b->af == AF_INET ? 32 : 128) ||
2739			    unmask(&e->addr.v.a.mask, e->af) !=
2740			    (e->af == AF_INET ? 32 : 128) ||
2741			    b->next != NULL || b->not ||
2742			    e->next != NULL || e->not) {
2743				free(b);
2744				free(e);
2745				free($1);
2746				free($3);
2747				yyerror("invalid address range");
2748				YYERROR;
2749			}
2750			memcpy(&b->addr.v.a.mask, &e->addr.v.a.addr,
2751			    sizeof(b->addr.v.a.mask));
2752			b->addr.type = PF_ADDR_RANGE;
2753			$$ = b;
2754			free(e);
2755			free($1);
2756			free($3);
2757		}
2758		| STRING '/' NUMBER		{
2759			char	*buf;
2760
2761			if (asprintf(&buf, "%s/%lld", $1, $3) == -1)
2762				err(1, "host: asprintf");
2763			free($1);
2764			if (($$ = host(buf)) == NULL)	{
2765				/* error. "any" is handled elsewhere */
2766				free(buf);
2767				yyerror("could not parse host specification");
2768				YYERROR;
2769			}
2770			free(buf);
2771		}
2772		| NUMBER '/' NUMBER		{
2773			char	*buf;
2774
2775			/* ie. for 10/8 parsing */
2776			if (asprintf(&buf, "%lld/%lld", $1, $3) == -1)
2777				err(1, "host: asprintf");
2778			if (($$ = host(buf)) == NULL)	{
2779				/* error. "any" is handled elsewhere */
2780				free(buf);
2781				yyerror("could not parse host specification");
2782				YYERROR;
2783			}
2784			free(buf);
2785		}
2786		| dynaddr
2787		| dynaddr '/' NUMBER		{
2788			struct node_host	*n;
2789
2790			if ($3 < 0 || $3 > 128) {
2791				yyerror("bit number too big");
2792				YYERROR;
2793			}
2794			$$ = $1;
2795			for (n = $1; n != NULL; n = n->next)
2796				set_ipmask(n, $3);
2797		}
2798		| '<' STRING '>'	{
2799			if (strlen($2) >= PF_TABLE_NAME_SIZE) {
2800				yyerror("table name '%s' too long", $2);
2801				free($2);
2802				YYERROR;
2803			}
2804			$$ = calloc(1, sizeof(struct node_host));
2805			if ($$ == NULL)
2806				err(1, "host: calloc");
2807			$$->addr.type = PF_ADDR_TABLE;
2808			if (strlcpy($$->addr.v.tblname, $2,
2809			    sizeof($$->addr.v.tblname)) >=
2810			    sizeof($$->addr.v.tblname))
2811				errx(1, "host: strlcpy");
2812			free($2);
2813			$$->next = NULL;
2814			$$->tail = $$;
2815		}
2816		| ROUTE	STRING		{
2817			$$ = calloc(1, sizeof(struct node_host));
2818			if ($$ == NULL) {
2819				free($2);
2820				err(1, "host: calloc");
2821			}
2822			$$->addr.type = PF_ADDR_RTLABEL;
2823			if (strlcpy($$->addr.v.rtlabelname, $2,
2824			    sizeof($$->addr.v.rtlabelname)) >=
2825			    sizeof($$->addr.v.rtlabelname)) {
2826				yyerror("route label too long, max %u chars",
2827				    sizeof($$->addr.v.rtlabelname) - 1);
2828				free($2);
2829				free($$);
2830				YYERROR;
2831			}
2832			$$->next = NULL;
2833			$$->tail = $$;
2834			free($2);
2835		}
2836		;
2837
2838number		: NUMBER
2839		| STRING		{
2840			u_long	ulval;
2841
2842			if (atoul($1, &ulval) == -1) {
2843				yyerror("%s is not a number", $1);
2844				free($1);
2845				YYERROR;
2846			} else
2847				$$ = ulval;
2848			free($1);
2849		}
2850		;
2851
2852dynaddr		: '(' STRING ')'		{
2853			int	 flags = 0;
2854			char	*p, *op;
2855
2856			op = $2;
2857			if (!isalpha(op[0])) {
2858				yyerror("invalid interface name '%s'", op);
2859				free(op);
2860				YYERROR;
2861			}
2862			while ((p = strrchr($2, ':')) != NULL) {
2863				if (!strcmp(p+1, "network"))
2864					flags |= PFI_AFLAG_NETWORK;
2865				else if (!strcmp(p+1, "broadcast"))
2866					flags |= PFI_AFLAG_BROADCAST;
2867				else if (!strcmp(p+1, "peer"))
2868					flags |= PFI_AFLAG_PEER;
2869				else if (!strcmp(p+1, "0"))
2870					flags |= PFI_AFLAG_NOALIAS;
2871				else {
2872					yyerror("interface %s has bad modifier",
2873					    $2);
2874					free(op);
2875					YYERROR;
2876				}
2877				*p = '\0';
2878			}
2879			if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) {
2880				free(op);
2881				yyerror("illegal combination of "
2882				    "interface modifiers");
2883				YYERROR;
2884			}
2885			$$ = calloc(1, sizeof(struct node_host));
2886			if ($$ == NULL)
2887				err(1, "address: calloc");
2888			$$->af = 0;
2889			set_ipmask($$, 128);
2890			$$->addr.type = PF_ADDR_DYNIFTL;
2891			$$->addr.iflags = flags;
2892			if (strlcpy($$->addr.v.ifname, $2,
2893			    sizeof($$->addr.v.ifname)) >=
2894			    sizeof($$->addr.v.ifname)) {
2895				free(op);
2896				free($$);
2897				yyerror("interface name too long");
2898				YYERROR;
2899			}
2900			free(op);
2901			$$->next = NULL;
2902			$$->tail = $$;
2903		}
2904		;
2905
2906portspec	: port_item			{ $$ = $1; }
2907		| '{' optnl port_list '}'	{ $$ = $3; }
2908		;
2909
2910port_list	: port_item optnl		{ $$ = $1; }
2911		| port_list comma port_item optnl	{
2912			$1->tail->next = $3;
2913			$1->tail = $3;
2914			$$ = $1;
2915		}
2916		;
2917
2918port_item	: portrange			{
2919			$$ = calloc(1, sizeof(struct node_port));
2920			if ($$ == NULL)
2921				err(1, "port_item: calloc");
2922			$$->port[0] = $1.a;
2923			$$->port[1] = $1.b;
2924			if ($1.t)
2925				$$->op = PF_OP_RRG;
2926			else
2927				$$->op = PF_OP_EQ;
2928			$$->next = NULL;
2929			$$->tail = $$;
2930		}
2931		| unaryop portrange	{
2932			if ($2.t) {
2933				yyerror("':' cannot be used with an other "
2934				    "port operator");
2935				YYERROR;
2936			}
2937			$$ = calloc(1, sizeof(struct node_port));
2938			if ($$ == NULL)
2939				err(1, "port_item: calloc");
2940			$$->port[0] = $2.a;
2941			$$->port[1] = $2.b;
2942			$$->op = $1;
2943			$$->next = NULL;
2944			$$->tail = $$;
2945		}
2946		| portrange PORTBINARY portrange	{
2947			if ($1.t || $3.t) {
2948				yyerror("':' cannot be used with an other "
2949				    "port operator");
2950				YYERROR;
2951			}
2952			$$ = calloc(1, sizeof(struct node_port));
2953			if ($$ == NULL)
2954				err(1, "port_item: calloc");
2955			$$->port[0] = $1.a;
2956			$$->port[1] = $3.a;
2957			$$->op = $2;
2958			$$->next = NULL;
2959			$$->tail = $$;
2960		}
2961		;
2962
2963portplain	: numberstring			{
2964			if (parseport($1, &$$, 0) == -1) {
2965				free($1);
2966				YYERROR;
2967			}
2968			free($1);
2969		}
2970		;
2971
2972portrange	: numberstring			{
2973			if (parseport($1, &$$, PPORT_RANGE) == -1) {
2974				free($1);
2975				YYERROR;
2976			}
2977			free($1);
2978		}
2979		;
2980
2981uids		: uid_item			{ $$ = $1; }
2982		| '{' optnl uid_list '}'	{ $$ = $3; }
2983		;
2984
2985uid_list	: uid_item optnl		{ $$ = $1; }
2986		| uid_list comma uid_item optnl	{
2987			$1->tail->next = $3;
2988			$1->tail = $3;
2989			$$ = $1;
2990		}
2991		;
2992
2993uid_item	: uid				{
2994			$$ = calloc(1, sizeof(struct node_uid));
2995			if ($$ == NULL)
2996				err(1, "uid_item: calloc");
2997			$$->uid[0] = $1;
2998			$$->uid[1] = $1;
2999			$$->op = PF_OP_EQ;
3000			$$->next = NULL;
3001			$$->tail = $$;
3002		}
3003		| unaryop uid			{
3004			if ($2 == UID_MAX && $1 != PF_OP_EQ && $1 != PF_OP_NE) {
3005				yyerror("user unknown requires operator = or "
3006				    "!=");
3007				YYERROR;
3008			}
3009			$$ = calloc(1, sizeof(struct node_uid));
3010			if ($$ == NULL)
3011				err(1, "uid_item: calloc");
3012			$$->uid[0] = $2;
3013			$$->uid[1] = $2;
3014			$$->op = $1;
3015			$$->next = NULL;
3016			$$->tail = $$;
3017		}
3018		| uid PORTBINARY uid		{
3019			if ($1 == UID_MAX || $3 == UID_MAX) {
3020				yyerror("user unknown requires operator = or "
3021				    "!=");
3022				YYERROR;
3023			}
3024			$$ = calloc(1, sizeof(struct node_uid));
3025			if ($$ == NULL)
3026				err(1, "uid_item: calloc");
3027			$$->uid[0] = $1;
3028			$$->uid[1] = $3;
3029			$$->op = $2;
3030			$$->next = NULL;
3031			$$->tail = $$;
3032		}
3033		;
3034
3035uid		: STRING			{
3036			if (!strcmp($1, "unknown"))
3037				$$ = UID_MAX;
3038			else {
3039				struct passwd	*pw;
3040
3041				if ((pw = getpwnam($1)) == NULL) {
3042					yyerror("unknown user %s", $1);
3043					free($1);
3044					YYERROR;
3045				}
3046				$$ = pw->pw_uid;
3047			}
3048			free($1);
3049		}
3050		| NUMBER			{
3051			if ($1 < 0 || $1 >= UID_MAX) {
3052				yyerror("illegal uid value %lu", $1);
3053				YYERROR;
3054			}
3055			$$ = $1;
3056		}
3057		;
3058
3059gids		: gid_item			{ $$ = $1; }
3060		| '{' optnl gid_list '}'	{ $$ = $3; }
3061		;
3062
3063gid_list	: gid_item optnl		{ $$ = $1; }
3064		| gid_list comma gid_item optnl	{
3065			$1->tail->next = $3;
3066			$1->tail = $3;
3067			$$ = $1;
3068		}
3069		;
3070
3071gid_item	: gid				{
3072			$$ = calloc(1, sizeof(struct node_gid));
3073			if ($$ == NULL)
3074				err(1, "gid_item: calloc");
3075			$$->gid[0] = $1;
3076			$$->gid[1] = $1;
3077			$$->op = PF_OP_EQ;
3078			$$->next = NULL;
3079			$$->tail = $$;
3080		}
3081		| unaryop gid			{
3082			if ($2 == GID_MAX && $1 != PF_OP_EQ && $1 != PF_OP_NE) {
3083				yyerror("group unknown requires operator = or "
3084				    "!=");
3085				YYERROR;
3086			}
3087			$$ = calloc(1, sizeof(struct node_gid));
3088			if ($$ == NULL)
3089				err(1, "gid_item: calloc");
3090			$$->gid[0] = $2;
3091			$$->gid[1] = $2;
3092			$$->op = $1;
3093			$$->next = NULL;
3094			$$->tail = $$;
3095		}
3096		| gid PORTBINARY gid		{
3097			if ($1 == GID_MAX || $3 == GID_MAX) {
3098				yyerror("group unknown requires operator = or "
3099				    "!=");
3100				YYERROR;
3101			}
3102			$$ = calloc(1, sizeof(struct node_gid));
3103			if ($$ == NULL)
3104				err(1, "gid_item: calloc");
3105			$$->gid[0] = $1;
3106			$$->gid[1] = $3;
3107			$$->op = $2;
3108			$$->next = NULL;
3109			$$->tail = $$;
3110		}
3111		;
3112
3113gid		: STRING			{
3114			if (!strcmp($1, "unknown"))
3115				$$ = GID_MAX;
3116			else {
3117				struct group	*grp;
3118
3119				if ((grp = getgrnam($1)) == NULL) {
3120					yyerror("unknown group %s", $1);
3121					free($1);
3122					YYERROR;
3123				}
3124				$$ = grp->gr_gid;
3125			}
3126			free($1);
3127		}
3128		| NUMBER			{
3129			if ($1 < 0 || $1 >= GID_MAX) {
3130				yyerror("illegal gid value %lu", $1);
3131				YYERROR;
3132			}
3133			$$ = $1;
3134		}
3135		;
3136
3137flag		: STRING			{
3138			int	f;
3139
3140			if ((f = parse_flags($1)) < 0) {
3141				yyerror("bad flags %s", $1);
3142				free($1);
3143				YYERROR;
3144			}
3145			free($1);
3146			$$.b1 = f;
3147		}
3148		;
3149
3150flags		: FLAGS flag '/' flag	{ $$.b1 = $2.b1; $$.b2 = $4.b1; }
3151		| FLAGS '/' flag	{ $$.b1 = 0; $$.b2 = $3.b1; }
3152		| FLAGS ANY		{ $$.b1 = 0; $$.b2 = 0; }
3153		;
3154
3155icmpspec	: ICMPTYPE icmp_item			{ $$ = $2; }
3156		| ICMPTYPE '{' optnl icmp_list '}'	{ $$ = $4; }
3157		| ICMP6TYPE icmp6_item			{ $$ = $2; }
3158		| ICMP6TYPE '{' optnl icmp6_list '}'	{ $$ = $4; }
3159		;
3160
3161icmp_list	: icmp_item optnl		{ $$ = $1; }
3162		| icmp_list comma icmp_item optnl {
3163			$1->tail->next = $3;
3164			$1->tail = $3;
3165			$$ = $1;
3166		}
3167		;
3168
3169icmp6_list	: icmp6_item optnl		{ $$ = $1; }
3170		| icmp6_list comma icmp6_item optnl {
3171			$1->tail->next = $3;
3172			$1->tail = $3;
3173			$$ = $1;
3174		}
3175		;
3176
3177icmp_item	: icmptype		{
3178			$$ = calloc(1, sizeof(struct node_icmp));
3179			if ($$ == NULL)
3180				err(1, "icmp_item: calloc");
3181			$$->type = $1;
3182			$$->code = 0;
3183			$$->proto = IPPROTO_ICMP;
3184			$$->next = NULL;
3185			$$->tail = $$;
3186		}
3187		| icmptype CODE STRING	{
3188			const struct icmpcodeent	*p;
3189
3190			if ((p = geticmpcodebyname($1-1, $3, AF_INET)) == NULL) {
3191				yyerror("unknown icmp-code %s", $3);
3192				free($3);
3193				YYERROR;
3194			}
3195
3196			free($3);
3197			$$ = calloc(1, sizeof(struct node_icmp));
3198			if ($$ == NULL)
3199				err(1, "icmp_item: calloc");
3200			$$->type = $1;
3201			$$->code = p->code + 1;
3202			$$->proto = IPPROTO_ICMP;
3203			$$->next = NULL;
3204			$$->tail = $$;
3205		}
3206		| icmptype CODE NUMBER	{
3207			if ($3 < 0 || $3 > 255) {
3208				yyerror("illegal icmp-code %lu", $3);
3209				YYERROR;
3210			}
3211			$$ = calloc(1, sizeof(struct node_icmp));
3212			if ($$ == NULL)
3213				err(1, "icmp_item: calloc");
3214			$$->type = $1;
3215			$$->code = $3 + 1;
3216			$$->proto = IPPROTO_ICMP;
3217			$$->next = NULL;
3218			$$->tail = $$;
3219		}
3220		;
3221
3222icmp6_item	: icmp6type		{
3223			$$ = calloc(1, sizeof(struct node_icmp));
3224			if ($$ == NULL)
3225				err(1, "icmp_item: calloc");
3226			$$->type = $1;
3227			$$->code = 0;
3228			$$->proto = IPPROTO_ICMPV6;
3229			$$->next = NULL;
3230			$$->tail = $$;
3231		}
3232		| icmp6type CODE STRING	{
3233			const struct icmpcodeent	*p;
3234
3235			if ((p = geticmpcodebyname($1-1, $3, AF_INET6)) == NULL) {
3236				yyerror("unknown icmp6-code %s", $3);
3237				free($3);
3238				YYERROR;
3239			}
3240			free($3);
3241
3242			$$ = calloc(1, sizeof(struct node_icmp));
3243			if ($$ == NULL)
3244				err(1, "icmp_item: calloc");
3245			$$->type = $1;
3246			$$->code = p->code + 1;
3247			$$->proto = IPPROTO_ICMPV6;
3248			$$->next = NULL;
3249			$$->tail = $$;
3250		}
3251		| icmp6type CODE NUMBER	{
3252			if ($3 < 0 || $3 > 255) {
3253				yyerror("illegal icmp-code %lu", $3);
3254				YYERROR;
3255			}
3256			$$ = calloc(1, sizeof(struct node_icmp));
3257			if ($$ == NULL)
3258				err(1, "icmp_item: calloc");
3259			$$->type = $1;
3260			$$->code = $3 + 1;
3261			$$->proto = IPPROTO_ICMPV6;
3262			$$->next = NULL;
3263			$$->tail = $$;
3264		}
3265		;
3266
3267icmptype	: STRING			{
3268			const struct icmptypeent	*p;
3269
3270			if ((p = geticmptypebyname($1, AF_INET)) == NULL) {
3271				yyerror("unknown icmp-type %s", $1);
3272				free($1);
3273				YYERROR;
3274			}
3275			$$ = p->type + 1;
3276			free($1);
3277		}
3278		| NUMBER			{
3279			if ($1 < 0 || $1 > 255) {
3280				yyerror("illegal icmp-type %lu", $1);
3281				YYERROR;
3282			}
3283			$$ = $1 + 1;
3284		}
3285		;
3286
3287icmp6type	: STRING			{
3288			const struct icmptypeent	*p;
3289
3290			if ((p = geticmptypebyname($1, AF_INET6)) ==
3291			    NULL) {
3292				yyerror("unknown icmp6-type %s", $1);
3293				free($1);
3294				YYERROR;
3295			}
3296			$$ = p->type + 1;
3297			free($1);
3298		}
3299		| NUMBER			{
3300			if ($1 < 0 || $1 > 255) {
3301				yyerror("illegal icmp6-type %lu", $1);
3302				YYERROR;
3303			}
3304			$$ = $1 + 1;
3305		}
3306		;
3307
3308tos	: STRING			{
3309			int val;
3310			if (map_tos($1, &val))
3311				$$ = val;
3312			else if ($1[0] == '0' && $1[1] == 'x')
3313				$$ = strtoul($1, NULL, 16);
3314			else
3315				$$ = 256;		/* flag bad argument */
3316			if ($$ > 255) {
3317				yyerror("illegal tos value %s", $1);
3318				free($1);
3319				YYERROR;
3320			}
3321			free($1);
3322		}
3323		| NUMBER			{
3324			$$ = $1;
3325			if ($$ > 255) {
3326				yyerror("illegal tos value %s", $1);
3327				YYERROR;
3328			}
3329		}
3330		;
3331
3332sourcetrack	: /* empty */		{ $$ = PF_SRCTRACK; }
3333		| GLOBAL		{ $$ = PF_SRCTRACK_GLOBAL; }
3334		| RULE			{ $$ = PF_SRCTRACK_RULE; }
3335		;
3336
3337statelock	: IFBOUND {
3338			$$ = PFRULE_IFBOUND;
3339		}
3340		| FLOATING {
3341			$$ = 0;
3342		}
3343		;
3344
3345keep		: NO STATE			{
3346			$$.action = 0;
3347			$$.options = NULL;
3348		}
3349		| KEEP STATE state_opt_spec	{
3350			$$.action = PF_STATE_NORMAL;
3351			$$.options = $3;
3352		}
3353		| MODULATE STATE state_opt_spec {
3354			$$.action = PF_STATE_MODULATE;
3355			$$.options = $3;
3356		}
3357		| SYNPROXY STATE state_opt_spec {
3358			$$.action = PF_STATE_SYNPROXY;
3359			$$.options = $3;
3360		}
3361		;
3362
3363flush		: /* empty */			{ $$ = 0; }
3364		| FLUSH				{ $$ = PF_FLUSH; }
3365		| FLUSH GLOBAL			{
3366			$$ = PF_FLUSH | PF_FLUSH_GLOBAL;
3367		}
3368		;
3369
3370state_opt_spec	: '(' state_opt_list ')'	{ $$ = $2; }
3371		| /* empty */			{ $$ = NULL; }
3372		;
3373
3374state_opt_list	: state_opt_item		{ $$ = $1; }
3375		| state_opt_list comma state_opt_item {
3376			$1->tail->next = $3;
3377			$1->tail = $3;
3378			$$ = $1;
3379		}
3380		;
3381
3382state_opt_item	: MAXIMUM NUMBER		{
3383			if ($2 < 0 || $2 > UINT_MAX) {
3384				yyerror("only positive values permitted");
3385				YYERROR;
3386			}
3387			$$ = calloc(1, sizeof(struct node_state_opt));
3388			if ($$ == NULL)
3389				err(1, "state_opt_item: calloc");
3390			$$->type = PF_STATE_OPT_MAX;
3391			$$->data.max_states = $2;
3392			$$->next = NULL;
3393			$$->tail = $$;
3394		}
3395		| NOSYNC				{
3396			$$ = calloc(1, sizeof(struct node_state_opt));
3397			if ($$ == NULL)
3398				err(1, "state_opt_item: calloc");
3399			$$->type = PF_STATE_OPT_NOSYNC;
3400			$$->next = NULL;
3401			$$->tail = $$;
3402		}
3403		| MAXSRCSTATES NUMBER			{
3404			if ($2 < 0 || $2 > UINT_MAX) {
3405				yyerror("only positive values permitted");
3406				YYERROR;
3407			}
3408			$$ = calloc(1, sizeof(struct node_state_opt));
3409			if ($$ == NULL)
3410				err(1, "state_opt_item: calloc");
3411			$$->type = PF_STATE_OPT_MAX_SRC_STATES;
3412			$$->data.max_src_states = $2;
3413			$$->next = NULL;
3414			$$->tail = $$;
3415		}
3416		| MAXSRCCONN NUMBER			{
3417			if ($2 < 0 || $2 > UINT_MAX) {
3418				yyerror("only positive values permitted");
3419				YYERROR;
3420			}
3421			$$ = calloc(1, sizeof(struct node_state_opt));
3422			if ($$ == NULL)
3423				err(1, "state_opt_item: calloc");
3424			$$->type = PF_STATE_OPT_MAX_SRC_CONN;
3425			$$->data.max_src_conn = $2;
3426			$$->next = NULL;
3427			$$->tail = $$;
3428		}
3429		| MAXSRCCONNRATE NUMBER '/' NUMBER	{
3430			if ($2 < 0 || $2 > UINT_MAX ||
3431			    $4 < 0 || $4 > UINT_MAX) {
3432				yyerror("only positive values permitted");
3433				YYERROR;
3434			}
3435			$$ = calloc(1, sizeof(struct node_state_opt));
3436			if ($$ == NULL)
3437				err(1, "state_opt_item: calloc");
3438			$$->type = PF_STATE_OPT_MAX_SRC_CONN_RATE;
3439			$$->data.max_src_conn_rate.limit = $2;
3440			$$->data.max_src_conn_rate.seconds = $4;
3441			$$->next = NULL;
3442			$$->tail = $$;
3443		}
3444		| OVERLOAD '<' STRING '>' flush		{
3445			if (strlen($3) >= PF_TABLE_NAME_SIZE) {
3446				yyerror("table name '%s' too long", $3);
3447				free($3);
3448				YYERROR;
3449			}
3450			$$ = calloc(1, sizeof(struct node_state_opt));
3451			if ($$ == NULL)
3452				err(1, "state_opt_item: calloc");
3453			if (strlcpy($$->data.overload.tblname, $3,
3454			    PF_TABLE_NAME_SIZE) >= PF_TABLE_NAME_SIZE)
3455				errx(1, "state_opt_item: strlcpy");
3456			free($3);
3457			$$->type = PF_STATE_OPT_OVERLOAD;
3458			$$->data.overload.flush = $5;
3459			$$->next = NULL;
3460			$$->tail = $$;
3461		}
3462		| MAXSRCNODES NUMBER			{
3463			if ($2 < 0 || $2 > UINT_MAX) {
3464				yyerror("only positive values permitted");
3465				YYERROR;
3466			}
3467			$$ = calloc(1, sizeof(struct node_state_opt));
3468			if ($$ == NULL)
3469				err(1, "state_opt_item: calloc");
3470			$$->type = PF_STATE_OPT_MAX_SRC_NODES;
3471			$$->data.max_src_nodes = $2;
3472			$$->next = NULL;
3473			$$->tail = $$;
3474		}
3475		| SOURCETRACK sourcetrack {
3476			$$ = calloc(1, sizeof(struct node_state_opt));
3477			if ($$ == NULL)
3478				err(1, "state_opt_item: calloc");
3479			$$->type = PF_STATE_OPT_SRCTRACK;
3480			$$->data.src_track = $2;
3481			$$->next = NULL;
3482			$$->tail = $$;
3483		}
3484		| statelock {
3485			$$ = calloc(1, sizeof(struct node_state_opt));
3486			if ($$ == NULL)
3487				err(1, "state_opt_item: calloc");
3488			$$->type = PF_STATE_OPT_STATELOCK;
3489			$$->data.statelock = $1;
3490			$$->next = NULL;
3491			$$->tail = $$;
3492		}
3493		| SLOPPY {
3494			$$ = calloc(1, sizeof(struct node_state_opt));
3495			if ($$ == NULL)
3496				err(1, "state_opt_item: calloc");
3497			$$->type = PF_STATE_OPT_SLOPPY;
3498			$$->next = NULL;
3499			$$->tail = $$;
3500		}
3501		| PFLOW {
3502			$$ = calloc(1, sizeof(struct node_state_opt));
3503			if ($$ == NULL)
3504				err(1, "state_opt_item: calloc");
3505			$$->type = PF_STATE_OPT_PFLOW;
3506			$$->next = NULL;
3507			$$->tail = $$;
3508		}
3509		| STRING NUMBER			{
3510			int	i;
3511
3512			if ($2 < 0 || $2 > UINT_MAX) {
3513				yyerror("only positive values permitted");
3514				YYERROR;
3515			}
3516			for (i = 0; pf_timeouts[i].name &&
3517			    strcmp(pf_timeouts[i].name, $1); ++i)
3518				;	/* nothing */
3519			if (!pf_timeouts[i].name) {
3520				yyerror("illegal timeout name %s", $1);
3521				free($1);
3522				YYERROR;
3523			}
3524			if (strchr(pf_timeouts[i].name, '.') == NULL) {
3525				yyerror("illegal state timeout %s", $1);
3526				free($1);
3527				YYERROR;
3528			}
3529			free($1);
3530			$$ = calloc(1, sizeof(struct node_state_opt));
3531			if ($$ == NULL)
3532				err(1, "state_opt_item: calloc");
3533			$$->type = PF_STATE_OPT_TIMEOUT;
3534			$$->data.timeout.number = pf_timeouts[i].timeout;
3535			$$->data.timeout.seconds = $2;
3536			$$->next = NULL;
3537			$$->tail = $$;
3538		}
3539		;
3540
3541label		: STRING			{
3542			$$ = $1;
3543		}
3544		;
3545
3546qname		: STRING				{
3547			$$.qname = $1;
3548			$$.pqname = NULL;
3549		}
3550		| '(' STRING ')'			{
3551			$$.qname = $2;
3552			$$.pqname = NULL;
3553		}
3554		| '(' STRING comma STRING ')'	{
3555			$$.qname = $2;
3556			$$.pqname = $4;
3557		}
3558		;
3559
3560portstar	: numberstring			{
3561			if (parseport($1, &$$, PPORT_RANGE|PPORT_STAR) == -1) {
3562				free($1);
3563				YYERROR;
3564			}
3565			free($1);
3566		}
3567		;
3568
3569redirspec	: host				{ $$ = $1; }
3570		| '{' optnl redir_host_list '}'	{ $$ = $3; }
3571		;
3572
3573redir_host_list	: host optnl			{
3574			if ($1->addr.type != PF_ADDR_ADDRMASK) {
3575				free($1);
3576				yyerror("only addresses can be listed for"
3577				    "redirection pools ");
3578				YYERROR;
3579			}
3580			$$ = $1;
3581		}
3582		| redir_host_list comma host optnl {
3583			$1->tail->next = $3;
3584			$1->tail = $3->tail;
3585			$$ = $1;
3586		}
3587		;
3588
3589redirpool	: redirspec		{
3590			$$ = calloc(1, sizeof(struct redirection));
3591			if ($$ == NULL)
3592				err(1, "redirection: calloc");
3593			$$->host = $1;
3594			$$->rport.a = $$->rport.b = $$->rport.t = 0;
3595		}
3596		| redirspec PORT portstar	{
3597			$$ = calloc(1, sizeof(struct redirection));
3598			if ($$ == NULL)
3599				err(1, "redirection: calloc");
3600			$$->host = $1;
3601			$$->rport = $3;
3602		}
3603		;
3604
3605hashkey		: /* empty */
3606		{
3607			$$ = calloc(1, sizeof(struct pf_poolhashkey));
3608			if ($$ == NULL)
3609				err(1, "hashkey: calloc");
3610			$$->key32[0] = arc4random();
3611			$$->key32[1] = arc4random();
3612			$$->key32[2] = arc4random();
3613			$$->key32[3] = arc4random();
3614		}
3615		| string
3616		{
3617			if (!strncmp($1, "0x", 2)) {
3618				if (strlen($1) != 34) {
3619					free($1);
3620					yyerror("hex key must be 128 bits "
3621						"(32 hex digits) long");
3622					YYERROR;
3623				}
3624				$$ = calloc(1, sizeof(struct pf_poolhashkey));
3625				if ($$ == NULL)
3626					err(1, "hashkey: calloc");
3627
3628				if (sscanf($1, "0x%8x%8x%8x%8x",
3629				    &$$->key32[0], &$$->key32[1],
3630				    &$$->key32[2], &$$->key32[3]) != 4) {
3631					free($$);
3632					free($1);
3633					yyerror("invalid hex key");
3634					YYERROR;
3635				}
3636			} else {
3637				MD5_CTX	context;
3638
3639				$$ = calloc(1, sizeof(struct pf_poolhashkey));
3640				if ($$ == NULL)
3641					err(1, "hashkey: calloc");
3642				MD5Init(&context);
3643				MD5Update(&context, (unsigned char *)$1,
3644				    strlen($1));
3645				MD5Final((unsigned char *)$$, &context);
3646				HTONL($$->key32[0]);
3647				HTONL($$->key32[1]);
3648				HTONL($$->key32[2]);
3649				HTONL($$->key32[3]);
3650			}
3651			free($1);
3652		}
3653		;
3654
3655pool_opts	:	{ bzero(&pool_opts, sizeof pool_opts); }
3656		    pool_opts_l
3657			{ $$ = pool_opts; }
3658		| /* empty */	{
3659			bzero(&pool_opts, sizeof pool_opts);
3660			$$ = pool_opts;
3661		}
3662		;
3663
3664pool_opts_l	: pool_opts_l pool_opt
3665		| pool_opt
3666		;
3667
3668pool_opt	: BITMASK	{
3669			if (pool_opts.type) {
3670				yyerror("pool type cannot be redefined");
3671				YYERROR;
3672			}
3673			pool_opts.type =  PF_POOL_BITMASK;
3674		}
3675		| RANDOM	{
3676			if (pool_opts.type) {
3677				yyerror("pool type cannot be redefined");
3678				YYERROR;
3679			}
3680			pool_opts.type = PF_POOL_RANDOM;
3681		}
3682		| SOURCEHASH hashkey {
3683			if (pool_opts.type) {
3684				yyerror("pool type cannot be redefined");
3685				YYERROR;
3686			}
3687			pool_opts.type = PF_POOL_SRCHASH;
3688			pool_opts.key = $2;
3689		}
3690		| ROUNDROBIN	{
3691			if (pool_opts.type) {
3692				yyerror("pool type cannot be redefined");
3693				YYERROR;
3694			}
3695			pool_opts.type = PF_POOL_ROUNDROBIN;
3696		}
3697		| STATICPORT	{
3698			if (pool_opts.staticport) {
3699				yyerror("static-port cannot be redefined");
3700				YYERROR;
3701			}
3702			pool_opts.staticport = 1;
3703		}
3704		| STICKYADDRESS	{
3705			if (filter_opts.marker & POM_STICKYADDRESS) {
3706				yyerror("sticky-address cannot be redefined");
3707				YYERROR;
3708			}
3709			pool_opts.marker |= POM_STICKYADDRESS;
3710			pool_opts.opts |= PF_POOL_STICKYADDR;
3711		}
3712		;
3713
3714route_host	: STRING			{
3715			/* try to find @if0 address specs */
3716			if (strrchr($1, '@') != NULL) {
3717				if (($$ = host($1)) == NULL)	{
3718					yyerror("invalid host for route spec");
3719					YYERROR;
3720				}
3721				free($1);
3722			} else {
3723				$$ = calloc(1, sizeof(struct node_host));
3724				if ($$ == NULL)
3725					err(1, "route_host: calloc");
3726				$$->ifname = $1;
3727				$$->addr.type = PF_ADDR_NONE;
3728				set_ipmask($$, 128);
3729				$$->next = NULL;
3730				$$->tail = $$;
3731			}
3732		}
3733		| STRING '/' STRING 		{
3734			char	*buf;
3735
3736			if (asprintf(&buf, "%s/%s", $1, $3) == -1)
3737				err(1, "host: asprintf");
3738			free($1);
3739			if (($$ = host(buf)) == NULL)	{
3740				/* error. "any" is handled elsewhere */
3741				free(buf);
3742				yyerror("could not parse host specification");
3743				YYERROR;
3744			}
3745			free(buf);
3746		}
3747		| '<' STRING '>'	{
3748			if (strlen($2) >= PF_TABLE_NAME_SIZE) {
3749				yyerror("table name '%s' too long", $2);
3750				free($2);
3751				YYERROR;
3752			}
3753			$$ = calloc(1, sizeof(struct node_host));
3754			if ($$ == NULL)
3755				err(1, "host: calloc");
3756			$$->addr.type = PF_ADDR_TABLE;
3757			if (strlcpy($$->addr.v.tblname, $2,
3758			    sizeof($$->addr.v.tblname)) >=
3759			    sizeof($$->addr.v.tblname))
3760				errx(1, "host: strlcpy");
3761			free($2);
3762			$$->next = NULL;
3763			$$->tail = $$;
3764		}
3765		| dynaddr '/' NUMBER		{
3766			struct node_host	*n;
3767
3768			if ($3 < 0 || $3 > 128) {
3769				yyerror("bit number too big");
3770				YYERROR;
3771			}
3772			$$ = $1;
3773			for (n = $1; n != NULL; n = n->next)
3774				set_ipmask(n, $3);
3775		}
3776		| '(' STRING host ')'		{
3777			struct node_host	*n;
3778
3779			$$ = $3;
3780			/* XXX check masks, only full mask should be allowed */
3781			for (n = $3; n != NULL; n = n->next) {
3782				if ($$->ifname) {
3783					yyerror("cannot specify interface twice "
3784					    "in route spec");
3785					YYERROR;
3786				}
3787				if (($$->ifname = strdup($2)) == NULL)
3788					errx(1, "host: strdup");
3789			}
3790			free($2);
3791		}
3792		;
3793
3794route_host_list	: route_host optnl			{ $$ = $1; }
3795		| route_host_list comma route_host optnl {
3796			if ($1->af == 0)
3797				$1->af = $3->af;
3798			if ($1->af != $3->af) {
3799				yyerror("all pool addresses must be in the "
3800				    "same address family");
3801				YYERROR;
3802			}
3803			$1->tail->next = $3;
3804			$1->tail = $3->tail;
3805			$$ = $1;
3806		}
3807		;
3808
3809routespec	: route_host			{ $$ = $1; }
3810		| '{' optnl route_host_list '}'	{ $$ = $3; }
3811		;
3812
3813timeout_spec	: STRING NUMBER
3814		{
3815			if (check_rulestate(PFCTL_STATE_OPTION)) {
3816				free($1);
3817				YYERROR;
3818			}
3819			if ($2 < 0 || $2 > UINT_MAX) {
3820				yyerror("only positive values permitted");
3821				YYERROR;
3822			}
3823			if (pfctl_set_timeout(pf, $1, $2, 0) != 0) {
3824				yyerror("unknown timeout %s", $1);
3825				free($1);
3826				YYERROR;
3827			}
3828			free($1);
3829		}
3830		;
3831
3832timeout_list	: timeout_list comma timeout_spec optnl
3833		| timeout_spec optnl
3834		;
3835
3836limit_spec	: STRING NUMBER
3837		{
3838			if (check_rulestate(PFCTL_STATE_OPTION)) {
3839				free($1);
3840				YYERROR;
3841			}
3842			if ($2 < 0 || $2 > UINT_MAX) {
3843				yyerror("only positive values permitted");
3844				YYERROR;
3845			}
3846			if (pfctl_set_limit(pf, $1, $2) != 0) {
3847				yyerror("unable to set limit %s %u", $1, $2);
3848				free($1);
3849				YYERROR;
3850			}
3851			free($1);
3852		}
3853		;
3854
3855limit_list	: limit_list comma limit_spec optnl
3856		| limit_spec optnl
3857		;
3858
3859comma		: ','
3860		| /* empty */
3861		;
3862
3863yesno		: NO			{ $$ = 0; }
3864		| STRING		{
3865			if (!strcmp($1, "yes"))
3866				$$ = 1;
3867			else {
3868				yyerror("invalid value '%s', expected 'yes' "
3869				    "or 'no'", $1);
3870				free($1);
3871				YYERROR;
3872			}
3873			free($1);
3874		}
3875		;
3876
3877unaryop		: '='		{ $$ = PF_OP_EQ; }
3878		| NE		{ $$ = PF_OP_NE; }
3879		| LE		{ $$ = PF_OP_LE; }
3880		| '<'		{ $$ = PF_OP_LT; }
3881		| GE		{ $$ = PF_OP_GE; }
3882		| '>'		{ $$ = PF_OP_GT; }
3883		;
3884
3885%%
3886
3887int
3888yyerror(const char *fmt, ...)
3889{
3890	va_list		 ap;
3891
3892	file->errors++;
3893	va_start(ap, fmt);
3894	fprintf(stderr, "%s:%d: ", file->name, yylval.lineno);
3895	vfprintf(stderr, fmt, ap);
3896	fprintf(stderr, "\n");
3897	va_end(ap);
3898	return (0);
3899}
3900
3901int
3902disallow_table(struct node_host *h, const char *fmt)
3903{
3904	for (; h != NULL; h = h->next)
3905		if (h->addr.type == PF_ADDR_TABLE) {
3906			yyerror(fmt, h->addr.v.tblname);
3907			return (1);
3908		}
3909	return (0);
3910}
3911
3912int
3913disallow_urpf_failed(struct node_host *h, const char *fmt)
3914{
3915	for (; h != NULL; h = h->next)
3916		if (h->addr.type == PF_ADDR_URPFFAILED) {
3917			yyerror(fmt);
3918			return (1);
3919		}
3920	return (0);
3921}
3922
3923int
3924disallow_alias(struct node_host *h, const char *fmt)
3925{
3926	for (; h != NULL; h = h->next)
3927		if (DYNIF_MULTIADDR(h->addr)) {
3928			yyerror(fmt, h->addr.v.tblname);
3929			return (1);
3930		}
3931	return (0);
3932}
3933
3934int
3935rule_consistent(struct pf_rule *r, int anchor_call)
3936{
3937	int	problems = 0;
3938
3939	if (r->proto != IPPROTO_TCP && r->proto != IPPROTO_UDP &&
3940	    (r->src.port_op || r->dst.port_op)) {
3941		yyerror("port only applies to tcp/udp");
3942		problems++;
3943	}
3944	if (r->proto != IPPROTO_ICMP && r->proto != IPPROTO_ICMPV6 &&
3945	    (r->type || r->code)) {
3946		yyerror("icmp-type/code only applies to icmp");
3947		problems++;
3948	}
3949	if (!r->af && (r->type || r->code)) {
3950		yyerror("must indicate address family with icmp-type/code");
3951		problems++;
3952	}
3953	if (r->overload_tblname[0] &&
3954	    r->max_src_conn == 0 && r->max_src_conn_rate.seconds == 0) {
3955		yyerror("'overload' requires 'max-src-conn' "
3956		    "or 'max-src-conn-rate'");
3957		problems++;
3958	}
3959	if ((r->proto == IPPROTO_ICMP && r->af == AF_INET6) ||
3960	    (r->proto == IPPROTO_ICMPV6 && r->af == AF_INET)) {
3961		yyerror("proto %s doesn't match address family %s",
3962		    r->proto == IPPROTO_ICMP ? "icmp" : "icmp6",
3963		    r->af == AF_INET ? "inet" : "inet6");
3964		problems++;
3965	}
3966	if (r->allow_opts && r->action != PF_PASS) {
3967		yyerror("allow-opts can only be specified for pass rules");
3968		problems++;
3969	}
3970	if (r->rule_flag & PFRULE_FRAGMENT && (r->src.port_op ||
3971	    r->dst.port_op || r->flagset || r->type || r->code)) {
3972		yyerror("fragments can be filtered only on IP header fields");
3973		problems++;
3974	}
3975	if (r->rule_flag & PFRULE_RETURNRST && r->proto != IPPROTO_TCP) {
3976		yyerror("return-rst can only be applied to TCP rules");
3977		problems++;
3978	}
3979	if (r->max_src_nodes && !(r->rule_flag & PFRULE_RULESRCTRACK)) {
3980		yyerror("max-src-nodes requires 'source-track rule'");
3981		problems++;
3982	}
3983	if (r->action != PF_PASS && r->keep_state) {
3984		yyerror("keep state is great, but only for pass rules");
3985		problems++;
3986	}
3987	if (r->rule_flag & PFRULE_STATESLOPPY &&
3988	    (r->keep_state == PF_STATE_MODULATE ||
3989	    r->keep_state == PF_STATE_SYNPROXY)) {
3990		yyerror("sloppy state matching cannot be used with "
3991		    "synproxy state or modulate state");
3992		problems++;
3993	}
3994	if ((r->nat.addr.type != PF_ADDR_NONE ||
3995	    r->rdr.addr.type != PF_ADDR_NONE) &&
3996	    r->action != PF_MATCH && !r->keep_state) {
3997		yyerror("nat-to and rdr-to require keep state");
3998		problems++;
3999	}
4000	if (r->nat.addr.type != PF_ADDR_NONE && r->direction != PF_OUT) {
4001		yyerror("nat-to can only be used outbound");
4002		problems++;
4003	}
4004	if (r->rdr.addr.type != PF_ADDR_NONE && r->direction != PF_IN) {
4005		yyerror("rdr-to can only be used inbound");
4006		problems++;
4007	}
4008
4009	/* match rules rules */
4010	if (r->action == PF_MATCH) {
4011		if (r->divert.port) {
4012			yyerror("divert is not supported on match rules");
4013			problems++;
4014		}
4015		if (r->divert_packet.port) {
4016			yyerror("divert is not supported on match rules");
4017			problems++;
4018		}
4019		if (r->rt) {
4020			yyerror("route-to, reply-to, dup-to and fastroute "
4021			   "must not be used on match rules");
4022			problems++;
4023		}
4024	}
4025	return (-problems);
4026}
4027
4028int
4029process_tabledef(char *name, struct table_opts *opts)
4030{
4031	struct pfr_buffer	 ab;
4032	struct node_tinit	*ti;
4033
4034	bzero(&ab, sizeof(ab));
4035	ab.pfrb_type = PFRB_ADDRS;
4036	SIMPLEQ_FOREACH(ti, &opts->init_nodes, entries) {
4037		if (ti->file)
4038			if (pfr_buf_load(&ab, ti->file, 0, append_addr)) {
4039				if (errno)
4040					yyerror("cannot load \"%s\": %s",
4041					    ti->file, strerror(errno));
4042				else
4043					yyerror("file \"%s\" contains bad data",
4044					    ti->file);
4045				goto _error;
4046			}
4047		if (ti->host)
4048			if (append_addr_host(&ab, ti->host, 0, 0)) {
4049				yyerror("cannot create address buffer: %s",
4050				    strerror(errno));
4051				goto _error;
4052			}
4053	}
4054	if (pf->opts & PF_OPT_VERBOSE)
4055		print_tabledef(name, opts->flags, opts->init_addr,
4056		    &opts->init_nodes);
4057	if (!(pf->opts & PF_OPT_NOACTION) &&
4058	    pfctl_define_table(name, opts->flags, opts->init_addr,
4059	    pf->anchor->name, &ab, pf->anchor->ruleset.tticket)) {
4060		yyerror("cannot define table %s: %s", name,
4061		    pfr_strerror(errno));
4062		goto _error;
4063	}
4064	pf->tdirty = 1;
4065	pfr_buf_clear(&ab);
4066	return (0);
4067_error:
4068	pfr_buf_clear(&ab);
4069	return (-1);
4070}
4071
4072struct keywords {
4073	const char	*k_name;
4074	int		 k_val;
4075};
4076
4077/* macro gore, but you should've seen the prior indentation nightmare... */
4078
4079#define FREE_LIST(T,r) \
4080	do { \
4081		T *p, *node = r; \
4082		while (node != NULL) { \
4083			p = node; \
4084			node = node->next; \
4085			free(p); \
4086		} \
4087	} while (0)
4088
4089#define LOOP_THROUGH(T,n,r,C) \
4090	do { \
4091		T *n; \
4092		if (r == NULL) { \
4093			r = calloc(1, sizeof(T)); \
4094			if (r == NULL) \
4095				err(1, "LOOP: calloc"); \
4096			r->next = NULL; \
4097		} \
4098		n = r; \
4099		while (n != NULL) { \
4100			do { \
4101				C; \
4102			} while (0); \
4103			n = n->next; \
4104		} \
4105	} while (0)
4106
4107void
4108expand_label_str(char *label, size_t len, const char *srch, const char *repl)
4109{
4110	char *tmp;
4111	char *p, *q;
4112
4113	if ((tmp = calloc(1, len)) == NULL)
4114		err(1, "expand_label_str: calloc");
4115	p = q = label;
4116	while ((q = strstr(p, srch)) != NULL) {
4117		*q = '\0';
4118		if ((strlcat(tmp, p, len) >= len) ||
4119		    (strlcat(tmp, repl, len) >= len))
4120			errx(1, "expand_label: label too long");
4121		q += strlen(srch);
4122		p = q;
4123	}
4124	if (strlcat(tmp, p, len) >= len)
4125		errx(1, "expand_label: label too long");
4126	strlcpy(label, tmp, len);	/* always fits */
4127	free(tmp);
4128}
4129
4130void
4131expand_label_if(const char *name, char *label, size_t len, const char *ifname)
4132{
4133	if (strstr(label, name) != NULL) {
4134		if (!*ifname)
4135			expand_label_str(label, len, name, "any");
4136		else
4137			expand_label_str(label, len, name, ifname);
4138	}
4139}
4140
4141void
4142expand_label_addr(const char *name, char *label, size_t len, sa_family_t af,
4143    struct node_host *h)
4144{
4145	char tmp[64], tmp_not[66];
4146
4147	if (strstr(label, name) != NULL) {
4148		switch (h->addr.type) {
4149		case PF_ADDR_DYNIFTL:
4150			snprintf(tmp, sizeof(tmp), "(%s)", h->addr.v.ifname);
4151			break;
4152		case PF_ADDR_TABLE:
4153			snprintf(tmp, sizeof(tmp), "<%s>", h->addr.v.tblname);
4154			break;
4155		case PF_ADDR_NOROUTE:
4156			snprintf(tmp, sizeof(tmp), "no-route");
4157			break;
4158		case PF_ADDR_URPFFAILED:
4159			snprintf(tmp, sizeof(tmp), "urpf-failed");
4160			break;
4161		case PF_ADDR_ADDRMASK:
4162			if (!af || (PF_AZERO(&h->addr.v.a.addr, af) &&
4163			    PF_AZERO(&h->addr.v.a.mask, af)))
4164				snprintf(tmp, sizeof(tmp), "any");
4165			else {
4166				char	a[48];
4167				int	bits;
4168
4169				if (inet_ntop(af, &h->addr.v.a.addr, a,
4170				    sizeof(a)) == NULL)
4171					snprintf(tmp, sizeof(tmp), "?");
4172				else {
4173					bits = unmask(&h->addr.v.a.mask, af);
4174					if ((af == AF_INET && bits < 32) ||
4175					    (af == AF_INET6 && bits < 128))
4176						snprintf(tmp, sizeof(tmp),
4177						    "%s/%d", a, bits);
4178					else
4179						snprintf(tmp, sizeof(tmp),
4180						    "%s", a);
4181				}
4182			}
4183			break;
4184		default:
4185			snprintf(tmp, sizeof(tmp), "?");
4186			break;
4187		}
4188
4189		if (h->not) {
4190			snprintf(tmp_not, sizeof(tmp_not), "! %s", tmp);
4191			expand_label_str(label, len, name, tmp_not);
4192		} else
4193			expand_label_str(label, len, name, tmp);
4194	}
4195}
4196
4197void
4198expand_label_port(const char *name, char *label, size_t len,
4199    struct node_port *port)
4200{
4201	char	 a1[6], a2[6], op[13] = "";
4202
4203	if (strstr(label, name) != NULL) {
4204		snprintf(a1, sizeof(a1), "%u", ntohs(port->port[0]));
4205		snprintf(a2, sizeof(a2), "%u", ntohs(port->port[1]));
4206		if (!port->op)
4207			;
4208		else if (port->op == PF_OP_IRG)
4209			snprintf(op, sizeof(op), "%s><%s", a1, a2);
4210		else if (port->op == PF_OP_XRG)
4211			snprintf(op, sizeof(op), "%s<>%s", a1, a2);
4212		else if (port->op == PF_OP_EQ)
4213			snprintf(op, sizeof(op), "%s", a1);
4214		else if (port->op == PF_OP_NE)
4215			snprintf(op, sizeof(op), "!=%s", a1);
4216		else if (port->op == PF_OP_LT)
4217			snprintf(op, sizeof(op), "<%s", a1);
4218		else if (port->op == PF_OP_LE)
4219			snprintf(op, sizeof(op), "<=%s", a1);
4220		else if (port->op == PF_OP_GT)
4221			snprintf(op, sizeof(op), ">%s", a1);
4222		else if (port->op == PF_OP_GE)
4223			snprintf(op, sizeof(op), ">=%s", a1);
4224		expand_label_str(label, len, name, op);
4225	}
4226}
4227
4228void
4229expand_label_proto(const char *name, char *label, size_t len, u_int8_t proto)
4230{
4231	struct protoent *pe;
4232	char n[4];
4233
4234	if (strstr(label, name) != NULL) {
4235		pe = getprotobynumber(proto);
4236		if (pe != NULL)
4237			expand_label_str(label, len, name, pe->p_name);
4238		else {
4239			snprintf(n, sizeof(n), "%u", proto);
4240			expand_label_str(label, len, name, n);
4241		}
4242	}
4243}
4244
4245void
4246expand_label_nr(const char *name, char *label, size_t len)
4247{
4248	char n[11];
4249
4250	if (strstr(label, name) != NULL) {
4251		snprintf(n, sizeof(n), "%u", pf->anchor->match);
4252		expand_label_str(label, len, name, n);
4253	}
4254}
4255
4256void
4257expand_label(char *label, size_t len, const char *ifname, sa_family_t af,
4258    struct node_host *src_host, struct node_port *src_port,
4259    struct node_host *dst_host, struct node_port *dst_port,
4260    u_int8_t proto)
4261{
4262	expand_label_if("$if", label, len, ifname);
4263	expand_label_addr("$srcaddr", label, len, af, src_host);
4264	expand_label_addr("$dstaddr", label, len, af, dst_host);
4265	expand_label_port("$srcport", label, len, src_port);
4266	expand_label_port("$dstport", label, len, dst_port);
4267	expand_label_proto("$proto", label, len, proto);
4268	expand_label_nr("$nr", label, len);
4269}
4270
4271int
4272expand_altq(struct pf_altq *a, struct node_if *interfaces,
4273    struct node_queue *nqueues, struct node_queue_bw bwspec,
4274    struct node_queue_opt *opts)
4275{
4276	struct pf_altq		 pa, pb;
4277	char			 qname[PF_QNAME_SIZE];
4278	struct node_queue	*n;
4279	struct node_queue_bw	 bw;
4280	int			 errs = 0;
4281
4282	if ((pf->loadopt & PFCTL_FLAG_ALTQ) == 0) {
4283		FREE_LIST(struct node_if, interfaces);
4284		FREE_LIST(struct node_queue, nqueues);
4285		return (0);
4286	}
4287
4288	LOOP_THROUGH(struct node_if, interface, interfaces,
4289		memcpy(&pa, a, sizeof(struct pf_altq));
4290		if (strlcpy(pa.ifname, interface->ifname,
4291		    sizeof(pa.ifname)) >= sizeof(pa.ifname))
4292			errx(1, "expand_altq: strlcpy");
4293
4294		if (interface->not) {
4295			yyerror("altq on ! <interface> is not supported");
4296			errs++;
4297		} else {
4298			if (eval_pfaltq(pf, &pa, &bwspec, opts))
4299				errs++;
4300			else
4301				if (pfctl_add_altq(pf, &pa))
4302					errs++;
4303
4304			if (pf->opts & PF_OPT_VERBOSE) {
4305				print_altq(&pf->paltq->altq, 0,
4306				    &bwspec, opts);
4307				if (nqueues && nqueues->tail) {
4308					printf("queue { ");
4309					LOOP_THROUGH(struct node_queue, queue,
4310					    nqueues,
4311						printf("%s ",
4312						    queue->queue);
4313					);
4314					printf("}");
4315				}
4316				printf("\n");
4317			}
4318
4319			if (pa.scheduler == ALTQT_CBQ ||
4320			    pa.scheduler == ALTQT_HFSC) {
4321				/* now create a root queue */
4322				memset(&pb, 0, sizeof(struct pf_altq));
4323				if (strlcpy(qname, "root_", sizeof(qname)) >=
4324				    sizeof(qname))
4325					errx(1, "expand_altq: strlcpy");
4326				if (strlcat(qname, interface->ifname,
4327				    sizeof(qname)) >= sizeof(qname))
4328					errx(1, "expand_altq: strlcat");
4329				if (strlcpy(pb.qname, qname,
4330				    sizeof(pb.qname)) >= sizeof(pb.qname))
4331					errx(1, "expand_altq: strlcpy");
4332				if (strlcpy(pb.ifname, interface->ifname,
4333				    sizeof(pb.ifname)) >= sizeof(pb.ifname))
4334					errx(1, "expand_altq: strlcpy");
4335				pb.qlimit = pa.qlimit;
4336				pb.scheduler = pa.scheduler;
4337				bw.bw_absolute = pa.ifbandwidth;
4338				bw.bw_percent = 0;
4339				if (eval_pfqueue(pf, &pb, &bw, opts))
4340					errs++;
4341				else
4342					if (pfctl_add_altq(pf, &pb))
4343						errs++;
4344			}
4345
4346			LOOP_THROUGH(struct node_queue, queue, nqueues,
4347				n = calloc(1, sizeof(struct node_queue));
4348				if (n == NULL)
4349					err(1, "expand_altq: calloc");
4350				if (pa.scheduler == ALTQT_CBQ ||
4351				    pa.scheduler == ALTQT_HFSC)
4352					if (strlcpy(n->parent, qname,
4353					    sizeof(n->parent)) >=
4354					    sizeof(n->parent))
4355						errx(1, "expand_altq: strlcpy");
4356				if (strlcpy(n->queue, queue->queue,
4357				    sizeof(n->queue)) >= sizeof(n->queue))
4358					errx(1, "expand_altq: strlcpy");
4359				if (strlcpy(n->ifname, interface->ifname,
4360				    sizeof(n->ifname)) >= sizeof(n->ifname))
4361					errx(1, "expand_altq: strlcpy");
4362				n->scheduler = pa.scheduler;
4363				n->next = NULL;
4364				n->tail = n;
4365				if (queues == NULL)
4366					queues = n;
4367				else {
4368					queues->tail->next = n;
4369					queues->tail = n;
4370				}
4371			);
4372		}
4373	);
4374	FREE_LIST(struct node_if, interfaces);
4375	FREE_LIST(struct node_queue, nqueues);
4376
4377	return (errs);
4378}
4379
4380int
4381expand_queue(struct pf_altq *a, struct node_if *interfaces,
4382    struct node_queue *nqueues, struct node_queue_bw bwspec,
4383    struct node_queue_opt *opts)
4384{
4385	struct node_queue	*n, *nq;
4386	struct pf_altq		 pa;
4387	u_int8_t		 found = 0;
4388	u_int8_t		 errs = 0;
4389
4390	if ((pf->loadopt & PFCTL_FLAG_ALTQ) == 0) {
4391		FREE_LIST(struct node_queue, nqueues);
4392		return (0);
4393	}
4394
4395	if (queues == NULL) {
4396		yyerror("queue %s has no parent", a->qname);
4397		FREE_LIST(struct node_queue, nqueues);
4398		return (1);
4399	}
4400
4401	LOOP_THROUGH(struct node_if, interface, interfaces,
4402		LOOP_THROUGH(struct node_queue, tqueue, queues,
4403			if (!strncmp(a->qname, tqueue->queue, PF_QNAME_SIZE) &&
4404			    (interface->ifname[0] == 0 ||
4405			    (!interface->not && !strncmp(interface->ifname,
4406			    tqueue->ifname, IFNAMSIZ)) ||
4407			    (interface->not && strncmp(interface->ifname,
4408			    tqueue->ifname, IFNAMSIZ)))) {
4409				/* found ourself in queues */
4410				found++;
4411
4412				memcpy(&pa, a, sizeof(struct pf_altq));
4413
4414				if (pa.scheduler != ALTQT_NONE &&
4415				    pa.scheduler != tqueue->scheduler) {
4416					yyerror("exactly one scheduler type "
4417					    "per interface allowed");
4418					return (1);
4419				}
4420				pa.scheduler = tqueue->scheduler;
4421
4422				/* scheduler dependent error checking */
4423				switch (pa.scheduler) {
4424				case ALTQT_PRIQ:
4425					if (nqueues != NULL) {
4426						yyerror("priq queues cannot "
4427						    "have child queues");
4428						return (1);
4429					}
4430					if (bwspec.bw_absolute > 0 ||
4431					    bwspec.bw_percent < 100) {
4432						yyerror("priq doesn't take "
4433						    "bandwidth");
4434						return (1);
4435					}
4436					break;
4437				default:
4438					break;
4439				}
4440
4441				if (strlcpy(pa.ifname, tqueue->ifname,
4442				    sizeof(pa.ifname)) >= sizeof(pa.ifname))
4443					errx(1, "expand_queue: strlcpy");
4444				if (strlcpy(pa.parent, tqueue->parent,
4445				    sizeof(pa.parent)) >= sizeof(pa.parent))
4446					errx(1, "expand_queue: strlcpy");
4447
4448				if (eval_pfqueue(pf, &pa, &bwspec, opts))
4449					errs++;
4450				else
4451					if (pfctl_add_altq(pf, &pa))
4452						errs++;
4453
4454				for (nq = nqueues; nq != NULL; nq = nq->next) {
4455					if (!strcmp(a->qname, nq->queue)) {
4456						yyerror("queue cannot have "
4457						    "itself as child");
4458						errs++;
4459						continue;
4460					}
4461					n = calloc(1,
4462					    sizeof(struct node_queue));
4463					if (n == NULL)
4464						err(1, "expand_queue: calloc");
4465					if (strlcpy(n->parent, a->qname,
4466					    sizeof(n->parent)) >=
4467					    sizeof(n->parent))
4468						errx(1, "expand_queue strlcpy");
4469					if (strlcpy(n->queue, nq->queue,
4470					    sizeof(n->queue)) >=
4471					    sizeof(n->queue))
4472						errx(1, "expand_queue strlcpy");
4473					if (strlcpy(n->ifname, tqueue->ifname,
4474					    sizeof(n->ifname)) >=
4475					    sizeof(n->ifname))
4476						errx(1, "expand_queue strlcpy");
4477					n->scheduler = tqueue->scheduler;
4478					n->next = NULL;
4479					n->tail = n;
4480					if (queues == NULL)
4481						queues = n;
4482					else {
4483						queues->tail->next = n;
4484						queues->tail = n;
4485					}
4486				}
4487				if ((pf->opts & PF_OPT_VERBOSE) && (
4488				    (found == 1 && interface->ifname[0] == 0) ||
4489				    (found > 0 && interface->ifname[0] != 0))) {
4490					print_queue(&pf->paltq->altq, 0,
4491					    &bwspec, interface->ifname[0] != 0,
4492					    opts);
4493					if (nqueues && nqueues->tail) {
4494						printf("{ ");
4495						LOOP_THROUGH(struct node_queue,
4496						    queue, nqueues,
4497							printf("%s ",
4498							    queue->queue);
4499						);
4500						printf("}");
4501					}
4502					printf("\n");
4503				}
4504			}
4505		);
4506	);
4507
4508	FREE_LIST(struct node_queue, nqueues);
4509	FREE_LIST(struct node_if, interfaces);
4510
4511	if (!found) {
4512		yyerror("queue %s has no parent", a->qname);
4513		errs++;
4514	}
4515
4516	if (errs)
4517		return (1);
4518	else
4519		return (0);
4520}
4521
4522int
4523collapse_redirspec(struct pf_pool *rpool, struct pf_rule *r,
4524    struct redirspec *rs, u_int8_t allow_if)
4525{
4526	struct pf_opt_tbl *tbl = NULL;
4527	struct node_host *h;
4528	struct pf_rule_addr ra;
4529	int	i = 0;
4530
4531
4532	if (!rs || !rs->rdr || rs->rdr->host == NULL) {
4533		rpool->addr.type = PF_ADDR_NONE;
4534		return (0);
4535	}
4536
4537	/* count matching addresses */
4538	for (h = rs->rdr->host; h != NULL; h = h->next) {
4539		if (!r->af || !h->af || h->af == r->af) {
4540			i++;
4541			if (h->af && !r->af)
4542				r->af = h->af;
4543		}
4544	}
4545
4546	if (i == 0) {		/* no pool address */
4547		yyerror("af mismatch in %s spec",
4548		    allow_if ? "routing" : "translation");
4549		return (1);
4550	} else if (i == 1) {	/* only one address */
4551		for (h = rs->rdr->host; h != NULL; h = h->next)
4552			if (!h->af || !r->af || r->af == h->af)
4553				break;
4554		rpool->addr = h->addr;
4555		if (!allow_if && h->ifname) {
4556			yyerror("@if not permitted for translation");
4557			return (1);
4558		}
4559		if (h->ifname && strlcpy(rpool->ifname, h->ifname,
4560		    sizeof(rpool->ifname)) >= sizeof(rpool->ifname))
4561			errx(1, "collapse_redirspec: strlcpy");
4562
4563		return (0);
4564	} else {		/* more than one address */
4565		if (rs->pool_opts.type &&
4566		     rs->pool_opts.type != PF_POOL_ROUNDROBIN) {
4567			yyerror("only round-robin valid for multiple "
4568			    "translation or routing addresses");
4569			return (1);
4570		}
4571		for (h = rs->rdr->host; h != NULL; h = h->next) {
4572			if (r->af != h->af)
4573				continue;
4574			if (h->addr.type != PF_ADDR_ADDRMASK &&
4575			    h->addr.type != PF_ADDR_NONE) {
4576				yyerror("multiple tables or dynamic interfaces "
4577				    "not supported for translation or routing");
4578				return (1);
4579			}
4580			if (!allow_if && h->ifname) {
4581				yyerror("@if not permitted for translation");
4582				return (1);
4583			}
4584			memset(&ra, 0, sizeof(ra));
4585			ra.addr = h->addr;
4586			if (add_opt_table(pf, &tbl,
4587			    h->af, &ra, h->ifname))
4588				return (1);
4589                }
4590	}
4591	if (tbl) {
4592		if ((pf->opts & PF_OPT_NOACTION) == 0 &&
4593		     pf_opt_create_table(pf, tbl))
4594				return (1);
4595
4596		pf->tdirty = 1;
4597
4598		if (pf->opts & PF_OPT_VERBOSE)
4599			print_tabledef(tbl->pt_name, PFR_TFLAG_CONST,
4600			    1, &tbl->pt_nodes);
4601
4602		memset(&rpool->addr, 0, sizeof(rpool->addr));
4603		rpool->addr.type = PF_ADDR_TABLE;
4604		strlcpy(rpool->addr.v.tblname, tbl->pt_name,
4605		    sizeof(rpool->addr.v.tblname));
4606
4607		pfr_buf_clear(tbl->pt_buf);
4608		free(tbl->pt_buf);
4609		tbl->pt_buf = NULL;
4610		free(tbl);
4611	}
4612	return (0);
4613}
4614
4615
4616int
4617apply_redirspec(struct pf_pool *rpool, struct pf_rule *r, struct redirspec *rs,
4618    int isrdr, struct node_port *np)
4619{
4620	if (!rs || !rs->rdr)
4621		return (0);
4622
4623	rpool->proxy_port[0] = ntohs(rs->rdr->rport.a);
4624
4625	if (isrdr) {
4626		if (!rs->rdr->rport.b && rs->rdr->rport.t && np->port != NULL) {
4627			rpool->proxy_port[1] = ntohs(rs->rdr->rport.a) +
4628			    (ntohs(np->port[1]) - ntohs(np->port[0]));
4629		} else
4630			rpool->proxy_port[1] = ntohs(rs->rdr->rport.b);
4631	} else {
4632		rpool->proxy_port[1] = ntohs(rs->rdr->rport.b);
4633		if (!rpool->proxy_port[0] && !rpool->proxy_port[1]) {
4634			rpool->proxy_port[0] = PF_NAT_PROXY_PORT_LOW;
4635			rpool->proxy_port[1] = PF_NAT_PROXY_PORT_HIGH;
4636		} else if (!rpool->proxy_port[1])
4637			rpool->proxy_port[1] = rpool->proxy_port[0];
4638	}
4639
4640	rpool->opts = rs->pool_opts.type;
4641	if (rpool->addr.type == PF_ADDR_TABLE ||
4642	    DYNIF_MULTIADDR(rpool->addr))
4643		rpool->opts |= PF_POOL_ROUNDROBIN;
4644
4645	if (rs->pool_opts.key != NULL)
4646		memcpy(&rpool->key, rs->pool_opts.key,
4647		    sizeof(struct pf_poolhashkey));
4648
4649	if (rs->pool_opts.opts)
4650		rpool->opts |= rs->pool_opts.opts;
4651
4652	if (rs->pool_opts.staticport) {
4653		if (isrdr) {
4654			yyerror("the 'static-port' option is only valid with "
4655			    "nat rules");
4656			return (1);
4657		}
4658		if (rpool->proxy_port[0] != PF_NAT_PROXY_PORT_LOW &&
4659		    rpool->proxy_port[1] != PF_NAT_PROXY_PORT_HIGH) {
4660			yyerror("the 'static-port' option can't be used when "
4661			    "specifying a port range");
4662			return (1);
4663		}
4664		rpool->proxy_port[0] = 0;
4665		rpool->proxy_port[1] = 0;
4666	}
4667
4668	return (0);
4669}
4670
4671
4672void
4673expand_rule(struct pf_rule *r, int keeprule, struct node_if *interfaces,
4674    struct redirspec *nat, struct redirspec *rdr, struct redirspec *rroute,
4675    struct node_proto *protos, struct node_os *src_oses,
4676    struct node_host *src_hosts, struct node_port *src_ports,
4677    struct node_host *dst_hosts, struct node_port *dst_ports,
4678    struct node_uid *uids, struct node_gid *gids, struct node_if *rcv,
4679    struct node_icmp *icmp_types, const char *anchor_call)
4680{
4681	sa_family_t		 af = r->af;
4682	int			 added = 0, error = 0;
4683	char			 ifname[IF_NAMESIZE];
4684	char			 label[PF_RULE_LABEL_SIZE];
4685	char			 tagname[PF_TAG_NAME_SIZE];
4686	char			 match_tagname[PF_TAG_NAME_SIZE];
4687	u_int8_t		 flags, flagset, keep_state;
4688	struct node_host	*srch, *dsth;
4689	struct redirspec	 binat;
4690	struct pf_rule		 rb;
4691	int			 dir = r->direction;
4692
4693	if (strlcpy(label, r->label, sizeof(label)) >= sizeof(label))
4694		errx(1, "expand_rule: strlcpy");
4695	if (strlcpy(tagname, r->tagname, sizeof(tagname)) >= sizeof(tagname))
4696		errx(1, "expand_rule: strlcpy");
4697	if (strlcpy(match_tagname, r->match_tagname, sizeof(match_tagname)) >=
4698	    sizeof(match_tagname))
4699		errx(1, "expand_rule: strlcpy");
4700	flags = r->flags;
4701	flagset = r->flagset;
4702	keep_state = r->keep_state;
4703
4704	r->src.addr.type = r->dst.addr.type = PF_ADDR_ADDRMASK;
4705
4706	LOOP_THROUGH(struct node_if, interface, interfaces,
4707	LOOP_THROUGH(struct node_proto, proto, protos,
4708	LOOP_THROUGH(struct node_icmp, icmp_type, icmp_types,
4709	LOOP_THROUGH(struct node_host, src_host, src_hosts,
4710	LOOP_THROUGH(struct node_port, src_port, src_ports,
4711	LOOP_THROUGH(struct node_os, src_os, src_oses,
4712	LOOP_THROUGH(struct node_host, dst_host, dst_hosts,
4713	LOOP_THROUGH(struct node_port, dst_port, dst_ports,
4714	LOOP_THROUGH(struct node_uid, uid, uids,
4715	LOOP_THROUGH(struct node_gid, gid, gids,
4716
4717		r->af = af;
4718
4719		error += collapse_redirspec(&r->rdr, r, rdr, 0);
4720		error += collapse_redirspec(&r->nat, r, nat, 0);
4721		error += collapse_redirspec(&r->route, r, rroute, 1);
4722
4723		/* disallow @if in from or to for the time being */
4724		if ((src_host->addr.type == PF_ADDR_ADDRMASK &&
4725		    src_host->ifname) ||
4726		    (dst_host->addr.type == PF_ADDR_ADDRMASK &&
4727		    dst_host->ifname)) {
4728			yyerror("@if syntax not permitted in from or to");
4729			error++;
4730		}
4731		/* for link-local IPv6 address, interface must match up */
4732		if ((r->af && src_host->af && r->af != src_host->af) ||
4733		    (r->af && dst_host->af && r->af != dst_host->af) ||
4734		    (src_host->af && dst_host->af &&
4735		    src_host->af != dst_host->af) ||
4736		    (src_host->ifindex && dst_host->ifindex &&
4737		    src_host->ifindex != dst_host->ifindex) ||
4738		    (src_host->ifindex && *interface->ifname &&
4739		    src_host->ifindex != if_nametoindex(interface->ifname)) ||
4740		    (dst_host->ifindex && *interface->ifname &&
4741		    dst_host->ifindex != if_nametoindex(interface->ifname)))
4742			continue;
4743		if (!r->af && src_host->af)
4744			r->af = src_host->af;
4745		else if (!r->af && dst_host->af)
4746			r->af = dst_host->af;
4747
4748		if (*interface->ifname)
4749			strlcpy(r->ifname, interface->ifname,
4750			    sizeof(r->ifname));
4751		else if (if_indextoname(src_host->ifindex, ifname))
4752			strlcpy(r->ifname, ifname, sizeof(r->ifname));
4753		else if (if_indextoname(dst_host->ifindex, ifname))
4754			strlcpy(r->ifname, ifname, sizeof(r->ifname));
4755		else
4756			memset(r->ifname, '\0', sizeof(r->ifname));
4757
4758		if (strlcpy(r->label, label, sizeof(r->label)) >=
4759		    sizeof(r->label))
4760			errx(1, "expand_rule: strlcpy");
4761		if (strlcpy(r->tagname, tagname, sizeof(r->tagname)) >=
4762		    sizeof(r->tagname))
4763			errx(1, "expand_rule: strlcpy");
4764		if (strlcpy(r->match_tagname, match_tagname,
4765		    sizeof(r->match_tagname)) >= sizeof(r->match_tagname))
4766			errx(1, "expand_rule: strlcpy");
4767		expand_label(r->label, PF_RULE_LABEL_SIZE, r->ifname, r->af,
4768		    src_host, src_port, dst_host, dst_port, proto->proto);
4769		expand_label(r->tagname, PF_TAG_NAME_SIZE, r->ifname, r->af,
4770		    src_host, src_port, dst_host, dst_port, proto->proto);
4771		expand_label(r->match_tagname, PF_TAG_NAME_SIZE, r->ifname,
4772		    r->af, src_host, src_port, dst_host, dst_port,
4773		    proto->proto);
4774
4775		error += check_netmask(src_host, r->af);
4776		error += check_netmask(dst_host, r->af);
4777
4778		r->ifnot = interface->not;
4779		r->proto = proto->proto;
4780		r->src.addr = src_host->addr;
4781		r->src.neg = src_host->not;
4782		r->src.port[0] = src_port->port[0];
4783		r->src.port[1] = src_port->port[1];
4784		r->src.port_op = src_port->op;
4785		r->dst.addr = dst_host->addr;
4786		r->dst.neg = dst_host->not;
4787		r->dst.port[0] = dst_port->port[0];
4788		r->dst.port[1] = dst_port->port[1];
4789		r->dst.port_op = dst_port->op;
4790		r->uid.op = uid->op;
4791		r->uid.uid[0] = uid->uid[0];
4792		r->uid.uid[1] = uid->uid[1];
4793		r->gid.op = gid->op;
4794		r->gid.gid[0] = gid->gid[0];
4795		r->gid.gid[1] = gid->gid[1];
4796		if (rcv) {
4797			strlcpy(r->rcv_ifname, rcv->ifname,
4798			    sizeof(r->rcv_ifname));
4799		}
4800		r->type = icmp_type->type;
4801		r->code = icmp_type->code;
4802
4803		if ((keep_state == PF_STATE_MODULATE ||
4804		    keep_state == PF_STATE_SYNPROXY) &&
4805		    r->proto && r->proto != IPPROTO_TCP)
4806			r->keep_state = PF_STATE_NORMAL;
4807		else
4808			r->keep_state = keep_state;
4809
4810		if (r->proto && r->proto != IPPROTO_TCP) {
4811			r->flags = 0;
4812			r->flagset = 0;
4813		} else {
4814			r->flags = flags;
4815			r->flagset = flagset;
4816		}
4817		if (icmp_type->proto && r->proto != icmp_type->proto) {
4818			yyerror("icmp-type mismatch");
4819			error++;
4820		}
4821
4822		if (src_os && src_os->os) {
4823			r->os_fingerprint = pfctl_get_fingerprint(src_os->os);
4824			if ((pf->opts & PF_OPT_VERBOSE2) &&
4825			    r->os_fingerprint == PF_OSFP_NOMATCH)
4826				fprintf(stderr,
4827				    "warning: unknown '%s' OS fingerprint\n",
4828				    src_os->os);
4829		} else {
4830			r->os_fingerprint = PF_OSFP_ANY;
4831		}
4832
4833		if (nat && nat->rdr && nat->binat) {
4834			if (disallow_table(src_host, "invalid use of table "
4835			    "<%s> as the source address of a binat-to rule") ||
4836			    disallow_alias(src_host, "invalid use of interface "
4837			    "(%s) as the source address of a binat-to rule")) {
4838				error++;
4839			} else if ((r->src.addr.type != PF_ADDR_ADDRMASK &&
4840			    r->src.addr.type != PF_ADDR_DYNIFTL) ||
4841			    (r->nat.addr.type != PF_ADDR_ADDRMASK &&
4842			    r->nat.addr.type != PF_ADDR_DYNIFTL)) {
4843				yyerror("binat-to requires a specified "
4844				    "source and redirect address");
4845				error++;
4846			}
4847			if (DYNIF_MULTIADDR(r->src.addr) ||
4848			    DYNIF_MULTIADDR(r->nat.addr)) {
4849				yyerror ("dynamic interfaces must be used with "
4850				    ":0 in a binat-to rule");
4851				error++;
4852			}
4853			if (PF_AZERO(&r->src.addr.v.a.mask, af) ||
4854			    PF_AZERO(&r->nat.addr.v.a.mask, af)) {
4855				yyerror ("source and redir addresess must have "
4856				    "a matching network mask in binat-rule");
4857				error++;
4858			}
4859			if (r->nat.addr.type == PF_ADDR_TABLE) {
4860				yyerror ("tables cannot be used as the redirect "
4861				    "address of a binat-to rule");
4862				error++;
4863			}
4864			if (r->direction != PF_INOUT) {
4865				yyerror("binat-to cannot be specified "
4866				    "with a direction");
4867				error++;
4868			}
4869
4870			/* first specify outbound NAT rule */
4871			r->direction = PF_OUT;
4872		}
4873
4874		error += apply_redirspec(&r->nat, r, nat, 0, dst_port);
4875		error += apply_redirspec(&r->rdr, r, rdr, 1, dst_port);
4876		error += apply_redirspec(&r->route, r, rroute, 2, dst_port);
4877
4878		if (rule_consistent(r, anchor_call[0]) < 0 || error)
4879			yyerror("skipping rule due to errors");
4880		else {
4881			r->nr = pf->astack[pf->asd]->match++;
4882			pfctl_add_rule(pf, r, anchor_call);
4883			added++;
4884		}
4885		r->direction = dir;
4886
4887		/* Generate binat's matching inbound rule */
4888		if (!error && nat && nat->rdr && nat->binat) {
4889			bcopy(r, &rb, sizeof(rb));
4890
4891			/* now specify inbound rdr rule */
4892			rb.direction = PF_IN;
4893
4894			if ((srch = calloc(1, sizeof(*srch))) == NULL)
4895				err(1, "expand_rule: calloc");
4896			bcopy(src_host, srch, sizeof(*srch));
4897			srch->ifname = NULL;
4898			srch->next = NULL;
4899			srch->tail = NULL;
4900
4901			if ((dsth = calloc(1, sizeof(*dsth))) == NULL)
4902				err(1, "expand_rule: calloc");
4903			bcopy(&rb.nat.addr, &dsth->addr, sizeof(dsth->addr));
4904			dsth->ifname = NULL;
4905			dsth->next = NULL;
4906			dsth->tail = NULL;
4907
4908			if ((binat.rdr =
4909			    calloc(1, sizeof(*binat.rdr))) == NULL)
4910				err(1, "expand_rule: calloc");
4911			bcopy(nat->rdr, binat.rdr, sizeof(*binat.rdr));
4912			bcopy(&nat->pool_opts, &binat.pool_opts,
4913			    sizeof(binat.pool_opts));
4914			binat.pool_opts.staticport = 0;
4915			binat.rdr->host = srch;
4916
4917			expand_rule(&rb, 1, interface, NULL, &binat, NULL,
4918			    proto,
4919			    src_os, dst_host, dst_port, dsth, src_port,
4920			    uid, gid, rcv, icmp_type, anchor_call);
4921		}
4922
4923	))))))))));
4924
4925	if (!keeprule) {
4926		FREE_LIST(struct node_if, interfaces);
4927		FREE_LIST(struct node_proto, protos);
4928		FREE_LIST(struct node_host, src_hosts);
4929		FREE_LIST(struct node_port, src_ports);
4930		FREE_LIST(struct node_os, src_oses);
4931		FREE_LIST(struct node_host, dst_hosts);
4932		FREE_LIST(struct node_port, dst_ports);
4933		FREE_LIST(struct node_uid, uids);
4934		FREE_LIST(struct node_gid, gids);
4935		FREE_LIST(struct node_icmp, icmp_types);
4936		if (nat && nat->rdr)
4937			FREE_LIST(struct node_host, nat->rdr->host);
4938		if (rdr && rdr->rdr)
4939			FREE_LIST(struct node_host, rdr->rdr->host);
4940
4941	}
4942
4943	if (!added)
4944		yyerror("rule expands to no valid combination");
4945}
4946
4947int
4948expand_skip_interface(struct node_if *interfaces)
4949{
4950	int	errs = 0;
4951
4952	if (!interfaces || (!interfaces->next && !interfaces->not &&
4953	    !strcmp(interfaces->ifname, "none"))) {
4954		if (pf->opts & PF_OPT_VERBOSE)
4955			printf("set skip on none\n");
4956		errs = pfctl_set_interface_flags(pf, "", PFI_IFLAG_SKIP, 0);
4957		return (errs);
4958	}
4959
4960	if (pf->opts & PF_OPT_VERBOSE)
4961		printf("set skip on {");
4962	LOOP_THROUGH(struct node_if, interface, interfaces,
4963		if (pf->opts & PF_OPT_VERBOSE)
4964			printf(" %s", interface->ifname);
4965		if (interface->not) {
4966			yyerror("skip on ! <interface> is not supported");
4967			errs++;
4968		} else
4969			errs += pfctl_set_interface_flags(pf,
4970			    interface->ifname, PFI_IFLAG_SKIP, 1);
4971	);
4972	if (pf->opts & PF_OPT_VERBOSE)
4973		printf(" }\n");
4974
4975	FREE_LIST(struct node_if, interfaces);
4976
4977	if (errs)
4978		return (1);
4979	else
4980		return (0);
4981}
4982
4983void
4984freehostlist(struct node_host *h)
4985{
4986	struct node_host *n;
4987
4988	for (n = h; n != NULL; n = n->next)
4989		if (n->ifname)
4990			free(n->ifname);
4991	FREE_LIST(struct node_host, h);
4992}
4993
4994#undef FREE_LIST
4995#undef LOOP_THROUGH
4996
4997int
4998check_rulestate(int desired_state)
4999{
5000	if (require_order && (rulestate > desired_state)) {
5001		yyerror("Rules must be in order: options, normalization, "
5002		    "queueing, translation, filtering");
5003		return (1);
5004	}
5005	rulestate = desired_state;
5006	return (0);
5007}
5008
5009int
5010kw_cmp(const void *k, const void *e)
5011{
5012	return (strcmp(k, ((const struct keywords *)e)->k_name));
5013}
5014
5015int
5016lookup(char *s)
5017{
5018	/* this has to be sorted always */
5019	static const struct keywords keywords[] = {
5020		{ "all",		ALL},
5021		{ "allow-opts",		ALLOWOPTS},
5022		{ "altq",		ALTQ},
5023		{ "anchor",		ANCHOR},
5024		{ "antispoof",		ANTISPOOF},
5025		{ "any",		ANY},
5026		{ "bandwidth",		BANDWIDTH},
5027		{ "binat-to",		BINATTO},
5028		{ "bitmask",		BITMASK},
5029		{ "block",		BLOCK},
5030		{ "block-policy",	BLOCKPOLICY},
5031		{ "cbq",		CBQ},
5032		{ "code",		CODE},
5033		{ "crop",		FRAGCROP},
5034		{ "debug",		DEBUG},
5035		{ "divert-packet",	DIVERTPACKET},
5036		{ "divert-reply",	DIVERTREPLY},
5037		{ "divert-to",		DIVERTTO},
5038		{ "drop",		DROP},
5039		{ "drop-ovl",		FRAGDROP},
5040		{ "dup-to",		DUPTO},
5041		{ "fastroute",		FASTROUTE},
5042		{ "file",		FILENAME},
5043		{ "fingerprints",	FINGERPRINTS},
5044		{ "flags",		FLAGS},
5045		{ "floating",		FLOATING},
5046		{ "flush",		FLUSH},
5047		{ "for",		FOR},
5048		{ "fragment",		FRAGMENT},
5049		{ "from",		FROM},
5050		{ "global",		GLOBAL},
5051		{ "group",		GROUP},
5052		{ "hfsc",		HFSC},
5053		{ "hostid",		HOSTID},
5054		{ "icmp-type",		ICMPTYPE},
5055		{ "icmp6-type",		ICMP6TYPE},
5056		{ "if-bound",		IFBOUND},
5057		{ "in",			IN},
5058		{ "include",		INCLUDE},
5059		{ "inet",		INET},
5060		{ "inet6",		INET6},
5061		{ "keep",		KEEP},
5062		{ "label",		LABEL},
5063		{ "limit",		LIMIT},
5064		{ "linkshare",		LINKSHARE},
5065		{ "load",		LOAD},
5066		{ "log",		LOG},
5067		{ "loginterface",	LOGINTERFACE},
5068		{ "match",		MATCH},
5069		{ "max",		MAXIMUM},
5070		{ "max-mss",		MAXMSS},
5071		{ "max-src-conn",	MAXSRCCONN},
5072		{ "max-src-conn-rate",	MAXSRCCONNRATE},
5073		{ "max-src-nodes",	MAXSRCNODES},
5074		{ "max-src-states",	MAXSRCSTATES},
5075		{ "min-ttl",		MINTTL},
5076		{ "modulate",		MODULATE},
5077		{ "nat",		NAT},
5078		{ "nat-anchor",		NATANCHOR},
5079		{ "nat-to",		NATTO},
5080		{ "no",			NO},
5081		{ "no-df",		NODF},
5082		{ "no-route",		NOROUTE},
5083		{ "no-sync",		NOSYNC},
5084		{ "on",			ON},
5085		{ "optimization",	OPTIMIZATION},
5086		{ "os",			OS},
5087		{ "out",		OUT},
5088		{ "overload",		OVERLOAD},
5089		{ "pass",		PASS},
5090		{ "pflow",		PFLOW},
5091		{ "port",		PORT},
5092		{ "priority",		PRIORITY},
5093		{ "priq",		PRIQ},
5094		{ "probability",	PROBABILITY},
5095		{ "proto",		PROTO},
5096		{ "qlimit",		QLIMIT},
5097		{ "queue",		QUEUE},
5098		{ "quick",		QUICK},
5099		{ "random",		RANDOM},
5100		{ "random-id",		RANDOMID},
5101		{ "rdr",		RDR},
5102		{ "rdr-anchor",		RDRANCHOR},
5103		{ "rdr-to",		RDRTO},
5104		{ "realtime",		REALTIME},
5105		{ "reassemble",		REASSEMBLE},
5106		{ "received-on",	RECEIVEDON},
5107		{ "reply-to",		REPLYTO},
5108		{ "require-order",	REQUIREORDER},
5109		{ "return",		RETURN},
5110		{ "return-icmp",	RETURNICMP},
5111		{ "return-icmp6",	RETURNICMP6},
5112		{ "return-rst",		RETURNRST},
5113		{ "round-robin",	ROUNDROBIN},
5114		{ "route",		ROUTE},
5115		{ "route-to",		ROUTETO},
5116		{ "rtable",		RTABLE},
5117		{ "rule",		RULE},
5118		{ "ruleset-optimization",	RULESET_OPTIMIZATION},
5119		{ "scrub",		SCRUB},
5120		{ "set",		SET},
5121		{ "set-tos",		SETTOS},
5122		{ "skip",		SKIP},
5123		{ "sloppy",		SLOPPY},
5124		{ "source-hash",	SOURCEHASH},
5125		{ "source-track",	SOURCETRACK},
5126		{ "state",		STATE},
5127		{ "state-defaults",	STATEDEFAULTS},
5128		{ "state-policy",	STATEPOLICY},
5129		{ "static-port",	STATICPORT},
5130		{ "sticky-address",	STICKYADDRESS},
5131		{ "synproxy",		SYNPROXY},
5132		{ "table",		TABLE},
5133		{ "tag",		TAG},
5134		{ "tagged",		TAGGED},
5135		{ "tbrsize",		TBRSIZE},
5136		{ "timeout",		TIMEOUT},
5137		{ "to",			TO},
5138		{ "tos",		TOS},
5139		{ "ttl",		TTL},
5140		{ "upperlimit",		UPPERLIMIT},
5141		{ "urpf-failed",	URPFFAILED},
5142		{ "user",		USER},
5143	};
5144	const struct keywords	*p;
5145
5146	p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
5147	    sizeof(keywords[0]), kw_cmp);
5148
5149	if (p) {
5150		if (debug > 1)
5151			fprintf(stderr, "%s: %d\n", s, p->k_val);
5152		return (p->k_val);
5153	} else {
5154		if (debug > 1)
5155			fprintf(stderr, "string: %s\n", s);
5156		return (STRING);
5157	}
5158}
5159
5160#define MAXPUSHBACK	128
5161
5162char	*parsebuf;
5163int	 parseindex;
5164char	 pushback_buffer[MAXPUSHBACK];
5165int	 pushback_index = 0;
5166
5167int
5168lgetc(int quotec)
5169{
5170	int		c, next;
5171
5172	if (parsebuf) {
5173		/* Read character from the parsebuffer instead of input. */
5174		if (parseindex >= 0) {
5175			c = parsebuf[parseindex++];
5176			if (c != '\0')
5177				return (c);
5178			parsebuf = NULL;
5179		} else
5180			parseindex++;
5181	}
5182
5183	if (pushback_index)
5184		return (pushback_buffer[--pushback_index]);
5185
5186	if (quotec) {
5187		if ((c = getc(file->stream)) == EOF) {
5188			yyerror("reached end of file while parsing quoted string");
5189			if (popfile() == EOF)
5190				return (EOF);
5191			return (quotec);
5192		}
5193		return (c);
5194	}
5195
5196	while ((c = getc(file->stream)) == '\\') {
5197		next = getc(file->stream);
5198		if (next != '\n') {
5199			c = next;
5200			break;
5201		}
5202		yylval.lineno = file->lineno;
5203		file->lineno++;
5204	}
5205
5206	while (c == EOF) {
5207		if (popfile() == EOF)
5208			return (EOF);
5209		c = getc(file->stream);
5210	}
5211	return (c);
5212}
5213
5214int
5215lungetc(int c)
5216{
5217	if (c == EOF)
5218		return (EOF);
5219	if (parsebuf) {
5220		parseindex--;
5221		if (parseindex >= 0)
5222			return (c);
5223	}
5224	if (pushback_index < MAXPUSHBACK-1)
5225		return (pushback_buffer[pushback_index++] = c);
5226	else
5227		return (EOF);
5228}
5229
5230int
5231findeol(void)
5232{
5233	int	c;
5234
5235	parsebuf = NULL;
5236
5237	/* skip to either EOF or the first real EOL */
5238	while (1) {
5239		if (pushback_index)
5240			c = pushback_buffer[--pushback_index];
5241		else
5242			c = lgetc(0);
5243		if (c == '\n') {
5244			file->lineno++;
5245			break;
5246		}
5247		if (c == EOF)
5248			break;
5249	}
5250	return (ERROR);
5251}
5252
5253int
5254yylex(void)
5255{
5256	char	 buf[8096];
5257	char	*p, *val;
5258	int	 quotec, next, c;
5259	int	 token;
5260
5261top:
5262	p = buf;
5263	while ((c = lgetc(0)) == ' ' || c == '\t')
5264		; /* nothing */
5265
5266	yylval.lineno = file->lineno;
5267	if (c == '#')
5268		while ((c = lgetc(0)) != '\n' && c != EOF)
5269			; /* nothing */
5270	if (c == '$' && parsebuf == NULL) {
5271		while (1) {
5272			if ((c = lgetc(0)) == EOF)
5273				return (0);
5274
5275			if (p + 1 >= buf + sizeof(buf) - 1) {
5276				yyerror("string too long");
5277				return (findeol());
5278			}
5279			if (isalnum(c) || c == '_') {
5280				*p++ = (char)c;
5281				continue;
5282			}
5283			*p = '\0';
5284			lungetc(c);
5285			break;
5286		}
5287		val = symget(buf);
5288		if (val == NULL) {
5289			yyerror("macro '%s' not defined", buf);
5290			return (findeol());
5291		}
5292		parsebuf = val;
5293		parseindex = 0;
5294		goto top;
5295	}
5296
5297	switch (c) {
5298	case '\'':
5299	case '"':
5300		quotec = c;
5301		while (1) {
5302			if ((c = lgetc(quotec)) == EOF)
5303				return (0);
5304			if (c == '\n') {
5305				file->lineno++;
5306				continue;
5307			} else if (c == '\\') {
5308				if ((next = lgetc(quotec)) == EOF)
5309					return (0);
5310				if (next == quotec || c == ' ' || c == '\t')
5311					c = next;
5312				else if (next == '\n')
5313					continue;
5314				else
5315					lungetc(next);
5316			} else if (c == quotec) {
5317				*p = '\0';
5318				break;
5319			}
5320			if (p + 1 >= buf + sizeof(buf) - 1) {
5321				yyerror("string too long");
5322				return (findeol());
5323			}
5324			*p++ = (char)c;
5325		}
5326		yylval.v.string = strdup(buf);
5327		if (yylval.v.string == NULL)
5328			err(1, "yylex: strdup");
5329		return (STRING);
5330	case '!':
5331		next = lgetc(0);
5332		if (next == '=')
5333			return (NE);
5334		lungetc(next);
5335		break;
5336	case '<':
5337		next = lgetc(0);
5338		if (next == '>') {
5339			yylval.v.i = PF_OP_XRG;
5340			return (PORTBINARY);
5341		} else if (next == '=')
5342			return (LE);
5343		lungetc(next);
5344		break;
5345	case '>':
5346		next = lgetc(0);
5347		if (next == '<') {
5348			yylval.v.i = PF_OP_IRG;
5349			return (PORTBINARY);
5350		} else if (next == '=')
5351			return (GE);
5352		lungetc(next);
5353		break;
5354	}
5355
5356#define allowed_to_end_number(x) \
5357	(isspace(x) || x == ')' || x ==',' || x == '/' || x == '}' || x == '=')
5358
5359	if (c == '-' || isdigit(c)) {
5360		do {
5361			*p++ = c;
5362			if ((unsigned)(p-buf) >= sizeof(buf)) {
5363				yyerror("string too long");
5364				return (findeol());
5365			}
5366		} while ((c = lgetc(0)) != EOF && isdigit(c));
5367		lungetc(c);
5368		if (p == buf + 1 && buf[0] == '-')
5369			goto nodigits;
5370		if (c == EOF || allowed_to_end_number(c)) {
5371			const char *errstr = NULL;
5372
5373			*p = '\0';
5374			yylval.v.number = strtonum(buf, LLONG_MIN,
5375			    LLONG_MAX, &errstr);
5376			if (errstr) {
5377				yyerror("\"%s\" invalid number: %s",
5378				    buf, errstr);
5379				return (findeol());
5380			}
5381			return (NUMBER);
5382		} else {
5383nodigits:
5384			while (p > buf + 1)
5385				lungetc(*--p);
5386			c = *--p;
5387			if (c == '-')
5388				return (c);
5389		}
5390	}
5391
5392#define allowed_in_string(x) \
5393	(isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
5394	x != '{' && x != '}' && x != '<' && x != '>' && \
5395	x != '!' && x != '=' && x != '/' && x != '#' && \
5396	x != ','))
5397
5398	if (isalnum(c) || c == ':' || c == '_') {
5399		do {
5400			*p++ = c;
5401			if ((unsigned)(p-buf) >= sizeof(buf)) {
5402				yyerror("string too long");
5403				return (findeol());
5404			}
5405		} while ((c = lgetc(0)) != EOF && (allowed_in_string(c)));
5406		lungetc(c);
5407		*p = '\0';
5408		if ((token = lookup(buf)) == STRING)
5409			if ((yylval.v.string = strdup(buf)) == NULL)
5410				err(1, "yylex: strdup");
5411		return (token);
5412	}
5413	if (c == '\n') {
5414		yylval.lineno = file->lineno;
5415		file->lineno++;
5416	}
5417	if (c == EOF)
5418		return (0);
5419	return (c);
5420}
5421
5422int
5423check_file_secrecy(int fd, const char *fname)
5424{
5425	struct stat	st;
5426
5427	if (fstat(fd, &st)) {
5428		warn("cannot stat %s", fname);
5429		return (-1);
5430	}
5431	if (st.st_uid != 0 && st.st_uid != getuid()) {
5432		warnx("%s: owner not root or current user", fname);
5433		return (-1);
5434	}
5435	if (st.st_mode & (S_IRWXG | S_IRWXO)) {
5436		warnx("%s: group/world readable/writeable", fname);
5437		return (-1);
5438	}
5439	return (0);
5440}
5441
5442struct file *
5443pushfile(const char *name, int secret)
5444{
5445	struct file	*nfile;
5446
5447	if ((nfile = calloc(1, sizeof(struct file))) == NULL ||
5448	    (nfile->name = strdup(name)) == NULL) {
5449		if (nfile)
5450			free(nfile);
5451		warn("malloc");
5452		return (NULL);
5453	}
5454	if (TAILQ_FIRST(&files) == NULL && strcmp(nfile->name, "-") == 0) {
5455		nfile->stream = stdin;
5456		free(nfile->name);
5457		if ((nfile->name = strdup("stdin")) == NULL) {
5458			warn("strdup");
5459			free(nfile);
5460			return (NULL);
5461		}
5462	} else if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
5463		warn("%s", nfile->name);
5464		free(nfile->name);
5465		free(nfile);
5466		return (NULL);
5467	} else if (secret &&
5468	    check_file_secrecy(fileno(nfile->stream), nfile->name)) {
5469		fclose(nfile->stream);
5470		free(nfile->name);
5471		free(nfile);
5472		return (NULL);
5473	}
5474	nfile->lineno = 1;
5475	TAILQ_INSERT_TAIL(&files, nfile, entry);
5476	return (nfile);
5477}
5478
5479int
5480popfile(void)
5481{
5482	struct file	*prev;
5483
5484	if ((prev = TAILQ_PREV(file, files, entry)) != NULL) {
5485		prev->errors += file->errors;
5486		TAILQ_REMOVE(&files, file, entry);
5487		fclose(file->stream);
5488		free(file->name);
5489		free(file);
5490		file = prev;
5491		return (0);
5492	}
5493	return (EOF);
5494}
5495
5496int
5497parse_config(char *filename, struct pfctl *xpf)
5498{
5499	int		 errors = 0;
5500	struct sym	*sym;
5501
5502	pf = xpf;
5503	errors = 0;
5504	rulestate = PFCTL_STATE_NONE;
5505	returnicmpdefault = (ICMP_UNREACH << 8) | ICMP_UNREACH_PORT;
5506	returnicmp6default =
5507	    (ICMP6_DST_UNREACH << 8) | ICMP6_DST_UNREACH_NOPORT;
5508	blockpolicy = PFRULE_DROP;
5509	require_order = 0;
5510
5511	if ((file = pushfile(filename, 0)) == NULL) {
5512		warn("cannot open the main config file!");
5513		return (-1);
5514	}
5515
5516	yyparse();
5517	errors = file->errors;
5518	popfile();
5519
5520	/* Free macros and check which have not been used. */
5521	while ((sym = TAILQ_FIRST(&symhead))) {
5522		if ((pf->opts & PF_OPT_VERBOSE2) && !sym->used)
5523			fprintf(stderr, "warning: macro '%s' not "
5524			    "used\n", sym->nam);
5525		free(sym->nam);
5526		free(sym->val);
5527		TAILQ_REMOVE(&symhead, sym, entry);
5528		free(sym);
5529	}
5530
5531	return (errors ? -1 : 0);
5532}
5533
5534int
5535symset(const char *nam, const char *val, int persist)
5536{
5537	struct sym	*sym;
5538
5539	for (sym = TAILQ_FIRST(&symhead); sym && strcmp(nam, sym->nam);
5540	    sym = TAILQ_NEXT(sym, entry))
5541		;	/* nothing */
5542
5543	if (sym != NULL) {
5544		if (sym->persist == 1)
5545			return (0);
5546		else {
5547			free(sym->nam);
5548			free(sym->val);
5549			TAILQ_REMOVE(&symhead, sym, entry);
5550			free(sym);
5551		}
5552	}
5553	if ((sym = calloc(1, sizeof(*sym))) == NULL)
5554		return (-1);
5555
5556	sym->nam = strdup(nam);
5557	if (sym->nam == NULL) {
5558		free(sym);
5559		return (-1);
5560	}
5561	sym->val = strdup(val);
5562	if (sym->val == NULL) {
5563		free(sym->nam);
5564		free(sym);
5565		return (-1);
5566	}
5567	sym->used = 0;
5568	sym->persist = persist;
5569	TAILQ_INSERT_TAIL(&symhead, sym, entry);
5570	return (0);
5571}
5572
5573int
5574pfctl_cmdline_symset(char *s)
5575{
5576	char	*sym, *val;
5577	int	 ret;
5578
5579	if ((val = strrchr(s, '=')) == NULL)
5580		return (-1);
5581
5582	if ((sym = malloc(strlen(s) - strlen(val) + 1)) == NULL)
5583		err(1, "pfctl_cmdline_symset: malloc");
5584
5585	strlcpy(sym, s, strlen(s) - strlen(val) + 1);
5586
5587	ret = symset(sym, val + 1, 1);
5588	free(sym);
5589
5590	return (ret);
5591}
5592
5593char *
5594symget(const char *nam)
5595{
5596	struct sym	*sym;
5597
5598	TAILQ_FOREACH(sym, &symhead, entry)
5599		if (strcmp(nam, sym->nam) == 0) {
5600			sym->used = 1;
5601			return (sym->val);
5602		}
5603	return (NULL);
5604}
5605
5606void
5607mv_rules(struct pf_ruleset *src, struct pf_ruleset *dst)
5608{
5609	struct pf_rule *r;
5610
5611	while ((r = TAILQ_FIRST(src->rules.active.ptr)) != NULL) {
5612		TAILQ_REMOVE(src->rules.active.ptr, r, entries);
5613		TAILQ_INSERT_TAIL(dst->rules.active.ptr, r, entries);
5614		dst->anchor->match++;
5615	}
5616	src->anchor->match = 0;
5617	while ((r = TAILQ_FIRST(src->rules.inactive.ptr)) != NULL) {
5618		TAILQ_REMOVE(src->rules.inactive.ptr, r, entries);
5619		TAILQ_INSERT_TAIL(dst->rules.inactive.ptr, r, entries);
5620	}
5621}
5622
5623void
5624decide_address_family(struct node_host *n, sa_family_t *af)
5625{
5626	if (*af != 0 || n == NULL)
5627		return;
5628	*af = n->af;
5629	while ((n = n->next) != NULL) {
5630		if (n->af != *af) {
5631			*af = 0;
5632			return;
5633		}
5634	}
5635}
5636
5637int
5638invalid_redirect(struct node_host *nh, sa_family_t af)
5639{
5640	if (!af) {
5641		struct node_host *n;
5642
5643		/* tables and dyniftl are ok without an address family */
5644		for (n = nh; n != NULL; n = n->next) {
5645			if (n->addr.type != PF_ADDR_TABLE &&
5646			    n->addr.type != PF_ADDR_DYNIFTL) {
5647				yyerror("address family not given and "
5648				    "translation address expands to multiple "
5649				    "address families");
5650				return (1);
5651			}
5652		}
5653	}
5654	if (nh == NULL) {
5655		yyerror("no translation address with matching address family "
5656		    "found.");
5657		return (1);
5658	}
5659	return (0);
5660}
5661
5662int
5663atoul(char *s, u_long *ulvalp)
5664{
5665	u_long	 ulval;
5666	char	*ep;
5667
5668	errno = 0;
5669	ulval = strtoul(s, &ep, 0);
5670	if (s[0] == '\0' || *ep != '\0')
5671		return (-1);
5672	if (errno == ERANGE && ulval == ULONG_MAX)
5673		return (-1);
5674	*ulvalp = ulval;
5675	return (0);
5676}
5677
5678int
5679getservice(char *n)
5680{
5681	struct servent	*s;
5682	u_long		 ulval;
5683
5684	if (atoul(n, &ulval) == 0) {
5685		if (ulval > 65535) {
5686			yyerror("illegal port value %lu", ulval);
5687			return (-1);
5688		}
5689		return (htons(ulval));
5690	} else {
5691		s = getservbyname(n, "tcp");
5692		if (s == NULL)
5693			s = getservbyname(n, "udp");
5694		if (s == NULL) {
5695			yyerror("unknown port %s", n);
5696			return (-1);
5697		}
5698		return (s->s_port);
5699	}
5700}
5701
5702int
5703rule_label(struct pf_rule *r, char *s)
5704{
5705	if (s) {
5706		if (strlcpy(r->label, s, sizeof(r->label)) >=
5707		    sizeof(r->label)) {
5708			yyerror("rule label too long (max %d chars)",
5709			    sizeof(r->label)-1);
5710			return (-1);
5711		}
5712	}
5713	return (0);
5714}
5715
5716u_int16_t
5717parseicmpspec(char *w, sa_family_t af)
5718{
5719	const struct icmpcodeent	*p;
5720	u_long				 ulval;
5721	u_int8_t			 icmptype;
5722
5723	if (af == AF_INET)
5724		icmptype = returnicmpdefault >> 8;
5725	else
5726		icmptype = returnicmp6default >> 8;
5727
5728	if (atoul(w, &ulval) == -1) {
5729		if ((p = geticmpcodebyname(icmptype, w, af)) == NULL) {
5730			yyerror("unknown icmp code %s", w);
5731			return (0);
5732		}
5733		ulval = p->code;
5734	}
5735	if (ulval > 255) {
5736		yyerror("invalid icmp code %lu", ulval);
5737		return (0);
5738	}
5739	return (icmptype << 8 | ulval);
5740}
5741
5742int
5743parseport(char *port, struct range *r, int extensions)
5744{
5745	char	*p = strchr(port, ':');
5746
5747	if (p == NULL) {
5748		if ((r->a = getservice(port)) == -1)
5749			return (-1);
5750		r->b = 0;
5751		r->t = PF_OP_NONE;
5752		return (0);
5753	}
5754	if ((extensions & PPORT_STAR) && !strcmp(p+1, "*")) {
5755		*p = 0;
5756		if ((r->a = getservice(port)) == -1)
5757			return (-1);
5758		r->b = 0;
5759		r->t = PF_OP_IRG;
5760		return (0);
5761	}
5762	if ((extensions & PPORT_RANGE)) {
5763		*p++ = 0;
5764		if ((r->a = getservice(port)) == -1 ||
5765		    (r->b = getservice(p)) == -1)
5766			return (-1);
5767		if (r->a == r->b) {
5768			r->b = 0;
5769			r->t = PF_OP_NONE;
5770		} else
5771			r->t = PF_OP_RRG;
5772		return (0);
5773	}
5774	return (-1);
5775}
5776
5777int
5778pfctl_load_anchors(int dev, struct pfctl *pf, struct pfr_buffer *trans)
5779{
5780	struct loadanchors	*la;
5781
5782	TAILQ_FOREACH(la, &loadanchorshead, entries) {
5783		if (pf->opts & PF_OPT_VERBOSE)
5784			fprintf(stderr, "\nLoading anchor %s from %s\n",
5785			    la->anchorname, la->filename);
5786		if (pfctl_rules(dev, la->filename, pf->opts, pf->optimize,
5787		    la->anchorname, trans) == -1)
5788			return (-1);
5789	}
5790
5791	return (0);
5792}
5793
5794int
5795kw_casecmp(const void *k, const void *e)
5796{
5797	return (strcasecmp(k, ((const struct keywords *)e)->k_name));
5798}
5799
5800int
5801map_tos(char *s, int *val)
5802{
5803	/* DiffServ Codepoints and other TOS mappings */
5804	const struct keywords	 toswords[] = {
5805		{ "af11",		IPTOS_DSCP_AF11 },
5806		{ "af12",		IPTOS_DSCP_AF12 },
5807		{ "af13",		IPTOS_DSCP_AF13 },
5808		{ "af21",		IPTOS_DSCP_AF21 },
5809		{ "af22",		IPTOS_DSCP_AF22 },
5810		{ "af23",		IPTOS_DSCP_AF23 },
5811		{ "af31",		IPTOS_DSCP_AF31 },
5812		{ "af32",		IPTOS_DSCP_AF32 },
5813		{ "af33",		IPTOS_DSCP_AF33 },
5814		{ "af41",		IPTOS_DSCP_AF41 },
5815		{ "af42",		IPTOS_DSCP_AF42 },
5816		{ "af43",		IPTOS_DSCP_AF43 },
5817		{ "critical",		IPTOS_PREC_CRITIC_ECP },
5818		{ "cs0",		IPTOS_DSCP_CS0 },
5819		{ "cs1",		IPTOS_DSCP_CS1 },
5820		{ "cs2",		IPTOS_DSCP_CS2 },
5821		{ "cs3",		IPTOS_DSCP_CS3 },
5822		{ "cs4",		IPTOS_DSCP_CS4 },
5823		{ "cs5",		IPTOS_DSCP_CS5 },
5824		{ "cs6",		IPTOS_DSCP_CS6 },
5825		{ "cs7",		IPTOS_DSCP_CS7 },
5826		{ "ef",			IPTOS_DSCP_EF },
5827		{ "inetcontrol",	IPTOS_PREC_INTERNETCONTROL },
5828		{ "lowdelay",		IPTOS_LOWDELAY },
5829		{ "netcontrol",		IPTOS_PREC_NETCONTROL },
5830		{ "reliability",	IPTOS_RELIABILITY },
5831		{ "throughput",		IPTOS_THROUGHPUT }
5832	};
5833	const struct keywords	*p;
5834
5835	p = bsearch(s, toswords, sizeof(toswords)/sizeof(toswords[0]),
5836	    sizeof(toswords[0]), kw_casecmp);
5837
5838	if (p) {
5839		*val = p->k_val;
5840		return (1);
5841	}
5842	return (0);
5843}
5844