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