]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/pfctl/parse.y
Merge llvm-project release/14.x llvmorg-14-init-18315-g190be5457c90
[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                         /* stepping 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                         if ($2.src.host != NULL &&
3265                             $2.src.host->addr.type != PF_ADDR_ADDRMASK &&
3266                             $2.src.host->addr.type != PF_ADDR_TABLE) {
3267                                 yyerror("from must be an address or table");
3268                                 YYERROR;
3269                         }
3270                         if ($2.dst.host != NULL &&
3271                             $2.dst.host->addr.type != PF_ADDR_ADDRMASK &&
3272                             $2.dst.host->addr.type != PF_ADDR_TABLE) {
3273                                 yyerror("to must be an address or table");
3274                                 YYERROR;
3275                         }
3276                         $$ = $2;
3277                 }
3278                 ;
3279 etherfromto     : ALL                           {
3280                         $$.src = NULL;
3281                         $$.dst = NULL;
3282                 }
3283                 | etherfrom etherto             {
3284                         $$.src = $1.mac;
3285                         $$.dst = $2.mac;
3286                 }
3287                 ;
3288
3289 etherfrom       : /* emtpy */                   {
3290                         bzero(&$$, sizeof($$));
3291                 }
3292                 | FROM macspec                  {
3293                         $$.mac = $2;
3294                 }
3295                 ;
3296
3297 etherto         : /* empty */                   {
3298                         bzero(&$$, sizeof($$));
3299                 }
3300                 | TO macspec                    {
3301                         $$.mac = $2;
3302                 }
3303                 ;
3304
3305 mac             : string '/' NUMBER             {
3306                         $$ = node_mac_from_string_masklen($1, $3);
3307                         free($1);
3308                         if ($$ == NULL)
3309                                 YYERROR;
3310                 }
3311                 | string                        {
3312                         if (strchr($1, '&')) {
3313                                 /* mac&mask */
3314                                 char *mac = strtok($1, "&");
3315                                 char *mask = strtok(NULL, "&");
3316                                 $$ = node_mac_from_string_mask(mac, mask);
3317                         } else {
3318                                 $$ = node_mac_from_string($1);
3319                         }
3320                         free($1);
3321                         if ($$ == NULL)
3322                                 YYERROR;
3323
3324                 }
3325 xmac            : not mac {
3326                         struct node_mac *n;
3327
3328                         for (n = $2; n != NULL; n = n->next)
3329                                 n->neg = $1;
3330                         $$ = $2;
3331                 }
3332                 ;
3333 macspec         : xmac {
3334                         $$ = $1;
3335                 }
3336                 | '{' optnl mac_list '}'
3337                 {
3338                         $$ = $3;
3339                 }
3340                 ;
3341 mac_list        : xmac optnl {
3342                         $$ = $1;
3343                 }
3344                 | mac_list comma xmac {
3345                         if ($3 == NULL)
3346                                 $$ = $1;
3347                         else if ($1 == NULL)
3348                                 $$ = $3;
3349                         else {
3350                                 $1->tail->next = $3;
3351                                 $1->tail = $3->tail;
3352                                 $$ = $1;
3353                         }
3354                 }
3355
3356 fromto          : ALL                           {
3357                         $$.src.host = NULL;
3358                         $$.src.port = NULL;
3359                         $$.dst.host = NULL;
3360                         $$.dst.port = NULL;
3361                         $$.src_os = NULL;
3362                 }
3363                 | from os to                    {
3364                         $$.src = $1;
3365                         $$.src_os = $2;
3366                         $$.dst = $3;
3367                 }
3368                 ;
3369
3370 os              : /* empty */                   { $$ = NULL; }
3371                 | OS xos                        { $$ = $2; }
3372                 | OS '{' optnl os_list '}'      { $$ = $4; }
3373                 ;
3374
3375 xos             : STRING {
3376                         $$ = calloc(1, sizeof(struct node_os));
3377                         if ($$ == NULL)
3378                                 err(1, "os: calloc");
3379                         $$->os = $1;
3380                         $$->tail = $$;
3381                 }
3382                 ;
3383
3384 os_list         : xos optnl                     { $$ = $1; }
3385                 | os_list comma xos optnl       {
3386                         $1->tail->next = $3;
3387                         $1->tail = $3;
3388                         $$ = $1;
3389                 }
3390                 ;
3391
3392 from            : /* empty */                   {
3393                         $$.host = NULL;
3394                         $$.port = NULL;
3395                 }
3396                 | FROM ipportspec               {
3397                         $$ = $2;
3398                 }
3399                 ;
3400
3401 to              : /* empty */                   {
3402                         $$.host = NULL;
3403                         $$.port = NULL;
3404                 }
3405                 | TO ipportspec         {
3406                         if (disallow_urpf_failed($2.host, "\"urpf-failed\" is "
3407                             "not permitted in a destination address"))
3408                                 YYERROR;
3409                         $$ = $2;
3410                 }
3411                 ;
3412
3413 ipportspec      : ipspec                        {
3414                         $$.host = $1;
3415                         $$.port = NULL;
3416                 }
3417                 | ipspec PORT portspec          {
3418                         $$.host = $1;
3419                         $$.port = $3;
3420                 }
3421                 | PORT portspec                 {
3422                         $$.host = NULL;
3423                         $$.port = $2;
3424                 }
3425                 ;
3426
3427 optnl           : '\n' optnl
3428                 |
3429                 ;
3430
3431 ipspec          : ANY                           { $$ = NULL; }
3432                 | xhost                         { $$ = $1; }
3433                 | '{' optnl host_list '}'       { $$ = $3; }
3434                 ;
3435
3436 toipspec        : TO ipspec                     { $$ = $2; }
3437                 | /* empty */                   { $$ = NULL; }
3438                 ;
3439
3440 host_list       : ipspec optnl                  { $$ = $1; }
3441                 | host_list comma ipspec optnl  {
3442                         if ($3 == NULL)
3443                                 $$ = $1;
3444                         else if ($1 == NULL)
3445                                 $$ = $3;
3446                         else {
3447                                 $1->tail->next = $3;
3448                                 $1->tail = $3->tail;
3449                                 $$ = $1;
3450                         }
3451                 }
3452                 ;
3453
3454 xhost           : not host                      {
3455                         struct node_host        *n;
3456
3457                         for (n = $2; n != NULL; n = n->next)
3458                                 n->not = $1;
3459                         $$ = $2;
3460                 }
3461                 | not NOROUTE                   {
3462                         $$ = calloc(1, sizeof(struct node_host));
3463                         if ($$ == NULL)
3464                                 err(1, "xhost: calloc");
3465                         $$->addr.type = PF_ADDR_NOROUTE;
3466                         $$->next = NULL;
3467                         $$->not = $1;
3468                         $$->tail = $$;
3469                 }
3470                 | not URPFFAILED                {
3471                         $$ = calloc(1, sizeof(struct node_host));
3472                         if ($$ == NULL)
3473                                 err(1, "xhost: calloc");
3474                         $$->addr.type = PF_ADDR_URPFFAILED;
3475                         $$->next = NULL;
3476                         $$->not = $1;
3477                         $$->tail = $$;
3478                 }
3479                 ;
3480
3481 host            : STRING                        {
3482                         if (($$ = host($1)) == NULL)    {
3483                                 /* error. "any" is handled elsewhere */
3484                                 free($1);
3485                                 yyerror("could not parse host specification");
3486                                 YYERROR;
3487                         }
3488                         free($1);
3489
3490                 }
3491                 | STRING '-' STRING             {
3492                         struct node_host *b, *e;
3493
3494                         if ((b = host($1)) == NULL || (e = host($3)) == NULL) {
3495                                 free($1);
3496                                 free($3);
3497                                 yyerror("could not parse host specification");
3498                                 YYERROR;
3499                         }
3500                         if (b->af != e->af ||
3501                             b->addr.type != PF_ADDR_ADDRMASK ||
3502                             e->addr.type != PF_ADDR_ADDRMASK ||
3503                             unmask(&b->addr.v.a.mask, b->af) !=
3504                             (b->af == AF_INET ? 32 : 128) ||
3505                             unmask(&e->addr.v.a.mask, e->af) !=
3506                             (e->af == AF_INET ? 32 : 128) ||
3507                             b->next != NULL || b->not ||
3508                             e->next != NULL || e->not) {
3509                                 free(b);
3510                                 free(e);
3511                                 free($1);
3512                                 free($3);
3513                                 yyerror("invalid address range");
3514                                 YYERROR;
3515                         }
3516                         memcpy(&b->addr.v.a.mask, &e->addr.v.a.addr,
3517                             sizeof(b->addr.v.a.mask));
3518                         b->addr.type = PF_ADDR_RANGE;
3519                         $$ = b;
3520                         free(e);
3521                         free($1);
3522                         free($3);
3523                 }
3524                 | STRING '/' NUMBER             {
3525                         char    *buf;
3526
3527                         if (asprintf(&buf, "%s/%lld", $1, (long long)$3) == -1)
3528                                 err(1, "host: asprintf");
3529                         free($1);
3530                         if (($$ = host(buf)) == NULL)   {
3531                                 /* error. "any" is handled elsewhere */
3532                                 free(buf);
3533                                 yyerror("could not parse host specification");
3534                                 YYERROR;
3535                         }
3536                         free(buf);
3537                 }
3538                 | NUMBER '/' NUMBER             {
3539                         char    *buf;
3540
3541                         /* ie. for 10/8 parsing */
3542 #ifdef __FreeBSD__
3543                         if (asprintf(&buf, "%lld/%lld", (long long)$1, (long long)$3) == -1)
3544 #else
3545                         if (asprintf(&buf, "%lld/%lld", $1, $3) == -1)
3546 #endif
3547                                 err(1, "host: asprintf");
3548                         if (($$ = host(buf)) == NULL)   {
3549                                 /* error. "any" is handled elsewhere */
3550                                 free(buf);
3551                                 yyerror("could not parse host specification");
3552                                 YYERROR;
3553                         }
3554                         free(buf);
3555                 }
3556                 | dynaddr
3557                 | dynaddr '/' NUMBER            {
3558                         struct node_host        *n;
3559
3560                         if ($3 < 0 || $3 > 128) {
3561                                 yyerror("bit number too big");
3562                                 YYERROR;
3563                         }
3564                         $$ = $1;
3565                         for (n = $1; n != NULL; n = n->next)
3566                                 set_ipmask(n, $3);
3567                 }
3568                 | '<' STRING '>'        {
3569                         if (strlen($2) >= PF_TABLE_NAME_SIZE) {
3570                                 yyerror("table name '%s' too long", $2);
3571                                 free($2);
3572                                 YYERROR;
3573                         }
3574                         $$ = calloc(1, sizeof(struct node_host));
3575                         if ($$ == NULL)
3576                                 err(1, "host: calloc");
3577                         $$->addr.type = PF_ADDR_TABLE;
3578                         if (strlcpy($$->addr.v.tblname, $2,
3579                             sizeof($$->addr.v.tblname)) >=
3580                             sizeof($$->addr.v.tblname))
3581                                 errx(1, "host: strlcpy");
3582                         free($2);
3583                         $$->next = NULL;
3584                         $$->tail = $$;
3585                 }
3586                 ;
3587
3588 number          : NUMBER
3589                 | STRING                {
3590                         u_long  ulval;
3591
3592                         if (atoul($1, &ulval) == -1) {
3593                                 yyerror("%s is not a number", $1);
3594                                 free($1);
3595                                 YYERROR;
3596                         } else
3597                                 $$ = ulval;
3598                         free($1);
3599                 }
3600                 ;
3601
3602 dynaddr         : '(' STRING ')'                {
3603                         int      flags = 0;
3604                         char    *p, *op;
3605
3606                         op = $2;
3607                         if (!isalpha(op[0])) {
3608                                 yyerror("invalid interface name '%s'", op);
3609                                 free(op);
3610                                 YYERROR;
3611                         }
3612                         while ((p = strrchr($2, ':')) != NULL) {
3613                                 if (!strcmp(p+1, "network"))
3614                                         flags |= PFI_AFLAG_NETWORK;
3615                                 else if (!strcmp(p+1, "broadcast"))
3616                                         flags |= PFI_AFLAG_BROADCAST;
3617                                 else if (!strcmp(p+1, "peer"))
3618                                         flags |= PFI_AFLAG_PEER;
3619                                 else if (!strcmp(p+1, "0"))
3620                                         flags |= PFI_AFLAG_NOALIAS;
3621                                 else {
3622                                         yyerror("interface %s has bad modifier",
3623                                             $2);
3624                                         free(op);
3625                                         YYERROR;
3626                                 }
3627                                 *p = '\0';
3628                         }
3629                         if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) {
3630                                 free(op);
3631                                 yyerror("illegal combination of "
3632                                     "interface modifiers");
3633                                 YYERROR;
3634                         }
3635                         $$ = calloc(1, sizeof(struct node_host));
3636                         if ($$ == NULL)
3637                                 err(1, "address: calloc");
3638                         $$->af = 0;
3639                         set_ipmask($$, 128);
3640                         $$->addr.type = PF_ADDR_DYNIFTL;
3641                         $$->addr.iflags = flags;
3642                         if (strlcpy($$->addr.v.ifname, $2,
3643                             sizeof($$->addr.v.ifname)) >=
3644                             sizeof($$->addr.v.ifname)) {
3645                                 free(op);
3646                                 free($$);
3647                                 yyerror("interface name too long");
3648                                 YYERROR;
3649                         }
3650                         free(op);
3651                         $$->next = NULL;
3652                         $$->tail = $$;
3653                 }
3654                 ;
3655
3656 portspec        : port_item                     { $$ = $1; }
3657                 | '{' optnl port_list '}'       { $$ = $3; }
3658                 ;
3659
3660 port_list       : port_item optnl               { $$ = $1; }
3661                 | port_list comma port_item optnl       {
3662                         $1->tail->next = $3;
3663                         $1->tail = $3;
3664                         $$ = $1;
3665                 }
3666                 ;
3667
3668 port_item       : portrange                     {
3669                         $$ = calloc(1, sizeof(struct node_port));
3670                         if ($$ == NULL)
3671                                 err(1, "port_item: calloc");
3672                         $$->port[0] = $1.a;
3673                         $$->port[1] = $1.b;
3674                         if ($1.t)
3675                                 $$->op = PF_OP_RRG;
3676                         else
3677                                 $$->op = PF_OP_EQ;
3678                         $$->next = NULL;
3679                         $$->tail = $$;
3680                 }
3681                 | unaryop portrange     {
3682                         if ($2.t) {
3683                                 yyerror("':' cannot be used with an other "
3684                                     "port operator");
3685                                 YYERROR;
3686                         }
3687                         $$ = calloc(1, sizeof(struct node_port));
3688                         if ($$ == NULL)
3689                                 err(1, "port_item: calloc");
3690                         $$->port[0] = $2.a;
3691                         $$->port[1] = $2.b;
3692                         $$->op = $1;
3693                         $$->next = NULL;
3694                         $$->tail = $$;
3695                 }
3696                 | portrange PORTBINARY portrange        {
3697                         if ($1.t || $3.t) {
3698                                 yyerror("':' cannot be used with an other "
3699                                     "port operator");
3700                                 YYERROR;
3701                         }
3702                         $$ = calloc(1, sizeof(struct node_port));
3703                         if ($$ == NULL)
3704                                 err(1, "port_item: calloc");
3705                         $$->port[0] = $1.a;
3706                         $$->port[1] = $3.a;
3707                         $$->op = $2;
3708                         $$->next = NULL;
3709                         $$->tail = $$;
3710                 }
3711                 ;
3712
3713 portplain       : numberstring                  {
3714                         if (parseport($1, &$$, 0) == -1) {
3715                                 free($1);
3716                                 YYERROR;
3717                         }
3718                         free($1);
3719                 }
3720                 ;
3721
3722 portrange       : numberstring                  {
3723                         if (parseport($1, &$$, PPORT_RANGE) == -1) {
3724                                 free($1);
3725                                 YYERROR;
3726                         }
3727                         free($1);
3728                 }
3729                 ;
3730
3731 uids            : uid_item                      { $$ = $1; }
3732                 | '{' optnl uid_list '}'        { $$ = $3; }
3733                 ;
3734
3735 uid_list        : uid_item optnl                { $$ = $1; }
3736                 | uid_list comma uid_item optnl {
3737                         $1->tail->next = $3;
3738                         $1->tail = $3;
3739                         $$ = $1;
3740                 }
3741                 ;
3742
3743 uid_item        : uid                           {
3744                         $$ = calloc(1, sizeof(struct node_uid));
3745                         if ($$ == NULL)
3746                                 err(1, "uid_item: calloc");
3747                         $$->uid[0] = $1;
3748                         $$->uid[1] = $1;
3749                         $$->op = PF_OP_EQ;
3750                         $$->next = NULL;
3751                         $$->tail = $$;
3752                 }
3753                 | unaryop uid                   {
3754                         if ($2 == UID_MAX && $1 != PF_OP_EQ && $1 != PF_OP_NE) {
3755                                 yyerror("user unknown requires operator = or "
3756                                     "!=");
3757                                 YYERROR;
3758                         }
3759                         $$ = calloc(1, sizeof(struct node_uid));
3760                         if ($$ == NULL)
3761                                 err(1, "uid_item: calloc");
3762                         $$->uid[0] = $2;
3763                         $$->uid[1] = $2;
3764                         $$->op = $1;
3765                         $$->next = NULL;
3766                         $$->tail = $$;
3767                 }
3768                 | uid PORTBINARY uid            {
3769                         if ($1 == UID_MAX || $3 == UID_MAX) {
3770                                 yyerror("user unknown requires operator = or "
3771                                     "!=");
3772                                 YYERROR;
3773                         }
3774                         $$ = calloc(1, sizeof(struct node_uid));
3775                         if ($$ == NULL)
3776                                 err(1, "uid_item: calloc");
3777                         $$->uid[0] = $1;
3778                         $$->uid[1] = $3;
3779                         $$->op = $2;
3780                         $$->next = NULL;
3781                         $$->tail = $$;
3782                 }
3783                 ;
3784
3785 uid             : STRING                        {
3786                         if (!strcmp($1, "unknown"))
3787                                 $$ = UID_MAX;
3788                         else {
3789                                 struct passwd   *pw;
3790
3791                                 if ((pw = getpwnam($1)) == NULL) {
3792                                         yyerror("unknown user %s", $1);
3793                                         free($1);
3794                                         YYERROR;
3795                                 }
3796                                 $$ = pw->pw_uid;
3797                         }
3798                         free($1);
3799                 }
3800                 | NUMBER                        {
3801                         if ($1 < 0 || $1 >= UID_MAX) {
3802                                 yyerror("illegal uid value %lu", $1);
3803                                 YYERROR;
3804                         }
3805                         $$ = $1;
3806                 }
3807                 ;
3808
3809 gids            : gid_item                      { $$ = $1; }
3810                 | '{' optnl gid_list '}'        { $$ = $3; }
3811                 ;
3812
3813 gid_list        : gid_item optnl                { $$ = $1; }
3814                 | gid_list comma gid_item optnl {
3815                         $1->tail->next = $3;
3816                         $1->tail = $3;
3817                         $$ = $1;
3818                 }
3819                 ;
3820
3821 gid_item        : gid                           {
3822                         $$ = calloc(1, sizeof(struct node_gid));
3823                         if ($$ == NULL)
3824                                 err(1, "gid_item: calloc");
3825                         $$->gid[0] = $1;
3826                         $$->gid[1] = $1;
3827                         $$->op = PF_OP_EQ;
3828                         $$->next = NULL;
3829                         $$->tail = $$;
3830                 }
3831                 | unaryop gid                   {
3832                         if ($2 == GID_MAX && $1 != PF_OP_EQ && $1 != PF_OP_NE) {
3833                                 yyerror("group unknown requires operator = or "
3834                                     "!=");
3835                                 YYERROR;
3836                         }
3837                         $$ = calloc(1, sizeof(struct node_gid));
3838                         if ($$ == NULL)
3839                                 err(1, "gid_item: calloc");
3840                         $$->gid[0] = $2;
3841                         $$->gid[1] = $2;
3842                         $$->op = $1;
3843                         $$->next = NULL;
3844                         $$->tail = $$;
3845                 }
3846                 | gid PORTBINARY gid            {
3847                         if ($1 == GID_MAX || $3 == GID_MAX) {
3848                                 yyerror("group unknown requires operator = or "
3849                                     "!=");
3850                                 YYERROR;
3851                         }
3852                         $$ = calloc(1, sizeof(struct node_gid));
3853                         if ($$ == NULL)
3854                                 err(1, "gid_item: calloc");
3855                         $$->gid[0] = $1;
3856                         $$->gid[1] = $3;
3857                         $$->op = $2;
3858                         $$->next = NULL;
3859                         $$->tail = $$;
3860                 }
3861                 ;
3862
3863 gid             : STRING                        {
3864                         if (!strcmp($1, "unknown"))
3865                                 $$ = GID_MAX;
3866                         else {
3867                                 struct group    *grp;
3868
3869                                 if ((grp = getgrnam($1)) == NULL) {
3870                                         yyerror("unknown group %s", $1);
3871                                         free($1);
3872                                         YYERROR;
3873                                 }
3874                                 $$ = grp->gr_gid;
3875                         }
3876                         free($1);
3877                 }
3878                 | NUMBER                        {
3879                         if ($1 < 0 || $1 >= GID_MAX) {
3880                                 yyerror("illegal gid value %lu", $1);
3881                                 YYERROR;
3882                         }
3883                         $$ = $1;
3884                 }
3885                 ;
3886
3887 flag            : STRING                        {
3888                         int     f;
3889
3890                         if ((f = parse_flags($1)) < 0) {
3891                                 yyerror("bad flags %s", $1);
3892                                 free($1);
3893                                 YYERROR;
3894                         }
3895                         free($1);
3896                         $$.b1 = f;
3897                 }
3898                 ;
3899
3900 flags           : FLAGS flag '/' flag   { $$.b1 = $2.b1; $$.b2 = $4.b1; }
3901                 | FLAGS '/' flag        { $$.b1 = 0; $$.b2 = $3.b1; }
3902                 | FLAGS ANY             { $$.b1 = 0; $$.b2 = 0; }
3903                 ;
3904
3905 icmpspec        : ICMPTYPE icmp_item                    { $$ = $2; }
3906                 | ICMPTYPE '{' optnl icmp_list '}'      { $$ = $4; }
3907                 | ICMP6TYPE icmp6_item                  { $$ = $2; }
3908                 | ICMP6TYPE '{' optnl icmp6_list '}'    { $$ = $4; }
3909                 ;
3910
3911 icmp_list       : icmp_item optnl               { $$ = $1; }
3912                 | icmp_list comma icmp_item optnl {
3913                         $1->tail->next = $3;
3914                         $1->tail = $3;
3915                         $$ = $1;
3916                 }
3917                 ;
3918
3919 icmp6_list      : icmp6_item optnl              { $$ = $1; }
3920                 | icmp6_list comma icmp6_item optnl {
3921                         $1->tail->next = $3;
3922                         $1->tail = $3;
3923                         $$ = $1;
3924                 }
3925                 ;
3926
3927 icmp_item       : icmptype              {
3928                         $$ = calloc(1, sizeof(struct node_icmp));
3929                         if ($$ == NULL)
3930                                 err(1, "icmp_item: calloc");
3931                         $$->type = $1;
3932                         $$->code = 0;
3933                         $$->proto = IPPROTO_ICMP;
3934                         $$->next = NULL;
3935                         $$->tail = $$;
3936                 }
3937                 | icmptype CODE STRING  {
3938                         const struct icmpcodeent        *p;
3939
3940                         if ((p = geticmpcodebyname($1-1, $3, AF_INET)) == NULL) {
3941                                 yyerror("unknown icmp-code %s", $3);
3942                                 free($3);
3943                                 YYERROR;
3944                         }
3945
3946                         free($3);
3947                         $$ = calloc(1, sizeof(struct node_icmp));
3948                         if ($$ == NULL)
3949                                 err(1, "icmp_item: calloc");
3950                         $$->type = $1;
3951                         $$->code = p->code + 1;
3952                         $$->proto = IPPROTO_ICMP;
3953                         $$->next = NULL;
3954                         $$->tail = $$;
3955                 }
3956                 | icmptype CODE NUMBER  {
3957                         if ($3 < 0 || $3 > 255) {
3958                                 yyerror("illegal icmp-code %lu", $3);
3959                                 YYERROR;
3960                         }
3961                         $$ = calloc(1, sizeof(struct node_icmp));
3962                         if ($$ == NULL)
3963                                 err(1, "icmp_item: calloc");
3964                         $$->type = $1;
3965                         $$->code = $3 + 1;
3966                         $$->proto = IPPROTO_ICMP;
3967                         $$->next = NULL;
3968                         $$->tail = $$;
3969                 }
3970                 ;
3971
3972 icmp6_item      : icmp6type             {
3973                         $$ = calloc(1, sizeof(struct node_icmp));
3974                         if ($$ == NULL)
3975                                 err(1, "icmp_item: calloc");
3976                         $$->type = $1;
3977                         $$->code = 0;
3978                         $$->proto = IPPROTO_ICMPV6;
3979                         $$->next = NULL;
3980                         $$->tail = $$;
3981                 }
3982                 | icmp6type CODE STRING {
3983                         const struct icmpcodeent        *p;
3984
3985                         if ((p = geticmpcodebyname($1-1, $3, AF_INET6)) == NULL) {
3986                                 yyerror("unknown icmp6-code %s", $3);
3987                                 free($3);
3988                                 YYERROR;
3989                         }
3990                         free($3);
3991
3992                         $$ = calloc(1, sizeof(struct node_icmp));
3993                         if ($$ == NULL)
3994                                 err(1, "icmp_item: calloc");
3995                         $$->type = $1;
3996                         $$->code = p->code + 1;
3997                         $$->proto = IPPROTO_ICMPV6;
3998                         $$->next = NULL;
3999                         $$->tail = $$;
4000                 }
4001                 | icmp6type CODE NUMBER {
4002                         if ($3 < 0 || $3 > 255) {
4003                                 yyerror("illegal icmp-code %lu", $3);
4004                                 YYERROR;
4005                         }
4006                         $$ = calloc(1, sizeof(struct node_icmp));
4007                         if ($$ == NULL)
4008                                 err(1, "icmp_item: calloc");
4009                         $$->type = $1;
4010                         $$->code = $3 + 1;
4011                         $$->proto = IPPROTO_ICMPV6;
4012                         $$->next = NULL;
4013                         $$->tail = $$;
4014                 }
4015                 ;
4016
4017 icmptype        : STRING                        {
4018                         const struct icmptypeent        *p;
4019
4020                         if ((p = geticmptypebyname($1, AF_INET)) == NULL) {
4021                                 yyerror("unknown icmp-type %s", $1);
4022                                 free($1);
4023                                 YYERROR;
4024                         }
4025                         $$ = p->type + 1;
4026                         free($1);
4027                 }
4028                 | NUMBER                        {
4029                         if ($1 < 0 || $1 > 255) {
4030                                 yyerror("illegal icmp-type %lu", $1);
4031                                 YYERROR;
4032                         }
4033                         $$ = $1 + 1;
4034                 }
4035                 ;
4036
4037 icmp6type       : STRING                        {
4038                         const struct icmptypeent        *p;
4039
4040                         if ((p = geticmptypebyname($1, AF_INET6)) ==
4041                             NULL) {
4042                                 yyerror("unknown icmp6-type %s", $1);
4043                                 free($1);
4044                                 YYERROR;
4045                         }
4046                         $$ = p->type + 1;
4047                         free($1);
4048                 }
4049                 | NUMBER                        {
4050                         if ($1 < 0 || $1 > 255) {
4051                                 yyerror("illegal icmp6-type %lu", $1);
4052                                 YYERROR;
4053                         }
4054                         $$ = $1 + 1;
4055                 }
4056                 ;
4057
4058 tos     : STRING                        {
4059                         int val;
4060                         char *end;
4061
4062                         if (map_tos($1, &val))
4063                                 $$ = val;
4064                         else if ($1[0] == '0' && $1[1] == 'x') {
4065                                 errno = 0;
4066                                 $$ = strtoul($1, &end, 16);
4067                                 if (errno || *end != '\0')
4068                                         $$ = 256;
4069                         } else
4070                                 $$ = 256;               /* flag bad argument */
4071                         if ($$ < 0 || $$ > 255) {
4072                                 yyerror("illegal tos value %s", $1);
4073                                 free($1);
4074                                 YYERROR;
4075                         }
4076                         free($1);
4077                 }
4078                 | NUMBER                        {
4079                         $$ = $1;
4080                         if ($$ < 0 || $$ > 255) {
4081                                 yyerror("illegal tos value %s", $1);
4082                                 YYERROR;
4083                         }
4084                 }
4085                 ;
4086
4087 sourcetrack     : SOURCETRACK           { $$ = PF_SRCTRACK; }
4088                 | SOURCETRACK GLOBAL    { $$ = PF_SRCTRACK_GLOBAL; }
4089                 | SOURCETRACK RULE      { $$ = PF_SRCTRACK_RULE; }
4090                 ;
4091
4092 statelock       : IFBOUND {
4093                         $$ = PFRULE_IFBOUND;
4094                 }
4095                 | FLOATING {
4096                         $$ = 0;
4097                 }
4098                 ;
4099
4100 keep            : NO STATE                      {
4101                         $$.action = 0;
4102                         $$.options = NULL;
4103                 }
4104                 | KEEP STATE state_opt_spec     {
4105                         $$.action = PF_STATE_NORMAL;
4106                         $$.options = $3;
4107                 }
4108                 | MODULATE STATE state_opt_spec {
4109                         $$.action = PF_STATE_MODULATE;
4110                         $$.options = $3;
4111                 }
4112                 | SYNPROXY STATE state_opt_spec {
4113                         $$.action = PF_STATE_SYNPROXY;
4114                         $$.options = $3;
4115                 }
4116                 ;
4117
4118 flush           : /* empty */                   { $$ = 0; }
4119                 | FLUSH                         { $$ = PF_FLUSH; }
4120                 | FLUSH GLOBAL                  {
4121                         $$ = PF_FLUSH | PF_FLUSH_GLOBAL;
4122                 }
4123                 ;
4124
4125 state_opt_spec  : '(' state_opt_list ')'        { $$ = $2; }
4126                 | /* empty */                   { $$ = NULL; }
4127                 ;
4128
4129 state_opt_list  : state_opt_item                { $$ = $1; }
4130                 | state_opt_list comma state_opt_item {
4131                         $1->tail->next = $3;
4132                         $1->tail = $3;
4133                         $$ = $1;
4134                 }
4135                 ;
4136
4137 state_opt_item  : MAXIMUM NUMBER                {
4138                         if ($2 < 0 || $2 > UINT_MAX) {
4139                                 yyerror("only positive values permitted");
4140                                 YYERROR;
4141                         }
4142                         $$ = calloc(1, sizeof(struct node_state_opt));
4143                         if ($$ == NULL)
4144                                 err(1, "state_opt_item: calloc");
4145                         $$->type = PF_STATE_OPT_MAX;
4146                         $$->data.max_states = $2;
4147                         $$->next = NULL;
4148                         $$->tail = $$;
4149                 }
4150                 | NOSYNC                                {
4151                         $$ = calloc(1, sizeof(struct node_state_opt));
4152                         if ($$ == NULL)
4153                                 err(1, "state_opt_item: calloc");
4154                         $$->type = PF_STATE_OPT_NOSYNC;
4155                         $$->next = NULL;
4156                         $$->tail = $$;
4157                 }
4158                 | MAXSRCSTATES NUMBER                   {
4159                         if ($2 < 0 || $2 > UINT_MAX) {
4160                                 yyerror("only positive values permitted");
4161                                 YYERROR;
4162                         }
4163                         $$ = calloc(1, sizeof(struct node_state_opt));
4164                         if ($$ == NULL)
4165                                 err(1, "state_opt_item: calloc");
4166                         $$->type = PF_STATE_OPT_MAX_SRC_STATES;
4167                         $$->data.max_src_states = $2;
4168                         $$->next = NULL;
4169                         $$->tail = $$;
4170                 }
4171                 | MAXSRCCONN NUMBER                     {
4172                         if ($2 < 0 || $2 > UINT_MAX) {
4173                                 yyerror("only positive values permitted");
4174                                 YYERROR;
4175                         }
4176                         $$ = calloc(1, sizeof(struct node_state_opt));
4177                         if ($$ == NULL)
4178                                 err(1, "state_opt_item: calloc");
4179                         $$->type = PF_STATE_OPT_MAX_SRC_CONN;
4180                         $$->data.max_src_conn = $2;
4181                         $$->next = NULL;
4182                         $$->tail = $$;
4183                 }
4184                 | MAXSRCCONNRATE NUMBER '/' NUMBER      {
4185                         if ($2 < 0 || $2 > UINT_MAX ||
4186                             $4 < 0 || $4 > UINT_MAX) {
4187                                 yyerror("only positive values permitted");
4188                                 YYERROR;
4189                         }
4190                         $$ = calloc(1, sizeof(struct node_state_opt));
4191                         if ($$ == NULL)
4192                                 err(1, "state_opt_item: calloc");
4193                         $$->type = PF_STATE_OPT_MAX_SRC_CONN_RATE;
4194                         $$->data.max_src_conn_rate.limit = $2;
4195                         $$->data.max_src_conn_rate.seconds = $4;
4196                         $$->next = NULL;
4197                         $$->tail = $$;
4198                 }
4199                 | OVERLOAD '<' STRING '>' flush         {
4200                         if (strlen($3) >= PF_TABLE_NAME_SIZE) {
4201                                 yyerror("table name '%s' too long", $3);
4202                                 free($3);
4203                                 YYERROR;
4204                         }
4205                         $$ = calloc(1, sizeof(struct node_state_opt));
4206                         if ($$ == NULL)
4207                                 err(1, "state_opt_item: calloc");
4208                         if (strlcpy($$->data.overload.tblname, $3,
4209                             PF_TABLE_NAME_SIZE) >= PF_TABLE_NAME_SIZE)
4210                                 errx(1, "state_opt_item: strlcpy");
4211                         free($3);
4212                         $$->type = PF_STATE_OPT_OVERLOAD;
4213                         $$->data.overload.flush = $5;
4214                         $$->next = NULL;
4215                         $$->tail = $$;
4216                 }
4217                 | MAXSRCNODES NUMBER                    {
4218                         if ($2 < 0 || $2 > UINT_MAX) {
4219                                 yyerror("only positive values permitted");
4220                                 YYERROR;
4221                         }
4222                         $$ = calloc(1, sizeof(struct node_state_opt));
4223                         if ($$ == NULL)
4224                                 err(1, "state_opt_item: calloc");
4225                         $$->type = PF_STATE_OPT_MAX_SRC_NODES;
4226                         $$->data.max_src_nodes = $2;
4227                         $$->next = NULL;
4228                         $$->tail = $$;
4229                 }
4230                 | sourcetrack {
4231                         $$ = calloc(1, sizeof(struct node_state_opt));
4232                         if ($$ == NULL)
4233                                 err(1, "state_opt_item: calloc");
4234                         $$->type = PF_STATE_OPT_SRCTRACK;
4235                         $$->data.src_track = $1;
4236                         $$->next = NULL;
4237                         $$->tail = $$;
4238                 }
4239                 | statelock {
4240                         $$ = calloc(1, sizeof(struct node_state_opt));
4241                         if ($$ == NULL)
4242                                 err(1, "state_opt_item: calloc");
4243                         $$->type = PF_STATE_OPT_STATELOCK;
4244                         $$->data.statelock = $1;
4245                         $$->next = NULL;
4246                         $$->tail = $$;
4247                 }
4248                 | SLOPPY {
4249                         $$ = calloc(1, sizeof(struct node_state_opt));
4250                         if ($$ == NULL)
4251                                 err(1, "state_opt_item: calloc");
4252                         $$->type = PF_STATE_OPT_SLOPPY;
4253                         $$->next = NULL;
4254                         $$->tail = $$;
4255                 }
4256                 | STRING NUMBER                 {
4257                         int     i;
4258
4259                         if ($2 < 0 || $2 > UINT_MAX) {
4260                                 yyerror("only positive values permitted");
4261                                 YYERROR;
4262                         }
4263                         for (i = 0; pf_timeouts[i].name &&
4264                             strcmp(pf_timeouts[i].name, $1); ++i)
4265                                 ;       /* nothing */
4266                         if (!pf_timeouts[i].name) {
4267                                 yyerror("illegal timeout name %s", $1);
4268                                 free($1);
4269                                 YYERROR;
4270                         }
4271                         if (strchr(pf_timeouts[i].name, '.') == NULL) {
4272                                 yyerror("illegal state timeout %s", $1);
4273                                 free($1);
4274                                 YYERROR;
4275                         }
4276                         free($1);
4277                         $$ = calloc(1, sizeof(struct node_state_opt));
4278                         if ($$ == NULL)
4279                                 err(1, "state_opt_item: calloc");
4280                         $$->type = PF_STATE_OPT_TIMEOUT;
4281                         $$->data.timeout.number = pf_timeouts[i].timeout;
4282                         $$->data.timeout.seconds = $2;
4283                         $$->next = NULL;
4284                         $$->tail = $$;
4285                 }
4286                 ;
4287
4288 label           : LABEL STRING                  {
4289                         $$ = $2;
4290                 }
4291                 ;
4292
4293 etherqname      : QUEUE STRING                          {
4294                         $$.qname = $2;
4295                 }
4296                 | QUEUE '(' STRING ')'                  {
4297                         $$.qname = $3;
4298                 }
4299                 ;
4300
4301 qname           : QUEUE STRING                          {
4302                         $$.qname = $2;
4303                         $$.pqname = NULL;
4304                 }
4305                 | QUEUE '(' STRING ')'                  {
4306                         $$.qname = $3;
4307                         $$.pqname = NULL;
4308                 }
4309                 | QUEUE '(' STRING comma STRING ')'     {
4310                         $$.qname = $3;
4311                         $$.pqname = $5;
4312                 }
4313                 ;
4314
4315 no              : /* empty */                   { $$ = 0; }
4316                 | NO                            { $$ = 1; }
4317                 ;
4318
4319 portstar        : numberstring                  {
4320                         if (parseport($1, &$$, PPORT_RANGE|PPORT_STAR) == -1) {
4321                                 free($1);
4322                                 YYERROR;
4323                         }
4324                         free($1);
4325                 }
4326                 ;
4327
4328 redirspec       : host                          { $$ = $1; }
4329                 | '{' optnl redir_host_list '}' { $$ = $3; }
4330                 ;
4331
4332 redir_host_list : host optnl                    { $$ = $1; }
4333                 | redir_host_list comma host optnl {
4334                         $1->tail->next = $3;
4335                         $1->tail = $3->tail;
4336                         $$ = $1;
4337                 }
4338                 ;
4339
4340 redirpool       : /* empty */                   { $$ = NULL; }
4341                 | ARROW redirspec               {
4342                         $$ = calloc(1, sizeof(struct redirection));
4343                         if ($$ == NULL)
4344                                 err(1, "redirection: calloc");
4345                         $$->host = $2;
4346                         $$->rport.a = $$->rport.b = $$->rport.t = 0;
4347                 }
4348                 | ARROW redirspec PORT portstar {
4349                         $$ = calloc(1, sizeof(struct redirection));
4350                         if ($$ == NULL)
4351                                 err(1, "redirection: calloc");
4352                         $$->host = $2;
4353                         $$->rport = $4;
4354                 }
4355                 ;
4356
4357 hashkey         : /* empty */
4358                 {
4359                         $$ = calloc(1, sizeof(struct pf_poolhashkey));
4360                         if ($$ == NULL)
4361                                 err(1, "hashkey: calloc");
4362                         $$->key32[0] = arc4random();
4363                         $$->key32[1] = arc4random();
4364                         $$->key32[2] = arc4random();
4365                         $$->key32[3] = arc4random();
4366                 }
4367                 | string
4368                 {
4369                         if (!strncmp($1, "0x", 2)) {
4370                                 if (strlen($1) != 34) {
4371                                         free($1);
4372                                         yyerror("hex key must be 128 bits "
4373                                                 "(32 hex digits) long");
4374                                         YYERROR;
4375                                 }
4376                                 $$ = calloc(1, sizeof(struct pf_poolhashkey));
4377                                 if ($$ == NULL)
4378                                         err(1, "hashkey: calloc");
4379
4380                                 if (sscanf($1, "0x%8x%8x%8x%8x",
4381                                     &$$->key32[0], &$$->key32[1],
4382                                     &$$->key32[2], &$$->key32[3]) != 4) {
4383                                         free($$);
4384                                         free($1);
4385                                         yyerror("invalid hex key");
4386                                         YYERROR;
4387                                 }
4388                         } else {
4389                                 MD5_CTX context;
4390
4391                                 $$ = calloc(1, sizeof(struct pf_poolhashkey));
4392                                 if ($$ == NULL)
4393                                         err(1, "hashkey: calloc");
4394                                 MD5Init(&context);
4395                                 MD5Update(&context, (unsigned char *)$1,
4396                                     strlen($1));
4397                                 MD5Final((unsigned char *)$$, &context);
4398                                 HTONL($$->key32[0]);
4399                                 HTONL($$->key32[1]);
4400                                 HTONL($$->key32[2]);
4401                                 HTONL($$->key32[3]);
4402                         }
4403                         free($1);
4404                 }
4405                 ;
4406
4407 pool_opts       :       { bzero(&pool_opts, sizeof pool_opts); }
4408                     pool_opts_l
4409                         { $$ = pool_opts; }
4410                 | /* empty */   {
4411                         bzero(&pool_opts, sizeof pool_opts);
4412                         $$ = pool_opts;
4413                 }
4414                 ;
4415
4416 pool_opts_l     : pool_opts_l pool_opt
4417                 | pool_opt
4418                 ;
4419
4420 pool_opt        : BITMASK       {
4421                         if (pool_opts.type) {
4422                                 yyerror("pool type cannot be redefined");
4423                                 YYERROR;
4424                         }
4425                         pool_opts.type =  PF_POOL_BITMASK;
4426                 }
4427                 | RANDOM        {
4428                         if (pool_opts.type) {
4429                                 yyerror("pool type cannot be redefined");
4430                                 YYERROR;
4431                         }
4432                         pool_opts.type = PF_POOL_RANDOM;
4433                 }
4434                 | SOURCEHASH hashkey {
4435                         if (pool_opts.type) {
4436                                 yyerror("pool type cannot be redefined");
4437                                 YYERROR;
4438                         }
4439                         pool_opts.type = PF_POOL_SRCHASH;
4440                         pool_opts.key = $2;
4441                 }
4442                 | ROUNDROBIN    {
4443                         if (pool_opts.type) {
4444                                 yyerror("pool type cannot be redefined");
4445                                 YYERROR;
4446                         }
4447                         pool_opts.type = PF_POOL_ROUNDROBIN;
4448                 }
4449                 | STATICPORT    {
4450                         if (pool_opts.staticport) {
4451                                 yyerror("static-port cannot be redefined");
4452                                 YYERROR;
4453                         }
4454                         pool_opts.staticport = 1;
4455                 }
4456                 | STICKYADDRESS {
4457                         if (filter_opts.marker & POM_STICKYADDRESS) {
4458                                 yyerror("sticky-address cannot be redefined");
4459                                 YYERROR;
4460                         }
4461                         pool_opts.marker |= POM_STICKYADDRESS;
4462                         pool_opts.opts |= PF_POOL_STICKYADDR;
4463                 }
4464                 | MAPEPORTSET number '/' number '/' number {
4465                         if (pool_opts.mape.offset) {
4466                                 yyerror("map-e-portset cannot be redefined");
4467                                 YYERROR;
4468                         }
4469                         if (pool_opts.type) {
4470                                 yyerror("map-e-portset cannot be used with "
4471                                         "address pools");
4472                                 YYERROR;
4473                         }
4474                         if ($2 <= 0 || $2 >= 16) {
4475                                 yyerror("MAP-E PSID offset must be 1-15");
4476                                 YYERROR;
4477                         }
4478                         if ($4 < 0 || $4 >= 16 || $2 + $4 > 16) {
4479                                 yyerror("Invalid MAP-E PSID length");
4480                                 YYERROR;
4481                         } else if ($4 == 0) {
4482                                 yyerror("PSID Length = 0: this means"
4483                                     " you do not need MAP-E");
4484                                 YYERROR;
4485                         }
4486                         if ($6 < 0 || $6 > 65535) {
4487                                 yyerror("Invalid MAP-E PSID");
4488                                 YYERROR;
4489                         }
4490                         pool_opts.mape.offset = $2;
4491                         pool_opts.mape.psidlen = $4;
4492                         pool_opts.mape.psid = $6;
4493                 }
4494                 ;
4495
4496 redirection     : /* empty */                   { $$ = NULL; }
4497                 | ARROW host                    {
4498                         $$ = calloc(1, sizeof(struct redirection));
4499                         if ($$ == NULL)
4500                                 err(1, "redirection: calloc");
4501                         $$->host = $2;
4502                         $$->rport.a = $$->rport.b = $$->rport.t = 0;
4503                 }
4504                 | ARROW host PORT portstar      {
4505                         $$ = calloc(1, sizeof(struct redirection));
4506                         if ($$ == NULL)
4507                                 err(1, "redirection: calloc");
4508                         $$->host = $2;
4509                         $$->rport = $4;
4510                 }
4511                 ;
4512
4513 natpasslog      : /* empty */   { $$.b1 = $$.b2 = 0; $$.w2 = 0; }
4514                 | PASS          { $$.b1 = 1; $$.b2 = 0; $$.w2 = 0; }
4515                 | PASS log      { $$.b1 = 1; $$.b2 = $2.log; $$.w2 = $2.logif; }
4516                 | log           { $$.b1 = 0; $$.b2 = $1.log; $$.w2 = $1.logif; }
4517                 ;
4518
4519 nataction       : no NAT natpasslog {
4520                         if ($1 && $3.b1) {
4521                                 yyerror("\"pass\" not valid with \"no\"");
4522                                 YYERROR;
4523                         }
4524                         if ($1)
4525                                 $$.b1 = PF_NONAT;
4526                         else
4527                                 $$.b1 = PF_NAT;
4528                         $$.b2 = $3.b1;
4529                         $$.w = $3.b2;
4530                         $$.w2 = $3.w2;
4531                 }
4532                 | no RDR natpasslog {
4533                         if ($1 && $3.b1) {
4534                                 yyerror("\"pass\" not valid with \"no\"");
4535                                 YYERROR;
4536                         }
4537                         if ($1)
4538                                 $$.b1 = PF_NORDR;
4539                         else
4540                                 $$.b1 = PF_RDR;
4541                         $$.b2 = $3.b1;
4542                         $$.w = $3.b2;
4543                         $$.w2 = $3.w2;
4544                 }
4545                 ;
4546
4547 natrule         : nataction interface af proto fromto tag tagged rtable
4548                     redirpool pool_opts
4549                 {
4550                         struct pfctl_rule       r;
4551
4552                         if (check_rulestate(PFCTL_STATE_NAT))
4553                                 YYERROR;
4554
4555                         memset(&r, 0, sizeof(r));
4556
4557                         r.action = $1.b1;
4558                         r.natpass = $1.b2;
4559                         r.log = $1.w;
4560                         r.logif = $1.w2;
4561                         r.af = $3;
4562
4563                         if (!r.af) {
4564                                 if ($5.src.host && $5.src.host->af &&
4565                                     !$5.src.host->ifindex)
4566                                         r.af = $5.src.host->af;
4567                                 else if ($5.dst.host && $5.dst.host->af &&
4568                                     !$5.dst.host->ifindex)
4569                                         r.af = $5.dst.host->af;
4570                         }
4571
4572                         if ($6 != NULL)
4573                                 if (strlcpy(r.tagname, $6, PF_TAG_NAME_SIZE) >=
4574                                     PF_TAG_NAME_SIZE) {
4575                                         yyerror("tag too long, max %u chars",
4576                                             PF_TAG_NAME_SIZE - 1);
4577                                         YYERROR;
4578                                 }
4579
4580                         if ($7.name)
4581                                 if (strlcpy(r.match_tagname, $7.name,
4582                                     PF_TAG_NAME_SIZE) >= PF_TAG_NAME_SIZE) {
4583                                         yyerror("tag too long, max %u chars",
4584                                             PF_TAG_NAME_SIZE - 1);
4585                                         YYERROR;
4586                                 }
4587                         r.match_tag_not = $7.neg;
4588                         r.rtableid = $8;
4589
4590                         if (r.action == PF_NONAT || r.action == PF_NORDR) {
4591                                 if ($9 != NULL) {
4592                                         yyerror("translation rule with 'no' "
4593                                             "does not need '->'");
4594                                         YYERROR;
4595                                 }
4596                         } else {
4597                                 if ($9 == NULL || $9->host == NULL) {
4598                                         yyerror("translation rule requires '-> "
4599                                             "address'");
4600                                         YYERROR;
4601                                 }
4602                                 if (!r.af && ! $9->host->ifindex)
4603                                         r.af = $9->host->af;
4604
4605                                 remove_invalid_hosts(&$9->host, &r.af);
4606                                 if (invalid_redirect($9->host, r.af))
4607                                         YYERROR;
4608                                 if (check_netmask($9->host, r.af))
4609                                         YYERROR;
4610
4611                                 r.rpool.proxy_port[0] = ntohs($9->rport.a);
4612
4613                                 switch (r.action) {
4614                                 case PF_RDR:
4615                                         if (!$9->rport.b && $9->rport.t &&
4616                                             $5.dst.port != NULL) {
4617                                                 r.rpool.proxy_port[1] =
4618                                                     ntohs($9->rport.a) +
4619                                                     (ntohs(
4620                                                     $5.dst.port->port[1]) -
4621                                                     ntohs(
4622                                                     $5.dst.port->port[0]));
4623                                         } else
4624                                                 r.rpool.proxy_port[1] =
4625                                                     ntohs($9->rport.b);
4626                                         break;
4627                                 case PF_NAT:
4628                                         r.rpool.proxy_port[1] =
4629                                             ntohs($9->rport.b);
4630                                         if (!r.rpool.proxy_port[0] &&
4631                                             !r.rpool.proxy_port[1]) {
4632                                                 r.rpool.proxy_port[0] =
4633                                                     PF_NAT_PROXY_PORT_LOW;
4634                                                 r.rpool.proxy_port[1] =
4635                                                     PF_NAT_PROXY_PORT_HIGH;
4636                                         } else if (!r.rpool.proxy_port[1])
4637                                                 r.rpool.proxy_port[1] =
4638                                                     r.rpool.proxy_port[0];
4639                                         break;
4640                                 default:
4641                                         break;
4642                                 }
4643
4644                                 r.rpool.opts = $10.type;
4645                                 if ((r.rpool.opts & PF_POOL_TYPEMASK) ==
4646                                     PF_POOL_NONE && ($9->host->next != NULL ||
4647                                     $9->host->addr.type == PF_ADDR_TABLE ||
4648                                     DYNIF_MULTIADDR($9->host->addr)))
4649                                         r.rpool.opts = PF_POOL_ROUNDROBIN;
4650                                 if ((r.rpool.opts & PF_POOL_TYPEMASK) !=
4651                                     PF_POOL_ROUNDROBIN &&
4652                                     disallow_table($9->host, "tables are only "
4653                                     "supported in round-robin redirection "
4654                                     "pools"))
4655                                         YYERROR;
4656                                 if ((r.rpool.opts & PF_POOL_TYPEMASK) !=
4657                                     PF_POOL_ROUNDROBIN &&
4658                                     disallow_alias($9->host, "interface (%s) "
4659                                     "is only supported in round-robin "
4660                                     "redirection pools"))
4661                                         YYERROR;
4662                                 if ($9->host->next != NULL) {
4663                                         if ((r.rpool.opts & PF_POOL_TYPEMASK) !=
4664                                             PF_POOL_ROUNDROBIN) {
4665                                                 yyerror("only round-robin "
4666                                                     "valid for multiple "
4667                                                     "redirection addresses");
4668                                                 YYERROR;
4669                                         }
4670                                 }
4671                         }
4672
4673                         if ($10.key != NULL)
4674                                 memcpy(&r.rpool.key, $10.key,
4675                                     sizeof(struct pf_poolhashkey));
4676
4677                          if ($10.opts)
4678                                 r.rpool.opts |= $10.opts;
4679
4680                         if ($10.staticport) {
4681                                 if (r.action != PF_NAT) {
4682                                         yyerror("the 'static-port' option is "
4683                                             "only valid with nat rules");
4684                                         YYERROR;
4685                                 }
4686                                 if (r.rpool.proxy_port[0] !=
4687                                     PF_NAT_PROXY_PORT_LOW &&
4688                                     r.rpool.proxy_port[1] !=
4689                                     PF_NAT_PROXY_PORT_HIGH) {
4690                                         yyerror("the 'static-port' option can't"
4691                                             " be used when specifying a port"
4692                                             " range");
4693                                         YYERROR;
4694                                 }
4695                                 r.rpool.proxy_port[0] = 0;
4696                                 r.rpool.proxy_port[1] = 0;
4697                         }
4698
4699                         if ($10.mape.offset) {
4700                                 if (r.action != PF_NAT) {
4701                                         yyerror("the 'map-e-portset' option is"
4702                                             " only valid with nat rules");
4703                                         YYERROR;
4704                                 }
4705                                 if ($10.staticport) {
4706                                         yyerror("the 'map-e-portset' option"
4707                                             " can't be used 'static-port'");
4708                                         YYERROR;
4709                                 }
4710                                 if (r.rpool.proxy_port[0] !=
4711                                     PF_NAT_PROXY_PORT_LOW &&
4712                                     r.rpool.proxy_port[1] !=
4713                                     PF_NAT_PROXY_PORT_HIGH) {
4714                                         yyerror("the 'map-e-portset' option"
4715                                             " can't be used when specifying"
4716                                             " a port range");
4717                                         YYERROR;
4718                                 }
4719                                 r.rpool.mape = $10.mape;
4720                         }
4721
4722                         expand_rule(&r, $2, $9 == NULL ? NULL : $9->host, $4,
4723                             $5.src_os, $5.src.host, $5.src.port, $5.dst.host,
4724                             $5.dst.port, 0, 0, 0, "");
4725                         free($9);
4726                 }
4727                 ;
4728
4729 binatrule       : no BINAT natpasslog interface af proto FROM ipspec toipspec tag
4730                     tagged rtable redirection
4731                 {
4732                         struct pfctl_rule       binat;
4733                         struct pf_pooladdr      *pa;
4734
4735                         if (check_rulestate(PFCTL_STATE_NAT))
4736                                 YYERROR;
4737                         if (disallow_urpf_failed($9, "\"urpf-failed\" is not "
4738                             "permitted as a binat destination"))
4739                                 YYERROR;
4740
4741                         memset(&binat, 0, sizeof(binat));
4742
4743                         if ($1 && $3.b1) {
4744                                 yyerror("\"pass\" not valid with \"no\"");
4745                                 YYERROR;
4746                         }
4747                         if ($1)
4748                                 binat.action = PF_NOBINAT;
4749                         else
4750                                 binat.action = PF_BINAT;
4751                         binat.natpass = $3.b1;
4752                         binat.log = $3.b2;
4753                         binat.logif = $3.w2;
4754                         binat.af = $5;
4755                         if (!binat.af && $8 != NULL && $8->af)
4756                                 binat.af = $8->af;
4757                         if (!binat.af && $9 != NULL && $9->af)
4758                                 binat.af = $9->af;
4759
4760                         if (!binat.af && $13 != NULL && $13->host)
4761                                 binat.af = $13->host->af;
4762                         if (!binat.af) {
4763                                 yyerror("address family (inet/inet6) "
4764                                     "undefined");
4765                                 YYERROR;
4766                         }
4767
4768                         if ($4 != NULL) {
4769                                 memcpy(binat.ifname, $4->ifname,
4770                                     sizeof(binat.ifname));
4771                                 binat.ifnot = $4->not;
4772                                 free($4);
4773                         }
4774
4775                         if ($10 != NULL)
4776                                 if (strlcpy(binat.tagname, $10,
4777                                     PF_TAG_NAME_SIZE) >= PF_TAG_NAME_SIZE) {
4778                                         yyerror("tag too long, max %u chars",
4779                                             PF_TAG_NAME_SIZE - 1);
4780                                         YYERROR;
4781                                 }
4782                         if ($11.name)
4783                                 if (strlcpy(binat.match_tagname, $11.name,
4784                                     PF_TAG_NAME_SIZE) >= PF_TAG_NAME_SIZE) {
4785                                         yyerror("tag too long, max %u chars",
4786                                             PF_TAG_NAME_SIZE - 1);
4787                                         YYERROR;
4788                                 }
4789                         binat.match_tag_not = $11.neg;
4790                         binat.rtableid = $12;
4791
4792                         if ($6 != NULL) {
4793                                 binat.proto = $6->proto;
4794                                 free($6);
4795                         }
4796
4797                         if ($8 != NULL && disallow_table($8, "invalid use of "
4798                             "table <%s> as the source address of a binat rule"))
4799                                 YYERROR;
4800                         if ($8 != NULL && disallow_alias($8, "invalid use of "
4801                             "interface (%s) as the source address of a binat "
4802                             "rule"))
4803                                 YYERROR;
4804                         if ($13 != NULL && $13->host != NULL && disallow_table(
4805                             $13->host, "invalid use of table <%s> as the "
4806                             "redirect address of a binat rule"))
4807                                 YYERROR;
4808                         if ($13 != NULL && $13->host != NULL && disallow_alias(
4809                             $13->host, "invalid use of interface (%s) as the "
4810                             "redirect address of a binat rule"))
4811                                 YYERROR;
4812
4813                         if ($8 != NULL) {
4814                                 if ($8->next) {
4815                                         yyerror("multiple binat ip addresses");
4816                                         YYERROR;
4817                                 }
4818                                 if ($8->addr.type == PF_ADDR_DYNIFTL)
4819                                         $8->af = binat.af;
4820                                 if ($8->af != binat.af) {
4821                                         yyerror("binat ip versions must match");
4822                                         YYERROR;
4823                                 }
4824                                 if (check_netmask($8, binat.af))
4825                                         YYERROR;
4826                                 memcpy(&binat.src.addr, &$8->addr,
4827                                     sizeof(binat.src.addr));
4828                                 free($8);
4829                         }
4830                         if ($9 != NULL) {
4831                                 if ($9->next) {
4832                                         yyerror("multiple binat ip addresses");
4833                                         YYERROR;
4834                                 }
4835                                 if ($9->af != binat.af && $9->af) {
4836                                         yyerror("binat ip versions must match");
4837                                         YYERROR;
4838                                 }
4839                                 if (check_netmask($9, binat.af))
4840                                         YYERROR;
4841                                 memcpy(&binat.dst.addr, &$9->addr,
4842                                     sizeof(binat.dst.addr));
4843                                 binat.dst.neg = $9->not;
4844                                 free($9);
4845                         }
4846
4847                         if (binat.action == PF_NOBINAT) {
4848                                 if ($13 != NULL) {
4849                                         yyerror("'no binat' rule does not need"
4850                                             " '->'");
4851                                         YYERROR;
4852                                 }
4853                         } else {
4854                                 if ($13 == NULL || $13->host == NULL) {
4855                                         yyerror("'binat' rule requires"
4856                                             " '-> address'");
4857                                         YYERROR;
4858                                 }
4859
4860                                 remove_invalid_hosts(&$13->host, &binat.af);
4861                                 if (invalid_redirect($13->host, binat.af))
4862                                         YYERROR;
4863                                 if ($13->host->next != NULL) {
4864                                         yyerror("binat rule must redirect to "
4865                                             "a single address");
4866                                         YYERROR;
4867                                 }
4868                                 if (check_netmask($13->host, binat.af))
4869                                         YYERROR;
4870
4871                                 if (!PF_AZERO(&binat.src.addr.v.a.mask,
4872                                     binat.af) &&
4873                                     !PF_AEQ(&binat.src.addr.v.a.mask,
4874                                     &$13->host->addr.v.a.mask, binat.af)) {
4875                                         yyerror("'binat' source mask and "
4876                                             "redirect mask must be the same");
4877                                         YYERROR;
4878                                 }
4879
4880                                 TAILQ_INIT(&binat.rpool.list);
4881                                 pa = calloc(1, sizeof(struct pf_pooladdr));
4882                                 if (pa == NULL)
4883                                         err(1, "binat: calloc");
4884                                 pa->addr = $13->host->addr;
4885                                 pa->ifname[0] = 0;
4886                                 TAILQ_INSERT_TAIL(&binat.rpool.list,
4887                                     pa, entries);
4888
4889                                 free($13);
4890                         }
4891
4892                         pfctl_append_rule(pf, &binat, "");
4893                 }
4894                 ;
4895
4896 tag             : /* empty */           { $$ = NULL; }
4897                 | TAG STRING            { $$ = $2; }
4898                 ;
4899
4900 tagged          : /* empty */           { $$.neg = 0; $$.name = NULL; }
4901                 | not TAGGED string     { $$.neg = $1; $$.name = $3; }
4902                 ;
4903
4904 rtable          : /* empty */           { $$ = -1; }
4905                 | RTABLE NUMBER         {
4906                         if ($2 < 0 || $2 > rt_tableid_max()) {
4907                                 yyerror("invalid rtable id");
4908                                 YYERROR;
4909                         }
4910                         $$ = $2;
4911                 }
4912                 ;
4913
4914 route_host      : STRING                        {
4915                         $$ = calloc(1, sizeof(struct node_host));
4916                         if ($$ == NULL)
4917                                 err(1, "route_host: calloc");
4918                         if (strlen($1) >= IFNAMSIZ) {
4919                                 yyerror("interface name too long");
4920                                 YYERROR;
4921                         }
4922                         $$->ifname = strdup($1);
4923                         set_ipmask($$, 128);
4924                         $$->next = NULL;
4925                         $$->tail = $$;
4926                 }
4927                 | '(' STRING host ')'           {
4928                         struct node_host *n;
4929
4930                         $$ = $3;
4931                         for (n = $3; n != NULL; n = n->next) {
4932                                 if (strlen($2) >= IFNAMSIZ) {
4933                                         yyerror("interface name too long");
4934                                         YYERROR;
4935                                 }
4936                                 n->ifname = strdup($2);
4937                         }
4938                 }
4939                 ;
4940
4941 route_host_list : route_host optnl                      { $$ = $1; }
4942                 | route_host_list comma route_host optnl {
4943                         if ($1->af == 0)
4944                                 $1->af = $3->af;
4945                         if ($1->af != $3->af) {
4946                                 yyerror("all pool addresses must be in the "
4947                                     "same address family");
4948                                 YYERROR;
4949                         }
4950                         $1->tail->next = $3;
4951                         $1->tail = $3->tail;
4952                         $$ = $1;
4953                 }
4954                 ;
4955
4956 routespec       : route_host                    { $$ = $1; }
4957                 | '{' optnl route_host_list '}' { $$ = $3; }
4958                 ;
4959
4960 route           : /* empty */                   {
4961                         $$.host = NULL;
4962                         $$.rt = 0;
4963                         $$.pool_opts = 0;
4964                 }
4965                 | FASTROUTE {
4966                         /* backwards-compat */
4967                         $$.host = NULL;
4968                         $$.rt = 0;
4969                         $$.pool_opts = 0;
4970                 }
4971                 | ROUTETO routespec pool_opts {
4972                         $$.host = $2;
4973                         $$.rt = PF_ROUTETO;
4974                         $$.pool_opts = $3.type | $3.opts;
4975                         if ($3.key != NULL)
4976                                 $$.key = $3.key;
4977                 }
4978                 | REPLYTO routespec pool_opts {
4979                         $$.host = $2;
4980                         $$.rt = PF_REPLYTO;
4981                         $$.pool_opts = $3.type | $3.opts;
4982                         if ($3.key != NULL)
4983                                 $$.key = $3.key;
4984                 }
4985                 | DUPTO routespec pool_opts {
4986                         $$.host = $2;
4987                         $$.rt = PF_DUPTO;
4988                         $$.pool_opts = $3.type | $3.opts;
4989                         if ($3.key != NULL)
4990                                 $$.key = $3.key;
4991                 }
4992                 ;
4993
4994 timeout_spec    : STRING NUMBER
4995                 {
4996                         if (check_rulestate(PFCTL_STATE_OPTION)) {
4997                                 free($1);
4998                                 YYERROR;
4999                         }
5000                         if ($2 < 0 || $2 > UINT_MAX) {
5001                                 yyerror("only positive values permitted");
5002                                 YYERROR;
5003                         }
5004                         if (pfctl_set_timeout(pf, $1, $2, 0) != 0) {
5005                                 yyerror("unknown timeout %s", $1);
5006                                 free($1);
5007                                 YYERROR;
5008                         }
5009                         free($1);
5010                 }
5011                 | INTERVAL NUMBER               {
5012                         if (check_rulestate(PFCTL_STATE_OPTION))
5013                                 YYERROR;
5014                         if ($2 < 0 || $2 > UINT_MAX) {
5015                                 yyerror("only positive values permitted");
5016                                 YYERROR;
5017                         }
5018                         if (pfctl_set_timeout(pf, "interval", $2, 0) != 0)
5019                                 YYERROR;
5020                 }
5021                 ;
5022
5023 timeout_list    : timeout_list comma timeout_spec optnl
5024                 | timeout_spec optnl
5025                 ;
5026
5027 limit_spec      : STRING NUMBER
5028                 {
5029                         if (check_rulestate(PFCTL_STATE_OPTION)) {
5030                                 free($1);
5031                                 YYERROR;
5032                         }
5033                         if ($2 < 0 || $2 > UINT_MAX) {
5034                                 yyerror("only positive values permitted");
5035                                 YYERROR;
5036                         }
5037                         if (pfctl_set_limit(pf, $1, $2) != 0) {
5038                                 yyerror("unable to set limit %s %u", $1, $2);
5039                                 free($1);
5040                                 YYERROR;
5041                         }
5042                         free($1);
5043                 }
5044                 ;
5045
5046 limit_list      : limit_list comma limit_spec optnl
5047                 | limit_spec optnl
5048                 ;
5049
5050 comma           : ','
5051                 | /* empty */
5052                 ;
5053
5054 yesno           : NO                    { $$ = 0; }
5055                 | STRING                {
5056                         if (!strcmp($1, "yes"))
5057                                 $$ = 1;
5058                         else {
5059                                 yyerror("invalid value '%s', expected 'yes' "
5060                                     "or 'no'", $1);
5061                                 free($1);
5062                                 YYERROR;
5063                         }
5064                         free($1);
5065                 }
5066                 ;
5067
5068 unaryop         : '='           { $$ = PF_OP_EQ; }
5069                 | '!' '='       { $$ = PF_OP_NE; }
5070                 | '<' '='       { $$ = PF_OP_LE; }
5071                 | '<'           { $$ = PF_OP_LT; }
5072                 | '>' '='       { $$ = PF_OP_GE; }
5073                 | '>'           { $$ = PF_OP_GT; }
5074                 ;
5075
5076 %%
5077
5078 int
5079 yyerror(const char *fmt, ...)
5080 {
5081         va_list          ap;
5082
5083         file->errors++;
5084         va_start(ap, fmt);
5085         fprintf(stderr, "%s:%d: ", file->name, yylval.lineno);
5086         vfprintf(stderr, fmt, ap);
5087         fprintf(stderr, "\n");
5088         va_end(ap);
5089         return (0);
5090 }
5091
5092 int
5093 disallow_table(struct node_host *h, const char *fmt)
5094 {
5095         for (; h != NULL; h = h->next)
5096                 if (h->addr.type == PF_ADDR_TABLE) {
5097                         yyerror(fmt, h->addr.v.tblname);
5098                         return (1);
5099                 }
5100         return (0);
5101 }
5102
5103 int
5104 disallow_urpf_failed(struct node_host *h, const char *fmt)
5105 {
5106         for (; h != NULL; h = h->next)
5107                 if (h->addr.type == PF_ADDR_URPFFAILED) {
5108                         yyerror(fmt);
5109                         return (1);
5110                 }
5111         return (0);
5112 }
5113
5114 int
5115 disallow_alias(struct node_host *h, const char *fmt)
5116 {
5117         for (; h != NULL; h = h->next)
5118                 if (DYNIF_MULTIADDR(h->addr)) {
5119                         yyerror(fmt, h->addr.v.tblname);
5120                         return (1);
5121                 }
5122         return (0);
5123 }
5124
5125 int
5126 rule_consistent(struct pfctl_rule *r, int anchor_call)
5127 {
5128         int     problems = 0;
5129
5130         switch (r->action) {
5131         case PF_PASS:
5132         case PF_DROP:
5133         case PF_SCRUB:
5134         case PF_NOSCRUB:
5135                 problems = filter_consistent(r, anchor_call);
5136                 break;
5137         case PF_NAT:
5138         case PF_NONAT:
5139                 problems = nat_consistent(r);
5140                 break;
5141         case PF_RDR:
5142         case PF_NORDR:
5143                 problems = rdr_consistent(r);
5144                 break;
5145         case PF_BINAT:
5146         case PF_NOBINAT:
5147         default:
5148                 break;
5149         }
5150         return (problems);
5151 }
5152
5153 int
5154 filter_consistent(struct pfctl_rule *r, int anchor_call)
5155 {
5156         int     problems = 0;
5157
5158         if (r->proto != IPPROTO_TCP && r->proto != IPPROTO_UDP &&
5159             (r->src.port_op || r->dst.port_op)) {
5160                 yyerror("port only applies to tcp/udp");
5161                 problems++;
5162         }
5163         if (r->proto != IPPROTO_ICMP && r->proto != IPPROTO_ICMPV6 &&
5164             (r->type || r->code)) {
5165                 yyerror("icmp-type/code only applies to icmp");
5166                 problems++;
5167         }
5168         if (!r->af && (r->type || r->code)) {
5169                 yyerror("must indicate address family with icmp-type/code");
5170                 problems++;
5171         }
5172         if (r->overload_tblname[0] &&
5173             r->max_src_conn == 0 && r->max_src_conn_rate.seconds == 0) {
5174                 yyerror("'overload' requires 'max-src-conn' "
5175                     "or 'max-src-conn-rate'");
5176                 problems++;
5177         }
5178         if ((r->proto == IPPROTO_ICMP && r->af == AF_INET6) ||
5179             (r->proto == IPPROTO_ICMPV6 && r->af == AF_INET)) {
5180                 yyerror("proto %s doesn't match address family %s",
5181                     r->proto == IPPROTO_ICMP ? "icmp" : "icmp6",
5182                     r->af == AF_INET ? "inet" : "inet6");
5183                 problems++;
5184         }
5185         if (r->allow_opts && r->action != PF_PASS) {
5186                 yyerror("allow-opts can only be specified for pass rules");
5187                 problems++;
5188         }
5189         if (r->rule_flag & PFRULE_FRAGMENT && (r->src.port_op ||
5190             r->dst.port_op || r->flagset || r->type || r->code)) {
5191                 yyerror("fragments can be filtered only on IP header fields");
5192                 problems++;
5193         }
5194         if (r->rule_flag & PFRULE_RETURNRST && r->proto != IPPROTO_TCP) {
5195                 yyerror("return-rst can only be applied to TCP rules");
5196                 problems++;
5197         }
5198         if (r->max_src_nodes && !(r->rule_flag & PFRULE_RULESRCTRACK)) {
5199                 yyerror("max-src-nodes requires 'source-track rule'");
5200                 problems++;
5201         }
5202         if (r->action == PF_DROP && r->keep_state) {
5203                 yyerror("keep state on block rules doesn't make sense");
5204                 problems++;
5205         }
5206         if (r->rule_flag & PFRULE_STATESLOPPY &&
5207             (r->keep_state == PF_STATE_MODULATE ||
5208             r->keep_state == PF_STATE_SYNPROXY)) {
5209                 yyerror("sloppy state matching cannot be used with "
5210                     "synproxy state or modulate state");
5211                 problems++;
5212         }
5213         return (-problems);
5214 }
5215
5216 int
5217 nat_consistent(struct pfctl_rule *r)
5218 {
5219         return (0);     /* yeah! */
5220 }
5221
5222 int
5223 rdr_consistent(struct pfctl_rule *r)
5224 {
5225         int                      problems = 0;
5226
5227         if (r->proto != IPPROTO_TCP && r->proto != IPPROTO_UDP) {
5228                 if (r->src.port_op) {
5229                         yyerror("src port only applies to tcp/udp");
5230                         problems++;
5231                 }
5232                 if (r->dst.port_op) {
5233                         yyerror("dst port only applies to tcp/udp");
5234                         problems++;
5235                 }
5236                 if (r->rpool.proxy_port[0]) {
5237                         yyerror("rpool port only applies to tcp/udp");
5238                         problems++;
5239                 }
5240         }
5241         if (r->dst.port_op &&
5242             r->dst.port_op != PF_OP_EQ && r->dst.port_op != PF_OP_RRG) {
5243                 yyerror("invalid port operator for rdr destination port");
5244                 problems++;
5245         }
5246         return (-problems);
5247 }
5248
5249 int
5250 process_tabledef(char *name, struct table_opts *opts)
5251 {
5252         struct pfr_buffer        ab;
5253         struct node_tinit       *ti;
5254         unsigned long            maxcount;
5255         size_t                   s = sizeof(maxcount);
5256
5257         bzero(&ab, sizeof(ab));
5258         ab.pfrb_type = PFRB_ADDRS;
5259         SIMPLEQ_FOREACH(ti, &opts->init_nodes, entries) {
5260                 if (ti->file)
5261                         if (pfr_buf_load(&ab, ti->file, 0, append_addr)) {
5262                                 if (errno)
5263                                         yyerror("cannot load \"%s\": %s",
5264                                             ti->file, strerror(errno));
5265                                 else
5266                                         yyerror("file \"%s\" contains bad data",
5267                                             ti->file);
5268                                 goto _error;
5269                         }
5270                 if (ti->host)
5271                         if (append_addr_host(&ab, ti->host, 0, 0)) {
5272                                 yyerror("cannot create address buffer: %s",
5273                                     strerror(errno));
5274                                 goto _error;
5275                         }
5276         }
5277         if (pf->opts & PF_OPT_VERBOSE)
5278                 print_tabledef(name, opts->flags, opts->init_addr,
5279                     &opts->init_nodes);
5280         if (!(pf->opts & PF_OPT_NOACTION) &&
5281             pfctl_define_table(name, opts->flags, opts->init_addr,
5282             pf->anchor->name, &ab, pf->anchor->ruleset.tticket)) {
5283
5284                 if (sysctlbyname("net.pf.request_maxcount", &maxcount, &s,
5285                     NULL, 0) == -1)
5286                         maxcount = 65535;
5287
5288                 if (ab.pfrb_size > maxcount)
5289                         yyerror("cannot define table %s: too many elements.\n"
5290                             "Consider increasing net.pf.request_maxcount.",
5291                             name);
5292                 else
5293                         yyerror("cannot define table %s: %s", name,
5294                             pfr_strerror(errno));
5295
5296                 goto _error;
5297         }
5298         pf->tdirty = 1;
5299         pfr_buf_clear(&ab);
5300         return (0);
5301 _error:
5302         pfr_buf_clear(&ab);
5303         return (-1);
5304 }
5305
5306 struct keywords {
5307         const char      *k_name;
5308         int              k_val;
5309 };
5310
5311 /* macro gore, but you should've seen the prior indentation nightmare... */
5312
5313 #define FREE_LIST(T,r) \
5314         do { \
5315                 T *p, *node = r; \
5316                 while (node != NULL) { \
5317                         p = node; \
5318                         node = node->next; \
5319                         free(p); \
5320                 } \
5321         } while (0)
5322
5323 #define LOOP_THROUGH(T,n,r,C) \
5324         do { \
5325                 T *n; \
5326                 if (r == NULL) { \
5327                         r = calloc(1, sizeof(T)); \
5328                         if (r == NULL) \
5329                                 err(1, "LOOP: calloc"); \
5330                         r->next = NULL; \
5331                 } \
5332                 n = r; \
5333                 while (n != NULL) { \
5334                         do { \
5335                                 C; \
5336                         } while (0); \
5337                         n = n->next; \
5338                 } \
5339         } while (0)
5340
5341 void
5342 expand_label_str(char *label, size_t len, const char *srch, const char *repl)
5343 {
5344         char *tmp;
5345         char *p, *q;
5346
5347         if ((tmp = calloc(1, len)) == NULL)
5348                 err(1, "expand_label_str: calloc");
5349         p = q = label;
5350         while ((q = strstr(p, srch)) != NULL) {
5351                 *q = '\0';
5352                 if ((strlcat(tmp, p, len) >= len) ||
5353                     (strlcat(tmp, repl, len) >= len))
5354                         errx(1, "expand_label: label too long");
5355                 q += strlen(srch);
5356                 p = q;
5357         }
5358         if (strlcat(tmp, p, len) >= len)
5359                 errx(1, "expand_label: label too long");
5360         strlcpy(label, tmp, len);       /* always fits */
5361         free(tmp);
5362 }
5363
5364 void
5365 expand_label_if(const char *name, char *label, size_t len, const char *ifname)
5366 {
5367         if (strstr(label, name) != NULL) {
5368                 if (!*ifname)
5369                         expand_label_str(label, len, name, "any");
5370                 else
5371                         expand_label_str(label, len, name, ifname);
5372         }
5373 }
5374
5375 void
5376 expand_label_addr(const char *name, char *label, size_t len, sa_family_t af,
5377     struct pf_rule_addr *addr)
5378 {
5379         char tmp[64], tmp_not[66];
5380
5381         if (strstr(label, name) != NULL) {
5382                 switch (addr->addr.type) {
5383                 case PF_ADDR_DYNIFTL:
5384                         snprintf(tmp, sizeof(tmp), "(%s)", addr->addr.v.ifname);
5385                         break;
5386                 case PF_ADDR_TABLE:
5387                         snprintf(tmp, sizeof(tmp), "<%s>", addr->addr.v.tblname);
5388                         break;
5389                 case PF_ADDR_NOROUTE:
5390                         snprintf(tmp, sizeof(tmp), "no-route");
5391                         break;
5392                 case PF_ADDR_URPFFAILED:
5393                         snprintf(tmp, sizeof(tmp), "urpf-failed");
5394                         break;
5395                 case PF_ADDR_ADDRMASK:
5396                         if (!af || (PF_AZERO(&addr->addr.v.a.addr, af) &&
5397                             PF_AZERO(&addr->addr.v.a.mask, af)))
5398                                 snprintf(tmp, sizeof(tmp), "any");
5399                         else {
5400                                 char    a[48];
5401                                 int     bits;
5402
5403                                 if (inet_ntop(af, &addr->addr.v.a.addr, a,
5404                                     sizeof(a)) == NULL)
5405                                         snprintf(tmp, sizeof(tmp), "?");
5406                                 else {
5407                                         bits = unmask(&addr->addr.v.a.mask, af);
5408                                         if ((af == AF_INET && bits < 32) ||
5409                                             (af == AF_INET6 && bits < 128))
5410                                                 snprintf(tmp, sizeof(tmp),
5411                                                     "%s/%d", a, bits);
5412                                         else
5413                                                 snprintf(tmp, sizeof(tmp),
5414                                                     "%s", a);
5415                                 }
5416                         }
5417                         break;
5418                 default:
5419                         snprintf(tmp, sizeof(tmp), "?");
5420                         break;
5421                 }
5422
5423                 if (addr->neg) {
5424                         snprintf(tmp_not, sizeof(tmp_not), "! %s", tmp);
5425                         expand_label_str(label, len, name, tmp_not);
5426                 } else
5427                         expand_label_str(label, len, name, tmp);
5428         }
5429 }
5430
5431 void
5432 expand_label_port(const char *name, char *label, size_t len,
5433     struct pf_rule_addr *addr)
5434 {
5435         char     a1[6], a2[6], op[13] = "";
5436
5437         if (strstr(label, name) != NULL) {
5438                 snprintf(a1, sizeof(a1), "%u", ntohs(addr->port[0]));
5439                 snprintf(a2, sizeof(a2), "%u", ntohs(addr->port[1]));
5440                 if (!addr->port_op)
5441                         ;
5442                 else if (addr->port_op == PF_OP_IRG)
5443                         snprintf(op, sizeof(op), "%s><%s", a1, a2);
5444                 else if (addr->port_op == PF_OP_XRG)
5445                         snprintf(op, sizeof(op), "%s<>%s", a1, a2);
5446                 else if (addr->port_op == PF_OP_EQ)
5447                         snprintf(op, sizeof(op), "%s", a1);
5448                 else if (addr->port_op == PF_OP_NE)
5449                         snprintf(op, sizeof(op), "!=%s", a1);
5450                 else if (addr->port_op == PF_OP_LT)
5451                         snprintf(op, sizeof(op), "<%s", a1);
5452                 else if (addr->port_op == PF_OP_LE)
5453                         snprintf(op, sizeof(op), "<=%s", a1);
5454                 else if (addr->port_op == PF_OP_GT)
5455                         snprintf(op, sizeof(op), ">%s", a1);
5456                 else if (addr->port_op == PF_OP_GE)
5457                         snprintf(op, sizeof(op), ">=%s", a1);
5458                 expand_label_str(label, len, name, op);
5459         }
5460 }
5461
5462 void
5463 expand_label_proto(const char *name, char *label, size_t len, u_int8_t proto)
5464 {
5465         const char *protoname;
5466         char n[4];
5467
5468         if (strstr(label, name) != NULL) {
5469                 protoname = pfctl_proto2name(proto);
5470                 if (protoname != NULL)
5471                         expand_label_str(label, len, name, protoname);
5472                 else {
5473                         snprintf(n, sizeof(n), "%u", proto);
5474                         expand_label_str(label, len, name, n);
5475                 }
5476         }
5477 }
5478
5479 void
5480 expand_label_nr(const char *name, char *label, size_t len,
5481     struct pfctl_rule *r)
5482 {
5483         char n[11];
5484
5485         if (strstr(label, name) != NULL) {
5486                 snprintf(n, sizeof(n), "%u", r->nr);
5487                 expand_label_str(label, len, name, n);
5488         }
5489 }
5490
5491 void
5492 expand_label(char *label, size_t len, struct pfctl_rule *r)
5493 {
5494         expand_label_if("$if", label, len, r->ifname);
5495         expand_label_addr("$srcaddr", label, len, r->af, &r->src);
5496         expand_label_addr("$dstaddr", label, len, r->af, &r->dst);
5497         expand_label_port("$srcport", label, len, &r->src);
5498         expand_label_port("$dstport", label, len, &r->dst);
5499         expand_label_proto("$proto", label, len, r->proto);
5500         expand_label_nr("$nr", label, len, r);
5501 }
5502
5503 int
5504 expand_altq(struct pf_altq *a, struct node_if *interfaces,
5505     struct node_queue *nqueues, struct node_queue_bw bwspec,
5506     struct node_queue_opt *opts)
5507 {
5508         struct pf_altq           pa, pb;
5509         char                     qname[PF_QNAME_SIZE];
5510         struct node_queue       *n;
5511         struct node_queue_bw     bw;
5512         int                      errs = 0;
5513
5514         if ((pf->loadopt & PFCTL_FLAG_ALTQ) == 0) {
5515                 FREE_LIST(struct node_if, interfaces);
5516                 if (nqueues)
5517                         FREE_LIST(struct node_queue, nqueues);
5518                 return (0);
5519         }
5520
5521         LOOP_THROUGH(struct node_if, interface, interfaces,
5522                 memcpy(&pa, a, sizeof(struct pf_altq));
5523                 if (strlcpy(pa.ifname, interface->ifname,
5524                     sizeof(pa.ifname)) >= sizeof(pa.ifname))
5525                         errx(1, "expand_altq: strlcpy");
5526
5527                 if (interface->not) {
5528                         yyerror("altq on ! <interface> is not supported");
5529                         errs++;
5530                 } else {
5531                         if (eval_pfaltq(pf, &pa, &bwspec, opts))
5532                                 errs++;
5533                         else
5534                                 if (pfctl_add_altq(pf, &pa))
5535                                         errs++;
5536
5537                         if (pf->opts & PF_OPT_VERBOSE) {
5538                                 print_altq(&pf->paltq->altq, 0,
5539                                     &bwspec, opts);
5540                                 if (nqueues && nqueues->tail) {
5541                                         printf("queue { ");
5542                                         LOOP_THROUGH(struct node_queue, queue,
5543                                             nqueues,
5544                                                 printf("%s ",
5545                                                     queue->queue);
5546                                         );
5547                                         printf("}");
5548                                 }
5549                                 printf("\n");
5550                         }
5551
5552                         if (pa.scheduler == ALTQT_CBQ ||
5553                             pa.scheduler == ALTQT_HFSC ||
5554                             pa.scheduler == ALTQT_FAIRQ) {
5555                                 /* now create a root queue */
5556                                 memset(&pb, 0, sizeof(struct pf_altq));
5557                                 if (strlcpy(qname, "root_", sizeof(qname)) >=
5558                                     sizeof(qname))
5559                                         errx(1, "expand_altq: strlcpy");
5560                                 if (strlcat(qname, interface->ifname,
5561                                     sizeof(qname)) >= sizeof(qname))
5562                                         errx(1, "expand_altq: strlcat");
5563                                 if (strlcpy(pb.qname, qname,
5564                                     sizeof(pb.qname)) >= sizeof(pb.qname))
5565                                         errx(1, "expand_altq: strlcpy");
5566                                 if (strlcpy(pb.ifname, interface->ifname,
5567                                     sizeof(pb.ifname)) >= sizeof(pb.ifname))
5568                                         errx(1, "expand_altq: strlcpy");
5569                                 pb.qlimit = pa.qlimit;
5570                                 pb.scheduler = pa.scheduler;
5571                                 bw.bw_absolute = pa.ifbandwidth;
5572                                 bw.bw_percent = 0;
5573                                 if (eval_pfqueue(pf, &pb, &bw, opts))
5574                                         errs++;
5575                                 else
5576                                         if (pfctl_add_altq(pf, &pb))
5577                                                 errs++;
5578                         }
5579
5580                         LOOP_THROUGH(struct node_queue, queue, nqueues,
5581                                 n = calloc(1, sizeof(struct node_queue));
5582                                 if (n == NULL)
5583                                         err(1, "expand_altq: calloc");
5584                                 if (pa.scheduler == ALTQT_CBQ ||
5585                                     pa.scheduler == ALTQT_HFSC ||
5586                                     pa.scheduler == ALTQT_FAIRQ)
5587                                         if (strlcpy(n->parent, qname,
5588                                             sizeof(n->parent)) >=
5589                                             sizeof(n->parent))
5590                                                 errx(1, "expand_altq: strlcpy");
5591                                 if (strlcpy(n->queue, queue->queue,
5592                                     sizeof(n->queue)) >= sizeof(n->queue))
5593                                         errx(1, "expand_altq: strlcpy");
5594                                 if (strlcpy(n->ifname, interface->ifname,
5595                                     sizeof(n->ifname)) >= sizeof(n->ifname))
5596                                         errx(1, "expand_altq: strlcpy");
5597                                 n->scheduler = pa.scheduler;
5598                                 n->next = NULL;
5599                                 n->tail = n;
5600                                 if (queues == NULL)
5601                                         queues = n;
5602                                 else {
5603                                         queues->tail->next = n;
5604                                         queues->tail = n;
5605                                 }
5606                         );
5607                 }
5608         );
5609         FREE_LIST(struct node_if, interfaces);
5610         if (nqueues)
5611                 FREE_LIST(struct node_queue, nqueues);
5612
5613         return (errs);
5614 }
5615
5616 int
5617 expand_queue(struct pf_altq *a, struct node_if *interfaces,
5618     struct node_queue *nqueues, struct node_queue_bw bwspec,
5619     struct node_queue_opt *opts)
5620 {
5621         struct node_queue       *n, *nq;
5622         struct pf_altq           pa;
5623         u_int8_t                 found = 0;
5624         u_int8_t                 errs = 0;
5625
5626         if ((pf->loadopt & PFCTL_FLAG_ALTQ) == 0) {
5627                 FREE_LIST(struct node_queue, nqueues);
5628                 return (0);
5629         }
5630
5631         if (queues == NULL) {
5632                 yyerror("queue %s has no parent", a->qname);
5633                 FREE_LIST(struct node_queue, nqueues);
5634                 return (1);
5635         }
5636
5637         LOOP_THROUGH(struct node_if, interface, interfaces,
5638                 LOOP_THROUGH(struct node_queue, tqueue, queues,
5639                         if (!strncmp(a->qname, tqueue->queue, PF_QNAME_SIZE) &&
5640                             (interface->ifname[0] == 0 ||
5641                             (!interface->not && !strncmp(interface->ifname,
5642                             tqueue->ifname, IFNAMSIZ)) ||
5643                             (interface->not && strncmp(interface->ifname,
5644                             tqueue->ifname, IFNAMSIZ)))) {
5645                                 /* found ourself in queues */
5646                                 found++;
5647
5648                                 memcpy(&pa, a, sizeof(struct pf_altq));
5649
5650                                 if (pa.scheduler != ALTQT_NONE &&
5651                                     pa.scheduler != tqueue->scheduler) {
5652                                         yyerror("exactly one scheduler type "
5653                                             "per interface allowed");
5654                                         return (1);
5655                                 }
5656                                 pa.scheduler = tqueue->scheduler;
5657
5658                                 /* scheduler dependent error checking */
5659                                 switch (pa.scheduler) {
5660                                 case ALTQT_PRIQ:
5661                                         if (nqueues != NULL) {
5662                                                 yyerror("priq queues cannot "
5663                                                     "have child queues");
5664                                                 return (1);
5665                                         }
5666                                         if (bwspec.bw_absolute > 0 ||
5667                                             bwspec.bw_percent < 100) {
5668                                                 yyerror("priq doesn't take "
5669                                                     "bandwidth");
5670                                                 return (1);
5671                                         }
5672                                         break;
5673                                 default:
5674                                         break;
5675                                 }
5676
5677                                 if (strlcpy(pa.ifname, tqueue->ifname,
5678                                     sizeof(pa.ifname)) >= sizeof(pa.ifname))
5679                                         errx(1, "expand_queue: strlcpy");
5680                                 if (strlcpy(pa.parent, tqueue->parent,
5681                                     sizeof(pa.parent)) >= sizeof(pa.parent))
5682                                         errx(1, "expand_queue: strlcpy");
5683
5684                                 if (eval_pfqueue(pf, &pa, &bwspec, opts))
5685                                         errs++;
5686                                 else
5687                                         if (pfctl_add_altq(pf, &pa))
5688                                                 errs++;
5689
5690                                 for (nq = nqueues; nq != NULL; nq = nq->next) {
5691                                         if (!strcmp(a->qname, nq->queue)) {
5692                                                 yyerror("queue cannot have "
5693                                                     "itself as child");
5694                                                 errs++;
5695                                                 continue;
5696                                         }
5697                                         n = calloc(1,
5698                                             sizeof(struct node_queue));
5699                                         if (n == NULL)
5700                                                 err(1, "expand_queue: calloc");
5701                                         if (strlcpy(n->parent, a->qname,
5702                                             sizeof(n->parent)) >=
5703                                             sizeof(n->parent))
5704                                                 errx(1, "expand_queue strlcpy");
5705                                         if (strlcpy(n->queue, nq->queue,
5706                                             sizeof(n->queue)) >=
5707                                             sizeof(n->queue))
5708                                                 errx(1, "expand_queue strlcpy");
5709                                         if (strlcpy(n->ifname, tqueue->ifname,
5710                                             sizeof(n->ifname)) >=
5711                                             sizeof(n->ifname))
5712                                                 errx(1, "expand_queue strlcpy");
5713                                         n->scheduler = tqueue->scheduler;
5714                                         n->next = NULL;
5715                                         n->tail = n;
5716                                         if (queues == NULL)
5717                                                 queues = n;
5718                                         else {
5719                                                 queues->tail->next = n;
5720                                                 queues->tail = n;
5721                                         }
5722                                 }
5723                                 if ((pf->opts & PF_OPT_VERBOSE) && (
5724                                     (found == 1 && interface->ifname[0] == 0) ||
5725                                     (found > 0 && interface->ifname[0] != 0))) {
5726                                         print_queue(&pf->paltq->altq, 0,
5727                                             &bwspec, interface->ifname[0] != 0,
5728                                             opts);
5729                                         if (nqueues && nqueues->tail) {
5730                                                 printf("{ ");
5731                                                 LOOP_THROUGH(struct node_queue,
5732                                                     queue, nqueues,
5733                                                         printf("%s ",
5734                                                             queue->queue);
5735                                                 );
5736                                                 printf("}");
5737                                         }
5738                                         printf("\n");
5739                                 }
5740                         }
5741                 );
5742         );
5743
5744         FREE_LIST(struct node_queue, nqueues);
5745         FREE_LIST(struct node_if, interfaces);
5746
5747         if (!found) {
5748                 yyerror("queue %s has no parent", a->qname);
5749                 errs++;
5750         }
5751
5752         if (errs)
5753                 return (1);
5754         else
5755                 return (0);
5756 }
5757
5758 static int
5759 pf_af_to_proto(sa_family_t af)
5760 {
5761         if (af == AF_INET)
5762                 return (ETHERTYPE_IP);
5763         if (af == AF_INET6)
5764                 return (ETHERTYPE_IPV6);
5765
5766         return (0);
5767 }
5768
5769 void
5770 expand_eth_rule(struct pfctl_eth_rule *r,
5771     struct node_if *interfaces, struct node_etherproto *protos,
5772     struct node_mac *srcs, struct node_mac *dsts,
5773     struct node_host *ipsrcs, struct node_host *ipdsts, const char *anchor_call)
5774 {
5775         LOOP_THROUGH(struct node_if, interface, interfaces,
5776         LOOP_THROUGH(struct node_etherproto, proto, protos,
5777         LOOP_THROUGH(struct node_mac, src, srcs,
5778         LOOP_THROUGH(struct node_mac, dst, dsts,
5779         LOOP_THROUGH(struct node_host, ipsrc, ipsrcs,
5780         LOOP_THROUGH(struct node_host, ipdst, ipdsts,
5781                 strlcpy(r->ifname, interface->ifname,
5782                     sizeof(r->ifname));
5783                 r->ifnot = interface->not;
5784                 r->proto = proto->proto;
5785                 if (!r->proto && ipsrc->af)
5786                         r->proto = pf_af_to_proto(ipsrc->af);
5787                 else if (!r->proto && ipdst->af)
5788                         r->proto = pf_af_to_proto(ipdst->af);
5789                 bcopy(src->mac, r->src.addr, ETHER_ADDR_LEN);
5790                 bcopy(src->mask, r->src.mask, ETHER_ADDR_LEN);
5791                 r->src.neg = src->neg;
5792                 r->src.isset = src->isset;
5793                 r->ipsrc.addr = ipsrc->addr;
5794                 r->ipsrc.neg = ipsrc->not;
5795                 r->ipdst.addr = ipdst->addr;
5796                 r->ipdst.neg = ipdst->not;
5797                 bcopy(dst->mac, r->dst.addr, ETHER_ADDR_LEN);
5798                 bcopy(dst->mask, r->dst.mask, ETHER_ADDR_LEN);
5799                 r->dst.neg = dst->neg;
5800                 r->dst.isset = dst->isset;
5801                 r->nr = pf->eastack[pf->asd]->match++;
5802
5803                 pfctl_append_eth_rule(pf, r, anchor_call);
5804         ))))));
5805
5806         FREE_LIST(struct node_if, interfaces);
5807         FREE_LIST(struct node_etherproto, protos);
5808         FREE_LIST(struct node_mac, srcs);
5809         FREE_LIST(struct node_mac, dsts);
5810         FREE_LIST(struct node_host, ipsrcs);
5811         FREE_LIST(struct node_host, ipdsts);
5812 }
5813
5814 void
5815 expand_rule(struct pfctl_rule *r,
5816     struct node_if *interfaces, struct node_host *rpool_hosts,
5817     struct node_proto *protos, struct node_os *src_oses,
5818     struct node_host *src_hosts, struct node_port *src_ports,
5819     struct node_host *dst_hosts, struct node_port *dst_ports,
5820     struct node_uid *uids, struct node_gid *gids, struct node_icmp *icmp_types,
5821     const char *anchor_call)
5822 {
5823         sa_family_t              af = r->af;
5824         int                      added = 0, error = 0;
5825         char                     ifname[IF_NAMESIZE];
5826         char                     label[PF_RULE_MAX_LABEL_COUNT][PF_RULE_LABEL_SIZE];
5827         char                     tagname[PF_TAG_NAME_SIZE];
5828         char                     match_tagname[PF_TAG_NAME_SIZE];
5829         struct pf_pooladdr      *pa;
5830         struct node_host        *h;
5831         u_int8_t                 flags, flagset, keep_state;
5832
5833         memcpy(label, r->label, sizeof(r->label));
5834         assert(sizeof(r->label) == sizeof(label));
5835         if (strlcpy(tagname, r->tagname, sizeof(tagname)) >= sizeof(tagname))
5836                 errx(1, "expand_rule: strlcpy");
5837         if (strlcpy(match_tagname, r->match_tagname, sizeof(match_tagname)) >=
5838             sizeof(match_tagname))
5839                 errx(1, "expand_rule: strlcpy");
5840         flags = r->flags;
5841         flagset = r->flagset;
5842         keep_state = r->keep_state;
5843
5844         LOOP_THROUGH(struct node_if, interface, interfaces,
5845         LOOP_THROUGH(struct node_proto, proto, protos,
5846         LOOP_THROUGH(struct node_icmp, icmp_type, icmp_types,
5847         LOOP_THROUGH(struct node_host, src_host, src_hosts,
5848         LOOP_THROUGH(struct node_port, src_port, src_ports,
5849         LOOP_THROUGH(struct node_os, src_os, src_oses,
5850         LOOP_THROUGH(struct node_host, dst_host, dst_hosts,
5851         LOOP_THROUGH(struct node_port, dst_port, dst_ports,
5852         LOOP_THROUGH(struct node_uid, uid, uids,
5853         LOOP_THROUGH(struct node_gid, gid, gids,
5854
5855                 r->af = af;
5856                 /* for link-local IPv6 address, interface must match up */
5857                 if ((r->af && src_host->af && r->af != src_host->af) ||
5858                     (r->af && dst_host->af && r->af != dst_host->af) ||
5859                     (src_host->af && dst_host->af &&
5860                     src_host->af != dst_host->af) ||
5861                     (src_host->ifindex && dst_host->ifindex &&
5862                     src_host->ifindex != dst_host->ifindex) ||
5863                     (src_host->ifindex && *interface->ifname &&
5864                     src_host->ifindex != if_nametoindex(interface->ifname)) ||
5865                     (dst_host->ifindex && *interface->ifname &&
5866                     dst_host->ifindex != if_nametoindex(interface->ifname)))
5867                         continue;
5868                 if (!r->af && src_host->af)
5869                         r->af = src_host->af;
5870                 else if (!r->af && dst_host->af)
5871                         r->af = dst_host->af;
5872
5873                 if (*interface->ifname)
5874                         strlcpy(r->ifname, interface->ifname,
5875                             sizeof(r->ifname));
5876                 else if (if_indextoname(src_host->ifindex, ifname))
5877                         strlcpy(r->ifname, ifname, sizeof(r->ifname));
5878                 else if (if_indextoname(dst_host->ifindex, ifname))
5879                         strlcpy(r->ifname, ifname, sizeof(r->ifname));
5880                 else
5881                         memset(r->ifname, '\0', sizeof(r->ifname));
5882
5883                 memcpy(r->label, label, sizeof(r->label));
5884                 if (strlcpy(r->tagname, tagname, sizeof(r->tagname)) >=
5885                     sizeof(r->tagname))
5886                         errx(1, "expand_rule: strlcpy");
5887                 if (strlcpy(r->match_tagname, match_tagname,
5888                     sizeof(r->match_tagname)) >= sizeof(r->match_tagname))
5889                         errx(1, "expand_rule: strlcpy");
5890
5891                 error += check_netmask(src_host, r->af);
5892                 error += check_netmask(dst_host, r->af);
5893
5894                 r->ifnot = interface->not;
5895                 r->proto = proto->proto;
5896                 r->src.addr = src_host->addr;
5897                 r->src.neg = src_host->not;
5898                 r->src.port[0] = src_port->port[0];
5899                 r->src.port[1] = src_port->port[1];
5900                 r->src.port_op = src_port->op;
5901                 r->dst.addr = dst_host->addr;
5902                 r->dst.neg = dst_host->not;
5903                 r->dst.port[0] = dst_port->port[0];
5904                 r->dst.port[1] = dst_port->port[1];
5905                 r->dst.port_op = dst_port->op;
5906                 r->uid.op = uid->op;
5907                 r->uid.uid[0] = uid->uid[0];
5908                 r->uid.uid[1] = uid->uid[1];
5909                 r->gid.op = gid->op;
5910                 r->gid.gid[0] = gid->gid[0];
5911                 r->gid.gid[1] = gid->gid[1];
5912                 r->type = icmp_type->type;
5913                 r->code = icmp_type->code;
5914
5915                 if ((keep_state == PF_STATE_MODULATE ||
5916                     keep_state == PF_STATE_SYNPROXY) &&
5917                     r->proto && r->proto != IPPROTO_TCP)
5918                         r->keep_state = PF_STATE_NORMAL;
5919                 else
5920                         r->keep_state = keep_state;
5921
5922                 if (r->proto && r->proto != IPPROTO_TCP) {
5923                         r->flags = 0;
5924                         r->flagset = 0;
5925                 } else {
5926                         r->flags = flags;
5927                         r->flagset = flagset;
5928                 }
5929                 if (icmp_type->proto && r->proto != icmp_type->proto) {
5930                         yyerror("icmp-type mismatch");
5931                         error++;
5932                 }
5933
5934                 if (src_os && src_os->os) {
5935                         r->os_fingerprint = pfctl_get_fingerprint(src_os->os);
5936                         if ((pf->opts & PF_OPT_VERBOSE2) &&
5937                             r->os_fingerprint == PF_OSFP_NOMATCH)
5938                                 fprintf(stderr,
5939                                     "warning: unknown '%s' OS fingerprint\n",
5940                                     src_os->os);
5941                 } else {
5942                         r->os_fingerprint = PF_OSFP_ANY;
5943                 }
5944
5945                 TAILQ_INIT(&r->rpool.list);
5946                 for (h = rpool_hosts; h != NULL; h = h->next) {
5947                         pa = calloc(1, sizeof(struct pf_pooladdr));
5948                         if (pa == NULL)
5949                                 err(1, "expand_rule: calloc");
5950                         pa->addr = h->addr;
5951                         if (h->ifname != NULL) {
5952                                 if (strlcpy(pa->ifname, h->ifname,
5953                                     sizeof(pa->ifname)) >=
5954                                     sizeof(pa->ifname))
5955                                         errx(1, "expand_rule: strlcpy");
5956                         } else
5957                                 pa->ifname[0] = 0;
5958                         TAILQ_INSERT_TAIL(&r->rpool.list, pa, entries);
5959                 }
5960
5961                 if (rule_consistent(r, anchor_call[0]) < 0 || error)
5962                         yyerror("skipping rule due to errors");
5963                 else {
5964                         r->nr = pf->astack[pf->asd]->match++;
5965                         pfctl_append_rule(pf, r, anchor_call);
5966                         added++;
5967                 }
5968
5969         ))))))))));
5970
5971         FREE_LIST(struct node_if, interfaces);
5972         FREE_LIST(struct node_proto, protos);
5973         FREE_LIST(struct node_host, src_hosts);
5974         FREE_LIST(struct node_port, src_ports);
5975         FREE_LIST(struct node_os, src_oses);
5976         FREE_LIST(struct node_host, dst_hosts);
5977         FREE_LIST(struct node_port, dst_ports);
5978         FREE_LIST(struct node_uid, uids);
5979         FREE_LIST(struct node_gid, gids);
5980         FREE_LIST(struct node_icmp, icmp_types);
5981         FREE_LIST(struct node_host, rpool_hosts);
5982
5983         if (!added)
5984                 yyerror("rule expands to no valid combination");
5985 }
5986
5987 int
5988 expand_skip_interface(struct node_if *interfaces)
5989 {
5990         int     errs = 0;
5991
5992         if (!interfaces || (!interfaces->next && !interfaces->not &&
5993             !strcmp(interfaces->ifname, "none"))) {
5994                 if (pf->opts & PF_OPT_VERBOSE)
5995                         printf("set skip on none\n");
5996                 errs = pfctl_set_interface_flags(pf, "", PFI_IFLAG_SKIP, 0);
5997                 return (errs);
5998         }
5999
6000         if (pf->opts & PF_OPT_VERBOSE)
6001                 printf("set skip on {");
6002         LOOP_THROUGH(struct node_if, interface, interfaces,
6003                 if (pf->opts & PF_OPT_VERBOSE)
6004                         printf(" %s", interface->ifname);
6005                 if (interface->not) {
6006                         yyerror("skip on ! <interface> is not supported");
6007                         errs++;
6008                 } else
6009                         errs += pfctl_set_interface_flags(pf,
6010                             interface->ifname, PFI_IFLAG_SKIP, 1);
6011         );
6012         if (pf->opts & PF_OPT_VERBOSE)
6013                 printf(" }\n");
6014
6015         FREE_LIST(struct node_if, interfaces);
6016
6017         if (errs)
6018                 return (1);
6019         else
6020                 return (0);
6021 }
6022
6023 #undef FREE_LIST
6024 #undef LOOP_THROUGH
6025
6026 int
6027 check_rulestate(int desired_state)
6028 {
6029         if (require_order && (rulestate > desired_state)) {
6030                 yyerror("Rules must be in order: options, ethernet, "
6031                     "normalization, queueing, translation, filtering");
6032                 return (1);
6033         }
6034         rulestate = desired_state;
6035         return (0);
6036 }
6037
6038 int
6039 kw_cmp(const void *k, const void *e)
6040 {
6041         return (strcmp(k, ((const struct keywords *)e)->k_name));
6042 }
6043
6044 int
6045 lookup(char *s)
6046 {
6047         /* this has to be sorted always */
6048         static const struct keywords keywords[] = {
6049                 { "all",                ALL},
6050                 { "allow-opts",         ALLOWOPTS},
6051                 { "altq",               ALTQ},
6052                 { "anchor",             ANCHOR},
6053                 { "antispoof",          ANTISPOOF},
6054                 { "any",                ANY},
6055                 { "bandwidth",          BANDWIDTH},
6056                 { "binat",              BINAT},
6057                 { "binat-anchor",       BINATANCHOR},
6058                 { "bitmask",            BITMASK},
6059                 { "block",              BLOCK},
6060                 { "block-policy",       BLOCKPOLICY},
6061                 { "buckets",            BUCKETS},
6062                 { "cbq",                CBQ},
6063                 { "code",               CODE},
6064                 { "codelq",             CODEL},
6065                 { "crop",               FRAGCROP},
6066                 { "debug",              DEBUG},
6067                 { "divert-reply",       DIVERTREPLY},
6068                 { "divert-to",          DIVERTTO},
6069                 { "dnpipe",             DNPIPE},
6070                 { "dnqueue",            DNQUEUE},
6071                 { "drop",               DROP},
6072                 { "drop-ovl",           FRAGDROP},
6073                 { "dup-to",             DUPTO},
6074                 { "ether",              ETHER},
6075                 { "fail-policy",        FAILPOLICY},
6076                 { "fairq",              FAIRQ},
6077                 { "fastroute",          FASTROUTE},
6078                 { "file",               FILENAME},
6079                 { "fingerprints",       FINGERPRINTS},
6080                 { "flags",              FLAGS},
6081                 { "floating",           FLOATING},
6082                 { "flush",              FLUSH},
6083                 { "for",                FOR},
6084                 { "fragment",           FRAGMENT},
6085                 { "from",               FROM},
6086                 { "global",             GLOBAL},
6087                 { "group",              GROUP},
6088                 { "hfsc",               HFSC},
6089                 { "hogs",               HOGS},
6090                 { "hostid",             HOSTID},
6091                 { "icmp-type",          ICMPTYPE},
6092                 { "icmp6-type",         ICMP6TYPE},
6093                 { "if-bound",           IFBOUND},
6094                 { "in",                 IN},
6095                 { "include",            INCLUDE},
6096                 { "inet",               INET},
6097                 { "inet6",              INET6},
6098                 { "interval",           INTERVAL},
6099                 { "keep",               KEEP},
6100                 { "keepcounters",       KEEPCOUNTERS},
6101                 { "l3",                 L3},
6102                 { "label",              LABEL},
6103                 { "limit",              LIMIT},
6104                 { "linkshare",          LINKSHARE},
6105                 { "load",               LOAD},
6106                 { "log",                LOG},
6107                 { "loginterface",       LOGINTERFACE},
6108                 { "map-e-portset",      MAPEPORTSET},
6109                 { "match",              MATCH},
6110                 { "max",                MAXIMUM},
6111                 { "max-mss",            MAXMSS},
6112                 { "max-src-conn",       MAXSRCCONN},
6113                 { "max-src-conn-rate",  MAXSRCCONNRATE},
6114                 { "max-src-nodes",      MAXSRCNODES},
6115                 { "max-src-states",     MAXSRCSTATES},
6116                 { "min-ttl",            MINTTL},
6117                 { "modulate",           MODULATE},
6118                 { "nat",                NAT},
6119                 { "nat-anchor",         NATANCHOR},
6120                 { "no",                 NO},
6121                 { "no-df",              NODF},
6122                 { "no-route",           NOROUTE},
6123                 { "no-sync",            NOSYNC},
6124                 { "on",                 ON},
6125                 { "optimization",       OPTIMIZATION},
6126                 { "os",                 OS},
6127                 { "out",                OUT},
6128                 { "overload",           OVERLOAD},
6129                 { "pass",               PASS},
6130                 { "port",               PORT},
6131                 { "prio",               PRIO},
6132                 { "priority",           PRIORITY},
6133                 { "priq",               PRIQ},
6134                 { "probability",        PROBABILITY},
6135                 { "proto",              PROTO},
6136                 { "qlimit",             QLIMIT},
6137                 { "queue",              QUEUE},
6138                 { "quick",              QUICK},
6139                 { "random",             RANDOM},
6140                 { "random-id",          RANDOMID},
6141                 { "rdr",                RDR},
6142                 { "rdr-anchor",         RDRANCHOR},
6143                 { "realtime",           REALTIME},
6144                 { "reassemble",         REASSEMBLE},
6145                 { "reply-to",           REPLYTO},
6146                 { "require-order",      REQUIREORDER},
6147                 { "return",             RETURN},
6148                 { "return-icmp",        RETURNICMP},
6149                 { "return-icmp6",       RETURNICMP6},
6150                 { "return-rst",         RETURNRST},
6151                 { "ridentifier",        RIDENTIFIER},
6152                 { "round-robin",        ROUNDROBIN},
6153                 { "route",              ROUTE},
6154                 { "route-to",           ROUTETO},
6155                 { "rtable",             RTABLE},
6156                 { "rule",               RULE},
6157                 { "ruleset-optimization",       RULESET_OPTIMIZATION},
6158                 { "scrub",              SCRUB},
6159                 { "set",                SET},
6160                 { "set-tos",            SETTOS},
6161                 { "skip",               SKIP},
6162                 { "sloppy",             SLOPPY},
6163                 { "source-hash",        SOURCEHASH},
6164                 { "source-track",       SOURCETRACK},
6165                 { "state",              STATE},
6166                 { "state-defaults",     STATEDEFAULTS},
6167                 { "state-policy",       STATEPOLICY},
6168                 { "static-port",        STATICPORT},
6169                 { "sticky-address",     STICKYADDRESS},
6170                 { "syncookies",         SYNCOOKIES},
6171                 { "synproxy",           SYNPROXY},
6172                 { "table",              TABLE},
6173                 { "tag",                TAG},
6174                 { "tagged",             TAGGED},
6175                 { "target",             TARGET},
6176                 { "tbrsize",            TBRSIZE},
6177                 { "timeout",            TIMEOUT},
6178                 { "to",                 TO},
6179                 { "tos",                TOS},
6180                 { "ttl",                TTL},
6181                 { "upperlimit",         UPPERLIMIT},
6182                 { "urpf-failed",        URPFFAILED},
6183                 { "user",               USER},
6184         };
6185         const struct keywords   *p;
6186
6187         p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
6188             sizeof(keywords[0]), kw_cmp);
6189
6190         if (p) {
6191                 if (debug > 1)
6192                         fprintf(stderr, "%s: %d\n", s, p->k_val);
6193                 return (p->k_val);
6194         } else {
6195                 if (debug > 1)
6196                         fprintf(stderr, "string: %s\n", s);
6197                 return (STRING);
6198         }
6199 }
6200
6201 #define MAXPUSHBACK     128
6202
6203 static char     *parsebuf;
6204 static int       parseindex;
6205 static char      pushback_buffer[MAXPUSHBACK];
6206 static int       pushback_index = 0;
6207
6208 int
6209 lgetc(int quotec)
6210 {
6211         int             c, next;
6212
6213         if (parsebuf) {
6214                 /* Read character from the parsebuffer instead of input. */
6215                 if (parseindex >= 0) {
6216                         c = parsebuf[parseindex++];
6217                         if (c != '\0')
6218                                 return (c);
6219                         parsebuf = NULL;
6220                 } else
6221                         parseindex++;
6222         }
6223
6224         if (pushback_index)
6225                 return (pushback_buffer[--pushback_index]);
6226
6227         if (quotec) {
6228                 if ((c = getc(file->stream)) == EOF) {
6229                         yyerror("reached end of file while parsing quoted string");
6230                         if (popfile() == EOF)
6231                                 return (EOF);
6232                         return (quotec);
6233                 }
6234                 return (c);
6235         }
6236
6237         while ((c = getc(file->stream)) == '\\') {
6238                 next = getc(file->stream);
6239                 if (next != '\n') {
6240                         c = next;
6241                         break;
6242                 }
6243                 yylval.lineno = file->lineno;
6244                 file->lineno++;
6245         }
6246
6247         while (c == EOF) {
6248                 if (popfile() == EOF)
6249                         return (EOF);
6250                 c = getc(file->stream);
6251         }
6252         return (c);
6253 }
6254
6255 int
6256 lungetc(int c)
6257 {
6258         if (c == EOF)
6259                 return (EOF);
6260         if (parsebuf) {
6261                 parseindex--;
6262                 if (parseindex >= 0)
6263                         return (c);
6264         }
6265         if (pushback_index < MAXPUSHBACK-1)
6266                 return (pushback_buffer[pushback_index++] = c);
6267         else
6268                 return (EOF);
6269 }
6270
6271 int
6272 findeol(void)
6273 {
6274         int     c;
6275
6276         parsebuf = NULL;
6277
6278         /* skip to either EOF or the first real EOL */
6279         while (1) {
6280                 if (pushback_index)
6281                         c = pushback_buffer[--pushback_index];
6282                 else
6283                         c = lgetc(0);
6284                 if (c == '\n') {
6285                         file->lineno++;
6286                         break;
6287                 }
6288                 if (c == EOF)
6289                         break;
6290         }
6291         return (ERROR);
6292 }
6293
6294 int
6295 yylex(void)
6296 {
6297         char     buf[8096];
6298         char    *p, *val;
6299         int      quotec, next, c;
6300         int      token;
6301
6302 top:
6303         p = buf;
6304         while ((c = lgetc(0)) == ' ' || c == '\t')
6305                 ; /* nothing */
6306
6307         yylval.lineno = file->lineno;
6308         if (c == '#')
6309                 while ((c = lgetc(0)) != '\n' && c != EOF)
6310                         ; /* nothing */
6311         if (c == '$' && parsebuf == NULL) {
6312                 while (1) {
6313                         if ((c = lgetc(0)) == EOF)
6314                                 return (0);
6315
6316                         if (p + 1 >= buf + sizeof(buf) - 1) {
6317                                 yyerror("string too long");
6318                                 return (findeol());
6319                         }
6320                         if (isalnum(c) || c == '_') {
6321                                 *p++ = (char)c;
6322                                 continue;
6323                         }
6324                         *p = '\0';
6325                         lungetc(c);
6326                         break;
6327                 }
6328                 val = symget(buf);
6329                 if (val == NULL) {
6330                         yyerror("macro '%s' not defined", buf);
6331                         return (findeol());
6332                 }
6333                 parsebuf = val;
6334                 parseindex = 0;
6335                 goto top;
6336         }
6337
6338         switch (c) {
6339         case '\'':
6340         case '"':
6341                 quotec = c;
6342                 while (1) {
6343                         if ((c = lgetc(quotec)) == EOF)
6344                                 return (0);
6345                         if (c == '\n') {
6346                                 file->lineno++;
6347                                 continue;
6348                         } else if (c == '\\') {
6349                                 if ((next = lgetc(quotec)) == EOF)
6350                                         return (0);
6351                                 if (next == quotec || c == ' ' || c == '\t')
6352                                         c = next;
6353                                 else if (next == '\n') {
6354                                         file->lineno++;
6355                                         continue;
6356                                 }
6357                                 else
6358                                         lungetc(next);
6359                         } else if (c == quotec) {
6360                                 *p = '\0';
6361                                 break;
6362                         }
6363                         if (p + 1 >= buf + sizeof(buf) - 1) {
6364                                 yyerror("string too long");
6365                                 return (findeol());
6366                         }
6367                         *p++ = (char)c;
6368                 }
6369                 yylval.v.string = strdup(buf);
6370                 if (yylval.v.string == NULL)
6371                         err(1, "yylex: strdup");
6372                 return (STRING);
6373         case '<':
6374                 next = lgetc(0);
6375                 if (next == '>') {
6376                         yylval.v.i = PF_OP_XRG;
6377                         return (PORTBINARY);
6378                 }
6379                 lungetc(next);
6380                 break;
6381         case '>':
6382                 next = lgetc(0);
6383                 if (next == '<') {
6384                         yylval.v.i = PF_OP_IRG;
6385                         return (PORTBINARY);
6386                 }
6387                 lungetc(next);
6388                 break;
6389         case '-':
6390                 next = lgetc(0);
6391                 if (next == '>')
6392                         return (ARROW);
6393                 lungetc(next);
6394                 break;
6395         }
6396
6397 #define allowed_to_end_number(x) \
6398         (isspace(x) || x == ')' || x ==',' || x == '/' || x == '}' || x == '=')
6399
6400         if (c == '-' || isdigit(c)) {
6401                 do {
6402                         *p++ = c;
6403                         if ((unsigned)(p-buf) >= sizeof(buf)) {
6404                                 yyerror("string too long");
6405                                 return (findeol());
6406                         }
6407                 } while ((c = lgetc(0)) != EOF && isdigit(c));
6408                 lungetc(c);
6409                 if (p == buf + 1 && buf[0] == '-')
6410                         goto nodigits;
6411                 if (c == EOF || allowed_to_end_number(c)) {
6412                         const char *errstr = NULL;
6413
6414                         *p = '\0';
6415                         yylval.v.number = strtonum(buf, LLONG_MIN,
6416                             LLONG_MAX, &errstr);
6417                         if (errstr) {
6418                                 yyerror("\"%s\" invalid number: %s",
6419                                     buf, errstr);
6420                                 return (findeol());
6421                         }
6422                         return (NUMBER);
6423                 } else {
6424 nodigits:
6425                         while (p > buf + 1)
6426                                 lungetc(*--p);
6427                         c = *--p;
6428                         if (c == '-')
6429                                 return (c);
6430                 }
6431         }
6432
6433 #define allowed_in_string(x) \
6434         (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \
6435         x != '{' && x != '}' && x != '<' && x != '>' && \
6436         x != '!' && x != '=' && x != '/' && x != '#' && \
6437         x != ','))
6438
6439         if (isalnum(c) || c == ':' || c == '_') {
6440                 do {
6441                         *p++ = c;
6442                         if ((unsigned)(p-buf) >= sizeof(buf)) {
6443                                 yyerror("string too long");
6444                                 return (findeol());
6445                         }
6446                 } while ((c = lgetc(0)) != EOF && (allowed_in_string(c)));
6447                 lungetc(c);
6448                 *p = '\0';
6449                 if ((token = lookup(buf)) == STRING)
6450                         if ((yylval.v.string = strdup(buf)) == NULL)
6451                                 err(1, "yylex: strdup");
6452                 return (token);
6453         }
6454         if (c == '\n') {
6455                 yylval.lineno = file->lineno;
6456                 file->lineno++;
6457         }
6458         if (c == EOF)
6459                 return (0);
6460         return (c);
6461 }
6462
6463 int
6464 check_file_secrecy(int fd, const char *fname)
6465 {
6466         struct stat     st;
6467
6468         if (fstat(fd, &st)) {
6469                 warn("cannot stat %s", fname);
6470                 return (-1);
6471         }
6472         if (st.st_uid != 0 && st.st_uid != getuid()) {
6473                 warnx("%s: owner not root or current user", fname);
6474                 return (-1);
6475         }
6476         if (st.st_mode & (S_IRWXG | S_IRWXO)) {
6477                 warnx("%s: group/world readable/writeable", fname);
6478                 return (-1);
6479         }
6480         return (0);
6481 }
6482
6483 struct file *
6484 pushfile(const char *name, int secret)
6485 {
6486         struct file     *nfile;
6487
6488         if ((nfile = calloc(1, sizeof(struct file))) == NULL ||
6489             (nfile->name = strdup(name)) == NULL) {
6490                 warn("malloc");
6491                 return (NULL);
6492         }
6493         if (TAILQ_FIRST(&files) == NULL && strcmp(nfile->name, "-") == 0) {
6494                 nfile->stream = stdin;
6495                 free(nfile->name);
6496                 if ((nfile->name = strdup("stdin")) == NULL) {
6497                         warn("strdup");
6498                         free(nfile);
6499                         return (NULL);
6500                 }
6501         } else if ((nfile->stream = fopen(nfile->name, "r")) == NULL) {
6502                 warn("%s", nfile->name);
6503                 free(nfile->name);
6504                 free(nfile);
6505                 return (NULL);
6506         } else if (secret &&
6507             check_file_secrecy(fileno(nfile->stream), nfile->name)) {
6508                 fclose(nfile->stream);
6509                 free(nfile->name);
6510                 free(nfile);
6511                 return (NULL);
6512         }
6513         nfile->lineno = 1;
6514         TAILQ_INSERT_TAIL(&files, nfile, entry);
6515         return (nfile);
6516 }
6517
6518 int
6519 popfile(void)
6520 {
6521         struct file     *prev;
6522
6523         if ((prev = TAILQ_PREV(file, files, entry)) != NULL) {
6524                 prev->errors += file->errors;
6525                 TAILQ_REMOVE(&files, file, entry);
6526                 fclose(file->stream);
6527                 free(file->name);
6528                 free(file);
6529                 file = prev;
6530                 return (0);
6531         }
6532         return (EOF);
6533 }
6534
6535 int
6536 parse_config(char *filename, struct pfctl *xpf)
6537 {
6538         int              errors = 0;
6539         struct sym      *sym;
6540
6541         pf = xpf;
6542         errors = 0;
6543         rulestate = PFCTL_STATE_NONE;
6544         returnicmpdefault = (ICMP_UNREACH << 8) | ICMP_UNREACH_PORT;
6545         returnicmp6default =
6546             (ICMP6_DST_UNREACH << 8) | ICMP6_DST_UNREACH_NOPORT;
6547         blockpolicy = PFRULE_DROP;
6548         failpolicy = PFRULE_DROP;
6549         require_order = 1;
6550
6551         if ((file = pushfile(filename, 0)) == NULL) {
6552                 warn("cannot open the main config file!");
6553                 return (-1);
6554         }
6555
6556         yyparse();
6557         errors = file->errors;
6558         popfile();
6559
6560         /* Free macros and check which have not been used. */
6561         while ((sym = TAILQ_FIRST(&symhead))) {
6562                 if ((pf->opts & PF_OPT_VERBOSE2) && !sym->used)
6563                         fprintf(stderr, "warning: macro '%s' not "
6564                             "used\n", sym->nam);
6565                 free(sym->nam);
6566                 free(sym->val);
6567                 TAILQ_REMOVE(&symhead, sym, entry);
6568                 free(sym);
6569         }
6570
6571         return (errors ? -1 : 0);
6572 }
6573
6574 int
6575 symset(const char *nam, const char *val, int persist)
6576 {
6577         struct sym      *sym;
6578
6579         for (sym = TAILQ_FIRST(&symhead); sym && strcmp(nam, sym->nam);
6580             sym = TAILQ_NEXT(sym, entry))
6581                 ;       /* nothing */
6582
6583         if (sym != NULL) {
6584                 if (sym->persist == 1)
6585                         return (0);
6586                 else {
6587                         free(sym->nam);
6588                         free(sym->val);
6589                         TAILQ_REMOVE(&symhead, sym, entry);
6590                         free(sym);
6591                 }
6592         }
6593         if ((sym = calloc(1, sizeof(*sym))) == NULL)
6594                 return (-1);
6595
6596         sym->nam = strdup(nam);
6597         if (sym->nam == NULL) {
6598                 free(sym);
6599                 return (-1);
6600         }
6601         sym->val = strdup(val);
6602         if (sym->val == NULL) {
6603                 free(sym->nam);
6604                 free(sym);
6605                 return (-1);
6606         }
6607         sym->used = 0;
6608         sym->persist = persist;
6609         TAILQ_INSERT_TAIL(&symhead, sym, entry);
6610         return (0);
6611 }
6612
6613 int
6614 pfctl_cmdline_symset(char *s)
6615 {
6616         char    *sym, *val;
6617         int      ret;
6618
6619         if ((val = strrchr(s, '=')) == NULL)
6620                 return (-1);
6621
6622         if ((sym = malloc(strlen(s) - strlen(val) + 1)) == NULL)
6623                 err(1, "pfctl_cmdline_symset: malloc");
6624
6625         strlcpy(sym, s, strlen(s) - strlen(val) + 1);
6626
6627         ret = symset(sym, val + 1, 1);
6628         free(sym);
6629
6630         return (ret);
6631 }
6632
6633 char *
6634 symget(const char *nam)
6635 {
6636         struct sym      *sym;
6637
6638         TAILQ_FOREACH(sym, &symhead, entry)
6639                 if (strcmp(nam, sym->nam) == 0) {
6640                         sym->used = 1;
6641                         return (sym->val);
6642                 }
6643         return (NULL);
6644 }
6645
6646 void
6647 mv_rules(struct pfctl_ruleset *src, struct pfctl_ruleset *dst)
6648 {
6649         int i;
6650         struct pfctl_rule *r;
6651
6652         for (i = 0; i < PF_RULESET_MAX; ++i) {
6653                 while ((r = TAILQ_FIRST(src->rules[i].active.ptr))
6654                     != NULL) {
6655                         TAILQ_REMOVE(src->rules[i].active.ptr, r, entries);
6656                         TAILQ_INSERT_TAIL(dst->rules[i].active.ptr, r, entries);
6657                         dst->anchor->match++;
6658                 }
6659                 src->anchor->match = 0;
6660                 while ((r = TAILQ_FIRST(src->rules[i].inactive.ptr))
6661                     != NULL) {
6662                         TAILQ_REMOVE(src->rules[i].inactive.ptr, r, entries);
6663                         TAILQ_INSERT_TAIL(dst->rules[i].inactive.ptr,
6664                                 r, entries);
6665                 }
6666         }
6667 }
6668
6669 void
6670 mv_eth_rules(struct pfctl_eth_ruleset *src, struct pfctl_eth_ruleset *dst)
6671 {
6672         struct pfctl_eth_rule *r;
6673
6674         while ((r = TAILQ_FIRST(&src->rules)) != NULL) {
6675                 TAILQ_REMOVE(&src->rules, r, entries);
6676                 TAILQ_INSERT_TAIL(&dst->rules, r, entries);
6677                 dst->anchor->match++;
6678         }
6679         src->anchor->match = 0;
6680 }
6681
6682 void
6683 decide_address_family(struct node_host *n, sa_family_t *af)
6684 {
6685         if (*af != 0 || n == NULL)
6686                 return;
6687         *af = n->af;
6688         while ((n = n->next) != NULL) {
6689                 if (n->af != *af) {
6690                         *af = 0;
6691                         return;
6692                 }
6693         }
6694 }
6695
6696 void
6697 remove_invalid_hosts(struct node_host **nh, sa_family_t *af)
6698 {
6699         struct node_host        *n = *nh, *prev = NULL;
6700
6701         while (n != NULL) {
6702                 if (*af && n->af && n->af != *af) {
6703                         /* unlink and free n */
6704                         struct node_host *next = n->next;
6705
6706                         /* adjust tail pointer */
6707                         if (n == (*nh)->tail)
6708                                 (*nh)->tail = prev;
6709                         /* adjust previous node's next pointer */
6710                         if (prev == NULL)
6711                                 *nh = next;
6712                         else
6713                                 prev->next = next;
6714                         /* free node */
6715                         if (n->ifname != NULL)
6716                                 free(n->ifname);
6717                         free(n);
6718                         n = next;
6719                 } else {
6720                         if (n->af && !*af)
6721                                 *af = n->af;
6722                         prev = n;
6723                         n = n->next;
6724                 }
6725         }
6726 }
6727
6728 int
6729 invalid_redirect(struct node_host *nh, sa_family_t af)
6730 {
6731         if (!af) {
6732                 struct node_host *n;
6733
6734                 /* tables and dyniftl are ok without an address family */
6735                 for (n = nh; n != NULL; n = n->next) {
6736                         if (n->addr.type != PF_ADDR_TABLE &&
6737                             n->addr.type != PF_ADDR_DYNIFTL) {
6738                                 yyerror("address family not given and "
6739                                     "translation address expands to multiple "
6740                                     "address families");
6741                                 return (1);
6742                         }
6743                 }
6744         }
6745         if (nh == NULL) {
6746                 yyerror("no translation address with matching address family "
6747                     "found.");
6748                 return (1);
6749         }
6750         return (0);
6751 }
6752
6753 int
6754 atoul(char *s, u_long *ulvalp)
6755 {
6756         u_long   ulval;
6757         char    *ep;
6758
6759         errno = 0;
6760         ulval = strtoul(s, &ep, 0);
6761         if (s[0] == '\0' || *ep != '\0')
6762                 return (-1);
6763         if (errno == ERANGE && ulval == ULONG_MAX)
6764                 return (-1);
6765         *ulvalp = ulval;
6766         return (0);
6767 }
6768
6769 int
6770 getservice(char *n)
6771 {
6772         struct servent  *s;
6773         u_long           ulval;
6774
6775         if (atoul(n, &ulval) == 0) {
6776                 if (ulval > 65535) {
6777                         yyerror("illegal port value %lu", ulval);
6778                         return (-1);
6779                 }
6780                 return (htons(ulval));
6781         } else {
6782                 s = getservbyname(n, "tcp");
6783                 if (s == NULL)
6784                         s = getservbyname(n, "udp");
6785                 if (s == NULL) {
6786                         yyerror("unknown port %s", n);
6787                         return (-1);
6788                 }
6789                 return (s->s_port);
6790         }
6791 }
6792
6793 int
6794 rule_label(struct pfctl_rule *r, char *s[PF_RULE_MAX_LABEL_COUNT])
6795 {
6796         for (int i = 0; i < PF_RULE_MAX_LABEL_COUNT; i++) {
6797                 if (s[i] == NULL)
6798                         return (0);
6799
6800                 if (strlcpy(r->label[i], s[i], sizeof(r->label[0])) >=
6801                     sizeof(r->label[0])) {
6802                         yyerror("rule label too long (max %d chars)",
6803                             sizeof(r->label[0])-1);
6804                         return (-1);
6805                 }
6806         }
6807         return (0);
6808 }
6809
6810 u_int16_t
6811 parseicmpspec(char *w, sa_family_t af)
6812 {
6813         const struct icmpcodeent        *p;
6814         u_long                           ulval;
6815         u_int8_t                         icmptype;
6816
6817         if (af == AF_INET)
6818                 icmptype = returnicmpdefault >> 8;
6819         else
6820                 icmptype = returnicmp6default >> 8;
6821
6822         if (atoul(w, &ulval) == -1) {
6823                 if ((p = geticmpcodebyname(icmptype, w, af)) == NULL) {
6824                         yyerror("unknown icmp code %s", w);
6825                         return (0);
6826                 }
6827                 ulval = p->code;
6828         }
6829         if (ulval > 255) {
6830                 yyerror("invalid icmp code %lu", ulval);
6831                 return (0);
6832         }
6833         return (icmptype << 8 | ulval);
6834 }
6835
6836 int
6837 parseport(char *port, struct range *r, int extensions)
6838 {
6839         char    *p = strchr(port, ':');
6840
6841         if (p == NULL) {
6842                 if ((r->a = getservice(port)) == -1)
6843                         return (-1);
6844                 r->b = 0;
6845                 r->t = PF_OP_NONE;
6846                 return (0);
6847         }
6848         if ((extensions & PPORT_STAR) && !strcmp(p+1, "*")) {
6849                 *p = 0;
6850                 if ((r->a = getservice(port)) == -1)
6851                         return (-1);
6852                 r->b = 0;
6853                 r->t = PF_OP_IRG;
6854                 return (0);
6855         }
6856         if ((extensions & PPORT_RANGE)) {
6857                 *p++ = 0;
6858                 if ((r->a = getservice(port)) == -1 ||
6859                     (r->b = getservice(p)) == -1)
6860                         return (-1);
6861                 if (r->a == r->b) {
6862                         r->b = 0;
6863                         r->t = PF_OP_NONE;
6864                 } else
6865                         r->t = PF_OP_RRG;
6866                 return (0);
6867         }
6868         return (-1);
6869 }
6870
6871 int
6872 pfctl_load_anchors(int dev, struct pfctl *pf, struct pfr_buffer *trans)
6873 {
6874         struct loadanchors      *la;
6875
6876         TAILQ_FOREACH(la, &loadanchorshead, entries) {
6877                 if (pf->opts & PF_OPT_VERBOSE)
6878                         fprintf(stderr, "\nLoading anchor %s from %s\n",
6879                             la->anchorname, la->filename);
6880                 if (pfctl_rules(dev, la->filename, pf->opts, pf->optimize,
6881                     la->anchorname, trans) == -1)
6882                         return (-1);
6883         }
6884
6885         return (0);
6886 }
6887
6888 int
6889 kw_casecmp(const void *k, const void *e)
6890 {
6891         return (strcasecmp(k, ((const struct keywords *)e)->k_name));
6892 }
6893
6894 int
6895 map_tos(char *s, int *val)
6896 {
6897         /* DiffServ Codepoints and other TOS mappings */
6898         const struct keywords    toswords[] = {
6899                 { "af11",               IPTOS_DSCP_AF11 },
6900                 { "af12",               IPTOS_DSCP_AF12 },
6901                 { "af13",               IPTOS_DSCP_AF13 },
6902                 { "af21",               IPTOS_DSCP_AF21 },
6903                 { "af22",               IPTOS_DSCP_AF22 },
6904                 { "af23",               IPTOS_DSCP_AF23 },
6905                 { "af31",               IPTOS_DSCP_AF31 },
6906                 { "af32",               IPTOS_DSCP_AF32 },
6907                 { "af33",               IPTOS_DSCP_AF33 },
6908                 { "af41",               IPTOS_DSCP_AF41 },
6909                 { "af42",               IPTOS_DSCP_AF42 },
6910                 { "af43",               IPTOS_DSCP_AF43 },
6911                 { "critical",           IPTOS_PREC_CRITIC_ECP },
6912                 { "cs0",                IPTOS_DSCP_CS0 },
6913                 { "cs1",                IPTOS_DSCP_CS1 },
6914                 { "cs2",                IPTOS_DSCP_CS2 },
6915                 { "cs3",                IPTOS_DSCP_CS3 },
6916                 { "cs4",                IPTOS_DSCP_CS4 },
6917                 { "cs5",                IPTOS_DSCP_CS5 },
6918                 { "cs6",                IPTOS_DSCP_CS6 },
6919                 { "cs7",                IPTOS_DSCP_CS7 },
6920                 { "ef",                 IPTOS_DSCP_EF },
6921                 { "inetcontrol",        IPTOS_PREC_INTERNETCONTROL },
6922                 { "lowdelay",           IPTOS_LOWDELAY },
6923                 { "netcontrol",         IPTOS_PREC_NETCONTROL },
6924                 { "reliability",        IPTOS_RELIABILITY },
6925                 { "throughput",         IPTOS_THROUGHPUT },
6926                 { "va",                 IPTOS_DSCP_VA }
6927         };
6928         const struct keywords   *p;
6929
6930         p = bsearch(s, toswords, sizeof(toswords)/sizeof(toswords[0]),
6931             sizeof(toswords[0]), kw_casecmp);
6932
6933         if (p) {
6934                 *val = p->k_val;
6935                 return (1);
6936         }
6937         return (0);
6938 }
6939
6940 int
6941 rt_tableid_max(void)
6942 {
6943 #ifdef __FreeBSD__
6944         int fibs;
6945         size_t l = sizeof(fibs);
6946
6947         if (sysctlbyname("net.fibs", &fibs, &l, NULL, 0) == -1)
6948                 fibs = 16;      /* XXX RT_MAXFIBS, at least limit it some. */
6949         /*
6950          * As the OpenBSD code only compares > and not >= we need to adjust
6951          * here given we only accept values of 0..n and want to avoid #ifdefs
6952          * in the grammar.
6953          */
6954         return (fibs - 1);
6955 #else
6956         return (RT_TABLEID_MAX);
6957 #endif
6958 }
6959
6960 struct node_mac*
6961 node_mac_from_string(const char *str)
6962 {
6963         struct node_mac *m;
6964
6965         m = calloc(1, sizeof(struct node_mac));
6966         if (m == NULL)
6967                 err(1, "mac: calloc");
6968
6969         if (sscanf(str, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
6970             &m->mac[0], &m->mac[1], &m->mac[2], &m->mac[3], &m->mac[4],
6971             &m->mac[5]) != 6) {
6972                 free(m);
6973                 yyerror("invalid MAC address");
6974                 return (NULL);
6975         }
6976
6977         memset(m->mask, 0xff, ETHER_ADDR_LEN);
6978         m->isset = true;
6979         m->next = NULL;
6980         m->tail = m;
6981
6982         return (m);
6983 }
6984
6985 struct node_mac*
6986 node_mac_from_string_masklen(const char *str, int masklen)
6987 {
6988         struct node_mac *m;
6989
6990         if (masklen < 0 || masklen > (ETHER_ADDR_LEN * 8)) {
6991                 yyerror("invalid MAC mask length");
6992                 return (NULL);
6993         }
6994
6995         m = node_mac_from_string(str);
6996         if (m == NULL)
6997                 return (NULL);
6998
6999         memset(m->mask, 0, ETHER_ADDR_LEN);
7000         for (int i = 0; i < masklen; i++)
7001                 m->mask[i / 8] |= 1 << (i % 8);
7002
7003         return (m);
7004 }
7005
7006 struct node_mac*
7007 node_mac_from_string_mask(const char *str, const char *mask)
7008 {
7009         struct node_mac *m;
7010
7011         m = node_mac_from_string(str);
7012         if (m == NULL)
7013                 return (NULL);
7014
7015         if (sscanf(mask, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
7016             &m->mask[0], &m->mask[1], &m->mask[2], &m->mask[3], &m->mask[4],
7017             &m->mask[5]) != 6) {
7018                 free(m);
7019                 yyerror("invalid MAC mask");
7020                 return (NULL);
7021         }
7022
7023         return (m);
7024 }