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