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