xref: /dflybsd-src/sys/net/pf/pf_ioctl.c (revision a9656fbcd49c376aba5e04370d8b0f1fa96e063c)
1 /*	$FreeBSD: src/sys/contrib/pf/net/pf_ioctl.c,v 1.12 2004/08/12 14:15:42 mlaier Exp $	*/
2 /*	$OpenBSD: pf_ioctl.c,v 1.112.2.2 2004/07/24 18:28:12 brad Exp $ */
3 /*	$OpenBSD: pf_ioctl.c,v 1.175 2007/02/26 22:47:43 deraadt Exp $ */
4 
5 /*
6  * Copyright (c) 2010 The DragonFly Project.  All rights reserved.
7  *
8  * Copyright (c) 2001 Daniel Hartmeier
9  * Copyright (c) 2002,2003 Henning Brauer
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  *
16  *    - Redistributions of source code must retain the above copyright
17  *      notice, this list of conditions and the following disclaimer.
18  *    - Redistributions in binary form must reproduce the above
19  *      copyright notice, this list of conditions and the following
20  *      disclaimer in the documentation and/or other materials provided
21  *      with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  *
36  * Effort sponsored in part by the Defense Advanced Research Projects
37  * Agency (DARPA) and Air Force Research Laboratory, Air Force
38  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
39  *
40  */
41 
42 #include "opt_inet.h"
43 #include "opt_inet6.h"
44 #include "use_pfsync.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/conf.h>
49 #include <sys/device.h>
50 #include <sys/mbuf.h>
51 #include <sys/filio.h>
52 #include <sys/fcntl.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/kernel.h>
56 #include <sys/kthread.h>
57 #include <sys/thread2.h>
58 #include <sys/time.h>
59 #include <sys/proc.h>
60 #include <sys/malloc.h>
61 #include <sys/module.h>
62 #include <vm/vm_zone.h>
63 #include <sys/lock.h>
64 
65 #include <net/if.h>
66 #include <net/if_types.h>
67 #include <net/route.h>
68 
69 #include <netinet/in.h>
70 #include <netinet/in_var.h>
71 #include <netinet/in_systm.h>
72 #include <netinet/ip.h>
73 #include <netinet/ip_var.h>
74 #include <netinet/ip_icmp.h>
75 
76 #include <net/pf/pfvar.h>
77 #include <sys/md5.h>
78 #include <net/pf/pfvar.h>
79 
80 #if NPFSYNC > 0
81 #include <net/pf/if_pfsync.h>
82 #endif /* NPFSYNC > 0 */
83 
84 #if NPFLOG > 0
85 #include <net/if_pflog.h>
86 #endif /* NPFLOG > 0 */
87 
88 #ifdef INET6
89 #include <netinet/ip6.h>
90 #include <netinet/in_pcb.h>
91 #endif /* INET6 */
92 
93 #ifdef ALTQ
94 #include <net/altq/altq.h>
95 #endif
96 
97 #include <machine/limits.h>
98 #include <net/pfil.h>
99 #include <sys/mutex.h>
100 
101 u_int rt_numfibs = RT_NUMFIBS;
102 
103 void			 init_zone_var(void);
104 void			 cleanup_pf_zone(void);
105 int			 pfattach(void);
106 void			 pf_thread_create(void *);
107 struct pf_pool		*pf_get_pool(char *, u_int32_t, u_int8_t, u_int32_t,
108 			    u_int8_t, u_int8_t, u_int8_t);
109 
110 void			 pf_mv_pool(struct pf_palist *, struct pf_palist *);
111 void			 pf_empty_pool(struct pf_palist *);
112 #ifdef ALTQ
113 int			 pf_begin_altq(u_int32_t *);
114 int			 pf_rollback_altq(u_int32_t);
115 int			 pf_commit_altq(u_int32_t);
116 int			 pf_enable_altq(struct pf_altq *);
117 int			 pf_disable_altq(struct pf_altq *);
118 #endif /* ALTQ */
119 int			 pf_begin_rules(u_int32_t *, int, const char *);
120 int			 pf_rollback_rules(u_int32_t, int, char *);
121 int			 pf_setup_pfsync_matching(struct pf_ruleset *);
122 void			 pf_hash_rule(MD5_CTX *, struct pf_rule *);
123 void			 pf_hash_rule_addr(MD5_CTX *, struct pf_rule_addr *);
124 int			 pf_commit_rules(u_int32_t, int, char *);
125 
126 struct pf_rule		 pf_default_rule;
127 struct lock		 pf_consistency_lock;
128 #ifdef ALTQ
129 static int		 pf_altq_running;
130 #endif
131 
132 #define	TAGID_MAX	 50000
133 TAILQ_HEAD(pf_tags, pf_tagname)	pf_tags = TAILQ_HEAD_INITIALIZER(pf_tags),
134 				pf_qids = TAILQ_HEAD_INITIALIZER(pf_qids);
135 
136 #if (PF_QNAME_SIZE != PF_TAG_NAME_SIZE)
137 #error PF_QNAME_SIZE must be equal to PF_TAG_NAME_SIZE
138 #endif
139 u_int16_t		 tagname2tag(struct pf_tags *, char *);
140 void			 tag2tagname(struct pf_tags *, u_int16_t, char *);
141 void			 tag_unref(struct pf_tags *, u_int16_t);
142 int			 pf_rtlabel_add(struct pf_addr_wrap *);
143 void			 pf_rtlabel_remove(struct pf_addr_wrap *);
144 void			 pf_rtlabel_copyout(struct pf_addr_wrap *);
145 
146 #define DPFPRINTF(n, x) if (pf_status.debug >= (n)) kprintf x
147 
148 static cdev_t	pf_dev;
149 
150 /*
151  * XXX - These are new and need to be checked when moveing to a new version
152  */
153 static void		 pf_clear_states(void);
154 static int		 pf_clear_tables(void);
155 static void		 pf_clear_srcnodes(void);
156 /*
157  * XXX - These are new and need to be checked when moveing to a new version
158  */
159 
160 /*
161  * Wrapper functions for pfil(9) hooks
162  */
163 static int pf_check_in(void *arg, struct mbuf **m, struct ifnet *ifp,
164 		int dir);
165 static int pf_check_out(void *arg, struct mbuf **m, struct ifnet *ifp,
166 		int dir);
167 #ifdef INET6
168 static int pf_check6_in(void *arg, struct mbuf **m, struct ifnet *ifp,
169 		int dir);
170 static int pf_check6_out(void *arg, struct mbuf **m, struct ifnet *ifp,
171 		int dir);
172 #endif
173 
174 static int 		 hook_pf(void);
175 static int 		 dehook_pf(void);
176 static int 		 shutdown_pf(void);
177 static int 		 pf_load(void);
178 static int 		 pf_unload(void);
179 
180 d_open_t	pfopen;
181 d_close_t	pfclose;
182 d_ioctl_t	pfioctl;
183 
184 static struct dev_ops pf_ops = {	    /* XXX convert to port model */
185 	{ PF_NAME, 73, 0 },
186 	.d_open =	pfopen,
187 	.d_close =	pfclose,
188 	.d_ioctl =	pfioctl
189 };
190 
191 static volatile int pf_pfil_hooked = 0;
192 int pf_end_threads = 0;
193 struct lock pf_task_lck;
194 
195 int debug_pfugidhack = 0;
196 SYSCTL_INT(_debug, OID_AUTO, pfugidhack, CTLFLAG_RW, &debug_pfugidhack, 0,
197 	"Enable/disable pf user/group rules mpsafe hack");
198 
199 
200 static void
201 init_pf_lck(void)
202 {
203 	lockinit(&pf_task_lck, "pf task lck", 0, LK_CANRECURSE);
204 }
205 
206 static void
207 destroy_pf_lck(void)
208 {
209 	lockuninit(&pf_task_lck);
210 }
211 
212 void
213 init_zone_var(void)
214 {
215 	pf_src_tree_pl = pf_rule_pl = NULL;
216 	pf_state_pl = pf_altq_pl = pf_pooladdr_pl = NULL;
217 	pf_frent_pl = pf_frag_pl = pf_cache_pl = pf_cent_pl = NULL;
218 	pf_state_scrub_pl = NULL;
219 	pfr_ktable_pl = pfr_kentry_pl = NULL;
220 }
221 
222 void
223 cleanup_pf_zone(void)
224 {
225 	ZONE_DESTROY(pf_src_tree_pl);
226 	ZONE_DESTROY(pf_rule_pl);
227 	ZONE_DESTROY(pf_state_pl);
228 	ZONE_DESTROY(pf_altq_pl);
229 	ZONE_DESTROY(pf_pooladdr_pl);
230 	ZONE_DESTROY(pf_frent_pl);
231 	ZONE_DESTROY(pf_frag_pl);
232 	ZONE_DESTROY(pf_cache_pl);
233 	ZONE_DESTROY(pf_cent_pl);
234 	ZONE_DESTROY(pfr_ktable_pl);
235 	ZONE_DESTROY(pfr_kentry_pl);
236 	ZONE_DESTROY(pf_state_scrub_pl);
237 	ZONE_DESTROY(pfi_addr_pl);
238 }
239 
240 int
241 pfattach(void)
242 {
243 	u_int32_t *my_timeout = pf_default_rule.timeout;
244 	int error = 1;
245 
246 	do {
247 		ZONE_CREATE(pf_src_tree_pl,struct pf_src_node, "pfsrctrpl");
248 		ZONE_CREATE(pf_rule_pl,    struct pf_rule, "pfrulepl");
249 		ZONE_CREATE(pf_state_pl,   struct pf_state, "pfstatepl");
250 		ZONE_CREATE(pf_altq_pl,    struct pf_altq, "pfaltqpl");
251 		ZONE_CREATE(pf_pooladdr_pl,struct pf_pooladdr, "pfpooladdrpl");
252 		ZONE_CREATE(pfr_ktable_pl, struct pfr_ktable, "pfrktable");
253 		ZONE_CREATE(pfr_kentry_pl, struct pfr_kentry, "pfrkentry");
254 		ZONE_CREATE(pf_frent_pl,   struct pf_frent, "pffrent");
255 		ZONE_CREATE(pf_frag_pl,    struct pf_fragment, "pffrag");
256 		ZONE_CREATE(pf_cache_pl,   struct pf_fragment, "pffrcache");
257 		ZONE_CREATE(pf_cent_pl,    struct pf_frcache, "pffrcent");
258 		ZONE_CREATE(pf_state_scrub_pl, struct pf_state_scrub,
259 		    "pfstatescrub");
260 		ZONE_CREATE(pfi_addr_pl,   struct pfi_dynaddr, "pfiaddrpl");
261 		error = 0;
262 	} while(0);
263 	if (error) {
264 		cleanup_pf_zone();
265 		return (error);
266 	}
267 	pfr_initialize();
268 	pfi_initialize();
269 	error = pf_osfp_initialize();
270 	if (error) {
271 		cleanup_pf_zone();
272 		pf_osfp_cleanup();
273 		return (error);
274 	}
275 
276 	pf_pool_limits[PF_LIMIT_STATES].pp = pf_state_pl;
277 	pf_pool_limits[PF_LIMIT_STATES].limit = PFSTATE_HIWAT;
278 	pf_pool_limits[PF_LIMIT_FRAGS].pp = pf_frent_pl;
279 	pf_pool_limits[PF_LIMIT_FRAGS].limit = PFFRAG_FRENT_HIWAT;
280 	/* XXX uma_zone_set_max(pf_pool_limits[PF_LIMIT_STATES].pp,
281 		pf_pool_limits[PF_LIMIT_STATES].limit);
282 	*/
283 	if (ctob(physmem) <= 100*1024*1024)
284 		pf_pool_limits[PF_LIMIT_TABLE_ENTRIES].limit =
285 		    PFR_KENTRY_HIWAT_SMALL;
286 	RB_INIT(&tree_src_tracking);
287 	RB_INIT(&pf_anchors);
288 	pf_init_ruleset(&pf_main_ruleset);
289 	TAILQ_INIT(&pf_altqs[0]);
290 	TAILQ_INIT(&pf_altqs[1]);
291 	TAILQ_INIT(&pf_pabuf);
292 	pf_altqs_active = &pf_altqs[0];
293 	pf_altqs_inactive = &pf_altqs[1];
294 	TAILQ_INIT(&state_list);
295 
296 	/* default rule should never be garbage collected */
297 	pf_default_rule.entries.tqe_prev = &pf_default_rule.entries.tqe_next;
298 	pf_default_rule.action = PF_PASS;
299 	pf_default_rule.nr = (uint32_t)(-1);
300 	pf_default_rule.rtableid = -1;
301 
302 	/* initialize default timeouts */
303 	my_timeout[PFTM_TCP_FIRST_PACKET] = 120;	/* First TCP packet */
304 	my_timeout[PFTM_TCP_OPENING] = 30; 		/* No response yet */
305 	my_timeout[PFTM_TCP_ESTABLISHED] = 24*60*60;	/* Established */
306 	my_timeout[PFTM_TCP_CLOSING] = 15 * 60;		/* Half closed */
307 	my_timeout[PFTM_TCP_FIN_WAIT] = 45;		/* Got both FINs */
308 	my_timeout[PFTM_TCP_CLOSED] = 90;		/* Got a RST */
309 	my_timeout[PFTM_UDP_FIRST_PACKET] = 60;		/* First UDP packet */
310 	my_timeout[PFTM_UDP_SINGLE] = 30;		/* Unidirectional */
311 	my_timeout[PFTM_UDP_MULTIPLE] = 60;		/* Bidirectional */
312 	my_timeout[PFTM_ICMP_FIRST_PACKET] = 20;	/* First ICMP packet */
313 	my_timeout[PFTM_ICMP_ERROR_REPLY] = 10;		/* Got error response */
314 	my_timeout[PFTM_OTHER_FIRST_PACKET] = 60;	/* First packet */
315 	my_timeout[PFTM_OTHER_SINGLE] = 30;		/* Unidirectional */
316 	my_timeout[PFTM_OTHER_MULTIPLE] = 60;		/* Bidirectional */
317 	my_timeout[PFTM_FRAG] = 30;			/* Fragment expire */
318 	my_timeout[PFTM_INTERVAL] = 10;			/* Expire interval */
319 	my_timeout[PFTM_SRC_NODE] = 0;		/* Source Tracking */
320 	my_timeout[PFTM_TS_DIFF] = 30;		/* Allowed TS diff */
321 	my_timeout[PFTM_ADAPTIVE_START] = PFSTATE_ADAPT_START;
322 	my_timeout[PFTM_ADAPTIVE_END] = PFSTATE_ADAPT_END;
323 
324 	pf_normalize_init();
325 	bzero(&pf_status, sizeof(pf_status));
326 	pf_status.debug = PF_DEBUG_URGENT;
327 
328 	/* XXX do our best to avoid a conflict */
329 	pf_status.hostid = karc4random();
330 
331 	/* require process context to purge states, so perform in a thread */
332 	kthread_create(pf_thread_create, NULL, NULL, "dummy");
333 
334 	return (error);
335 }
336 
337 void
338 pf_thread_create(void *v)
339 {
340 	if (kthread_create(pf_purge_thread, NULL, NULL, "pfpurge"))
341 		panic("pfpurge thread");
342 }
343 
344 int
345 pfopen(struct dev_open_args *ap)
346 {
347 	cdev_t dev = ap->a_head.a_dev;
348 	if (minor(dev) >= 1)
349 		return (ENXIO);
350 	return (0);
351 }
352 
353 int
354 pfclose(struct dev_close_args *ap)
355 {
356 	cdev_t dev = ap->a_head.a_dev;
357 	if (minor(dev) >= 1)
358 		return (ENXIO);
359 	return (0);
360 }
361 
362 struct pf_pool *
363 pf_get_pool(char *anchor, u_int32_t ticket, u_int8_t rule_action,
364     u_int32_t rule_number, u_int8_t r_last, u_int8_t active,
365     u_int8_t check_ticket)
366 {
367 	struct pf_ruleset	*ruleset;
368 	struct pf_rule		*rule;
369 	int			 rs_num;
370 
371 	ruleset = pf_find_ruleset(anchor);
372 	if (ruleset == NULL)
373 		return (NULL);
374 	rs_num = pf_get_ruleset_number(rule_action);
375 	if (rs_num >= PF_RULESET_MAX)
376 		return (NULL);
377 	if (active) {
378 		if (check_ticket && ticket !=
379 		    ruleset->rules[rs_num].active.ticket)
380 			return (NULL);
381 		if (r_last)
382 			rule = TAILQ_LAST(ruleset->rules[rs_num].active.ptr,
383 			    pf_rulequeue);
384 		else
385 			rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
386 	} else {
387 		if (check_ticket && ticket !=
388 		    ruleset->rules[rs_num].inactive.ticket)
389 			return (NULL);
390 		if (r_last)
391 			rule = TAILQ_LAST(ruleset->rules[rs_num].inactive.ptr,
392 			    pf_rulequeue);
393 		else
394 			rule = TAILQ_FIRST(ruleset->rules[rs_num].inactive.ptr);
395 	}
396 	if (!r_last) {
397 		while ((rule != NULL) && (rule->nr != rule_number))
398 			rule = TAILQ_NEXT(rule, entries);
399 	}
400 	if (rule == NULL)
401 		return (NULL);
402 
403 	return (&rule->rpool);
404 }
405 
406 void
407 pf_mv_pool(struct pf_palist *poola, struct pf_palist *poolb)
408 {
409 	struct pf_pooladdr	*mv_pool_pa;
410 
411 	while ((mv_pool_pa = TAILQ_FIRST(poola)) != NULL) {
412 		TAILQ_REMOVE(poola, mv_pool_pa, entries);
413 		TAILQ_INSERT_TAIL(poolb, mv_pool_pa, entries);
414 	}
415 }
416 
417 void
418 pf_empty_pool(struct pf_palist *poola)
419 {
420 	struct pf_pooladdr	*empty_pool_pa;
421 
422 	while ((empty_pool_pa = TAILQ_FIRST(poola)) != NULL) {
423 		pfi_dynaddr_remove(&empty_pool_pa->addr);
424 		pf_tbladdr_remove(&empty_pool_pa->addr);
425 		pfi_kif_unref(empty_pool_pa->kif, PFI_KIF_REF_RULE);
426 		TAILQ_REMOVE(poola, empty_pool_pa, entries);
427 		pool_put(&pf_pooladdr_pl, empty_pool_pa);
428 	}
429 }
430 
431 void
432 pf_rm_rule(struct pf_rulequeue *rulequeue, struct pf_rule *rule)
433 {
434 	if (rulequeue != NULL) {
435 		if (rule->states <= 0) {
436 			/*
437 			 * XXX - we need to remove the table *before* detaching
438 			 * the rule to make sure the table code does not delete
439 			 * the anchor under our feet.
440 			 */
441 			pf_tbladdr_remove(&rule->src.addr);
442 			pf_tbladdr_remove(&rule->dst.addr);
443 			if (rule->overload_tbl)
444 				pfr_detach_table(rule->overload_tbl);
445 		}
446 		TAILQ_REMOVE(rulequeue, rule, entries);
447 		rule->entries.tqe_prev = NULL;
448 		rule->nr = -1;
449 	}
450 
451 	if (rule->states > 0 || rule->src_nodes > 0 ||
452 	    rule->entries.tqe_prev != NULL)
453 		return;
454 	pf_tag_unref(rule->tag);
455 	pf_tag_unref(rule->match_tag);
456 #ifdef ALTQ
457 	if (rule->pqid != rule->qid)
458 		pf_qid_unref(rule->pqid);
459 	pf_qid_unref(rule->qid);
460 #endif
461 	pf_rtlabel_remove(&rule->src.addr);
462 	pf_rtlabel_remove(&rule->dst.addr);
463 	pfi_dynaddr_remove(&rule->src.addr);
464 	pfi_dynaddr_remove(&rule->dst.addr);
465 	if (rulequeue == NULL) {
466 		pf_tbladdr_remove(&rule->src.addr);
467 		pf_tbladdr_remove(&rule->dst.addr);
468 		if (rule->overload_tbl)
469 			pfr_detach_table(rule->overload_tbl);
470 	}
471 	pfi_kif_unref(rule->kif, PFI_KIF_REF_RULE);
472 	pf_anchor_remove(rule);
473 	pf_empty_pool(&rule->rpool.list);
474 	pool_put(&pf_rule_pl, rule);
475 }
476 
477 u_int16_t
478 tagname2tag(struct pf_tags *head, char *tagname)
479 {
480 	struct pf_tagname	*tag, *p = NULL;
481 	u_int16_t		 new_tagid = 1;
482 
483 	TAILQ_FOREACH(tag, head, entries)
484 		if (strcmp(tagname, tag->name) == 0) {
485 			tag->ref++;
486 			return (tag->tag);
487 		}
488 
489 	/*
490 	 * to avoid fragmentation, we do a linear search from the beginning
491 	 * and take the first free slot we find. if there is none or the list
492 	 * is empty, append a new entry at the end.
493 	 */
494 
495 	/* new entry */
496 	if (!TAILQ_EMPTY(head))
497 		for (p = TAILQ_FIRST(head); p != NULL &&
498 		    p->tag == new_tagid; p = TAILQ_NEXT(p, entries))
499 			new_tagid = p->tag + 1;
500 
501 	if (new_tagid > TAGID_MAX)
502 		return (0);
503 
504 	/* allocate and fill new struct pf_tagname */
505 	tag = kmalloc(sizeof(struct pf_tagname), M_TEMP, M_WAITOK);
506 	if (tag == NULL)
507 		return (0);
508 	bzero(tag, sizeof(struct pf_tagname));
509 	strlcpy(tag->name, tagname, sizeof(tag->name));
510 	tag->tag = new_tagid;
511 	tag->ref++;
512 
513 	if (p != NULL)	/* insert new entry before p */
514 		TAILQ_INSERT_BEFORE(p, tag, entries);
515 	else	/* either list empty or no free slot in between */
516 		TAILQ_INSERT_TAIL(head, tag, entries);
517 
518 	return (tag->tag);
519 }
520 
521 void
522 tag2tagname(struct pf_tags *head, u_int16_t tagid, char *p)
523 {
524 	struct pf_tagname	*tag;
525 
526 	TAILQ_FOREACH(tag, head, entries)
527 		if (tag->tag == tagid) {
528 			strlcpy(p, tag->name, PF_TAG_NAME_SIZE);
529 			return;
530 		}
531 }
532 
533 void
534 tag_unref(struct pf_tags *head, u_int16_t tag)
535 {
536 	struct pf_tagname	*p, *next;
537 
538 	if (tag == 0)
539 		return;
540 
541 	for (p = TAILQ_FIRST(head); p != NULL; p = next) {
542 		next = TAILQ_NEXT(p, entries);
543 		if (tag == p->tag) {
544 			if (--p->ref == 0) {
545 				TAILQ_REMOVE(head, p, entries);
546 				kfree(p, M_TEMP);
547 			}
548 			break;
549 		}
550 	}
551 }
552 
553 u_int16_t
554 pf_tagname2tag(char *tagname)
555 {
556 	return (tagname2tag(&pf_tags, tagname));
557 }
558 
559 void
560 pf_tag2tagname(u_int16_t tagid, char *p)
561 {
562 	tag2tagname(&pf_tags, tagid, p);
563 }
564 
565 void
566 pf_tag_ref(u_int16_t tag)
567 {
568 	struct pf_tagname *t;
569 
570 	TAILQ_FOREACH(t, &pf_tags, entries)
571 		if (t->tag == tag)
572 			break;
573 	if (t != NULL)
574 		t->ref++;
575 }
576 
577 void
578 pf_tag_unref(u_int16_t tag)
579 {
580 	tag_unref(&pf_tags, tag);
581 }
582 
583 int
584 pf_rtlabel_add(struct pf_addr_wrap *a)
585 {
586 	return (0);
587 }
588 
589 void
590 pf_rtlabel_remove(struct pf_addr_wrap *a)
591 {
592 }
593 
594 void
595 pf_rtlabel_copyout(struct pf_addr_wrap *a)
596 {
597 	if (a->type == PF_ADDR_RTLABEL && a->v.rtlabel)
598 		strlcpy(a->v.rtlabelname, "?", sizeof(a->v.rtlabelname));
599 }
600 
601 #ifdef ALTQ
602 u_int32_t
603 pf_qname2qid(char *qname)
604 {
605 	return ((u_int32_t)tagname2tag(&pf_qids, qname));
606 }
607 
608 void
609 pf_qid2qname(u_int32_t qid, char *p)
610 {
611 	tag2tagname(&pf_qids, (u_int16_t)qid, p);
612 }
613 
614 void
615 pf_qid_unref(u_int32_t qid)
616 {
617 	tag_unref(&pf_qids, (u_int16_t)qid);
618 }
619 
620 int
621 pf_begin_altq(u_int32_t *ticket)
622 {
623 	struct pf_altq	*altq;
624 	int		 error = 0;
625 
626 	/* Purge the old altq list */
627 	while ((altq = TAILQ_FIRST(pf_altqs_inactive)) != NULL) {
628 		TAILQ_REMOVE(pf_altqs_inactive, altq, entries);
629 		if (altq->qname[0] == 0) {
630 			/* detach and destroy the discipline */
631 			error = altq_remove(altq);
632 		} else
633 			pf_qid_unref(altq->qid);
634 		pool_put(&pf_altq_pl, altq);
635 	}
636 	if (error)
637 		return (error);
638 	*ticket = ++ticket_altqs_inactive;
639 	altqs_inactive_open = 1;
640 	return (0);
641 }
642 
643 int
644 pf_rollback_altq(u_int32_t ticket)
645 {
646 	struct pf_altq	*altq;
647 	int		 error = 0;
648 
649 	if (!altqs_inactive_open || ticket != ticket_altqs_inactive)
650 		return (0);
651 	/* Purge the old altq list */
652 	while ((altq = TAILQ_FIRST(pf_altqs_inactive)) != NULL) {
653 		TAILQ_REMOVE(pf_altqs_inactive, altq, entries);
654 		if (altq->qname[0] == 0) {
655 			/* detach and destroy the discipline */
656 			error = altq_remove(altq);
657 		} else
658 			pf_qid_unref(altq->qid);
659 		pool_put(&pf_altq_pl, altq);
660 	}
661 	altqs_inactive_open = 0;
662 	return (error);
663 }
664 
665 int
666 pf_commit_altq(u_int32_t ticket)
667 {
668 	struct pf_altqqueue	*old_altqs;
669 	struct pf_altq		*altq;
670 	int			 err, error = 0;
671 
672 	if (!altqs_inactive_open || ticket != ticket_altqs_inactive)
673 		return (EBUSY);
674 
675 	/* swap altqs, keep the old. */
676 	crit_enter();
677 	old_altqs = pf_altqs_active;
678 	pf_altqs_active = pf_altqs_inactive;
679 	pf_altqs_inactive = old_altqs;
680 	ticket_altqs_active = ticket_altqs_inactive;
681 
682 	/* Attach new disciplines */
683 	TAILQ_FOREACH(altq, pf_altqs_active, entries) {
684 		if (altq->qname[0] == 0) {
685 			/* attach the discipline */
686 			error = altq_pfattach(altq);
687 			if (error) {
688 				crit_exit();
689 				return (error);
690 			}
691 		}
692 	}
693 
694 	/* Purge the old altq list */
695 	while ((altq = TAILQ_FIRST(pf_altqs_inactive)) != NULL) {
696 		TAILQ_REMOVE(pf_altqs_inactive, altq, entries);
697 		if (altq->qname[0] == 0) {
698 			/* detach and destroy the discipline */
699 			if (pf_altq_running)
700 				error = pf_disable_altq(altq);
701 			err = altq_pfdetach(altq);
702 			if (err != 0 && error == 0)
703 				error = err;
704 			err = altq_remove(altq);
705 			if (err != 0 && error == 0)
706 				error = err;
707 		} else
708 			pf_qid_unref(altq->qid);
709 		pool_put(&pf_altq_pl, altq);
710 	}
711 	crit_exit();
712 
713 	altqs_inactive_open = 0;
714 	return (error);
715 }
716 
717 int
718 pf_enable_altq(struct pf_altq *altq)
719 {
720 	struct ifnet		*ifp;
721 	struct tb_profile	 tb;
722 	int			 error = 0;
723 
724 	if ((ifp = ifunit(altq->ifname)) == NULL)
725 		return (EINVAL);
726 
727 	if (ifp->if_snd.altq_type != ALTQT_NONE)
728 		error = altq_enable(&ifp->if_snd);
729 
730 	/* set tokenbucket regulator */
731 	if (error == 0 && ifp != NULL && ALTQ_IS_ENABLED(&ifp->if_snd)) {
732 		tb.rate = altq->ifbandwidth;
733 		tb.depth = altq->tbrsize;
734 		crit_enter();
735 		error = tbr_set(&ifp->if_snd, &tb);
736 		crit_exit();
737 	}
738 
739 	return (error);
740 }
741 
742 int
743 pf_disable_altq(struct pf_altq *altq)
744 {
745 	struct ifnet		*ifp;
746 	struct tb_profile	 tb;
747 	int			 error;
748 
749 	if ((ifp = ifunit(altq->ifname)) == NULL)
750 		return (EINVAL);
751 
752 	/*
753 	 * when the discipline is no longer referenced, it was overridden
754 	 * by a new one.  if so, just return.
755 	 */
756 	if (altq->altq_disc != ifp->if_snd.altq_disc)
757 		return (0);
758 
759 	error = altq_disable(&ifp->if_snd);
760 
761 	if (error == 0) {
762 		/* clear tokenbucket regulator */
763 		tb.rate = 0;
764 		crit_enter();
765 		error = tbr_set(&ifp->if_snd, &tb);
766 		crit_exit();
767 	}
768 
769 	return (error);
770 }
771 #endif /* ALTQ */
772 
773 int
774 pf_begin_rules(u_int32_t *ticket, int rs_num, const char *anchor)
775 {
776 	struct pf_ruleset	*rs;
777 	struct pf_rule		*rule;
778 
779 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
780 		return (EINVAL);
781 	rs = pf_find_or_create_ruleset(anchor);
782 	if (rs == NULL)
783 		return (EINVAL);
784 	while ((rule = TAILQ_FIRST(rs->rules[rs_num].inactive.ptr)) != NULL) {
785 		pf_rm_rule(rs->rules[rs_num].inactive.ptr, rule);
786 		rs->rules[rs_num].inactive.rcount--;
787 	}
788 	*ticket = ++rs->rules[rs_num].inactive.ticket;
789 	rs->rules[rs_num].inactive.open = 1;
790 	return (0);
791 }
792 
793 int
794 pf_rollback_rules(u_int32_t ticket, int rs_num, char *anchor)
795 {
796 	struct pf_ruleset	*rs;
797 	struct pf_rule		*rule;
798 
799 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
800 		return (EINVAL);
801 	rs = pf_find_ruleset(anchor);
802 	if (rs == NULL || !rs->rules[rs_num].inactive.open ||
803 	    rs->rules[rs_num].inactive.ticket != ticket)
804 		return (0);
805 	while ((rule = TAILQ_FIRST(rs->rules[rs_num].inactive.ptr)) != NULL) {
806 		pf_rm_rule(rs->rules[rs_num].inactive.ptr, rule);
807 		rs->rules[rs_num].inactive.rcount--;
808 	}
809 	rs->rules[rs_num].inactive.open = 0;
810 	return (0);
811 }
812 
813 #define PF_MD5_UPD(st, elm)						\
814 		MD5Update(ctx, (u_int8_t *) &(st)->elm, sizeof((st)->elm))
815 
816 #define PF_MD5_UPD_STR(st, elm)						\
817 		MD5Update(ctx, (u_int8_t *) (st)->elm, strlen((st)->elm))
818 
819 #define PF_MD5_UPD_HTONL(st, elm, stor) do {				\
820 		(stor) = htonl((st)->elm);				\
821 		MD5Update(ctx, (u_int8_t *) &(stor), sizeof(u_int32_t));\
822 } while (0)
823 
824 #define PF_MD5_UPD_HTONS(st, elm, stor) do {				\
825 		(stor) = htons((st)->elm);				\
826 		MD5Update(ctx, (u_int8_t *) &(stor), sizeof(u_int16_t));\
827 } while (0)
828 
829 void
830 pf_hash_rule_addr(MD5_CTX *ctx, struct pf_rule_addr *pfr)
831 {
832 	PF_MD5_UPD(pfr, addr.type);
833 	switch (pfr->addr.type) {
834 		case PF_ADDR_DYNIFTL:
835 			PF_MD5_UPD(pfr, addr.v.ifname);
836 			PF_MD5_UPD(pfr, addr.iflags);
837 			break;
838 		case PF_ADDR_TABLE:
839 			PF_MD5_UPD(pfr, addr.v.tblname);
840 			break;
841 		case PF_ADDR_ADDRMASK:
842 			/* XXX ignore af? */
843 			PF_MD5_UPD(pfr, addr.v.a.addr.addr32);
844 			PF_MD5_UPD(pfr, addr.v.a.mask.addr32);
845 			break;
846 		case PF_ADDR_RTLABEL:
847 			PF_MD5_UPD(pfr, addr.v.rtlabelname);
848 			break;
849 	}
850 
851 	PF_MD5_UPD(pfr, port[0]);
852 	PF_MD5_UPD(pfr, port[1]);
853 	PF_MD5_UPD(pfr, neg);
854 	PF_MD5_UPD(pfr, port_op);
855 }
856 
857 void
858 pf_hash_rule(MD5_CTX *ctx, struct pf_rule *rule)
859 {
860 	u_int16_t x;
861 	u_int32_t y;
862 
863 	pf_hash_rule_addr(ctx, &rule->src);
864 	pf_hash_rule_addr(ctx, &rule->dst);
865 	PF_MD5_UPD_STR(rule, label);
866 	PF_MD5_UPD_STR(rule, ifname);
867 	PF_MD5_UPD_STR(rule, match_tagname);
868 	PF_MD5_UPD_HTONS(rule, match_tag, x); /* dup? */
869 	PF_MD5_UPD_HTONL(rule, os_fingerprint, y);
870 	PF_MD5_UPD_HTONL(rule, prob, y);
871 	PF_MD5_UPD_HTONL(rule, uid.uid[0], y);
872 	PF_MD5_UPD_HTONL(rule, uid.uid[1], y);
873 	PF_MD5_UPD(rule, uid.op);
874 	PF_MD5_UPD_HTONL(rule, gid.gid[0], y);
875 	PF_MD5_UPD_HTONL(rule, gid.gid[1], y);
876 	PF_MD5_UPD(rule, gid.op);
877 	PF_MD5_UPD_HTONL(rule, rule_flag, y);
878 	PF_MD5_UPD(rule, action);
879 	PF_MD5_UPD(rule, direction);
880 	PF_MD5_UPD(rule, af);
881 	PF_MD5_UPD(rule, quick);
882 	PF_MD5_UPD(rule, ifnot);
883 	PF_MD5_UPD(rule, match_tag_not);
884 	PF_MD5_UPD(rule, natpass);
885 	PF_MD5_UPD(rule, keep_state);
886 	PF_MD5_UPD(rule, proto);
887 	PF_MD5_UPD(rule, type);
888 	PF_MD5_UPD(rule, code);
889 	PF_MD5_UPD(rule, flags);
890 	PF_MD5_UPD(rule, flagset);
891 	PF_MD5_UPD(rule, allow_opts);
892 	PF_MD5_UPD(rule, rt);
893 	PF_MD5_UPD(rule, tos);
894 }
895 
896 int
897 pf_commit_rules(u_int32_t ticket, int rs_num, char *anchor)
898 {
899 	struct pf_ruleset	*rs;
900 	struct pf_rule		*rule, **old_array;
901 	struct pf_rulequeue	*old_rules;
902 	int			 error;
903 	u_int32_t		 old_rcount;
904 
905 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
906 		return (EINVAL);
907 	rs = pf_find_ruleset(anchor);
908 	if (rs == NULL || !rs->rules[rs_num].inactive.open ||
909 	    ticket != rs->rules[rs_num].inactive.ticket)
910 		return (EBUSY);
911 
912 	/* Calculate checksum for the main ruleset */
913 	if (rs == &pf_main_ruleset) {
914 		error = pf_setup_pfsync_matching(rs);
915 		if (error != 0)
916 			return (error);
917 	}
918 
919 	/* Swap rules, keep the old. */
920 	crit_enter();
921 	old_rules = rs->rules[rs_num].active.ptr;
922 	old_rcount = rs->rules[rs_num].active.rcount;
923 	old_array = rs->rules[rs_num].active.ptr_array;
924 
925 	rs->rules[rs_num].active.ptr =
926 	    rs->rules[rs_num].inactive.ptr;
927 	rs->rules[rs_num].active.ptr_array =
928 	    rs->rules[rs_num].inactive.ptr_array;
929 	rs->rules[rs_num].active.rcount =
930 	    rs->rules[rs_num].inactive.rcount;
931 	rs->rules[rs_num].inactive.ptr = old_rules;
932 	rs->rules[rs_num].inactive.ptr_array = old_array;
933 	rs->rules[rs_num].inactive.rcount = old_rcount;
934 
935 	rs->rules[rs_num].active.ticket =
936 	    rs->rules[rs_num].inactive.ticket;
937 	pf_calc_skip_steps(rs->rules[rs_num].active.ptr);
938 
939 
940 	/* Purge the old rule list. */
941 	while ((rule = TAILQ_FIRST(old_rules)) != NULL)
942 		pf_rm_rule(old_rules, rule);
943 	if (rs->rules[rs_num].inactive.ptr_array)
944 		kfree(rs->rules[rs_num].inactive.ptr_array, M_TEMP);
945 	rs->rules[rs_num].inactive.ptr_array = NULL;
946 	rs->rules[rs_num].inactive.rcount = 0;
947 	rs->rules[rs_num].inactive.open = 0;
948 	pf_remove_if_empty_ruleset(rs);
949 	crit_exit();
950 	return (0);
951 }
952 
953 int
954 pf_setup_pfsync_matching(struct pf_ruleset *rs)
955 {
956 	MD5_CTX			 ctx;
957 	struct pf_rule		*rule;
958 	int			 rs_cnt;
959 	u_int8_t		 digest[PF_MD5_DIGEST_LENGTH];
960 
961 	MD5Init(&ctx);
962 	for (rs_cnt = 0; rs_cnt < PF_RULESET_MAX; rs_cnt++) {
963 		/* XXX PF_RULESET_SCRUB as well? */
964 		if (rs_cnt == PF_RULESET_SCRUB)
965 			continue;
966 
967 		if (rs->rules[rs_cnt].inactive.ptr_array)
968 			kfree(rs->rules[rs_cnt].inactive.ptr_array, M_TEMP);
969 		rs->rules[rs_cnt].inactive.ptr_array = NULL;
970 
971 		if (rs->rules[rs_cnt].inactive.rcount) {
972 			rs->rules[rs_cnt].inactive.ptr_array =
973 			    kmalloc(sizeof(caddr_t) *
974 				    rs->rules[rs_cnt].inactive.rcount,
975 				    M_TEMP, M_WAITOK);
976 
977 			if (!rs->rules[rs_cnt].inactive.ptr_array)
978 				return (ENOMEM);
979 		}
980 
981 		TAILQ_FOREACH(rule, rs->rules[rs_cnt].inactive.ptr,
982 		    entries) {
983 			pf_hash_rule(&ctx, rule);
984 			(rs->rules[rs_cnt].inactive.ptr_array)[rule->nr] = rule;
985 		}
986 	}
987 
988 	MD5Final(digest, &ctx);
989 	memcpy(pf_status.pf_chksum, digest, sizeof(pf_status.pf_chksum));
990 	return (0);
991 }
992 
993 int
994 pfioctl(struct dev_ioctl_args *ap)
995 {
996 	u_long cmd = ap->a_cmd;
997 	caddr_t addr = ap->a_data;
998 	struct pf_pooladdr	*pa = NULL;
999 	struct pf_pool		*pool = NULL;
1000 	int			 error = 0;
1001 
1002 	/* XXX keep in sync with switch() below */
1003 	if (securelevel > 1)
1004 		switch (cmd) {
1005 		case DIOCGETRULES:
1006 		case DIOCGETRULE:
1007 		case DIOCGETADDRS:
1008 		case DIOCGETADDR:
1009 		case DIOCGETSTATE:
1010 		case DIOCSETSTATUSIF:
1011 		case DIOCGETSTATUS:
1012 		case DIOCCLRSTATUS:
1013 		case DIOCNATLOOK:
1014 		case DIOCSETDEBUG:
1015 		case DIOCGETSTATES:
1016 		case DIOCGETTIMEOUT:
1017 		case DIOCCLRRULECTRS:
1018 		case DIOCGETLIMIT:
1019 		case DIOCGETALTQS:
1020 		case DIOCGETALTQ:
1021 		case DIOCGETQSTATS:
1022 		case DIOCGETRULESETS:
1023 		case DIOCGETRULESET:
1024 		case DIOCRGETTABLES:
1025 		case DIOCRGETTSTATS:
1026 		case DIOCRCLRTSTATS:
1027 		case DIOCRCLRADDRS:
1028 		case DIOCRADDADDRS:
1029 		case DIOCRDELADDRS:
1030 		case DIOCRSETADDRS:
1031 		case DIOCRGETADDRS:
1032 		case DIOCRGETASTATS:
1033 		case DIOCRCLRASTATS:
1034 		case DIOCRTSTADDRS:
1035 		case DIOCOSFPGET:
1036 		case DIOCGETSRCNODES:
1037 		case DIOCCLRSRCNODES:
1038 		case DIOCIGETIFACES:
1039 		case DIOCSETIFFLAG:
1040 		case DIOCCLRIFFLAG:
1041 		case DIOCGIFSPEED:
1042 			break;
1043 		case DIOCRCLRTABLES:
1044 		case DIOCRADDTABLES:
1045 		case DIOCRDELTABLES:
1046 		case DIOCRSETTFLAGS:
1047 			if (((struct pfioc_table *)addr)->pfrio_flags &
1048 			    PFR_FLAG_DUMMY)
1049 				break; /* dummy operation ok */
1050 			return (EPERM);
1051 		default:
1052 			return (EPERM);
1053 		}
1054 
1055 	if (!(ap->a_fflag & FWRITE))
1056 		switch (cmd) {
1057 		case DIOCGETRULES:
1058 		case DIOCGETADDRS:
1059 		case DIOCGETADDR:
1060 		case DIOCGETSTATE:
1061 		case DIOCGETSTATUS:
1062 		case DIOCGETSTATES:
1063 		case DIOCGETTIMEOUT:
1064 		case DIOCGETLIMIT:
1065 		case DIOCGETALTQS:
1066 		case DIOCGETALTQ:
1067 		case DIOCGETQSTATS:
1068 		case DIOCGETRULESETS:
1069 		case DIOCGETRULESET:
1070 		case DIOCNATLOOK:
1071 		case DIOCRGETTABLES:
1072 		case DIOCRGETTSTATS:
1073 		case DIOCRGETADDRS:
1074 		case DIOCRGETASTATS:
1075 		case DIOCRTSTADDRS:
1076 		case DIOCOSFPGET:
1077 		case DIOCGETSRCNODES:
1078 		case DIOCIGETIFACES:
1079 		case DIOCGIFSPEED:
1080 			break;
1081 		case DIOCRCLRTABLES:
1082 		case DIOCRADDTABLES:
1083 		case DIOCRDELTABLES:
1084 		case DIOCRCLRTSTATS:
1085 		case DIOCRCLRADDRS:
1086 		case DIOCRADDADDRS:
1087 		case DIOCRDELADDRS:
1088 		case DIOCRSETADDRS:
1089 		case DIOCRSETTFLAGS:
1090 			if (((struct pfioc_table *)addr)->pfrio_flags &
1091 			    PFR_FLAG_DUMMY)
1092 				break; /* dummy operation ok */
1093 			return (EACCES);
1094 		case DIOCGETRULE:
1095 			if (((struct pfioc_rule *)addr)->action == PF_GET_CLR_CNTR)
1096 				return (EACCES);
1097 			break;
1098 		default:
1099 			return (EACCES);
1100 		}
1101 
1102 	switch (cmd) {
1103 
1104 	case DIOCSTART:
1105 		if (pf_status.running)
1106 			error = EEXIST;
1107 		else {
1108 			error = hook_pf();
1109 			if (error) {
1110 				DPFPRINTF(PF_DEBUG_MISC,
1111 				    ("pf: pfil registration fail\n"));
1112 				break;
1113 			}
1114 			pf_status.running = 1;
1115 			pf_status.since = time_second;
1116 			if (pf_status.stateid == 0) {
1117 				pf_status.stateid = time_second;
1118 				pf_status.stateid = pf_status.stateid << 32;
1119 			}
1120 			DPFPRINTF(PF_DEBUG_MISC, ("pf: started\n"));
1121 		}
1122 		break;
1123 
1124 	case DIOCSTOP:
1125 		if (!pf_status.running)
1126 			error = ENOENT;
1127 		else {
1128 			pf_status.running = 0;
1129 			error = dehook_pf();
1130 			if (error) {
1131 				pf_status.running = 1;
1132 				DPFPRINTF(PF_DEBUG_MISC,
1133 					("pf: pfil unregistration failed\n"));
1134 			}
1135 			pf_status.since = time_second;
1136 			DPFPRINTF(PF_DEBUG_MISC, ("pf: stopped\n"));
1137 		}
1138 		break;
1139 
1140 	case DIOCADDRULE: {
1141 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
1142 		struct pf_ruleset	*ruleset;
1143 		struct pf_rule		*rule, *tail;
1144 		struct pf_pooladdr	*pa;
1145 		int			 rs_num;
1146 
1147 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
1148 		ruleset = pf_find_ruleset(pr->anchor);
1149 		if (ruleset == NULL) {
1150 			error = EINVAL;
1151 			break;
1152 		}
1153 		rs_num = pf_get_ruleset_number(pr->rule.action);
1154 		if (rs_num >= PF_RULESET_MAX) {
1155 			error = EINVAL;
1156 			break;
1157 		}
1158 		if (pr->rule.return_icmp >> 8 > ICMP_MAXTYPE) {
1159 			error = EINVAL;
1160 			break;
1161 		}
1162 		if (pr->ticket != ruleset->rules[rs_num].inactive.ticket) {
1163 			error = EBUSY;
1164 			break;
1165 		}
1166 		if (pr->pool_ticket != ticket_pabuf) {
1167 			error = EBUSY;
1168 			break;
1169 		}
1170 		rule = pool_get(&pf_rule_pl, PR_NOWAIT);
1171 		if (rule == NULL) {
1172 			error = ENOMEM;
1173 			break;
1174 		}
1175 		bcopy(&pr->rule, rule, sizeof(struct pf_rule));
1176 		rule->cuid = ap->a_cred->cr_ruid;
1177 		rule->cpid = (int)NULL;
1178 		rule->anchor = NULL;
1179 		rule->kif = NULL;
1180 		TAILQ_INIT(&rule->rpool.list);
1181 		/* initialize refcounting */
1182 		rule->states = 0;
1183 		rule->src_nodes = 0;
1184 		rule->entries.tqe_prev = NULL;
1185 #ifndef INET
1186 		if (rule->af == AF_INET) {
1187 			pool_put(&pf_rule_pl, rule);
1188 			error = EAFNOSUPPORT;
1189 			break;
1190 		}
1191 #endif /* INET */
1192 #ifndef INET6
1193 		if (rule->af == AF_INET6) {
1194 			pool_put(&pf_rule_pl, rule);
1195 			error = EAFNOSUPPORT;
1196 			break;
1197 		}
1198 #endif /* INET6 */
1199 		tail = TAILQ_LAST(ruleset->rules[rs_num].inactive.ptr,
1200 		    pf_rulequeue);
1201 		if (tail)
1202 			rule->nr = tail->nr + 1;
1203 		else
1204 			rule->nr = 0;
1205 		if (rule->ifname[0]) {
1206 			rule->kif = pfi_kif_get(rule->ifname);
1207 			if (rule->kif == NULL) {
1208 				pool_put(&pf_rule_pl, rule);
1209 				error = EINVAL;
1210 				break;
1211 			}
1212 			pfi_kif_ref(rule->kif, PFI_KIF_REF_RULE);
1213 		}
1214 
1215 		if (rule->rtableid > 0 && rule->rtableid > rt_numfibs)
1216 			error = EBUSY;
1217 
1218 #ifdef ALTQ
1219 		/* set queue IDs */
1220 		if (rule->qname[0] != 0) {
1221 			if ((rule->qid = pf_qname2qid(rule->qname)) == 0)
1222 				error = EBUSY;
1223 			else if (rule->pqname[0] != 0) {
1224 				if ((rule->pqid =
1225 				    pf_qname2qid(rule->pqname)) == 0)
1226 					error = EBUSY;
1227 			} else
1228 				rule->pqid = rule->qid;
1229 		}
1230 #endif
1231 		if (rule->tagname[0])
1232 			if ((rule->tag = pf_tagname2tag(rule->tagname)) == 0)
1233 				error = EBUSY;
1234 		if (rule->match_tagname[0])
1235 			if ((rule->match_tag =
1236 			    pf_tagname2tag(rule->match_tagname)) == 0)
1237 				error = EBUSY;
1238 		if (rule->rt && !rule->direction)
1239 			error = EINVAL;
1240 #if NPFLOG > 0
1241 		if (rule->logif >= PFLOGIFS_MAX)
1242 			error = EINVAL;
1243 #endif
1244 		if (pf_rtlabel_add(&rule->src.addr) ||
1245 		    pf_rtlabel_add(&rule->dst.addr))
1246 			error = EBUSY;
1247 		if (pfi_dynaddr_setup(&rule->src.addr, rule->af))
1248 			error = EINVAL;
1249 		if (pfi_dynaddr_setup(&rule->dst.addr, rule->af))
1250 			error = EINVAL;
1251 		if (pf_tbladdr_setup(ruleset, &rule->src.addr))
1252 			error = EINVAL;
1253 		if (pf_tbladdr_setup(ruleset, &rule->dst.addr))
1254 			error = EINVAL;
1255 		if (pf_anchor_setup(rule, ruleset, pr->anchor_call))
1256 			error = EINVAL;
1257 		TAILQ_FOREACH(pa, &pf_pabuf, entries)
1258 			if (pf_tbladdr_setup(ruleset, &pa->addr))
1259 				error = EINVAL;
1260 
1261 		if (rule->overload_tblname[0]) {
1262 			if ((rule->overload_tbl = pfr_attach_table(ruleset,
1263 			    rule->overload_tblname)) == NULL)
1264 				error = EINVAL;
1265 			else
1266 				rule->overload_tbl->pfrkt_flags |=
1267 				    PFR_TFLAG_ACTIVE;
1268 		}
1269 
1270 		pf_mv_pool(&pf_pabuf, &rule->rpool.list);
1271 		if (((((rule->action == PF_NAT) || (rule->action == PF_RDR) ||
1272 		    (rule->action == PF_BINAT)) && rule->anchor == NULL) ||
1273 		    (rule->rt > PF_FASTROUTE)) &&
1274 		    (TAILQ_FIRST(&rule->rpool.list) == NULL))
1275 			error = EINVAL;
1276 
1277 		if (error) {
1278 			pf_rm_rule(NULL, rule);
1279 			break;
1280 		}
1281 		rule->rpool.cur = TAILQ_FIRST(&rule->rpool.list);
1282 		rule->evaluations = rule->packets[0] = rule->packets[1] =
1283 		    rule->bytes[0] = rule->bytes[1] = 0;
1284 		TAILQ_INSERT_TAIL(ruleset->rules[rs_num].inactive.ptr,
1285 		    rule, entries);
1286 		ruleset->rules[rs_num].inactive.rcount++;
1287 		break;
1288 	}
1289 
1290 	case DIOCGETRULES: {
1291 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
1292 		struct pf_ruleset	*ruleset;
1293 		struct pf_rule		*tail;
1294 		int			 rs_num;
1295 
1296 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
1297 		ruleset = pf_find_ruleset(pr->anchor);
1298 		if (ruleset == NULL) {
1299 			error = EINVAL;
1300 			break;
1301 		}
1302 		rs_num = pf_get_ruleset_number(pr->rule.action);
1303 		if (rs_num >= PF_RULESET_MAX) {
1304 			error = EINVAL;
1305 			break;
1306 		}
1307 		tail = TAILQ_LAST(ruleset->rules[rs_num].active.ptr,
1308 		    pf_rulequeue);
1309 		if (tail)
1310 			pr->nr = tail->nr + 1;
1311 		else
1312 			pr->nr = 0;
1313 		pr->ticket = ruleset->rules[rs_num].active.ticket;
1314 		break;
1315 	}
1316 
1317 	case DIOCGETRULE: {
1318 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
1319 		struct pf_ruleset	*ruleset;
1320 		struct pf_rule		*rule;
1321 		int			 rs_num, i;
1322 
1323 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
1324 		ruleset = pf_find_ruleset(pr->anchor);
1325 		if (ruleset == NULL) {
1326 			error = EINVAL;
1327 			break;
1328 		}
1329 		rs_num = pf_get_ruleset_number(pr->rule.action);
1330 		if (rs_num >= PF_RULESET_MAX) {
1331 			error = EINVAL;
1332 			break;
1333 		}
1334 		if (pr->ticket != ruleset->rules[rs_num].active.ticket) {
1335 			error = EBUSY;
1336 			break;
1337 		}
1338 		rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
1339 		while ((rule != NULL) && (rule->nr != pr->nr))
1340 			rule = TAILQ_NEXT(rule, entries);
1341 		if (rule == NULL) {
1342 			error = EBUSY;
1343 			break;
1344 		}
1345 		bcopy(rule, &pr->rule, sizeof(struct pf_rule));
1346 		if (pf_anchor_copyout(ruleset, rule, pr)) {
1347 			error = EBUSY;
1348 			break;
1349 		}
1350 		pfi_dynaddr_copyout(&pr->rule.src.addr);
1351 		pfi_dynaddr_copyout(&pr->rule.dst.addr);
1352 		pf_tbladdr_copyout(&pr->rule.src.addr);
1353 		pf_tbladdr_copyout(&pr->rule.dst.addr);
1354 		pf_rtlabel_copyout(&pr->rule.src.addr);
1355 		pf_rtlabel_copyout(&pr->rule.dst.addr);
1356 		for (i = 0; i < PF_SKIP_COUNT; ++i)
1357 			if (rule->skip[i].ptr == NULL)
1358 				pr->rule.skip[i].nr = (uint32_t)(-1);
1359 			else
1360 				pr->rule.skip[i].nr =
1361 				    rule->skip[i].ptr->nr;
1362 
1363 		if (pr->action == PF_GET_CLR_CNTR) {
1364 			rule->evaluations = 0;
1365 			rule->packets[0] = rule->packets[1] = 0;
1366 			rule->bytes[0] = rule->bytes[1] = 0;
1367 		}
1368 		break;
1369 	}
1370 
1371 	case DIOCCHANGERULE: {
1372 		struct pfioc_rule	*pcr = (struct pfioc_rule *)addr;
1373 		struct pf_ruleset	*ruleset;
1374 		struct pf_rule		*oldrule = NULL, *newrule = NULL;
1375 		u_int32_t		 nr = 0;
1376 		int			 rs_num;
1377 
1378 		if (!(pcr->action == PF_CHANGE_REMOVE ||
1379 		    pcr->action == PF_CHANGE_GET_TICKET) &&
1380 		    pcr->pool_ticket != ticket_pabuf) {
1381 			error = EBUSY;
1382 			break;
1383 		}
1384 
1385 		if (pcr->action < PF_CHANGE_ADD_HEAD ||
1386 		    pcr->action > PF_CHANGE_GET_TICKET) {
1387 			error = EINVAL;
1388 			break;
1389 		}
1390 		ruleset = pf_find_ruleset(pcr->anchor);
1391 		if (ruleset == NULL) {
1392 			error = EINVAL;
1393 			break;
1394 		}
1395 		rs_num = pf_get_ruleset_number(pcr->rule.action);
1396 		if (rs_num >= PF_RULESET_MAX) {
1397 			error = EINVAL;
1398 			break;
1399 		}
1400 
1401 		if (pcr->action == PF_CHANGE_GET_TICKET) {
1402 			pcr->ticket = ++ruleset->rules[rs_num].active.ticket;
1403 			break;
1404 		} else {
1405 			if (pcr->ticket !=
1406 			    ruleset->rules[rs_num].active.ticket) {
1407 				error = EINVAL;
1408 				break;
1409 			}
1410 			if (pcr->rule.return_icmp >> 8 > ICMP_MAXTYPE) {
1411 				error = EINVAL;
1412 				break;
1413 			}
1414 		}
1415 
1416 		if (pcr->action != PF_CHANGE_REMOVE) {
1417 			newrule = pool_get(&pf_rule_pl, PR_NOWAIT);
1418 			if (newrule == NULL) {
1419 				error = ENOMEM;
1420 				break;
1421 			}
1422 			bcopy(&pcr->rule, newrule, sizeof(struct pf_rule));
1423 			newrule->cuid = ap->a_cred->cr_ruid;
1424 			newrule->cpid = (int)NULL;
1425 			TAILQ_INIT(&newrule->rpool.list);
1426 			/* initialize refcounting */
1427 			newrule->states = 0;
1428 			newrule->entries.tqe_prev = NULL;
1429 #ifndef INET
1430 			if (newrule->af == AF_INET) {
1431 				pool_put(&pf_rule_pl, newrule);
1432 				error = EAFNOSUPPORT;
1433 				break;
1434 			}
1435 #endif /* INET */
1436 #ifndef INET6
1437 			if (newrule->af == AF_INET6) {
1438 				pool_put(&pf_rule_pl, newrule);
1439 				error = EAFNOSUPPORT;
1440 				break;
1441 			}
1442 #endif /* INET6 */
1443 			if (newrule->ifname[0]) {
1444 				newrule->kif = pfi_kif_get(newrule->ifname);
1445 				if (newrule->kif == NULL) {
1446 					pool_put(&pf_rule_pl, newrule);
1447 					error = EINVAL;
1448 					break;
1449 				}
1450 				pfi_kif_ref(newrule->kif, PFI_KIF_REF_RULE);
1451 			} else
1452 				newrule->kif = NULL;
1453 
1454 			if (newrule->rtableid > 0 &&
1455 			    newrule->rtableid > rt_numfibs)
1456 				error = EBUSY;
1457 
1458 #ifdef ALTQ
1459 			/* set queue IDs */
1460 			if (newrule->qname[0] != 0) {
1461 				if ((newrule->qid =
1462 				    pf_qname2qid(newrule->qname)) == 0)
1463 					error = EBUSY;
1464 				else if (newrule->pqname[0] != 0) {
1465 					if ((newrule->pqid =
1466 					    pf_qname2qid(newrule->pqname)) == 0)
1467 						error = EBUSY;
1468 				} else
1469 					newrule->pqid = newrule->qid;
1470 			}
1471 #endif /* ALTQ */
1472 			if (newrule->tagname[0])
1473 				if ((newrule->tag =
1474 				    pf_tagname2tag(newrule->tagname)) == 0)
1475 					error = EBUSY;
1476 			if (newrule->match_tagname[0])
1477 				if ((newrule->match_tag = pf_tagname2tag(
1478 				    newrule->match_tagname)) == 0)
1479 					error = EBUSY;
1480 			if (newrule->rt && !newrule->direction)
1481 				error = EINVAL;
1482 			if (pf_rtlabel_add(&newrule->src.addr) ||
1483 			    pf_rtlabel_add(&newrule->dst.addr))
1484 				error = EBUSY;
1485 			if (pfi_dynaddr_setup(&newrule->src.addr, newrule->af))
1486 				error = EINVAL;
1487 			if (pfi_dynaddr_setup(&newrule->dst.addr, newrule->af))
1488 				error = EINVAL;
1489 			if (pf_tbladdr_setup(ruleset, &newrule->src.addr))
1490 				error = EINVAL;
1491 			if (pf_tbladdr_setup(ruleset, &newrule->dst.addr))
1492 				error = EINVAL;
1493 			if (pf_anchor_setup(newrule, ruleset, pcr->anchor_call))
1494 				error = EINVAL;
1495 			TAILQ_FOREACH(pa, &pf_pabuf, entries)
1496 				if (pf_tbladdr_setup(ruleset, &pa->addr))
1497 					error = EINVAL;
1498 
1499 			if (newrule->overload_tblname[0]) {
1500 				if ((newrule->overload_tbl = pfr_attach_table(
1501 				    ruleset, newrule->overload_tblname)) ==
1502 				    NULL)
1503 					error = EINVAL;
1504 				else
1505 					newrule->overload_tbl->pfrkt_flags |=
1506 					    PFR_TFLAG_ACTIVE;
1507 			}
1508 
1509 			pf_mv_pool(&pf_pabuf, &newrule->rpool.list);
1510 			if (((((newrule->action == PF_NAT) ||
1511 			    (newrule->action == PF_RDR) ||
1512 			    (newrule->action == PF_BINAT) ||
1513 			    (newrule->rt > PF_FASTROUTE)) &&
1514 			    !newrule->anchor)) &&
1515 			    (TAILQ_FIRST(&newrule->rpool.list) == NULL))
1516 				error = EINVAL;
1517 
1518 			if (error) {
1519 				pf_rm_rule(NULL, newrule);
1520 				break;
1521 			}
1522 			newrule->rpool.cur = TAILQ_FIRST(&newrule->rpool.list);
1523 			newrule->evaluations = 0;
1524 			newrule->packets[0] = newrule->packets[1] = 0;
1525 			newrule->bytes[0] = newrule->bytes[1] = 0;
1526 		}
1527 		pf_empty_pool(&pf_pabuf);
1528 
1529 		if (pcr->action == PF_CHANGE_ADD_HEAD)
1530 			oldrule = TAILQ_FIRST(
1531 			    ruleset->rules[rs_num].active.ptr);
1532 		else if (pcr->action == PF_CHANGE_ADD_TAIL)
1533 			oldrule = TAILQ_LAST(
1534 			    ruleset->rules[rs_num].active.ptr, pf_rulequeue);
1535 		else {
1536 			oldrule = TAILQ_FIRST(
1537 			    ruleset->rules[rs_num].active.ptr);
1538 			while ((oldrule != NULL) && (oldrule->nr != pcr->nr))
1539 				oldrule = TAILQ_NEXT(oldrule, entries);
1540 			if (oldrule == NULL) {
1541 				if (newrule != NULL)
1542 					pf_rm_rule(NULL, newrule);
1543 				error = EINVAL;
1544 				break;
1545 			}
1546 		}
1547 
1548 		if (pcr->action == PF_CHANGE_REMOVE) {
1549 			pf_rm_rule(ruleset->rules[rs_num].active.ptr, oldrule);
1550 			ruleset->rules[rs_num].active.rcount--;
1551 		} else {
1552 			if (oldrule == NULL)
1553 				TAILQ_INSERT_TAIL(
1554 				    ruleset->rules[rs_num].active.ptr,
1555 				    newrule, entries);
1556 			else if (pcr->action == PF_CHANGE_ADD_HEAD ||
1557 			    pcr->action == PF_CHANGE_ADD_BEFORE)
1558 				TAILQ_INSERT_BEFORE(oldrule, newrule, entries);
1559 			else
1560 				TAILQ_INSERT_AFTER(
1561 				    ruleset->rules[rs_num].active.ptr,
1562 				    oldrule, newrule, entries);
1563 			ruleset->rules[rs_num].active.rcount++;
1564 		}
1565 
1566 		nr = 0;
1567 		TAILQ_FOREACH(oldrule,
1568 		    ruleset->rules[rs_num].active.ptr, entries)
1569 			oldrule->nr = nr++;
1570 
1571 		ruleset->rules[rs_num].active.ticket++;
1572 
1573 		pf_calc_skip_steps(ruleset->rules[rs_num].active.ptr);
1574 		pf_remove_if_empty_ruleset(ruleset);
1575 
1576 		break;
1577 	}
1578 
1579 	case DIOCCLRSTATES: {
1580 		struct pf_state		*state, *nexts;
1581 		struct pfioc_state_kill *psk = (struct pfioc_state_kill *)addr;
1582 		int			 killed = 0;
1583 
1584 		for (state = RB_MIN(pf_state_tree_id, &tree_id); state;
1585 		    state = nexts) {
1586 			nexts = RB_NEXT(pf_state_tree_id, &tree_id, state);
1587 
1588 			if (!psk->psk_ifname[0] || !strcmp(psk->psk_ifname,
1589 			    state->u.s.kif->pfik_name)) {
1590 #if NPFSYNC
1591 				/* don't send out individual delete messages */
1592 				state->sync_flags = PFSTATE_NOSYNC;
1593 #endif
1594 				pf_unlink_state(state);
1595 				killed++;
1596 			}
1597 		}
1598 		psk->psk_af = killed;
1599 #if NPFSYNC
1600 		pfsync_clear_states(pf_status.hostid, psk->psk_ifname);
1601 #endif
1602 		break;
1603 	}
1604 
1605 	case DIOCKILLSTATES: {
1606 		struct pf_state		*state, *nexts;
1607 		struct pf_state_host	*src, *dst;
1608 		struct pfioc_state_kill	*psk = (struct pfioc_state_kill *)addr;
1609 		int			 killed = 0;
1610 
1611 		for (state = RB_MIN(pf_state_tree_id, &tree_id); state;
1612 		    state = nexts) {
1613 			nexts = RB_NEXT(pf_state_tree_id, &tree_id, state);
1614 
1615 			if (state->direction == PF_OUT) {
1616 				src = &state->lan;
1617 				dst = &state->ext;
1618 			} else {
1619 				src = &state->ext;
1620 				dst = &state->lan;
1621 			}
1622 			if ((!psk->psk_af || state->af == psk->psk_af)
1623 			    && (!psk->psk_proto || psk->psk_proto ==
1624 			    state->proto) &&
1625 			    PF_MATCHA(psk->psk_src.neg,
1626 			    &psk->psk_src.addr.v.a.addr,
1627 			    &psk->psk_src.addr.v.a.mask,
1628 			    &src->addr, state->af) &&
1629 			    PF_MATCHA(psk->psk_dst.neg,
1630 			    &psk->psk_dst.addr.v.a.addr,
1631 			    &psk->psk_dst.addr.v.a.mask,
1632 			    &dst->addr, state->af) &&
1633 			    (psk->psk_src.port_op == 0 ||
1634 			    pf_match_port(psk->psk_src.port_op,
1635 			    psk->psk_src.port[0], psk->psk_src.port[1],
1636 			    src->port)) &&
1637 			    (psk->psk_dst.port_op == 0 ||
1638 			    pf_match_port(psk->psk_dst.port_op,
1639 			    psk->psk_dst.port[0], psk->psk_dst.port[1],
1640 			    dst->port)) &&
1641 			    (!psk->psk_ifname[0] || !strcmp(psk->psk_ifname,
1642 			    state->u.s.kif->pfik_name))) {
1643 #if NPFSYNC > 0
1644 				/* send immediate delete of state */
1645 				pfsync_delete_state(state);
1646 				state->sync_flags |= PFSTATE_NOSYNC;
1647 #endif
1648 				pf_unlink_state(state);
1649 				killed++;
1650 			}
1651 		}
1652 		psk->psk_af = killed;
1653 		break;
1654 	}
1655 
1656 	case DIOCADDSTATE: {
1657 		struct pfioc_state	*ps = (struct pfioc_state *)addr;
1658 		struct pf_state		*state;
1659 		struct pfi_kif		*kif;
1660 
1661 		if (ps->state.timeout >= PFTM_MAX &&
1662 		    ps->state.timeout != PFTM_UNTIL_PACKET) {
1663 			error = EINVAL;
1664 			break;
1665 		}
1666 		state = pool_get(&pf_state_pl, PR_NOWAIT);
1667 		if (state == NULL) {
1668 			error = ENOMEM;
1669 			break;
1670 		}
1671 		kif = pfi_kif_get(ps->state.u.ifname);
1672 		if (kif == NULL) {
1673 			pool_put(&pf_state_pl, state);
1674 			error = ENOENT;
1675 			break;
1676 		}
1677 		bcopy(&ps->state, state, sizeof(struct pf_state));
1678 		bzero(&state->u, sizeof(state->u));
1679 		state->rule.ptr = &pf_default_rule;
1680 		state->nat_rule.ptr = NULL;
1681 		state->anchor.ptr = NULL;
1682 		state->rt_kif = NULL;
1683 		state->creation = time_second;
1684 		state->pfsync_time = 0;
1685 		state->packets[0] = state->packets[1] = 0;
1686 		state->bytes[0] = state->bytes[1] = 0;
1687 		state->hash = pf_state_hash(state);
1688 
1689 		if (pf_insert_state(kif, state)) {
1690 			pfi_kif_unref(kif, PFI_KIF_REF_NONE);
1691 			pool_put(&pf_state_pl, state);
1692 			error = ENOMEM;
1693 		}
1694 		break;
1695 	}
1696 
1697 	case DIOCGETSTATE: {
1698 		struct pfioc_state	*ps = (struct pfioc_state *)addr;
1699 		struct pf_state		*state;
1700 		u_int32_t		 nr;
1701 		int			 secs;
1702 
1703 		nr = 0;
1704 		RB_FOREACH(state, pf_state_tree_id, &tree_id) {
1705 			if (nr >= ps->nr)
1706 				break;
1707 			nr++;
1708 		}
1709 		if (state == NULL) {
1710 			error = EBUSY;
1711 			break;
1712 		}
1713 		secs = time_second;
1714 		bcopy(state, &ps->state, sizeof(ps->state));
1715 		strlcpy(ps->state.u.ifname, state->u.s.kif->pfik_name,
1716 		    sizeof(ps->state.u.ifname));
1717 		ps->state.rule.nr = state->rule.ptr->nr;
1718 		ps->state.nat_rule.nr = (state->nat_rule.ptr == NULL) ?
1719 		    (uint32_t)(-1) : state->nat_rule.ptr->nr;
1720 		ps->state.anchor.nr = (state->anchor.ptr == NULL) ?
1721 		    -1 : state->anchor.ptr->nr;
1722 		ps->state.creation = secs - ps->state.creation;
1723 		ps->state.expire = pf_state_expires(state);
1724 		if (ps->state.expire > secs)
1725 			ps->state.expire -= secs;
1726 		else
1727 			ps->state.expire = 0;
1728 		break;
1729 	}
1730 
1731 	case DIOCGETSTATES: {
1732 		struct pfioc_states	*ps = (struct pfioc_states *)addr;
1733 		struct pf_state		*state;
1734 		struct pf_state		*p, *pstore;
1735 		u_int32_t		 nr = 0;
1736 		int			 space = ps->ps_len;
1737 
1738 		if (space == 0) {
1739 			nr = pf_status.states;
1740 			ps->ps_len = sizeof(struct pf_state) * nr;
1741 			break;
1742 		}
1743 
1744 		pstore = kmalloc(sizeof(*pstore), M_TEMP, M_WAITOK);
1745 
1746 		p = ps->ps_states;
1747 
1748 		state = TAILQ_FIRST(&state_list);
1749 		while (state) {
1750 			if (state->timeout != PFTM_UNLINKED) {
1751 				int	secs = time_second;
1752 
1753 				if ((nr+1) * sizeof(*p) > (unsigned)ps->ps_len)
1754 					break;
1755 
1756 				bcopy(state, pstore, sizeof(*pstore));
1757 				strlcpy(pstore->u.ifname,
1758 				    state->u.s.kif->pfik_name,
1759 				    sizeof(pstore->u.ifname));
1760 				pstore->rule.nr = state->rule.ptr->nr;
1761 				pstore->nat_rule.nr = (state->nat_rule.ptr ==
1762 				    NULL) ? -1 : state->nat_rule.ptr->nr;
1763 				pstore->anchor.nr = (state->anchor.ptr ==
1764 				    NULL) ? -1 : state->anchor.ptr->nr;
1765 				pstore->creation = secs - pstore->creation;
1766 				pstore->expire = pf_state_expires(state);
1767 				if (pstore->expire > secs)
1768 					pstore->expire -= secs;
1769 				else
1770 					pstore->expire = 0;
1771 				error = copyout(pstore, p, sizeof(*p));
1772 				if (error) {
1773 					kfree(pstore, M_TEMP);
1774 					goto fail;
1775 				}
1776 				p++;
1777 				nr++;
1778 			}
1779 			state = TAILQ_NEXT(state, u.s.entry_list);
1780 		}
1781 
1782 		ps->ps_len = sizeof(struct pf_state) * nr;
1783 
1784 		kfree(pstore, M_TEMP);
1785 		break;
1786 	}
1787 
1788 	case DIOCGETSTATUS: {
1789 		struct pf_status *s = (struct pf_status *)addr;
1790 		bcopy(&pf_status, s, sizeof(struct pf_status));
1791 		pfi_fill_oldstatus(s);
1792 		break;
1793 	}
1794 
1795 	case DIOCSETSTATUSIF: {
1796 		struct pfioc_if	*pi = (struct pfioc_if *)addr;
1797 
1798 		if (pi->ifname[0] == 0) {
1799 			bzero(pf_status.ifname, IFNAMSIZ);
1800 			break;
1801 		}
1802 		if (ifunit(pi->ifname) == NULL) {
1803 			error = EINVAL;
1804 			break;
1805 		}
1806 		strlcpy(pf_status.ifname, pi->ifname, IFNAMSIZ);
1807 		break;
1808 	}
1809 
1810 	case DIOCCLRSTATUS: {
1811 		bzero(pf_status.counters, sizeof(pf_status.counters));
1812 		bzero(pf_status.fcounters, sizeof(pf_status.fcounters));
1813 		bzero(pf_status.scounters, sizeof(pf_status.scounters));
1814 		pf_status.since = time_second;
1815 		if (*pf_status.ifname)
1816 			pfi_clr_istats(pf_status.ifname);
1817 		break;
1818 	}
1819 
1820 	case DIOCNATLOOK: {
1821 		struct pfioc_natlook	*pnl = (struct pfioc_natlook *)addr;
1822 		struct pf_state		*state;
1823 		struct pf_state_cmp	 key;
1824 		int			 m = 0, direction = pnl->direction;
1825 
1826 		key.af = pnl->af;
1827 		key.proto = pnl->proto;
1828 
1829 		if (!pnl->proto ||
1830 		    PF_AZERO(&pnl->saddr, pnl->af) ||
1831 		    PF_AZERO(&pnl->daddr, pnl->af) ||
1832 		    ((pnl->proto == IPPROTO_TCP ||
1833 		    pnl->proto == IPPROTO_UDP) &&
1834 		    (!pnl->dport || !pnl->sport)))
1835 			error = EINVAL;
1836 		else {
1837 			/*
1838 			 * userland gives us source and dest of connection,
1839 			 * reverse the lookup so we ask for what happens with
1840 			 * the return traffic, enabling us to find it in the
1841 			 * state tree.
1842 			 */
1843 			if (direction == PF_IN) {
1844 				PF_ACPY(&key.ext.addr, &pnl->daddr, pnl->af);
1845 				key.ext.port = pnl->dport;
1846 				PF_ACPY(&key.gwy.addr, &pnl->saddr, pnl->af);
1847 				key.gwy.port = pnl->sport;
1848 				state = pf_find_state_all(&key, PF_EXT_GWY, &m);
1849 			} else {
1850 				PF_ACPY(&key.lan.addr, &pnl->daddr, pnl->af);
1851 				key.lan.port = pnl->dport;
1852 				PF_ACPY(&key.ext.addr, &pnl->saddr, pnl->af);
1853 				key.ext.port = pnl->sport;
1854 				state = pf_find_state_all(&key, PF_LAN_EXT, &m);
1855 			}
1856 			if (m > 1)
1857 				error = E2BIG;	/* more than one state */
1858 			else if (state != NULL) {
1859 				if (direction == PF_IN) {
1860 					PF_ACPY(&pnl->rsaddr, &state->lan.addr,
1861 					    state->af);
1862 					pnl->rsport = state->lan.port;
1863 					PF_ACPY(&pnl->rdaddr, &pnl->daddr,
1864 					    pnl->af);
1865 					pnl->rdport = pnl->dport;
1866 				} else {
1867 					PF_ACPY(&pnl->rdaddr, &state->gwy.addr,
1868 					    state->af);
1869 					pnl->rdport = state->gwy.port;
1870 					PF_ACPY(&pnl->rsaddr, &pnl->saddr,
1871 					    pnl->af);
1872 					pnl->rsport = pnl->sport;
1873 				}
1874 			} else
1875 				error = ENOENT;
1876 		}
1877 		break;
1878 	}
1879 
1880 	case DIOCSETTIMEOUT: {
1881 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
1882 		int		 old;
1883 
1884 		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX ||
1885 		    pt->seconds < 0) {
1886 			error = EINVAL;
1887 			goto fail;
1888 		}
1889 		old = pf_default_rule.timeout[pt->timeout];
1890 		if (pt->timeout == PFTM_INTERVAL && pt->seconds == 0)
1891 			pt->seconds = 1;
1892 		pf_default_rule.timeout[pt->timeout] = pt->seconds;
1893 		if (pt->timeout == PFTM_INTERVAL && pt->seconds < old)
1894 			wakeup(pf_purge_thread);
1895 		pt->seconds = old;
1896 		break;
1897 	}
1898 
1899 	case DIOCGETTIMEOUT: {
1900 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
1901 
1902 		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX) {
1903 			error = EINVAL;
1904 			goto fail;
1905 		}
1906 		pt->seconds = pf_default_rule.timeout[pt->timeout];
1907 		break;
1908 	}
1909 
1910 	case DIOCGETLIMIT: {
1911 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
1912 
1913 		if (pl->index < 0 || pl->index >= PF_LIMIT_MAX) {
1914 			error = EINVAL;
1915 			goto fail;
1916 		}
1917 		pl->limit = pf_pool_limits[pl->index].limit;
1918 		break;
1919 	}
1920 
1921 	case DIOCSETLIMIT: {
1922 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
1923 		int			 old_limit;
1924 
1925 		if (pl->index < 0 || pl->index >= PF_LIMIT_MAX ||
1926 		    pf_pool_limits[pl->index].pp == NULL) {
1927 			error = EINVAL;
1928 			goto fail;
1929 		}
1930 
1931 		/* XXX Get an API to set limits on the zone/pool */
1932 		old_limit = pf_pool_limits[pl->index].limit;
1933 		pf_pool_limits[pl->index].limit = pl->limit;
1934 		pl->limit = old_limit;
1935 		break;
1936 	}
1937 
1938 	case DIOCSETDEBUG: {
1939 		u_int32_t	*level = (u_int32_t *)addr;
1940 
1941 		pf_status.debug = *level;
1942 		break;
1943 	}
1944 
1945 	case DIOCCLRRULECTRS: {
1946 		/* obsoleted by DIOCGETRULE with action=PF_GET_CLR_CNTR */
1947 		struct pf_ruleset	*ruleset = &pf_main_ruleset;
1948 		struct pf_rule		*rule;
1949 
1950 		TAILQ_FOREACH(rule,
1951 		    ruleset->rules[PF_RULESET_FILTER].active.ptr, entries) {
1952 			rule->evaluations = 0;
1953 			rule->packets[0] = rule->packets[1] = 0;
1954 			rule->bytes[0] = rule->bytes[1] = 0;
1955 		}
1956 		break;
1957 	}
1958 
1959 	case DIOCGIFSPEED: {
1960 		struct pf_ifspeed	*psp = (struct pf_ifspeed *)addr;
1961 		struct pf_ifspeed	ps;
1962 		struct ifnet		*ifp;
1963 
1964 		if (psp->ifname[0] != 0) {
1965 			/* Can we completely trust user-land? */
1966 			strlcpy(ps.ifname, psp->ifname, IFNAMSIZ);
1967 			ifp = ifunit(ps.ifname);
1968 			if (ifp )
1969 				psp->baudrate = ifp->if_baudrate;
1970 			else
1971 				error = EINVAL;
1972 		} else
1973 			error = EINVAL;
1974 		break;
1975 	}
1976 #ifdef ALTQ
1977 	case DIOCSTARTALTQ: {
1978 		struct pf_altq		*altq;
1979 
1980 		/* enable all altq interfaces on active list */
1981 		TAILQ_FOREACH(altq, pf_altqs_active, entries) {
1982 			if (altq->qname[0] == 0) {
1983 				error = pf_enable_altq(altq);
1984 				if (error != 0)
1985 					break;
1986 			}
1987 		}
1988 		if (error == 0)
1989 			pf_altq_running = 1;
1990 		DPFPRINTF(PF_DEBUG_MISC, ("altq: started\n"));
1991 		break;
1992 	}
1993 
1994 	case DIOCSTOPALTQ: {
1995 		struct pf_altq		*altq;
1996 
1997 		/* disable all altq interfaces on active list */
1998 		TAILQ_FOREACH(altq, pf_altqs_active, entries) {
1999 			if (altq->qname[0] == 0) {
2000 				error = pf_disable_altq(altq);
2001 				if (error != 0)
2002 					break;
2003 			}
2004 		}
2005 		if (error == 0)
2006 			pf_altq_running = 0;
2007 		DPFPRINTF(PF_DEBUG_MISC, ("altq: stopped\n"));
2008 		break;
2009 	}
2010 
2011 	case DIOCADDALTQ: {
2012 		struct pfioc_altq	*pa = (struct pfioc_altq *)addr;
2013 		struct pf_altq		*altq, *a;
2014 
2015 		if (pa->ticket != ticket_altqs_inactive) {
2016 			error = EBUSY;
2017 			break;
2018 		}
2019 		altq = pool_get(&pf_altq_pl, PR_NOWAIT);
2020 		if (altq == NULL) {
2021 			error = ENOMEM;
2022 			break;
2023 		}
2024 		bcopy(&pa->altq, altq, sizeof(struct pf_altq));
2025 
2026 		/*
2027 		 * if this is for a queue, find the discipline and
2028 		 * copy the necessary fields
2029 		 */
2030 		if (altq->qname[0] != 0) {
2031 			if ((altq->qid = pf_qname2qid(altq->qname)) == 0) {
2032 				error = EBUSY;
2033 				pool_put(&pf_altq_pl, altq);
2034 				break;
2035 			}
2036 			TAILQ_FOREACH(a, pf_altqs_inactive, entries) {
2037 				if (strncmp(a->ifname, altq->ifname,
2038 				    IFNAMSIZ) == 0 && a->qname[0] == 0) {
2039 					altq->altq_disc = a->altq_disc;
2040 					break;
2041 				}
2042 			}
2043 		}
2044 
2045 		error = altq_add(altq);
2046 		if (error) {
2047 			pool_put(&pf_altq_pl, altq);
2048 			break;
2049 		}
2050 
2051 		TAILQ_INSERT_TAIL(pf_altqs_inactive, altq, entries);
2052 		bcopy(altq, &pa->altq, sizeof(struct pf_altq));
2053 		break;
2054 	}
2055 
2056 	case DIOCGETALTQS: {
2057 		struct pfioc_altq	*pa = (struct pfioc_altq *)addr;
2058 		struct pf_altq		*altq;
2059 
2060 		pa->nr = 0;
2061 		TAILQ_FOREACH(altq, pf_altqs_active, entries)
2062 			pa->nr++;
2063 		pa->ticket = ticket_altqs_active;
2064 		break;
2065 	}
2066 
2067 	case DIOCGETALTQ: {
2068 		struct pfioc_altq	*pa = (struct pfioc_altq *)addr;
2069 		struct pf_altq		*altq;
2070 		u_int32_t		 nr;
2071 
2072 		if (pa->ticket != ticket_altqs_active) {
2073 			error = EBUSY;
2074 			break;
2075 		}
2076 		nr = 0;
2077 		altq = TAILQ_FIRST(pf_altqs_active);
2078 		while ((altq != NULL) && (nr < pa->nr)) {
2079 			altq = TAILQ_NEXT(altq, entries);
2080 			nr++;
2081 		}
2082 		if (altq == NULL) {
2083 			error = EBUSY;
2084 			break;
2085 		}
2086 		bcopy(altq, &pa->altq, sizeof(struct pf_altq));
2087 		break;
2088 	}
2089 
2090 	case DIOCCHANGEALTQ:
2091 		/* CHANGEALTQ not supported yet! */
2092 		error = ENODEV;
2093 		break;
2094 
2095 	case DIOCGETQSTATS: {
2096 		struct pfioc_qstats	*pq = (struct pfioc_qstats *)addr;
2097 		struct pf_altq		*altq;
2098 		u_int32_t		 nr;
2099 		int			 nbytes;
2100 
2101 		if (pq->ticket != ticket_altqs_active) {
2102 			error = EBUSY;
2103 			break;
2104 		}
2105 		nbytes = pq->nbytes;
2106 		nr = 0;
2107 		altq = TAILQ_FIRST(pf_altqs_active);
2108 		while ((altq != NULL) && (nr < pq->nr)) {
2109 			altq = TAILQ_NEXT(altq, entries);
2110 			nr++;
2111 		}
2112 		if (altq == NULL) {
2113 			error = EBUSY;
2114 			break;
2115 		}
2116 		error = altq_getqstats(altq, pq->buf, &nbytes);
2117 		if (error == 0) {
2118 			pq->scheduler = altq->scheduler;
2119 			pq->nbytes = nbytes;
2120 		}
2121 		break;
2122 	}
2123 #endif /* ALTQ */
2124 
2125 	case DIOCBEGINADDRS: {
2126 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
2127 
2128 		pf_empty_pool(&pf_pabuf);
2129 		pp->ticket = ++ticket_pabuf;
2130 		break;
2131 	}
2132 
2133 	case DIOCADDADDR: {
2134 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
2135 
2136 		if (pp->ticket != ticket_pabuf) {
2137 			error = EBUSY;
2138 			break;
2139 		}
2140 #ifndef INET
2141 		if (pp->af == AF_INET) {
2142 			error = EAFNOSUPPORT;
2143 			break;
2144 		}
2145 #endif /* INET */
2146 #ifndef INET6
2147 		if (pp->af == AF_INET6) {
2148 			error = EAFNOSUPPORT;
2149 			break;
2150 		}
2151 #endif /* INET6 */
2152 		if (pp->addr.addr.type != PF_ADDR_ADDRMASK &&
2153 		    pp->addr.addr.type != PF_ADDR_DYNIFTL &&
2154 		    pp->addr.addr.type != PF_ADDR_TABLE) {
2155 			error = EINVAL;
2156 			break;
2157 		}
2158 		pa = pool_get(&pf_pooladdr_pl, PR_NOWAIT);
2159 		if (pa == NULL) {
2160 			error = ENOMEM;
2161 			break;
2162 		}
2163 		bcopy(&pp->addr, pa, sizeof(struct pf_pooladdr));
2164 		if (pa->ifname[0]) {
2165 			pa->kif = pfi_kif_get(pa->ifname);
2166 			if (pa->kif == NULL) {
2167 				pool_put(&pf_pooladdr_pl, pa);
2168 				error = EINVAL;
2169 				break;
2170 			}
2171 			pfi_kif_ref(pa->kif, PFI_KIF_REF_RULE);
2172 		}
2173 		if (pfi_dynaddr_setup(&pa->addr, pp->af)) {
2174 			pfi_dynaddr_remove(&pa->addr);
2175 			pfi_kif_unref(pa->kif, PFI_KIF_REF_RULE);
2176 			pool_put(&pf_pooladdr_pl, pa);
2177 			error = EINVAL;
2178 			break;
2179 		}
2180 		TAILQ_INSERT_TAIL(&pf_pabuf, pa, entries);
2181 		break;
2182 	}
2183 
2184 	case DIOCGETADDRS: {
2185 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
2186 
2187 		pp->nr = 0;
2188 		pool = pf_get_pool(pp->anchor, pp->ticket, pp->r_action,
2189 		    pp->r_num, 0, 1, 0);
2190 		if (pool == NULL) {
2191 			error = EBUSY;
2192 			break;
2193 		}
2194 		TAILQ_FOREACH(pa, &pool->list, entries)
2195 			pp->nr++;
2196 		break;
2197 	}
2198 
2199 	case DIOCGETADDR: {
2200 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
2201 		u_int32_t		 nr = 0;
2202 
2203 		pool = pf_get_pool(pp->anchor, pp->ticket, pp->r_action,
2204 		    pp->r_num, 0, 1, 1);
2205 		if (pool == NULL) {
2206 			error = EBUSY;
2207 			break;
2208 		}
2209 		pa = TAILQ_FIRST(&pool->list);
2210 		while ((pa != NULL) && (nr < pp->nr)) {
2211 			pa = TAILQ_NEXT(pa, entries);
2212 			nr++;
2213 		}
2214 		if (pa == NULL) {
2215 			error = EBUSY;
2216 			break;
2217 		}
2218 		bcopy(pa, &pp->addr, sizeof(struct pf_pooladdr));
2219 		pfi_dynaddr_copyout(&pp->addr.addr);
2220 		pf_tbladdr_copyout(&pp->addr.addr);
2221 		pf_rtlabel_copyout(&pp->addr.addr);
2222 		break;
2223 	}
2224 
2225 	case DIOCCHANGEADDR: {
2226 		struct pfioc_pooladdr	*pca = (struct pfioc_pooladdr *)addr;
2227 		struct pf_pooladdr	*oldpa = NULL, *newpa = NULL;
2228 		struct pf_ruleset	*ruleset;
2229 
2230 		if (pca->action < PF_CHANGE_ADD_HEAD ||
2231 		    pca->action > PF_CHANGE_REMOVE) {
2232 			error = EINVAL;
2233 			break;
2234 		}
2235 		if (pca->addr.addr.type != PF_ADDR_ADDRMASK &&
2236 		    pca->addr.addr.type != PF_ADDR_DYNIFTL &&
2237 		    pca->addr.addr.type != PF_ADDR_TABLE) {
2238 			error = EINVAL;
2239 			break;
2240 		}
2241 
2242 		ruleset = pf_find_ruleset(pca->anchor);
2243 		if (ruleset == NULL) {
2244 			error = EBUSY;
2245 			break;
2246 		}
2247 		pool = pf_get_pool(pca->anchor, pca->ticket, pca->r_action,
2248 		    pca->r_num, pca->r_last, 1, 1);
2249 		if (pool == NULL) {
2250 			error = EBUSY;
2251 			break;
2252 		}
2253 		if (pca->action != PF_CHANGE_REMOVE) {
2254 			newpa = pool_get(&pf_pooladdr_pl, PR_NOWAIT);
2255 			if (newpa == NULL) {
2256 				error = ENOMEM;
2257 				break;
2258 			}
2259 			bcopy(&pca->addr, newpa, sizeof(struct pf_pooladdr));
2260 #ifndef INET
2261 			if (pca->af == AF_INET) {
2262 				pool_put(&pf_pooladdr_pl, newpa);
2263 				error = EAFNOSUPPORT;
2264 				break;
2265 			}
2266 #endif /* INET */
2267 #ifndef INET6
2268 			if (pca->af == AF_INET6) {
2269 				pool_put(&pf_pooladdr_pl, newpa);
2270 				error = EAFNOSUPPORT;
2271 				break;
2272 			}
2273 #endif /* INET6 */
2274 			if (newpa->ifname[0]) {
2275 				newpa->kif = pfi_kif_get(newpa->ifname);
2276 				if (newpa->kif == NULL) {
2277 					pool_put(&pf_pooladdr_pl, newpa);
2278 					error = EINVAL;
2279 					break;
2280 				}
2281 				pfi_kif_ref(newpa->kif, PFI_KIF_REF_RULE);
2282 			} else
2283 				newpa->kif = NULL;
2284 			if (pfi_dynaddr_setup(&newpa->addr, pca->af) ||
2285 			    pf_tbladdr_setup(ruleset, &newpa->addr)) {
2286 				pfi_dynaddr_remove(&newpa->addr);
2287 				pfi_kif_unref(newpa->kif, PFI_KIF_REF_RULE);
2288 				pool_put(&pf_pooladdr_pl, newpa);
2289 				error = EINVAL;
2290 				break;
2291 			}
2292 		}
2293 
2294 		if (pca->action == PF_CHANGE_ADD_HEAD)
2295 			oldpa = TAILQ_FIRST(&pool->list);
2296 		else if (pca->action == PF_CHANGE_ADD_TAIL)
2297 			oldpa = TAILQ_LAST(&pool->list, pf_palist);
2298 		else {
2299 			int	i = 0;
2300 
2301 			oldpa = TAILQ_FIRST(&pool->list);
2302 			while ((oldpa != NULL) && (i < pca->nr)) {
2303 				oldpa = TAILQ_NEXT(oldpa, entries);
2304 				i++;
2305 			}
2306 			if (oldpa == NULL) {
2307 				error = EINVAL;
2308 				break;
2309 			}
2310 		}
2311 
2312 		if (pca->action == PF_CHANGE_REMOVE) {
2313 			TAILQ_REMOVE(&pool->list, oldpa, entries);
2314 			pfi_dynaddr_remove(&oldpa->addr);
2315 			pf_tbladdr_remove(&oldpa->addr);
2316 			pfi_kif_unref(oldpa->kif, PFI_KIF_REF_RULE);
2317 			pool_put(&pf_pooladdr_pl, oldpa);
2318 		} else {
2319 			if (oldpa == NULL)
2320 				TAILQ_INSERT_TAIL(&pool->list, newpa, entries);
2321 			else if (pca->action == PF_CHANGE_ADD_HEAD ||
2322 			    pca->action == PF_CHANGE_ADD_BEFORE)
2323 				TAILQ_INSERT_BEFORE(oldpa, newpa, entries);
2324 			else
2325 				TAILQ_INSERT_AFTER(&pool->list, oldpa,
2326 				    newpa, entries);
2327 		}
2328 
2329 		pool->cur = TAILQ_FIRST(&pool->list);
2330 		PF_ACPY(&pool->counter, &pool->cur->addr.v.a.addr,
2331 		    pca->af);
2332 		break;
2333 	}
2334 
2335 	case DIOCGETRULESETS: {
2336 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
2337 		struct pf_ruleset	*ruleset;
2338 		struct pf_anchor	*anchor;
2339 
2340 		pr->path[sizeof(pr->path) - 1] = 0;
2341 		if ((ruleset = pf_find_ruleset(pr->path)) == NULL) {
2342 			error = EINVAL;
2343 			break;
2344 		}
2345 		pr->nr = 0;
2346 		if (ruleset->anchor == NULL) {
2347 			/* XXX kludge for pf_main_ruleset */
2348 			RB_FOREACH(anchor, pf_anchor_global, &pf_anchors)
2349 				if (anchor->parent == NULL)
2350 					pr->nr++;
2351 		} else {
2352 			RB_FOREACH(anchor, pf_anchor_node,
2353 			    &ruleset->anchor->children)
2354 				pr->nr++;
2355 		}
2356 		break;
2357 	}
2358 
2359 	case DIOCGETRULESET: {
2360 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
2361 		struct pf_ruleset	*ruleset;
2362 		struct pf_anchor	*anchor;
2363 		u_int32_t		 nr = 0;
2364 
2365 		pr->path[sizeof(pr->path) - 1] = 0;
2366 		if ((ruleset = pf_find_ruleset(pr->path)) == NULL) {
2367 			error = EINVAL;
2368 			break;
2369 		}
2370 		pr->name[0] = 0;
2371 		if (ruleset->anchor == NULL) {
2372 			/* XXX kludge for pf_main_ruleset */
2373 			RB_FOREACH(anchor, pf_anchor_global, &pf_anchors)
2374 				if (anchor->parent == NULL && nr++ == pr->nr) {
2375 					strlcpy(pr->name, anchor->name,
2376 					    sizeof(pr->name));
2377 					break;
2378 				}
2379 		} else {
2380 			RB_FOREACH(anchor, pf_anchor_node,
2381 			    &ruleset->anchor->children)
2382 				if (nr++ == pr->nr) {
2383 					strlcpy(pr->name, anchor->name,
2384 					    sizeof(pr->name));
2385 					break;
2386 				}
2387 		}
2388 		if (!pr->name[0])
2389 			error = EBUSY;
2390 		break;
2391 	}
2392 
2393 	case DIOCRCLRTABLES: {
2394 		struct pfioc_table *io = (struct pfioc_table *)addr;
2395 
2396 		if (io->pfrio_esize != 0) {
2397 			error = ENODEV;
2398 			break;
2399 		}
2400 		error = pfr_clr_tables(&io->pfrio_table, &io->pfrio_ndel,
2401 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
2402 		break;
2403 	}
2404 
2405 	case DIOCRADDTABLES: {
2406 		struct pfioc_table *io = (struct pfioc_table *)addr;
2407 
2408 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2409 			error = ENODEV;
2410 			break;
2411 		}
2412 		error = pfr_add_tables(io->pfrio_buffer, io->pfrio_size,
2413 		    &io->pfrio_nadd, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2414 		break;
2415 	}
2416 
2417 	case DIOCRDELTABLES: {
2418 		struct pfioc_table *io = (struct pfioc_table *)addr;
2419 
2420 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2421 			error = ENODEV;
2422 			break;
2423 		}
2424 		error = pfr_del_tables(io->pfrio_buffer, io->pfrio_size,
2425 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2426 		break;
2427 	}
2428 
2429 	case DIOCRGETTABLES: {
2430 		struct pfioc_table *io = (struct pfioc_table *)addr;
2431 
2432 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2433 			error = ENODEV;
2434 			break;
2435 		}
2436 		error = pfr_get_tables(&io->pfrio_table, io->pfrio_buffer,
2437 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2438 		break;
2439 	}
2440 
2441 	case DIOCRGETTSTATS: {
2442 		struct pfioc_table *io = (struct pfioc_table *)addr;
2443 
2444 		if (io->pfrio_esize != sizeof(struct pfr_tstats)) {
2445 			error = ENODEV;
2446 			break;
2447 		}
2448 		error = pfr_get_tstats(&io->pfrio_table, io->pfrio_buffer,
2449 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2450 		break;
2451 	}
2452 
2453 	case DIOCRCLRTSTATS: {
2454 		struct pfioc_table *io = (struct pfioc_table *)addr;
2455 
2456 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2457 			error = ENODEV;
2458 			break;
2459 		}
2460 		error = pfr_clr_tstats(io->pfrio_buffer, io->pfrio_size,
2461 		    &io->pfrio_nzero, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2462 		break;
2463 	}
2464 
2465 	case DIOCRSETTFLAGS: {
2466 		struct pfioc_table *io = (struct pfioc_table *)addr;
2467 
2468 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2469 			error = ENODEV;
2470 			break;
2471 		}
2472 		error = pfr_set_tflags(io->pfrio_buffer, io->pfrio_size,
2473 		    io->pfrio_setflag, io->pfrio_clrflag, &io->pfrio_nchange,
2474 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2475 		break;
2476 	}
2477 
2478 	case DIOCRCLRADDRS: {
2479 		struct pfioc_table *io = (struct pfioc_table *)addr;
2480 
2481 		if (io->pfrio_esize != 0) {
2482 			error = ENODEV;
2483 			break;
2484 		}
2485 		error = pfr_clr_addrs(&io->pfrio_table, &io->pfrio_ndel,
2486 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
2487 		break;
2488 	}
2489 
2490 	case DIOCRADDADDRS: {
2491 		struct pfioc_table *io = (struct pfioc_table *)addr;
2492 
2493 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2494 			error = ENODEV;
2495 			break;
2496 		}
2497 		error = pfr_add_addrs(&io->pfrio_table, io->pfrio_buffer,
2498 		    io->pfrio_size, &io->pfrio_nadd, io->pfrio_flags |
2499 		    PFR_FLAG_USERIOCTL);
2500 		break;
2501 	}
2502 
2503 	case DIOCRDELADDRS: {
2504 		struct pfioc_table *io = (struct pfioc_table *)addr;
2505 
2506 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2507 			error = ENODEV;
2508 			break;
2509 		}
2510 		error = pfr_del_addrs(&io->pfrio_table, io->pfrio_buffer,
2511 		    io->pfrio_size, &io->pfrio_ndel, io->pfrio_flags |
2512 		    PFR_FLAG_USERIOCTL);
2513 		break;
2514 	}
2515 
2516 	case DIOCRSETADDRS: {
2517 		struct pfioc_table *io = (struct pfioc_table *)addr;
2518 
2519 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2520 			error = ENODEV;
2521 			break;
2522 		}
2523 		error = pfr_set_addrs(&io->pfrio_table, io->pfrio_buffer,
2524 		    io->pfrio_size, &io->pfrio_size2, &io->pfrio_nadd,
2525 		    &io->pfrio_ndel, &io->pfrio_nchange, io->pfrio_flags |
2526 		    PFR_FLAG_USERIOCTL, 0);
2527 		break;
2528 	}
2529 
2530 	case DIOCRGETADDRS: {
2531 		struct pfioc_table *io = (struct pfioc_table *)addr;
2532 
2533 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2534 			error = ENODEV;
2535 			break;
2536 		}
2537 		error = pfr_get_addrs(&io->pfrio_table, io->pfrio_buffer,
2538 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2539 		break;
2540 	}
2541 
2542 	case DIOCRGETASTATS: {
2543 		struct pfioc_table *io = (struct pfioc_table *)addr;
2544 
2545 		if (io->pfrio_esize != sizeof(struct pfr_astats)) {
2546 			error = ENODEV;
2547 			break;
2548 		}
2549 		error = pfr_get_astats(&io->pfrio_table, io->pfrio_buffer,
2550 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2551 		break;
2552 	}
2553 
2554 	case DIOCRCLRASTATS: {
2555 		struct pfioc_table *io = (struct pfioc_table *)addr;
2556 
2557 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2558 			error = ENODEV;
2559 			break;
2560 		}
2561 		error = pfr_clr_astats(&io->pfrio_table, io->pfrio_buffer,
2562 		    io->pfrio_size, &io->pfrio_nzero, io->pfrio_flags |
2563 		    PFR_FLAG_USERIOCTL);
2564 		break;
2565 	}
2566 
2567 	case DIOCRTSTADDRS: {
2568 		struct pfioc_table *io = (struct pfioc_table *)addr;
2569 
2570 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2571 			error = ENODEV;
2572 			break;
2573 		}
2574 		error = pfr_tst_addrs(&io->pfrio_table, io->pfrio_buffer,
2575 		    io->pfrio_size, &io->pfrio_nmatch, io->pfrio_flags |
2576 		    PFR_FLAG_USERIOCTL);
2577 		break;
2578 	}
2579 
2580 	case DIOCRINADEFINE: {
2581 		struct pfioc_table *io = (struct pfioc_table *)addr;
2582 
2583 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2584 			error = ENODEV;
2585 			break;
2586 		}
2587 		error = pfr_ina_define(&io->pfrio_table, io->pfrio_buffer,
2588 		    io->pfrio_size, &io->pfrio_nadd, &io->pfrio_naddr,
2589 		    io->pfrio_ticket, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2590 		break;
2591 	}
2592 
2593 	case DIOCOSFPADD: {
2594 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
2595 		error = pf_osfp_add(io);
2596 		break;
2597 	}
2598 
2599 	case DIOCOSFPGET: {
2600 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
2601 		error = pf_osfp_get(io);
2602 		break;
2603 	}
2604 
2605 	case DIOCXBEGIN: {
2606 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2607 		struct pfioc_trans_e	*ioe;
2608 		struct pfr_table	*table;
2609 		int			 i;
2610 
2611 		if (io->esize != sizeof(*ioe)) {
2612 			error = ENODEV;
2613 			goto fail;
2614 		}
2615 		ioe = (struct pfioc_trans_e *)kmalloc(sizeof(*ioe),
2616 		    M_TEMP, M_WAITOK);
2617 		table = (struct pfr_table *)kmalloc(sizeof(*table),
2618 		    M_TEMP, M_WAITOK);
2619 		for (i = 0; i < io->size; i++) {
2620 			if (copyin(io->array+i, ioe, sizeof(*ioe))) {
2621 				kfree(table, M_TEMP);
2622 				kfree(ioe, M_TEMP);
2623 				error = EFAULT;
2624 				goto fail;
2625 			}
2626 			switch (ioe->rs_num) {
2627 #ifdef ALTQ
2628 			case PF_RULESET_ALTQ:
2629 				if (ioe->anchor[0]) {
2630 					kfree(table, M_TEMP);
2631 					kfree(ioe, M_TEMP);
2632 					error = EINVAL;
2633 					goto fail;
2634 				}
2635 				if ((error = pf_begin_altq(&ioe->ticket))) {
2636 					kfree(table, M_TEMP);
2637 					kfree(ioe, M_TEMP);
2638 					goto fail;
2639 				}
2640 				break;
2641 #endif /* ALTQ */
2642 			case PF_RULESET_TABLE:
2643 				bzero(table, sizeof(*table));
2644 				strlcpy(table->pfrt_anchor, ioe->anchor,
2645 				    sizeof(table->pfrt_anchor));
2646 				if ((error = pfr_ina_begin(table,
2647 				    &ioe->ticket, NULL, 0))) {
2648 					kfree(table, M_TEMP);
2649 					kfree(ioe, M_TEMP);
2650 					goto fail;
2651 				}
2652 				break;
2653 			default:
2654 				if ((error = pf_begin_rules(&ioe->ticket,
2655 				    ioe->rs_num, ioe->anchor))) {
2656 					kfree(table, M_TEMP);
2657 					kfree(ioe, M_TEMP);
2658 					goto fail;
2659 				}
2660 				break;
2661 			}
2662 			if (copyout(ioe, io->array+i, sizeof(io->array[i]))) {
2663 				kfree(table, M_TEMP);
2664 				kfree(ioe, M_TEMP);
2665 				error = EFAULT;
2666 				goto fail;
2667 			}
2668 		}
2669 		kfree(table, M_TEMP);
2670 		kfree(ioe, M_TEMP);
2671 		break;
2672 	}
2673 
2674 	case DIOCXROLLBACK: {
2675 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2676 		struct pfioc_trans_e	*ioe;
2677 		struct pfr_table	*table;
2678 		int			 i;
2679 
2680 		if (io->esize != sizeof(*ioe)) {
2681 			error = ENODEV;
2682 			goto fail;
2683 		}
2684 		ioe = (struct pfioc_trans_e *)kmalloc(sizeof(*ioe),
2685 		    M_TEMP, M_WAITOK);
2686 		table = (struct pfr_table *)kmalloc(sizeof(*table),
2687 		    M_TEMP, M_WAITOK);
2688 		for (i = 0; i < io->size; i++) {
2689 			if (copyin(io->array+i, ioe, sizeof(*ioe))) {
2690 				kfree(table, M_TEMP);
2691 				kfree(ioe, M_TEMP);
2692 				error = EFAULT;
2693 				goto fail;
2694 			}
2695 			switch (ioe->rs_num) {
2696 #ifdef ALTQ
2697 			case PF_RULESET_ALTQ:
2698 				if (ioe->anchor[0]) {
2699 					kfree(table, M_TEMP);
2700 					kfree(ioe, M_TEMP);
2701 					error = EINVAL;
2702 					goto fail;
2703 				}
2704 				if ((error = pf_rollback_altq(ioe->ticket))) {
2705 					kfree(table, M_TEMP);
2706 					kfree(ioe, M_TEMP);
2707 					goto fail; /* really bad */
2708 				}
2709 				break;
2710 #endif /* ALTQ */
2711 			case PF_RULESET_TABLE:
2712 				bzero(table, sizeof(*table));
2713 				strlcpy(table->pfrt_anchor, ioe->anchor,
2714 				    sizeof(table->pfrt_anchor));
2715 				if ((error = pfr_ina_rollback(table,
2716 				    ioe->ticket, NULL, 0))) {
2717 					kfree(table, M_TEMP);
2718 					kfree(ioe, M_TEMP);
2719 					goto fail; /* really bad */
2720 				}
2721 				break;
2722 			default:
2723 				if ((error = pf_rollback_rules(ioe->ticket,
2724 				    ioe->rs_num, ioe->anchor))) {
2725 					kfree(table, M_TEMP);
2726 					kfree(ioe, M_TEMP);
2727 					goto fail; /* really bad */
2728 				}
2729 				break;
2730 			}
2731 		}
2732 		kfree(table, M_TEMP);
2733 		kfree(ioe, M_TEMP);
2734 		break;
2735 	}
2736 
2737 	case DIOCXCOMMIT: {
2738 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2739 		struct pfioc_trans_e	*ioe;
2740 		struct pfr_table	*table;
2741 		struct pf_ruleset	*rs;
2742 		int			 i;
2743 
2744 		if (io->esize != sizeof(*ioe)) {
2745 			error = ENODEV;
2746 			goto fail;
2747 		}
2748 		ioe = (struct pfioc_trans_e *)kmalloc(sizeof(*ioe),
2749 		    M_TEMP, M_WAITOK);
2750 		table = (struct pfr_table *)kmalloc(sizeof(*table),
2751 		    M_TEMP, M_WAITOK);
2752 		/* first makes sure everything will succeed */
2753 		for (i = 0; i < io->size; i++) {
2754 			if (copyin(io->array+i, ioe, sizeof(*ioe))) {
2755 				kfree(table, M_TEMP);
2756 				kfree(ioe, M_TEMP);
2757 				error = EFAULT;
2758 				goto fail;
2759 			}
2760 			switch (ioe->rs_num) {
2761 #ifdef ALTQ
2762 			case PF_RULESET_ALTQ:
2763 				if (ioe->anchor[0]) {
2764 					kfree(table, M_TEMP);
2765 					kfree(ioe, M_TEMP);
2766 					error = EINVAL;
2767 					goto fail;
2768 				}
2769 				if (!altqs_inactive_open || ioe->ticket !=
2770 				    ticket_altqs_inactive) {
2771 					kfree(table, M_TEMP);
2772 					kfree(ioe, M_TEMP);
2773 					error = EBUSY;
2774 					goto fail;
2775 				}
2776 				break;
2777 #endif /* ALTQ */
2778 			case PF_RULESET_TABLE:
2779 				rs = pf_find_ruleset(ioe->anchor);
2780 				if (rs == NULL || !rs->topen || ioe->ticket !=
2781 				     rs->tticket) {
2782 					kfree(table, M_TEMP);
2783 					kfree(ioe, M_TEMP);
2784 					error = EBUSY;
2785 					goto fail;
2786 				}
2787 				break;
2788 			default:
2789 				if (ioe->rs_num < 0 || ioe->rs_num >=
2790 				    PF_RULESET_MAX) {
2791 					kfree(table, M_TEMP);
2792 					kfree(ioe, M_TEMP);
2793 					error = EINVAL;
2794 					goto fail;
2795 				}
2796 				rs = pf_find_ruleset(ioe->anchor);
2797 				if (rs == NULL ||
2798 				    !rs->rules[ioe->rs_num].inactive.open ||
2799 				    rs->rules[ioe->rs_num].inactive.ticket !=
2800 				    ioe->ticket) {
2801 					kfree(table, M_TEMP);
2802 					kfree(ioe, M_TEMP);
2803 					error = EBUSY;
2804 					goto fail;
2805 				}
2806 				break;
2807 			}
2808 		}
2809 		/* now do the commit - no errors should happen here */
2810 		for (i = 0; i < io->size; i++) {
2811 			if (copyin(io->array+i, ioe, sizeof(*ioe))) {
2812 				kfree(table, M_TEMP);
2813 				kfree(ioe, M_TEMP);
2814 				error = EFAULT;
2815 				goto fail;
2816 			}
2817 			switch (ioe->rs_num) {
2818 #ifdef ALTQ
2819 			case PF_RULESET_ALTQ:
2820 				if ((error = pf_commit_altq(ioe->ticket))) {
2821 					kfree(table, M_TEMP);
2822 					kfree(ioe, M_TEMP);
2823 					goto fail; /* really bad */
2824 				}
2825 				break;
2826 #endif /* ALTQ */
2827 			case PF_RULESET_TABLE:
2828 				bzero(table, sizeof(*table));
2829 				strlcpy(table->pfrt_anchor, ioe->anchor,
2830 				    sizeof(table->pfrt_anchor));
2831 				if ((error = pfr_ina_commit(table, ioe->ticket,
2832 				    NULL, NULL, 0))) {
2833 					kfree(table, M_TEMP);
2834 					kfree(ioe, M_TEMP);
2835 					goto fail; /* really bad */
2836 				}
2837 				break;
2838 			default:
2839 				if ((error = pf_commit_rules(ioe->ticket,
2840 				    ioe->rs_num, ioe->anchor))) {
2841 					kfree(table, M_TEMP);
2842 					kfree(ioe, M_TEMP);
2843 					goto fail; /* really bad */
2844 				}
2845 				break;
2846 			}
2847 		}
2848 		kfree(table, M_TEMP);
2849 		kfree(ioe, M_TEMP);
2850 		break;
2851 	}
2852 
2853 	case DIOCGETSRCNODES: {
2854 		struct pfioc_src_nodes	*psn = (struct pfioc_src_nodes *)addr;
2855 		struct pf_src_node	*n, *p, *pstore;
2856 		u_int32_t		 nr = 0;
2857 		int			 space = psn->psn_len;
2858 
2859 		if (space == 0) {
2860 			RB_FOREACH(n, pf_src_tree, &tree_src_tracking)
2861 				nr++;
2862 			psn->psn_len = sizeof(struct pf_src_node) * nr;
2863 			break;
2864 		}
2865 
2866 		pstore = kmalloc(sizeof(*pstore), M_TEMP, M_WAITOK);
2867 
2868 		p = psn->psn_src_nodes;
2869 		RB_FOREACH(n, pf_src_tree, &tree_src_tracking) {
2870 			int	secs = time_second, diff;
2871 
2872 			if ((nr + 1) * sizeof(*p) > (unsigned)psn->psn_len)
2873 				break;
2874 
2875 			bcopy(n, pstore, sizeof(*pstore));
2876 			if (n->rule.ptr != NULL)
2877 				pstore->rule.nr = n->rule.ptr->nr;
2878 			pstore->creation = secs - pstore->creation;
2879 			if (pstore->expire > secs)
2880 				pstore->expire -= secs;
2881 			else
2882 				pstore->expire = 0;
2883 
2884 			/* adjust the connection rate estimate */
2885 			diff = secs - n->conn_rate.last;
2886 			if (diff >= n->conn_rate.seconds)
2887 				pstore->conn_rate.count = 0;
2888 			else
2889 				pstore->conn_rate.count -=
2890 				    n->conn_rate.count * diff /
2891 				    n->conn_rate.seconds;
2892 
2893 			error = copyout(pstore, p, sizeof(*p));
2894 			if (error) {
2895 				kfree(pstore, M_TEMP);
2896 				goto fail;
2897 			}
2898 			p++;
2899 			nr++;
2900 		}
2901 		psn->psn_len = sizeof(struct pf_src_node) * nr;
2902 
2903 		kfree(pstore, M_TEMP);
2904 		break;
2905 	}
2906 
2907 	case DIOCCLRSRCNODES: {
2908 		struct pf_src_node	*n;
2909 		struct pf_state		*state;
2910 
2911 		RB_FOREACH(state, pf_state_tree_id, &tree_id) {
2912 			state->src_node = NULL;
2913 			state->nat_src_node = NULL;
2914 		}
2915 		RB_FOREACH(n, pf_src_tree, &tree_src_tracking) {
2916 			n->expire = 1;
2917 			n->states = 0;
2918 		}
2919 		pf_purge_expired_src_nodes(1);
2920 		pf_status.src_nodes = 0;
2921 		break;
2922 	}
2923 
2924 	case DIOCKILLSRCNODES: {
2925 		struct pf_src_node	*sn;
2926 		struct pf_state		*s;
2927 		struct pfioc_src_node_kill *psnk = \
2928 			(struct pfioc_src_node_kill *) addr;
2929 		int			killed = 0;
2930 
2931 		RB_FOREACH(sn, pf_src_tree, &tree_src_tracking) {
2932         		if (PF_MATCHA(psnk->psnk_src.neg, \
2933 				      &psnk->psnk_src.addr.v.a.addr, \
2934 				      &psnk->psnk_src.addr.v.a.mask, \
2935 				      &sn->addr, sn->af) &&
2936 			    PF_MATCHA(psnk->psnk_dst.neg, \
2937 				      &psnk->psnk_dst.addr.v.a.addr, \
2938 				      &psnk->psnk_dst.addr.v.a.mask, \
2939 				      &sn->raddr, sn->af)) {
2940 				/* Handle state to src_node linkage */
2941 				if (sn->states != 0) {
2942 					RB_FOREACH(s, pf_state_tree_id,
2943 					    &tree_id) {
2944 						if (s->src_node == sn)
2945 							s->src_node = NULL;
2946 						if (s->nat_src_node == sn)
2947 							s->nat_src_node = NULL;
2948 					}
2949 					sn->states = 0;
2950 				}
2951 				sn->expire = 1;
2952 				killed++;
2953 			}
2954 		}
2955 
2956 		if (killed > 0)
2957 			pf_purge_expired_src_nodes(1);
2958 
2959 		psnk->psnk_af = killed;
2960 		break;
2961 	}
2962 
2963 	case DIOCSETHOSTID: {
2964 		u_int32_t	*hostid = (u_int32_t *)addr;
2965 
2966 		if (*hostid == 0)
2967 			pf_status.hostid = karc4random();
2968 		else
2969 			pf_status.hostid = *hostid;
2970 		break;
2971 	}
2972 
2973 	case DIOCOSFPFLUSH:
2974 		crit_enter();
2975 		pf_osfp_flush();
2976 		crit_exit();
2977 		break;
2978 
2979 	case DIOCIGETIFACES: {
2980 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
2981 
2982 		if (io->pfiio_esize != sizeof(struct pfi_kif)) {
2983 			error = ENODEV;
2984 			break;
2985 		}
2986 		error = pfi_get_ifaces(io->pfiio_name, io->pfiio_buffer,
2987 		    &io->pfiio_size);
2988 		break;
2989 	}
2990 
2991 	case DIOCSETIFFLAG: {
2992 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
2993 
2994 		error = pfi_set_flags(io->pfiio_name, io->pfiio_flags);
2995 		break;
2996 	}
2997 
2998 	case DIOCCLRIFFLAG: {
2999 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
3000 
3001 		error = pfi_clear_flags(io->pfiio_name, io->pfiio_flags);
3002 		break;
3003 	}
3004 
3005 	default:
3006 		error = ENODEV;
3007 		break;
3008 	}
3009 fail:
3010 	return (error);
3011 }
3012 
3013 /*
3014  * XXX - Check for version missmatch!!!
3015  */
3016 static void
3017 pf_clear_states(void)
3018 {
3019 	struct pf_state		*state;
3020 
3021 	RB_FOREACH(state, pf_state_tree_id, &tree_id) {
3022 		state->timeout = PFTM_PURGE;
3023 #if NPFSYNC
3024 		/* don't send out individual delete messages */
3025 		state->sync_flags = PFSTATE_NOSYNC;
3026 #endif
3027 		pf_unlink_state(state);
3028 	}
3029 	pf_status.states = 0;
3030 #if 0 /* NPFSYNC */
3031 /*
3032  * XXX This is called on module unload, we do not want to sync that over? */
3033  */
3034 	pfsync_clear_states(pf_status.hostid, psk->psk_ifname);
3035 #endif
3036 }
3037 
3038 static int
3039 pf_clear_tables(void)
3040 {
3041 	struct pfioc_table io;
3042 	int error;
3043 
3044 	bzero(&io, sizeof(io));
3045 
3046 	error = pfr_clr_tables(&io.pfrio_table, &io.pfrio_ndel,
3047 	    io.pfrio_flags);
3048 
3049 	return (error);
3050 }
3051 
3052 static void
3053 pf_clear_srcnodes(void)
3054 {
3055 	struct pf_src_node	*n;
3056 	struct pf_state		*state;
3057 
3058 	RB_FOREACH(state, pf_state_tree_id, &tree_id) {
3059 		state->src_node = NULL;
3060 		state->nat_src_node = NULL;
3061 	}
3062 	RB_FOREACH(n, pf_src_tree, &tree_src_tracking) {
3063 		n->expire = 1;
3064 		n->states = 0;
3065 	}
3066 	pf_purge_expired_src_nodes(0);
3067 	pf_status.src_nodes = 0;
3068 }
3069 /*
3070  * XXX - Check for version missmatch!!!
3071  */
3072 
3073 /*
3074  * Duplicate pfctl -Fa operation to get rid of as much as we can.
3075  */
3076 static int
3077 shutdown_pf(void)
3078 {
3079 	int error = 0;
3080 	u_int32_t t[5];
3081 	char nn = '\0';
3082 
3083 	pf_status.running = 0;
3084 	do {
3085 		if ((error = pf_begin_rules(&t[0], PF_RULESET_SCRUB, &nn)) != 0) {
3086 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: SCRUB\n"));
3087 			break;
3088 		}
3089 		if ((error = pf_begin_rules(&t[1], PF_RULESET_FILTER, &nn)) != 0) {
3090 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: FILTER\n"));
3091 			break;		/* XXX: rollback? */
3092 		}
3093 		if ((error = pf_begin_rules(&t[2], PF_RULESET_NAT, &nn))    != 0) {
3094 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: NAT\n"));
3095 			break;		/* XXX: rollback? */
3096 		}
3097 		if ((error = pf_begin_rules(&t[3], PF_RULESET_BINAT, &nn))
3098 		    != 0) {
3099 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: BINAT\n"));
3100 			break;		/* XXX: rollback? */
3101 		}
3102 		if ((error = pf_begin_rules(&t[4], PF_RULESET_RDR, &nn))
3103 		    != 0) {
3104 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: RDR\n"));
3105 			break;		/* XXX: rollback? */
3106 		}
3107 
3108 		/* XXX: these should always succeed here */
3109 		pf_commit_rules(t[0], PF_RULESET_SCRUB, &nn);
3110 		pf_commit_rules(t[1], PF_RULESET_FILTER, &nn);
3111 		pf_commit_rules(t[2], PF_RULESET_NAT, &nn);
3112 		pf_commit_rules(t[3], PF_RULESET_BINAT, &nn);
3113 		pf_commit_rules(t[4], PF_RULESET_RDR, &nn);
3114 
3115 		if ((error = pf_clear_tables()) != 0)
3116 			break;
3117 
3118 #ifdef ALTQ
3119 		if ((error = pf_begin_altq(&t[0])) != 0) {
3120 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: ALTQ\n"));
3121 			break;
3122 		}
3123 		pf_commit_altq(t[0]);
3124 #endif
3125 
3126 		pf_clear_states();
3127 
3128 		pf_clear_srcnodes();
3129 
3130 		/* status does not use malloced mem so no need to cleanup */
3131 		/* fingerprints and interfaces have their own cleanup code */
3132 	} while(0);
3133 
3134         return (error);
3135 }
3136 
3137 static int
3138 pf_check_in(void *arg, struct mbuf **m, struct ifnet *ifp, int dir)
3139 {
3140 	/*
3141 	 * DragonFly's version of pf uses FreeBSD's native host byte ordering
3142 	 * for ip_len/ip_off. This is why we don't have to change byte order
3143 	 * like the FreeBSD-5 version does.
3144 	 */
3145 	int chk;
3146 
3147 	chk = pf_test(PF_IN, ifp, m, NULL, NULL);
3148 	if (chk && *m) {
3149 		m_freem(*m);
3150 		*m = NULL;
3151 	}
3152 	return chk;
3153 }
3154 
3155 static int
3156 pf_check_out(void *arg, struct mbuf **m, struct ifnet *ifp, int dir)
3157 {
3158 	/*
3159 	 * DragonFly's version of pf uses FreeBSD's native host byte ordering
3160 	 * for ip_len/ip_off. This is why we don't have to change byte order
3161 	 * like the FreeBSD-5 version does.
3162 	 */
3163 	int chk;
3164 
3165 	/* We need a proper CSUM befor we start (s. OpenBSD ip_output) */
3166 	if ((*m)->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
3167 		in_delayed_cksum(*m);
3168 		(*m)->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
3169 	}
3170 	chk = pf_test(PF_OUT, ifp, m, NULL, NULL);
3171 	if (chk && *m) {
3172 		m_freem(*m);
3173 		*m = NULL;
3174 	}
3175 	return chk;
3176 }
3177 
3178 #ifdef INET6
3179 static int
3180 pf_check6_in(void *arg, struct mbuf **m, struct ifnet *ifp, int dir)
3181 {
3182 	/*
3183 	 * IPv6 is not affected by ip_len/ip_off byte order changes.
3184 	 */
3185 	int chk;
3186 
3187 	chk = pf_test6(PF_IN, ifp, m, NULL, NULL);
3188 	if (chk && *m) {
3189 		m_freem(*m);
3190 		*m = NULL;
3191 	}
3192 	return chk;
3193 }
3194 
3195 static int
3196 pf_check6_out(void *arg, struct mbuf **m, struct ifnet *ifp, int dir)
3197 {
3198 	/*
3199 	 * IPv6 is not affected by ip_len/ip_off byte order changes.
3200 	 */
3201 	int chk;
3202 
3203 	/* We need a proper CSUM befor we start (s. OpenBSD ip_output) */
3204 	if ((*m)->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
3205 		in_delayed_cksum(*m);
3206 		(*m)->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
3207 	}
3208 	chk = pf_test6(PF_OUT, ifp, m, NULL, NULL);
3209 	if (chk && *m) {
3210 		m_freem(*m);
3211 		*m = NULL;
3212 	}
3213 	return chk;
3214 }
3215 #endif /* INET6 */
3216 
3217 static int
3218 hook_pf(void)
3219 {
3220 	struct pfil_head *pfh_inet;
3221 #ifdef INET6
3222 	struct pfil_head *pfh_inet6;
3223 #endif
3224 
3225 	if (pf_pfil_hooked)
3226 		return (0);
3227 
3228 	pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
3229 	if (pfh_inet == NULL)
3230 		return (ENODEV);
3231 	pfil_add_hook(pf_check_in, NULL, PFIL_IN, pfh_inet);
3232 	pfil_add_hook(pf_check_out, NULL, PFIL_OUT, pfh_inet);
3233 #ifdef INET6
3234 	pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
3235 	if (pfh_inet6 == NULL) {
3236 		pfil_remove_hook(pf_check_in, NULL, PFIL_IN, pfh_inet);
3237 		pfil_remove_hook(pf_check_out, NULL, PFIL_OUT, pfh_inet);
3238 		return (ENODEV);
3239 	}
3240 	pfil_add_hook(pf_check6_in, NULL, PFIL_IN, pfh_inet6);
3241 	pfil_add_hook(pf_check6_out, NULL, PFIL_OUT, pfh_inet6);
3242 #endif
3243 
3244 	pf_pfil_hooked = 1;
3245 	return (0);
3246 }
3247 
3248 static int
3249 dehook_pf(void)
3250 {
3251 	struct pfil_head *pfh_inet;
3252 #ifdef INET6
3253 	struct pfil_head *pfh_inet6;
3254 #endif
3255 
3256 	if (pf_pfil_hooked == 0)
3257 		return (0);
3258 
3259 	pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
3260 	if (pfh_inet == NULL)
3261 		return (ENODEV);
3262 	pfil_remove_hook(pf_check_in, NULL, PFIL_IN, pfh_inet);
3263 	pfil_remove_hook(pf_check_out, NULL, PFIL_OUT, pfh_inet);
3264 #ifdef INET6
3265 	pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
3266 	if (pfh_inet6 == NULL)
3267 		return (ENODEV);
3268 	pfil_remove_hook(pf_check6_in, NULL, PFIL_IN, pfh_inet6);
3269 	pfil_remove_hook(pf_check6_out, NULL, PFIL_OUT, pfh_inet6);
3270 #endif
3271 
3272 	pf_pfil_hooked = 0;
3273 	return (0);
3274 }
3275 
3276 static int
3277 pf_load(void)
3278 {
3279 	int error;
3280 
3281 	init_zone_var();
3282 	init_pf_lck();
3283 	kprintf("pf_load() p1\n"); /*XXX*/
3284 	pf_dev = make_dev(&pf_ops, 0, 0, 0, 0600, PF_NAME);
3285 	kprintf("pf_load() p2\n"); /*XXX*/
3286 	error = pfattach();
3287 	kprintf("pf_load() p3\n"); /*XXX*/
3288 	if (error) {
3289 		dev_ops_remove_all(&pf_ops);
3290 		destroy_pf_lck();
3291 		return (error);
3292 	}
3293 	lockinit(&pf_consistency_lock, "pfconslck", 0, LK_CANRECURSE);
3294 	kprintf("pf_load() p4\n"); /*XXX*/
3295 	return (0);
3296 }
3297 
3298 static int
3299 pf_unload(void)
3300 {
3301 	int error;
3302 
3303 	pf_status.running = 0;
3304 	error = dehook_pf();
3305 	if (error) {
3306 		/*
3307 		 * Should not happen!
3308 		 * XXX Due to error code ESRCH, kldunload will show
3309 		 * a message like 'No such process'.
3310 		 */
3311 		kprintf("pfil unregistration fail\n");
3312 		return error;
3313 	}
3314 	shutdown_pf();
3315 	pf_end_threads = 1;
3316 	while (pf_end_threads < 2) {
3317 		wakeup_one(pf_purge_thread);
3318 		lksleep(pf_purge_thread, &pf_task_lck, 0, "pftmo", hz);
3319 
3320 	}
3321 	pfi_cleanup();
3322 	pf_osfp_flush();
3323 	pf_osfp_cleanup();
3324 	cleanup_pf_zone();
3325 	dev_ops_remove_all(&pf_ops);
3326 	lockuninit(&pf_consistency_lock);
3327 	destroy_pf_lck();
3328 	return 0;
3329 }
3330 
3331 static int
3332 pf_modevent(module_t mod, int type, void *data)
3333 {
3334 	int error = 0;
3335 
3336 	switch(type) {
3337 	case MOD_LOAD:
3338 		error = pf_load();
3339 		break;
3340 
3341 	case MOD_UNLOAD:
3342 		error = pf_unload();
3343 		break;
3344 	default:
3345 		error = EINVAL;
3346 		break;
3347 	}
3348 	return error;
3349 }
3350 
3351 static moduledata_t pf_mod = {
3352 	"pf",
3353 	pf_modevent,
3354 	0
3355 };
3356 DECLARE_MODULE(pf, pf_mod, SI_SUB_PSEUDO, SI_ORDER_FIRST);
3357 MODULE_VERSION(pf, PF_MODVER);
3358