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