if_pfsync.c revision 241056
1/*	$OpenBSD: if_pfsync.c,v 1.110 2009/02/24 05:39:19 dlg Exp $	*/
2
3/*
4 * Copyright (c) 2002 Michael Shalayeff
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
20 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
24 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
25 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26 * THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/*
30 * Copyright (c) 2009 David Gwynne <dlg@openbsd.org>
31 *
32 * Permission to use, copy, modify, and distribute this software for any
33 * purpose with or without fee is hereby granted, provided that the above
34 * copyright notice and this permission notice appear in all copies.
35 *
36 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
37 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
38 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
39 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
40 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
41 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
42 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
43 */
44
45/*
46 * Revisions picked from OpenBSD after revision 1.110 import:
47 * 1.118, 1.124, 1.148, 1.149, 1.151, 1.171 - fixes to bulk updates
48 * 1.120, 1.175 - use monotonic time_uptime
49 * 1.122 - reduce number of updates for non-TCP sessions
50 * 1.128 - cleanups
51 * 1.146 - bzero() mbuf before sparsely filling it with data
52 * 1.170 - SIOCSIFMTU checks
53 * 1.126, 1.142 - deferred packets processing
54 * 1.173 - correct expire time processing
55 */
56
57#include <sys/cdefs.h>
58__FBSDID("$FreeBSD: head/sys/netpfil/pf/if_pfsync.c 241056 2012-09-29 20:02:26Z glebius $");
59
60#include "opt_inet.h"
61#include "opt_inet6.h"
62#include "opt_pf.h"
63
64#include <sys/param.h>
65#include <sys/bus.h>
66#include <sys/endian.h>
67#include <sys/interrupt.h>
68#include <sys/kernel.h>
69#include <sys/lock.h>
70#include <sys/mbuf.h>
71#include <sys/module.h>
72#include <sys/mutex.h>
73#include <sys/priv.h>
74#include <sys/protosw.h>
75#include <sys/socket.h>
76#include <sys/sockio.h>
77#include <sys/sysctl.h>
78
79#include <net/bpf.h>
80#include <net/if.h>
81#include <net/if_clone.h>
82#include <net/if_types.h>
83#include <net/pfvar.h>
84#include <net/if_pfsync.h>
85
86#include <netinet/if_ether.h>
87#include <netinet/in.h>
88#include <netinet/in_var.h>
89#include <netinet/ip.h>
90#include <netinet/ip_carp.h>
91#include <netinet/ip_var.h>
92#include <netinet/tcp.h>
93#include <netinet/tcp_fsm.h>
94#include <netinet/tcp_seq.h>
95
96#define PFSYNC_MINPKT ( \
97	sizeof(struct ip) + \
98	sizeof(struct pfsync_header) + \
99	sizeof(struct pfsync_subheader) + \
100	sizeof(struct pfsync_eof))
101
102struct pfsync_pkt {
103	struct ip *ip;
104	struct in_addr src;
105	u_int8_t flags;
106};
107
108static int	pfsync_upd_tcp(struct pf_state *, struct pfsync_state_peer *,
109		    struct pfsync_state_peer *);
110static int	pfsync_in_clr(struct pfsync_pkt *, struct mbuf *, int, int);
111static int	pfsync_in_ins(struct pfsync_pkt *, struct mbuf *, int, int);
112static int	pfsync_in_iack(struct pfsync_pkt *, struct mbuf *, int, int);
113static int	pfsync_in_upd(struct pfsync_pkt *, struct mbuf *, int, int);
114static int	pfsync_in_upd_c(struct pfsync_pkt *, struct mbuf *, int, int);
115static int	pfsync_in_ureq(struct pfsync_pkt *, struct mbuf *, int, int);
116static int	pfsync_in_del(struct pfsync_pkt *, struct mbuf *, int, int);
117static int	pfsync_in_del_c(struct pfsync_pkt *, struct mbuf *, int, int);
118static int	pfsync_in_bus(struct pfsync_pkt *, struct mbuf *, int, int);
119static int	pfsync_in_tdb(struct pfsync_pkt *, struct mbuf *, int, int);
120static int	pfsync_in_eof(struct pfsync_pkt *, struct mbuf *, int, int);
121static int	pfsync_in_error(struct pfsync_pkt *, struct mbuf *, int, int);
122
123static int (*pfsync_acts[])(struct pfsync_pkt *, struct mbuf *, int, int) = {
124	pfsync_in_clr,			/* PFSYNC_ACT_CLR */
125	pfsync_in_ins,			/* PFSYNC_ACT_INS */
126	pfsync_in_iack,			/* PFSYNC_ACT_INS_ACK */
127	pfsync_in_upd,			/* PFSYNC_ACT_UPD */
128	pfsync_in_upd_c,		/* PFSYNC_ACT_UPD_C */
129	pfsync_in_ureq,			/* PFSYNC_ACT_UPD_REQ */
130	pfsync_in_del,			/* PFSYNC_ACT_DEL */
131	pfsync_in_del_c,		/* PFSYNC_ACT_DEL_C */
132	pfsync_in_error,		/* PFSYNC_ACT_INS_F */
133	pfsync_in_error,		/* PFSYNC_ACT_DEL_F */
134	pfsync_in_bus,			/* PFSYNC_ACT_BUS */
135	pfsync_in_tdb,			/* PFSYNC_ACT_TDB */
136	pfsync_in_eof			/* PFSYNC_ACT_EOF */
137};
138
139struct pfsync_q {
140	void		(*write)(struct pf_state *, void *);
141	size_t		len;
142	u_int8_t	action;
143};
144
145/* we have one of these for every PFSYNC_S_ */
146static void	pfsync_out_state(struct pf_state *, void *);
147static void	pfsync_out_iack(struct pf_state *, void *);
148static void	pfsync_out_upd_c(struct pf_state *, void *);
149static void	pfsync_out_del(struct pf_state *, void *);
150
151static struct pfsync_q pfsync_qs[] = {
152	{ pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_INS },
153	{ pfsync_out_iack,  sizeof(struct pfsync_ins_ack), PFSYNC_ACT_INS_ACK },
154	{ pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_UPD },
155	{ pfsync_out_upd_c, sizeof(struct pfsync_upd_c),   PFSYNC_ACT_UPD_C },
156	{ pfsync_out_del,   sizeof(struct pfsync_del_c),   PFSYNC_ACT_DEL_C }
157};
158
159static void	pfsync_q_ins(struct pf_state *, int);
160static void	pfsync_q_del(struct pf_state *);
161
162static void	pfsync_update_state(struct pf_state *);
163
164struct pfsync_upd_req_item {
165	TAILQ_ENTRY(pfsync_upd_req_item)	ur_entry;
166	struct pfsync_upd_req			ur_msg;
167};
168
169struct pfsync_deferral {
170	struct pfsync_softc		*pd_sc;
171	TAILQ_ENTRY(pfsync_deferral)	pd_entry;
172	u_int				pd_refs;
173	struct callout			pd_tmo;
174
175	struct pf_state			*pd_st;
176	struct mbuf			*pd_m;
177};
178
179struct pfsync_softc {
180	/* Configuration */
181	struct ifnet		*sc_ifp;
182	struct ifnet		*sc_sync_if;
183	struct ip_moptions	sc_imo;
184	struct in_addr		sc_sync_peer;
185	uint32_t		sc_flags;
186#define	PFSYNCF_OK		0x00000001
187#define	PFSYNCF_DEFER		0x00000002
188#define	PFSYNCF_PUSH		0x00000004
189	uint8_t			sc_maxupdates;
190	struct ip		sc_template;
191	struct callout		sc_tmo;
192	struct mtx		sc_mtx;
193
194	/* Queued data */
195	size_t			sc_len;
196	TAILQ_HEAD(, pf_state)			sc_qs[PFSYNC_S_COUNT];
197	TAILQ_HEAD(, pfsync_upd_req_item)	sc_upd_req_list;
198	TAILQ_HEAD(, pfsync_deferral)		sc_deferrals;
199	u_int			sc_deferred;
200	void			*sc_plus;
201	size_t			sc_pluslen;
202
203	/* Bulk update info */
204	struct mtx		sc_bulk_mtx;
205	uint32_t		sc_ureq_sent;
206	int			sc_bulk_tries;
207	uint32_t		sc_ureq_received;
208	int			sc_bulk_hashid;
209	uint64_t		sc_bulk_stateid;
210	uint32_t		sc_bulk_creatorid;
211	struct callout		sc_bulk_tmo;
212	struct callout		sc_bulkfail_tmo;
213};
214
215#define	PFSYNC_LOCK(sc)		mtx_lock(&(sc)->sc_mtx)
216#define	PFSYNC_UNLOCK(sc)	mtx_unlock(&(sc)->sc_mtx)
217#define	PFSYNC_LOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_mtx, MA_OWNED)
218
219#define	PFSYNC_BLOCK(sc)	mtx_lock(&(sc)->sc_bulk_mtx)
220#define	PFSYNC_BUNLOCK(sc)	mtx_unlock(&(sc)->sc_bulk_mtx)
221#define	PFSYNC_BLOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_bulk_mtx, MA_OWNED)
222
223static MALLOC_DEFINE(M_PFSYNC, "pfsync", "pfsync(4) data");
224static VNET_DEFINE(struct pfsync_softc	*, pfsyncif) = NULL;
225#define	V_pfsyncif		VNET(pfsyncif)
226static VNET_DEFINE(void *, pfsync_swi_cookie) = NULL;
227#define	V_pfsync_swi_cookie	VNET(pfsync_swi_cookie)
228static VNET_DEFINE(struct pfsyncstats, pfsyncstats);
229#define	V_pfsyncstats		VNET(pfsyncstats)
230static VNET_DEFINE(int, pfsync_carp_adj) = CARP_MAXSKEW;
231#define	V_pfsync_carp_adj	VNET(pfsync_carp_adj)
232
233static void	pfsync_timeout(void *);
234static void	pfsync_push(struct pfsync_softc *);
235static void	pfsyncintr(void *);
236static int	pfsync_multicast_setup(struct pfsync_softc *, struct ifnet *,
237		    void *);
238static void	pfsync_multicast_cleanup(struct pfsync_softc *);
239static int	pfsync_init(void);
240static void	pfsync_uninit(void);
241
242SYSCTL_NODE(_net, OID_AUTO, pfsync, CTLFLAG_RW, 0, "PFSYNC");
243SYSCTL_VNET_STRUCT(_net_pfsync, OID_AUTO, stats, CTLFLAG_RW,
244    &VNET_NAME(pfsyncstats), pfsyncstats,
245    "PFSYNC statistics (struct pfsyncstats, net/if_pfsync.h)");
246SYSCTL_INT(_net_pfsync, OID_AUTO, carp_demotion_factor, CTLFLAG_RW,
247    &VNET_NAME(pfsync_carp_adj), 0, "pfsync's CARP demotion factor adjustment");
248
249static int	pfsync_clone_create(struct if_clone *, int, caddr_t);
250static void	pfsync_clone_destroy(struct ifnet *);
251static int	pfsync_alloc_scrub_memory(struct pfsync_state_peer *,
252		    struct pf_state_peer *);
253static int	pfsyncoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
254		    struct route *);
255static int	pfsyncioctl(struct ifnet *, u_long, caddr_t);
256
257static int	pfsync_defer(struct pf_state *, struct mbuf *);
258static void	pfsync_undefer(struct pfsync_deferral *, int);
259static void	pfsync_undefer_state(struct pf_state *, int);
260static void	pfsync_defer_tmo(void *);
261
262static void	pfsync_request_update(u_int32_t, u_int64_t);
263static void	pfsync_update_state_req(struct pf_state *);
264
265static void	pfsync_drop(struct pfsync_softc *);
266static void	pfsync_sendout(int);
267static void	pfsync_send_plus(void *, size_t);
268
269static void	pfsync_bulk_start(void);
270static void	pfsync_bulk_status(u_int8_t);
271static void	pfsync_bulk_update(void *);
272static void	pfsync_bulk_fail(void *);
273
274#ifdef IPSEC
275static void	pfsync_update_net_tdb(struct pfsync_tdb *);
276#endif
277
278#define PFSYNC_MAX_BULKTRIES	12
279
280VNET_DEFINE(struct ifc_simple_data, pfsync_cloner_data);
281VNET_DEFINE(struct if_clone, pfsync_cloner);
282#define	V_pfsync_cloner_data	VNET(pfsync_cloner_data)
283#define	V_pfsync_cloner		VNET(pfsync_cloner)
284IFC_SIMPLE_DECLARE(pfsync, 1);
285
286static int
287pfsync_clone_create(struct if_clone *ifc, int unit, caddr_t param)
288{
289	struct pfsync_softc *sc;
290	struct ifnet *ifp;
291	int q;
292
293	if (unit != 0)
294		return (EINVAL);
295
296	sc = malloc(sizeof(struct pfsync_softc), M_PFSYNC, M_WAITOK | M_ZERO);
297	sc->sc_flags |= PFSYNCF_OK;
298
299	for (q = 0; q < PFSYNC_S_COUNT; q++)
300		TAILQ_INIT(&sc->sc_qs[q]);
301
302	TAILQ_INIT(&sc->sc_upd_req_list);
303	TAILQ_INIT(&sc->sc_deferrals);
304
305	sc->sc_len = PFSYNC_MINPKT;
306	sc->sc_maxupdates = 128;
307
308	ifp = sc->sc_ifp = if_alloc(IFT_PFSYNC);
309	if (ifp == NULL) {
310		free(sc, M_PFSYNC);
311		return (ENOSPC);
312	}
313	if_initname(ifp, ifc->ifc_name, unit);
314	ifp->if_softc = sc;
315	ifp->if_ioctl = pfsyncioctl;
316	ifp->if_output = pfsyncoutput;
317	ifp->if_type = IFT_PFSYNC;
318	ifp->if_snd.ifq_maxlen = ifqmaxlen;
319	ifp->if_hdrlen = sizeof(struct pfsync_header);
320	ifp->if_mtu = ETHERMTU;
321	mtx_init(&sc->sc_mtx, "pfsync", NULL, MTX_DEF);
322	mtx_init(&sc->sc_bulk_mtx, "pfsync bulk", NULL, MTX_DEF);
323	callout_init(&sc->sc_tmo, CALLOUT_MPSAFE);
324	callout_init_mtx(&sc->sc_bulk_tmo, &sc->sc_bulk_mtx, 0);
325	callout_init_mtx(&sc->sc_bulkfail_tmo, &sc->sc_bulk_mtx, 0);
326
327	if_attach(ifp);
328
329	bpfattach(ifp, DLT_PFSYNC, PFSYNC_HDRLEN);
330
331	V_pfsyncif = sc;
332
333	return (0);
334}
335
336static void
337pfsync_clone_destroy(struct ifnet *ifp)
338{
339	struct pfsync_softc *sc = ifp->if_softc;
340
341	/*
342	 * At this stage, everything should have already been
343	 * cleared by pfsync_uninit(), and we have only to
344	 * drain callouts.
345	 */
346	while (sc->sc_deferred > 0) {
347		struct pfsync_deferral *pd = TAILQ_FIRST(&sc->sc_deferrals);
348
349		TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
350		sc->sc_deferred--;
351		if (callout_stop(&pd->pd_tmo)) {
352			pf_release_state(pd->pd_st);
353			m_freem(pd->pd_m);
354			free(pd, M_PFSYNC);
355		} else {
356			pd->pd_refs++;
357			callout_drain(&pd->pd_tmo);
358			free(pd, M_PFSYNC);
359		}
360	}
361
362	callout_drain(&sc->sc_tmo);
363	callout_drain(&sc->sc_bulkfail_tmo);
364	callout_drain(&sc->sc_bulk_tmo);
365
366	if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
367		(*carp_demote_adj_p)(-V_pfsync_carp_adj, "pfsync destroy");
368	bpfdetach(ifp);
369	if_detach(ifp);
370
371	pfsync_drop(sc);
372
373	if_free(ifp);
374	if (sc->sc_imo.imo_membership)
375		pfsync_multicast_cleanup(sc);
376	mtx_destroy(&sc->sc_mtx);
377	mtx_destroy(&sc->sc_bulk_mtx);
378	free(sc, M_PFSYNC);
379
380	V_pfsyncif = NULL;
381}
382
383static int
384pfsync_alloc_scrub_memory(struct pfsync_state_peer *s,
385    struct pf_state_peer *d)
386{
387	if (s->scrub.scrub_flag && d->scrub == NULL) {
388		d->scrub = uma_zalloc(V_pf_state_scrub_z, M_NOWAIT | M_ZERO);
389		if (d->scrub == NULL)
390			return (ENOMEM);
391	}
392
393	return (0);
394}
395
396
397static int
398pfsync_state_import(struct pfsync_state *sp, u_int8_t flags)
399{
400	struct pfsync_softc *sc = V_pfsyncif;
401	struct pf_state	*st = NULL;
402	struct pf_state_key *skw = NULL, *sks = NULL;
403	struct pf_rule *r = NULL;
404	struct pfi_kif	*kif;
405	int error;
406
407	PF_RULES_RASSERT();
408
409	if (sp->creatorid == 0 && V_pf_status.debug >= PF_DEBUG_MISC) {
410		printf("%s: invalid creator id: %08x\n", __func__,
411		    ntohl(sp->creatorid));
412		return (EINVAL);
413	}
414
415	if ((kif = pfi_kif_find(sp->ifname)) == NULL) {
416		if (V_pf_status.debug >= PF_DEBUG_MISC)
417			printf("%s: unknown interface: %s\n", __func__,
418			    sp->ifname);
419		if (flags & PFSYNC_SI_IOCTL)
420			return (EINVAL);
421		return (0);	/* skip this state */
422	}
423
424	/*
425	 * If the ruleset checksums match or the state is coming from the ioctl,
426	 * it's safe to associate the state with the rule of that number.
427	 */
428	if (sp->rule != htonl(-1) && sp->anchor == htonl(-1) &&
429	    (flags & (PFSYNC_SI_IOCTL | PFSYNC_SI_CKSUM)) && ntohl(sp->rule) <
430	    pf_main_ruleset.rules[PF_RULESET_FILTER].active.rcount)
431		r = pf_main_ruleset.rules[
432		    PF_RULESET_FILTER].active.ptr_array[ntohl(sp->rule)];
433	else
434		r = &V_pf_default_rule;
435
436	if ((r->max_states && r->states_cur >= r->max_states))
437		goto cleanup;
438
439	/*
440	 * XXXGL: consider M_WAITOK in ioctl path after.
441	 */
442	if ((st = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO)) == NULL)
443		goto cleanup;
444
445	if ((skw = uma_zalloc(V_pf_state_key_z, M_NOWAIT)) == NULL)
446		goto cleanup;
447
448	if (PF_ANEQ(&sp->key[PF_SK_WIRE].addr[0],
449	    &sp->key[PF_SK_STACK].addr[0], sp->af) ||
450	    PF_ANEQ(&sp->key[PF_SK_WIRE].addr[1],
451	    &sp->key[PF_SK_STACK].addr[1], sp->af) ||
452	    sp->key[PF_SK_WIRE].port[0] != sp->key[PF_SK_STACK].port[0] ||
453	    sp->key[PF_SK_WIRE].port[1] != sp->key[PF_SK_STACK].port[1]) {
454		sks = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
455		if (sks == NULL)
456			goto cleanup;
457	} else
458		sks = skw;
459
460	/* allocate memory for scrub info */
461	if (pfsync_alloc_scrub_memory(&sp->src, &st->src) ||
462	    pfsync_alloc_scrub_memory(&sp->dst, &st->dst))
463		goto cleanup;
464
465	/* copy to state key(s) */
466	skw->addr[0] = sp->key[PF_SK_WIRE].addr[0];
467	skw->addr[1] = sp->key[PF_SK_WIRE].addr[1];
468	skw->port[0] = sp->key[PF_SK_WIRE].port[0];
469	skw->port[1] = sp->key[PF_SK_WIRE].port[1];
470	skw->proto = sp->proto;
471	skw->af = sp->af;
472	if (sks != skw) {
473		sks->addr[0] = sp->key[PF_SK_STACK].addr[0];
474		sks->addr[1] = sp->key[PF_SK_STACK].addr[1];
475		sks->port[0] = sp->key[PF_SK_STACK].port[0];
476		sks->port[1] = sp->key[PF_SK_STACK].port[1];
477		sks->proto = sp->proto;
478		sks->af = sp->af;
479	}
480
481	/* copy to state */
482	bcopy(&sp->rt_addr, &st->rt_addr, sizeof(st->rt_addr));
483	st->creation = time_uptime - ntohl(sp->creation);
484	st->expire = time_uptime;
485	if (sp->expire) {
486		uint32_t timeout;
487
488		timeout = r->timeout[sp->timeout];
489		if (!timeout)
490			timeout = V_pf_default_rule.timeout[sp->timeout];
491
492		/* sp->expire may have been adaptively scaled by export. */
493		st->expire -= timeout - ntohl(sp->expire);
494	}
495
496	st->direction = sp->direction;
497	st->log = sp->log;
498	st->timeout = sp->timeout;
499	st->state_flags = sp->state_flags;
500
501	st->id = sp->id;
502	st->creatorid = sp->creatorid;
503	pf_state_peer_ntoh(&sp->src, &st->src);
504	pf_state_peer_ntoh(&sp->dst, &st->dst);
505
506	st->rule.ptr = r;
507	st->nat_rule.ptr = NULL;
508	st->anchor.ptr = NULL;
509	st->rt_kif = NULL;
510
511	st->pfsync_time = time_uptime;
512	st->sync_state = PFSYNC_S_NONE;
513
514	/* XXX when we have nat_rule/anchors, use STATE_INC_COUNTERS */
515	r->states_cur++;
516	r->states_tot++;
517
518	if (!(flags & PFSYNC_SI_IOCTL))
519		st->state_flags |= PFSTATE_NOSYNC;
520
521	if ((error = pf_state_insert(kif, skw, sks, st)) != 0) {
522		/* XXX when we have nat_rule/anchors, use STATE_DEC_COUNTERS */
523		r->states_cur--;
524		goto cleanup_state;
525	}
526
527	if (!(flags & PFSYNC_SI_IOCTL)) {
528		st->state_flags &= ~PFSTATE_NOSYNC;
529		if (st->state_flags & PFSTATE_ACK) {
530			pfsync_q_ins(st, PFSYNC_S_IACK);
531			pfsync_push(sc);
532		}
533	}
534	st->state_flags &= ~PFSTATE_ACK;
535	PF_STATE_UNLOCK(st);
536
537	return (0);
538
539cleanup:
540	error = ENOMEM;
541	if (skw == sks)
542		sks = NULL;
543	if (skw != NULL)
544		uma_zfree(V_pf_state_key_z, skw);
545	if (sks != NULL)
546		uma_zfree(V_pf_state_key_z, sks);
547
548cleanup_state:	/* pf_state_insert() frees the state keys. */
549	if (st) {
550		if (st->dst.scrub)
551			uma_zfree(V_pf_state_scrub_z, st->dst.scrub);
552		if (st->src.scrub)
553			uma_zfree(V_pf_state_scrub_z, st->src.scrub);
554		uma_zfree(V_pf_state_z, st);
555	}
556	return (error);
557}
558
559static void
560pfsync_input(struct mbuf *m, __unused int off)
561{
562	struct pfsync_softc *sc = V_pfsyncif;
563	struct pfsync_pkt pkt;
564	struct ip *ip = mtod(m, struct ip *);
565	struct pfsync_header *ph;
566	struct pfsync_subheader subh;
567
568	int offset;
569	int rv;
570	uint16_t count;
571
572	V_pfsyncstats.pfsyncs_ipackets++;
573
574	/* Verify that we have a sync interface configured. */
575	if (!sc || !sc->sc_sync_if || !V_pf_status.running ||
576	    (sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
577		goto done;
578
579	/* verify that the packet came in on the right interface */
580	if (sc->sc_sync_if != m->m_pkthdr.rcvif) {
581		V_pfsyncstats.pfsyncs_badif++;
582		goto done;
583	}
584
585	sc->sc_ifp->if_ipackets++;
586	sc->sc_ifp->if_ibytes += m->m_pkthdr.len;
587	/* verify that the IP TTL is 255. */
588	if (ip->ip_ttl != PFSYNC_DFLTTL) {
589		V_pfsyncstats.pfsyncs_badttl++;
590		goto done;
591	}
592
593	offset = ip->ip_hl << 2;
594	if (m->m_pkthdr.len < offset + sizeof(*ph)) {
595		V_pfsyncstats.pfsyncs_hdrops++;
596		goto done;
597	}
598
599	if (offset + sizeof(*ph) > m->m_len) {
600		if (m_pullup(m, offset + sizeof(*ph)) == NULL) {
601			V_pfsyncstats.pfsyncs_hdrops++;
602			return;
603		}
604		ip = mtod(m, struct ip *);
605	}
606	ph = (struct pfsync_header *)((char *)ip + offset);
607
608	/* verify the version */
609	if (ph->version != PFSYNC_VERSION) {
610		V_pfsyncstats.pfsyncs_badver++;
611		goto done;
612	}
613
614	/* Cheaper to grab this now than having to mess with mbufs later */
615	pkt.ip = ip;
616	pkt.src = ip->ip_src;
617	pkt.flags = 0;
618
619	/*
620	 * Trusting pf_chksum during packet processing, as well as seeking
621	 * in interface name tree, require holding PF_RULES_RLOCK().
622	 */
623	PF_RULES_RLOCK();
624	if (!bcmp(&ph->pfcksum, &V_pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
625		pkt.flags |= PFSYNC_SI_CKSUM;
626
627	offset += sizeof(*ph);
628	for (;;) {
629		m_copydata(m, offset, sizeof(subh), (caddr_t)&subh);
630		offset += sizeof(subh);
631
632		if (subh.action >= PFSYNC_ACT_MAX) {
633			V_pfsyncstats.pfsyncs_badact++;
634			PF_RULES_RUNLOCK();
635			goto done;
636		}
637
638		count = ntohs(subh.count);
639		V_pfsyncstats.pfsyncs_iacts[subh.action] += count;
640		rv = (*pfsync_acts[subh.action])(&pkt, m, offset, count);
641		if (rv == -1) {
642			PF_RULES_RUNLOCK();
643			return;
644		}
645
646		offset += rv;
647	}
648	PF_RULES_RUNLOCK();
649
650done:
651	m_freem(m);
652}
653
654static int
655pfsync_in_clr(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
656{
657	struct pfsync_clr *clr;
658	struct mbuf *mp;
659	int len = sizeof(*clr) * count;
660	int i, offp;
661	u_int32_t creatorid;
662
663	mp = m_pulldown(m, offset, len, &offp);
664	if (mp == NULL) {
665		V_pfsyncstats.pfsyncs_badlen++;
666		return (-1);
667	}
668	clr = (struct pfsync_clr *)(mp->m_data + offp);
669
670	for (i = 0; i < count; i++) {
671		creatorid = clr[i].creatorid;
672
673		if (clr[i].ifname[0] != '\0' &&
674		    pfi_kif_find(clr[i].ifname) == NULL)
675			continue;
676
677		for (int i = 0; i <= V_pf_hashmask; i++) {
678			struct pf_idhash *ih = &V_pf_idhash[i];
679			struct pf_state *s;
680relock:
681			PF_HASHROW_LOCK(ih);
682			LIST_FOREACH(s, &ih->states, entry) {
683				if (s->creatorid == creatorid) {
684					s->state_flags |= PFSTATE_NOSYNC;
685					pf_unlink_state(s, PF_ENTER_LOCKED);
686					goto relock;
687				}
688			}
689			PF_HASHROW_UNLOCK(ih);
690		}
691	}
692
693	return (len);
694}
695
696static int
697pfsync_in_ins(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
698{
699	struct mbuf *mp;
700	struct pfsync_state *sa, *sp;
701	int len = sizeof(*sp) * count;
702	int i, offp;
703
704	mp = m_pulldown(m, offset, len, &offp);
705	if (mp == NULL) {
706		V_pfsyncstats.pfsyncs_badlen++;
707		return (-1);
708	}
709	sa = (struct pfsync_state *)(mp->m_data + offp);
710
711	for (i = 0; i < count; i++) {
712		sp = &sa[i];
713
714		/* Check for invalid values. */
715		if (sp->timeout >= PFTM_MAX ||
716		    sp->src.state > PF_TCPS_PROXY_DST ||
717		    sp->dst.state > PF_TCPS_PROXY_DST ||
718		    sp->direction > PF_OUT ||
719		    (sp->af != AF_INET && sp->af != AF_INET6)) {
720			if (V_pf_status.debug >= PF_DEBUG_MISC)
721				printf("%s: invalid value\n", __func__);
722			V_pfsyncstats.pfsyncs_badval++;
723			continue;
724		}
725
726		if (pfsync_state_import(sp, pkt->flags) == ENOMEM)
727			/* Drop out, but process the rest of the actions. */
728			break;
729	}
730
731	return (len);
732}
733
734static int
735pfsync_in_iack(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
736{
737	struct pfsync_ins_ack *ia, *iaa;
738	struct pf_state *st;
739
740	struct mbuf *mp;
741	int len = count * sizeof(*ia);
742	int offp, i;
743
744	mp = m_pulldown(m, offset, len, &offp);
745	if (mp == NULL) {
746		V_pfsyncstats.pfsyncs_badlen++;
747		return (-1);
748	}
749	iaa = (struct pfsync_ins_ack *)(mp->m_data + offp);
750
751	for (i = 0; i < count; i++) {
752		ia = &iaa[i];
753
754		st = pf_find_state_byid(ia->id, ia->creatorid);
755		if (st == NULL)
756			continue;
757
758		if (st->state_flags & PFSTATE_ACK) {
759			PFSYNC_LOCK(V_pfsyncif);
760			pfsync_undefer_state(st, 0);
761			PFSYNC_UNLOCK(V_pfsyncif);
762		}
763		PF_STATE_UNLOCK(st);
764	}
765	/*
766	 * XXX this is not yet implemented, but we know the size of the
767	 * message so we can skip it.
768	 */
769
770	return (count * sizeof(struct pfsync_ins_ack));
771}
772
773static int
774pfsync_upd_tcp(struct pf_state *st, struct pfsync_state_peer *src,
775    struct pfsync_state_peer *dst)
776{
777	int sfail = 0;
778
779	PF_STATE_LOCK_ASSERT(st);
780
781	/*
782	 * The state should never go backwards except
783	 * for syn-proxy states.  Neither should the
784	 * sequence window slide backwards.
785	 */
786	if (st->src.state > src->state &&
787	    (st->src.state < PF_TCPS_PROXY_SRC ||
788	    src->state >= PF_TCPS_PROXY_SRC))
789		sfail = 1;
790	else if (SEQ_GT(st->src.seqlo, ntohl(src->seqlo)))
791		sfail = 3;
792	else if (st->dst.state > dst->state) {
793		/* There might still be useful
794		 * information about the src state here,
795		 * so import that part of the update,
796		 * then "fail" so we send the updated
797		 * state back to the peer who is missing
798		 * our what we know. */
799		pf_state_peer_ntoh(src, &st->src);
800		/* XXX do anything with timeouts? */
801		sfail = 7;
802	} else if (st->dst.state >= TCPS_SYN_SENT &&
803	    SEQ_GT(st->dst.seqlo, ntohl(dst->seqlo)))
804		sfail = 4;
805
806	return (sfail);
807}
808
809static int
810pfsync_in_upd(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
811{
812	struct pfsync_softc *sc = V_pfsyncif;
813	struct pfsync_state *sa, *sp;
814	struct pf_state_key *sk;
815	struct pf_state *st;
816	int sfail;
817
818	struct mbuf *mp;
819	int len = count * sizeof(*sp);
820	int offp, i;
821
822	mp = m_pulldown(m, offset, len, &offp);
823	if (mp == NULL) {
824		V_pfsyncstats.pfsyncs_badlen++;
825		return (-1);
826	}
827	sa = (struct pfsync_state *)(mp->m_data + offp);
828
829	for (i = 0; i < count; i++) {
830		sp = &sa[i];
831
832		/* check for invalid values */
833		if (sp->timeout >= PFTM_MAX ||
834		    sp->src.state > PF_TCPS_PROXY_DST ||
835		    sp->dst.state > PF_TCPS_PROXY_DST) {
836			if (V_pf_status.debug >= PF_DEBUG_MISC) {
837				printf("pfsync_input: PFSYNC_ACT_UPD: "
838				    "invalid value\n");
839			}
840			V_pfsyncstats.pfsyncs_badval++;
841			continue;
842		}
843
844		st = pf_find_state_byid(sp->id, sp->creatorid);
845		if (st == NULL) {
846			/* insert the update */
847			if (pfsync_state_import(sp, 0))
848				V_pfsyncstats.pfsyncs_badstate++;
849			continue;
850		}
851
852		if (st->state_flags & PFSTATE_ACK) {
853			PFSYNC_LOCK(sc);
854			pfsync_undefer_state(st, 1);
855			PFSYNC_UNLOCK(sc);
856		}
857
858		sk = st->key[PF_SK_WIRE];	/* XXX right one? */
859		sfail = 0;
860		if (sk->proto == IPPROTO_TCP)
861			sfail = pfsync_upd_tcp(st, &sp->src, &sp->dst);
862		else {
863			/*
864			 * Non-TCP protocol state machine always go
865			 * forwards
866			 */
867			if (st->src.state > sp->src.state)
868				sfail = 5;
869			else if (st->dst.state > sp->dst.state)
870				sfail = 6;
871		}
872
873		if (sfail) {
874			if (V_pf_status.debug >= PF_DEBUG_MISC) {
875				printf("pfsync: %s stale update (%d)"
876				    " id: %016llx creatorid: %08x\n",
877				    (sfail < 7 ?  "ignoring" : "partial"),
878				    sfail, (unsigned long long)be64toh(st->id),
879				    ntohl(st->creatorid));
880			}
881			V_pfsyncstats.pfsyncs_stale++;
882
883			pfsync_update_state(st);
884			PF_STATE_UNLOCK(st);
885			PFSYNC_LOCK(sc);
886			pfsync_push(sc);
887			PFSYNC_UNLOCK(sc);
888			continue;
889		}
890		pfsync_alloc_scrub_memory(&sp->dst, &st->dst);
891		pf_state_peer_ntoh(&sp->src, &st->src);
892		pf_state_peer_ntoh(&sp->dst, &st->dst);
893		st->expire = time_uptime;
894		st->timeout = sp->timeout;
895		st->pfsync_time = time_uptime;
896		PF_STATE_UNLOCK(st);
897	}
898
899	return (len);
900}
901
902static int
903pfsync_in_upd_c(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
904{
905	struct pfsync_softc *sc = V_pfsyncif;
906	struct pfsync_upd_c *ua, *up;
907	struct pf_state_key *sk;
908	struct pf_state *st;
909
910	int len = count * sizeof(*up);
911	int sfail;
912
913	struct mbuf *mp;
914	int offp, i;
915
916	mp = m_pulldown(m, offset, len, &offp);
917	if (mp == NULL) {
918		V_pfsyncstats.pfsyncs_badlen++;
919		return (-1);
920	}
921	ua = (struct pfsync_upd_c *)(mp->m_data + offp);
922
923	for (i = 0; i < count; i++) {
924		up = &ua[i];
925
926		/* check for invalid values */
927		if (up->timeout >= PFTM_MAX ||
928		    up->src.state > PF_TCPS_PROXY_DST ||
929		    up->dst.state > PF_TCPS_PROXY_DST) {
930			if (V_pf_status.debug >= PF_DEBUG_MISC) {
931				printf("pfsync_input: "
932				    "PFSYNC_ACT_UPD_C: "
933				    "invalid value\n");
934			}
935			V_pfsyncstats.pfsyncs_badval++;
936			continue;
937		}
938
939		st = pf_find_state_byid(up->id, up->creatorid);
940		if (st == NULL) {
941			/* We don't have this state. Ask for it. */
942			PFSYNC_LOCK(sc);
943			pfsync_request_update(up->creatorid, up->id);
944			PFSYNC_UNLOCK(sc);
945			continue;
946		}
947
948		if (st->state_flags & PFSTATE_ACK) {
949			PFSYNC_LOCK(sc);
950			pfsync_undefer_state(st, 1);
951			PFSYNC_UNLOCK(sc);
952		}
953
954		sk = st->key[PF_SK_WIRE]; /* XXX right one? */
955		sfail = 0;
956		if (sk->proto == IPPROTO_TCP)
957			sfail = pfsync_upd_tcp(st, &up->src, &up->dst);
958		else {
959			/*
960			 * Non-TCP protocol state machine always go forwards
961			 */
962			if (st->src.state > up->src.state)
963				sfail = 5;
964			else if (st->dst.state > up->dst.state)
965				sfail = 6;
966		}
967
968		if (sfail) {
969			if (V_pf_status.debug >= PF_DEBUG_MISC) {
970				printf("pfsync: ignoring stale update "
971				    "(%d) id: %016llx "
972				    "creatorid: %08x\n", sfail,
973				    (unsigned long long)be64toh(st->id),
974				    ntohl(st->creatorid));
975			}
976			V_pfsyncstats.pfsyncs_stale++;
977
978			pfsync_update_state(st);
979			PF_STATE_UNLOCK(st);
980			PFSYNC_LOCK(sc);
981			pfsync_push(sc);
982			PFSYNC_UNLOCK(sc);
983			continue;
984		}
985		pfsync_alloc_scrub_memory(&up->dst, &st->dst);
986		pf_state_peer_ntoh(&up->src, &st->src);
987		pf_state_peer_ntoh(&up->dst, &st->dst);
988		st->expire = time_uptime;
989		st->timeout = up->timeout;
990		st->pfsync_time = time_uptime;
991		PF_STATE_UNLOCK(st);
992	}
993
994	return (len);
995}
996
997static int
998pfsync_in_ureq(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
999{
1000	struct pfsync_upd_req *ur, *ura;
1001	struct mbuf *mp;
1002	int len = count * sizeof(*ur);
1003	int i, offp;
1004
1005	struct pf_state *st;
1006
1007	mp = m_pulldown(m, offset, len, &offp);
1008	if (mp == NULL) {
1009		V_pfsyncstats.pfsyncs_badlen++;
1010		return (-1);
1011	}
1012	ura = (struct pfsync_upd_req *)(mp->m_data + offp);
1013
1014	for (i = 0; i < count; i++) {
1015		ur = &ura[i];
1016
1017		if (ur->id == 0 && ur->creatorid == 0)
1018			pfsync_bulk_start();
1019		else {
1020			st = pf_find_state_byid(ur->id, ur->creatorid);
1021			if (st == NULL) {
1022				V_pfsyncstats.pfsyncs_badstate++;
1023				continue;
1024			}
1025			if (st->state_flags & PFSTATE_NOSYNC) {
1026				PF_STATE_UNLOCK(st);
1027				continue;
1028			}
1029
1030			pfsync_update_state_req(st);
1031			PF_STATE_UNLOCK(st);
1032		}
1033	}
1034
1035	return (len);
1036}
1037
1038static int
1039pfsync_in_del(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1040{
1041	struct mbuf *mp;
1042	struct pfsync_state *sa, *sp;
1043	struct pf_state *st;
1044	int len = count * sizeof(*sp);
1045	int offp, i;
1046
1047	mp = m_pulldown(m, offset, len, &offp);
1048	if (mp == NULL) {
1049		V_pfsyncstats.pfsyncs_badlen++;
1050		return (-1);
1051	}
1052	sa = (struct pfsync_state *)(mp->m_data + offp);
1053
1054	for (i = 0; i < count; i++) {
1055		sp = &sa[i];
1056
1057		st = pf_find_state_byid(sp->id, sp->creatorid);
1058		if (st == NULL) {
1059			V_pfsyncstats.pfsyncs_badstate++;
1060			continue;
1061		}
1062		st->state_flags |= PFSTATE_NOSYNC;
1063		pf_unlink_state(st, PF_ENTER_LOCKED);
1064	}
1065
1066	return (len);
1067}
1068
1069static int
1070pfsync_in_del_c(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1071{
1072	struct mbuf *mp;
1073	struct pfsync_del_c *sa, *sp;
1074	struct pf_state *st;
1075	int len = count * sizeof(*sp);
1076	int offp, i;
1077
1078	mp = m_pulldown(m, offset, len, &offp);
1079	if (mp == NULL) {
1080		V_pfsyncstats.pfsyncs_badlen++;
1081		return (-1);
1082	}
1083	sa = (struct pfsync_del_c *)(mp->m_data + offp);
1084
1085	for (i = 0; i < count; i++) {
1086		sp = &sa[i];
1087
1088		st = pf_find_state_byid(sp->id, sp->creatorid);
1089		if (st == NULL) {
1090			V_pfsyncstats.pfsyncs_badstate++;
1091			continue;
1092		}
1093
1094		st->state_flags |= PFSTATE_NOSYNC;
1095		pf_unlink_state(st, PF_ENTER_LOCKED);
1096	}
1097
1098	return (len);
1099}
1100
1101static int
1102pfsync_in_bus(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1103{
1104	struct pfsync_softc *sc = V_pfsyncif;
1105	struct pfsync_bus *bus;
1106	struct mbuf *mp;
1107	int len = count * sizeof(*bus);
1108	int offp;
1109
1110	PFSYNC_BLOCK(sc);
1111
1112	/* If we're not waiting for a bulk update, who cares. */
1113	if (sc->sc_ureq_sent == 0) {
1114		PFSYNC_BUNLOCK(sc);
1115		return (len);
1116	}
1117
1118	mp = m_pulldown(m, offset, len, &offp);
1119	if (mp == NULL) {
1120		PFSYNC_BUNLOCK(sc);
1121		V_pfsyncstats.pfsyncs_badlen++;
1122		return (-1);
1123	}
1124	bus = (struct pfsync_bus *)(mp->m_data + offp);
1125
1126	switch (bus->status) {
1127	case PFSYNC_BUS_START:
1128		callout_reset(&sc->sc_bulkfail_tmo, 4 * hz +
1129		    V_pf_limits[PF_LIMIT_STATES].limit /
1130		    ((sc->sc_ifp->if_mtu - PFSYNC_MINPKT) /
1131		    sizeof(struct pfsync_state)),
1132		    pfsync_bulk_fail, sc);
1133		if (V_pf_status.debug >= PF_DEBUG_MISC)
1134			printf("pfsync: received bulk update start\n");
1135		break;
1136
1137	case PFSYNC_BUS_END:
1138		if (time_uptime - ntohl(bus->endtime) >=
1139		    sc->sc_ureq_sent) {
1140			/* that's it, we're happy */
1141			sc->sc_ureq_sent = 0;
1142			sc->sc_bulk_tries = 0;
1143			callout_stop(&sc->sc_bulkfail_tmo);
1144			if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
1145				(*carp_demote_adj_p)(-V_pfsync_carp_adj,
1146				    "pfsync bulk done");
1147			sc->sc_flags |= PFSYNCF_OK;
1148			if (V_pf_status.debug >= PF_DEBUG_MISC)
1149				printf("pfsync: received valid "
1150				    "bulk update end\n");
1151		} else {
1152			if (V_pf_status.debug >= PF_DEBUG_MISC)
1153				printf("pfsync: received invalid "
1154				    "bulk update end: bad timestamp\n");
1155		}
1156		break;
1157	}
1158	PFSYNC_BUNLOCK(sc);
1159
1160	return (len);
1161}
1162
1163static int
1164pfsync_in_tdb(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1165{
1166	int len = count * sizeof(struct pfsync_tdb);
1167
1168#if defined(IPSEC)
1169	struct pfsync_tdb *tp;
1170	struct mbuf *mp;
1171	int offp;
1172	int i;
1173	int s;
1174
1175	mp = m_pulldown(m, offset, len, &offp);
1176	if (mp == NULL) {
1177		V_pfsyncstats.pfsyncs_badlen++;
1178		return (-1);
1179	}
1180	tp = (struct pfsync_tdb *)(mp->m_data + offp);
1181
1182	for (i = 0; i < count; i++)
1183		pfsync_update_net_tdb(&tp[i]);
1184#endif
1185
1186	return (len);
1187}
1188
1189#if defined(IPSEC)
1190/* Update an in-kernel tdb. Silently fail if no tdb is found. */
1191static void
1192pfsync_update_net_tdb(struct pfsync_tdb *pt)
1193{
1194	struct tdb		*tdb;
1195	int			 s;
1196
1197	/* check for invalid values */
1198	if (ntohl(pt->spi) <= SPI_RESERVED_MAX ||
1199	    (pt->dst.sa.sa_family != AF_INET &&
1200	    pt->dst.sa.sa_family != AF_INET6))
1201		goto bad;
1202
1203	tdb = gettdb(pt->spi, &pt->dst, pt->sproto);
1204	if (tdb) {
1205		pt->rpl = ntohl(pt->rpl);
1206		pt->cur_bytes = (unsigned long long)be64toh(pt->cur_bytes);
1207
1208		/* Neither replay nor byte counter should ever decrease. */
1209		if (pt->rpl < tdb->tdb_rpl ||
1210		    pt->cur_bytes < tdb->tdb_cur_bytes) {
1211			goto bad;
1212		}
1213
1214		tdb->tdb_rpl = pt->rpl;
1215		tdb->tdb_cur_bytes = pt->cur_bytes;
1216	}
1217	return;
1218
1219bad:
1220	if (V_pf_status.debug >= PF_DEBUG_MISC)
1221		printf("pfsync_insert: PFSYNC_ACT_TDB_UPD: "
1222		    "invalid value\n");
1223	V_pfsyncstats.pfsyncs_badstate++;
1224	return;
1225}
1226#endif
1227
1228
1229static int
1230pfsync_in_eof(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1231{
1232	/* check if we are at the right place in the packet */
1233	if (offset != m->m_pkthdr.len - sizeof(struct pfsync_eof))
1234		V_pfsyncstats.pfsyncs_badact++;
1235
1236	/* we're done. free and let the caller return */
1237	m_freem(m);
1238	return (-1);
1239}
1240
1241static int
1242pfsync_in_error(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1243{
1244	V_pfsyncstats.pfsyncs_badact++;
1245
1246	m_freem(m);
1247	return (-1);
1248}
1249
1250static int
1251pfsyncoutput(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst,
1252	struct route *rt)
1253{
1254	m_freem(m);
1255	return (0);
1256}
1257
1258/* ARGSUSED */
1259static int
1260pfsyncioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1261{
1262	struct pfsync_softc *sc = ifp->if_softc;
1263	struct ifreq *ifr = (struct ifreq *)data;
1264	struct pfsyncreq pfsyncr;
1265	int error;
1266
1267	switch (cmd) {
1268	case SIOCSIFFLAGS:
1269		PFSYNC_LOCK(sc);
1270		if (ifp->if_flags & IFF_UP)
1271			ifp->if_drv_flags |= IFF_DRV_RUNNING;
1272		else
1273			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1274		PFSYNC_UNLOCK(sc);
1275		break;
1276	case SIOCSIFMTU:
1277		if (!sc->sc_sync_if ||
1278		    ifr->ifr_mtu <= PFSYNC_MINPKT ||
1279		    ifr->ifr_mtu > sc->sc_sync_if->if_mtu)
1280			return (EINVAL);
1281		if (ifr->ifr_mtu < ifp->if_mtu) {
1282			PFSYNC_LOCK(sc);
1283			if (sc->sc_len > PFSYNC_MINPKT)
1284				pfsync_sendout(1);
1285			PFSYNC_UNLOCK(sc);
1286		}
1287		ifp->if_mtu = ifr->ifr_mtu;
1288		break;
1289	case SIOCGETPFSYNC:
1290		bzero(&pfsyncr, sizeof(pfsyncr));
1291		PFSYNC_LOCK(sc);
1292		if (sc->sc_sync_if) {
1293			strlcpy(pfsyncr.pfsyncr_syncdev,
1294			    sc->sc_sync_if->if_xname, IFNAMSIZ);
1295		}
1296		pfsyncr.pfsyncr_syncpeer = sc->sc_sync_peer;
1297		pfsyncr.pfsyncr_maxupdates = sc->sc_maxupdates;
1298		pfsyncr.pfsyncr_defer = (PFSYNCF_DEFER ==
1299		    (sc->sc_flags & PFSYNCF_DEFER));
1300		PFSYNC_UNLOCK(sc);
1301		return (copyout(&pfsyncr, ifr->ifr_data, sizeof(pfsyncr)));
1302
1303	case SIOCSETPFSYNC:
1304	    {
1305		struct ip_moptions *imo = &sc->sc_imo;
1306		struct ifnet *sifp;
1307		struct ip *ip;
1308		void *mship = NULL;
1309
1310		if ((error = priv_check(curthread, PRIV_NETINET_PF)) != 0)
1311			return (error);
1312		if ((error = copyin(ifr->ifr_data, &pfsyncr, sizeof(pfsyncr))))
1313			return (error);
1314
1315		if (pfsyncr.pfsyncr_maxupdates > 255)
1316			return (EINVAL);
1317
1318		if (pfsyncr.pfsyncr_syncdev[0] == 0)
1319			sifp = NULL;
1320		else if ((sifp = ifunit_ref(pfsyncr.pfsyncr_syncdev)) == NULL)
1321			return (EINVAL);
1322
1323		if (pfsyncr.pfsyncr_syncpeer.s_addr == 0 && sifp != NULL)
1324			mship = malloc((sizeof(struct in_multi *) *
1325			    IP_MIN_MEMBERSHIPS), M_PFSYNC, M_WAITOK | M_ZERO);
1326
1327		PFSYNC_LOCK(sc);
1328		if (pfsyncr.pfsyncr_syncpeer.s_addr == 0)
1329			sc->sc_sync_peer.s_addr = htonl(INADDR_PFSYNC_GROUP);
1330		else
1331			sc->sc_sync_peer.s_addr =
1332			    pfsyncr.pfsyncr_syncpeer.s_addr;
1333
1334		sc->sc_maxupdates = pfsyncr.pfsyncr_maxupdates;
1335		if (pfsyncr.pfsyncr_defer) {
1336			sc->sc_flags |= PFSYNCF_DEFER;
1337			pfsync_defer_ptr = pfsync_defer;
1338		} else {
1339			sc->sc_flags &= ~PFSYNCF_DEFER;
1340			pfsync_defer_ptr = NULL;
1341		}
1342
1343		if (sifp == NULL) {
1344			if (sc->sc_sync_if)
1345				if_rele(sc->sc_sync_if);
1346			sc->sc_sync_if = NULL;
1347			if (imo->imo_membership)
1348				pfsync_multicast_cleanup(sc);
1349			PFSYNC_UNLOCK(sc);
1350			break;
1351		}
1352
1353		if (sc->sc_len > PFSYNC_MINPKT &&
1354		    (sifp->if_mtu < sc->sc_ifp->if_mtu ||
1355		    (sc->sc_sync_if != NULL &&
1356		    sifp->if_mtu < sc->sc_sync_if->if_mtu) ||
1357		    sifp->if_mtu < MCLBYTES - sizeof(struct ip)))
1358			pfsync_sendout(1);
1359
1360		if (imo->imo_membership)
1361			pfsync_multicast_cleanup(sc);
1362
1363		if (sc->sc_sync_peer.s_addr == htonl(INADDR_PFSYNC_GROUP)) {
1364			error = pfsync_multicast_setup(sc, sifp, mship);
1365			if (error) {
1366				if_rele(sifp);
1367				free(mship, M_PFSYNC);
1368				return (error);
1369			}
1370		}
1371		if (sc->sc_sync_if)
1372			if_rele(sc->sc_sync_if);
1373		sc->sc_sync_if = sifp;
1374
1375		ip = &sc->sc_template;
1376		bzero(ip, sizeof(*ip));
1377		ip->ip_v = IPVERSION;
1378		ip->ip_hl = sizeof(sc->sc_template) >> 2;
1379		ip->ip_tos = IPTOS_LOWDELAY;
1380		/* len and id are set later. */
1381		ip->ip_off = IP_DF;
1382		ip->ip_ttl = PFSYNC_DFLTTL;
1383		ip->ip_p = IPPROTO_PFSYNC;
1384		ip->ip_src.s_addr = INADDR_ANY;
1385		ip->ip_dst.s_addr = sc->sc_sync_peer.s_addr;
1386
1387		/* Request a full state table update. */
1388		if ((sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
1389			(*carp_demote_adj_p)(V_pfsync_carp_adj,
1390			    "pfsync bulk start");
1391		sc->sc_flags &= ~PFSYNCF_OK;
1392		if (V_pf_status.debug >= PF_DEBUG_MISC)
1393			printf("pfsync: requesting bulk update\n");
1394		pfsync_request_update(0, 0);
1395		PFSYNC_UNLOCK(sc);
1396		PFSYNC_BLOCK(sc);
1397		sc->sc_ureq_sent = time_uptime;
1398		callout_reset(&sc->sc_bulkfail_tmo, 5 * hz, pfsync_bulk_fail,
1399		    sc);
1400		PFSYNC_BUNLOCK(sc);
1401
1402		break;
1403	    }
1404	default:
1405		return (ENOTTY);
1406	}
1407
1408	return (0);
1409}
1410
1411static void
1412pfsync_out_state(struct pf_state *st, void *buf)
1413{
1414	struct pfsync_state *sp = buf;
1415
1416	pfsync_state_export(sp, st);
1417}
1418
1419static void
1420pfsync_out_iack(struct pf_state *st, void *buf)
1421{
1422	struct pfsync_ins_ack *iack = buf;
1423
1424	iack->id = st->id;
1425	iack->creatorid = st->creatorid;
1426}
1427
1428static void
1429pfsync_out_upd_c(struct pf_state *st, void *buf)
1430{
1431	struct pfsync_upd_c *up = buf;
1432
1433	bzero(up, sizeof(*up));
1434	up->id = st->id;
1435	pf_state_peer_hton(&st->src, &up->src);
1436	pf_state_peer_hton(&st->dst, &up->dst);
1437	up->creatorid = st->creatorid;
1438	up->timeout = st->timeout;
1439}
1440
1441static void
1442pfsync_out_del(struct pf_state *st, void *buf)
1443{
1444	struct pfsync_del_c *dp = buf;
1445
1446	dp->id = st->id;
1447	dp->creatorid = st->creatorid;
1448	st->state_flags |= PFSTATE_NOSYNC;
1449}
1450
1451static void
1452pfsync_drop(struct pfsync_softc *sc)
1453{
1454	struct pf_state *st, *next;
1455	struct pfsync_upd_req_item *ur;
1456	int q;
1457
1458	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1459		if (TAILQ_EMPTY(&sc->sc_qs[q]))
1460			continue;
1461
1462		TAILQ_FOREACH_SAFE(st, &sc->sc_qs[q], sync_list, next) {
1463			KASSERT(st->sync_state == q,
1464				("%s: st->sync_state == q",
1465					__func__));
1466			st->sync_state = PFSYNC_S_NONE;
1467			pf_release_state(st);
1468		}
1469		TAILQ_INIT(&sc->sc_qs[q]);
1470	}
1471
1472	while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
1473		TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
1474		free(ur, M_PFSYNC);
1475	}
1476
1477	sc->sc_plus = NULL;
1478	sc->sc_len = PFSYNC_MINPKT;
1479}
1480
1481static void
1482pfsync_sendout(int schedswi)
1483{
1484	struct pfsync_softc *sc = V_pfsyncif;
1485	struct ifnet *ifp = sc->sc_ifp;
1486	struct mbuf *m;
1487	struct ip *ip;
1488	struct pfsync_header *ph;
1489	struct pfsync_subheader *subh;
1490	struct pf_state *st;
1491	struct pfsync_upd_req_item *ur;
1492	int offset;
1493	int q, count = 0;
1494
1495	KASSERT(sc != NULL, ("%s: null sc", __func__));
1496	KASSERT(sc->sc_len > PFSYNC_MINPKT,
1497	    ("%s: sc_len %zu", __func__, sc->sc_len));
1498	PFSYNC_LOCK_ASSERT(sc);
1499
1500	if (ifp->if_bpf == NULL && sc->sc_sync_if == NULL) {
1501		pfsync_drop(sc);
1502		return;
1503	}
1504
1505	m = m_get2(M_NOWAIT, MT_DATA, M_PKTHDR, max_linkhdr + sc->sc_len);
1506	if (m == NULL) {
1507		sc->sc_ifp->if_oerrors++;
1508		V_pfsyncstats.pfsyncs_onomem++;
1509		return;
1510	}
1511	m->m_data += max_linkhdr;
1512	m->m_len = m->m_pkthdr.len = sc->sc_len;
1513
1514	/* build the ip header */
1515	ip = (struct ip *)m->m_data;
1516	bcopy(&sc->sc_template, ip, sizeof(*ip));
1517	offset = sizeof(*ip);
1518
1519	ip->ip_len = m->m_pkthdr.len;
1520	ip->ip_id = htons(ip_randomid());
1521
1522	/* build the pfsync header */
1523	ph = (struct pfsync_header *)(m->m_data + offset);
1524	bzero(ph, sizeof(*ph));
1525	offset += sizeof(*ph);
1526
1527	ph->version = PFSYNC_VERSION;
1528	ph->len = htons(sc->sc_len - sizeof(*ip));
1529	bcopy(V_pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
1530
1531	/* walk the queues */
1532	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1533		if (TAILQ_EMPTY(&sc->sc_qs[q]))
1534			continue;
1535
1536		subh = (struct pfsync_subheader *)(m->m_data + offset);
1537		offset += sizeof(*subh);
1538
1539		count = 0;
1540		TAILQ_FOREACH(st, &sc->sc_qs[q], sync_list) {
1541			KASSERT(st->sync_state == q,
1542				("%s: st->sync_state == q",
1543					__func__));
1544			/*
1545			 * XXXGL: some of write methods do unlocked reads
1546			 * of state data :(
1547			 */
1548			pfsync_qs[q].write(st, m->m_data + offset);
1549			offset += pfsync_qs[q].len;
1550			st->sync_state = PFSYNC_S_NONE;
1551			pf_release_state(st);
1552			count++;
1553		}
1554		TAILQ_INIT(&sc->sc_qs[q]);
1555
1556		bzero(subh, sizeof(*subh));
1557		subh->action = pfsync_qs[q].action;
1558		subh->count = htons(count);
1559		V_pfsyncstats.pfsyncs_oacts[pfsync_qs[q].action] += count;
1560	}
1561
1562	if (!TAILQ_EMPTY(&sc->sc_upd_req_list)) {
1563		subh = (struct pfsync_subheader *)(m->m_data + offset);
1564		offset += sizeof(*subh);
1565
1566		count = 0;
1567		while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
1568			TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
1569
1570			bcopy(&ur->ur_msg, m->m_data + offset,
1571			    sizeof(ur->ur_msg));
1572			offset += sizeof(ur->ur_msg);
1573			free(ur, M_PFSYNC);
1574			count++;
1575		}
1576
1577		bzero(subh, sizeof(*subh));
1578		subh->action = PFSYNC_ACT_UPD_REQ;
1579		subh->count = htons(count);
1580		V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_UPD_REQ] += count;
1581	}
1582
1583	/* has someone built a custom region for us to add? */
1584	if (sc->sc_plus != NULL) {
1585		bcopy(sc->sc_plus, m->m_data + offset, sc->sc_pluslen);
1586		offset += sc->sc_pluslen;
1587
1588		sc->sc_plus = NULL;
1589	}
1590
1591	subh = (struct pfsync_subheader *)(m->m_data + offset);
1592	offset += sizeof(*subh);
1593
1594	bzero(subh, sizeof(*subh));
1595	subh->action = PFSYNC_ACT_EOF;
1596	subh->count = htons(1);
1597	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_EOF]++;
1598
1599	/* XXX write checksum in EOF here */
1600
1601	/* we're done, let's put it on the wire */
1602	if (ifp->if_bpf) {
1603		m->m_data += sizeof(*ip);
1604		m->m_len = m->m_pkthdr.len = sc->sc_len - sizeof(*ip);
1605		BPF_MTAP(ifp, m);
1606		m->m_data -= sizeof(*ip);
1607		m->m_len = m->m_pkthdr.len = sc->sc_len;
1608	}
1609
1610	if (sc->sc_sync_if == NULL) {
1611		sc->sc_len = PFSYNC_MINPKT;
1612		m_freem(m);
1613		return;
1614	}
1615
1616	sc->sc_ifp->if_opackets++;
1617	sc->sc_ifp->if_obytes += m->m_pkthdr.len;
1618	sc->sc_len = PFSYNC_MINPKT;
1619
1620	if (!_IF_QFULL(&sc->sc_ifp->if_snd))
1621		_IF_ENQUEUE(&sc->sc_ifp->if_snd, m);
1622	else {
1623		m_freem(m);
1624		sc->sc_ifp->if_snd.ifq_drops++;
1625	}
1626	if (schedswi)
1627		swi_sched(V_pfsync_swi_cookie, 0);
1628}
1629
1630static void
1631pfsync_insert_state(struct pf_state *st)
1632{
1633	struct pfsync_softc *sc = V_pfsyncif;
1634
1635	if (st->state_flags & PFSTATE_NOSYNC)
1636		return;
1637
1638	if ((st->rule.ptr->rule_flag & PFRULE_NOSYNC) ||
1639	    st->key[PF_SK_WIRE]->proto == IPPROTO_PFSYNC) {
1640		st->state_flags |= PFSTATE_NOSYNC;
1641		return;
1642	}
1643
1644	KASSERT(st->sync_state == PFSYNC_S_NONE,
1645		("%s: st->sync_state == PFSYNC_S_NONE", __func__));
1646
1647	PFSYNC_LOCK(sc);
1648	if (sc->sc_len == PFSYNC_MINPKT)
1649		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1650
1651	pfsync_q_ins(st, PFSYNC_S_INS);
1652	PFSYNC_UNLOCK(sc);
1653
1654	st->sync_updates = 0;
1655}
1656
1657static int
1658pfsync_defer(struct pf_state *st, struct mbuf *m)
1659{
1660	struct pfsync_softc *sc = V_pfsyncif;
1661	struct pfsync_deferral *pd;
1662
1663	if (m->m_flags & (M_BCAST|M_MCAST))
1664		return (0);
1665
1666	PFSYNC_LOCK(sc);
1667
1668	if (sc == NULL || !(sc->sc_ifp->if_flags & IFF_DRV_RUNNING) ||
1669	    !(sc->sc_flags & PFSYNCF_DEFER)) {
1670		PFSYNC_UNLOCK(sc);
1671		return (0);
1672	}
1673
1674	 if (sc->sc_deferred >= 128)
1675		pfsync_undefer(TAILQ_FIRST(&sc->sc_deferrals), 0);
1676
1677	pd = malloc(sizeof(*pd), M_PFSYNC, M_NOWAIT);
1678	if (pd == NULL)
1679		return (0);
1680	sc->sc_deferred++;
1681
1682	m->m_flags |= M_SKIP_FIREWALL;
1683	st->state_flags |= PFSTATE_ACK;
1684
1685	pd->pd_sc = sc;
1686	pd->pd_refs = 0;
1687	pd->pd_st = st;
1688	pf_ref_state(st);
1689	pd->pd_m = m;
1690
1691	TAILQ_INSERT_TAIL(&sc->sc_deferrals, pd, pd_entry);
1692	callout_init_mtx(&pd->pd_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1693	callout_reset(&pd->pd_tmo, 10, pfsync_defer_tmo, pd);
1694
1695	pfsync_push(sc);
1696
1697	return (1);
1698}
1699
1700static void
1701pfsync_undefer(struct pfsync_deferral *pd, int drop)
1702{
1703	struct pfsync_softc *sc = pd->pd_sc;
1704	struct mbuf *m = pd->pd_m;
1705	struct pf_state *st = pd->pd_st;
1706
1707	PFSYNC_LOCK_ASSERT(sc);
1708
1709	TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
1710	sc->sc_deferred--;
1711	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
1712	free(pd, M_PFSYNC);
1713	pf_release_state(st);
1714
1715	if (drop)
1716		m_freem(m);
1717	else {
1718		_IF_ENQUEUE(&sc->sc_ifp->if_snd, m);
1719		pfsync_push(sc);
1720	}
1721}
1722
1723static void
1724pfsync_defer_tmo(void *arg)
1725{
1726	struct pfsync_deferral *pd = arg;
1727	struct pfsync_softc *sc = pd->pd_sc;
1728	struct mbuf *m = pd->pd_m;
1729	struct pf_state *st = pd->pd_st;
1730
1731	PFSYNC_LOCK_ASSERT(sc);
1732
1733	CURVNET_SET(m->m_pkthdr.rcvif->if_vnet);
1734
1735	TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
1736	sc->sc_deferred--;
1737	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
1738	if (pd->pd_refs == 0)
1739		free(pd, M_PFSYNC);
1740	PFSYNC_UNLOCK(sc);
1741
1742	ip_output(m, NULL, NULL, 0, NULL, NULL);
1743
1744	pf_release_state(st);
1745
1746	CURVNET_RESTORE();
1747}
1748
1749static void
1750pfsync_undefer_state(struct pf_state *st, int drop)
1751{
1752	struct pfsync_softc *sc = V_pfsyncif;
1753	struct pfsync_deferral *pd;
1754
1755	PFSYNC_LOCK_ASSERT(sc);
1756
1757	TAILQ_FOREACH(pd, &sc->sc_deferrals, pd_entry) {
1758		 if (pd->pd_st == st) {
1759			if (callout_stop(&pd->pd_tmo))
1760				pfsync_undefer(pd, drop);
1761			return;
1762		}
1763	}
1764
1765	panic("%s: unable to find deferred state", __func__);
1766}
1767
1768static void
1769pfsync_update_state(struct pf_state *st)
1770{
1771	struct pfsync_softc *sc = V_pfsyncif;
1772	int sync = 0;
1773
1774	PF_STATE_LOCK_ASSERT(st);
1775	PFSYNC_LOCK(sc);
1776
1777	if (st->state_flags & PFSTATE_ACK)
1778		pfsync_undefer_state(st, 0);
1779	if (st->state_flags & PFSTATE_NOSYNC) {
1780		if (st->sync_state != PFSYNC_S_NONE)
1781			pfsync_q_del(st);
1782		PFSYNC_UNLOCK(sc);
1783		return;
1784	}
1785
1786	if (sc->sc_len == PFSYNC_MINPKT)
1787		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1788
1789	switch (st->sync_state) {
1790	case PFSYNC_S_UPD_C:
1791	case PFSYNC_S_UPD:
1792	case PFSYNC_S_INS:
1793		/* we're already handling it */
1794
1795		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP) {
1796			st->sync_updates++;
1797			if (st->sync_updates >= sc->sc_maxupdates)
1798				sync = 1;
1799		}
1800		break;
1801
1802	case PFSYNC_S_IACK:
1803		pfsync_q_del(st);
1804	case PFSYNC_S_NONE:
1805		pfsync_q_ins(st, PFSYNC_S_UPD_C);
1806		st->sync_updates = 0;
1807		break;
1808
1809	default:
1810		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1811	}
1812
1813	if (sync || (time_uptime - st->pfsync_time) < 2)
1814		pfsync_push(sc);
1815
1816	PFSYNC_UNLOCK(sc);
1817}
1818
1819static void
1820pfsync_request_update(u_int32_t creatorid, u_int64_t id)
1821{
1822	struct pfsync_softc *sc = V_pfsyncif;
1823	struct pfsync_upd_req_item *item;
1824	size_t nlen = sizeof(struct pfsync_upd_req);
1825
1826	PFSYNC_LOCK_ASSERT(sc);
1827
1828	/*
1829	 * This code does nothing to prevent multiple update requests for the
1830	 * same state being generated.
1831	 */
1832	item = malloc(sizeof(*item), M_PFSYNC, M_NOWAIT);
1833	if (item == NULL)
1834		return; /* XXX stats */
1835
1836	item->ur_msg.id = id;
1837	item->ur_msg.creatorid = creatorid;
1838
1839	if (TAILQ_EMPTY(&sc->sc_upd_req_list))
1840		nlen += sizeof(struct pfsync_subheader);
1841
1842	if (sc->sc_len + nlen > sc->sc_ifp->if_mtu) {
1843		pfsync_sendout(1);
1844
1845		nlen = sizeof(struct pfsync_subheader) +
1846		    sizeof(struct pfsync_upd_req);
1847	}
1848
1849	TAILQ_INSERT_TAIL(&sc->sc_upd_req_list, item, ur_entry);
1850	sc->sc_len += nlen;
1851
1852	pfsync_push(sc);
1853}
1854
1855static void
1856pfsync_update_state_req(struct pf_state *st)
1857{
1858	struct pfsync_softc *sc = V_pfsyncif;
1859
1860	PF_STATE_LOCK_ASSERT(st);
1861	PFSYNC_LOCK(sc);
1862
1863	if (st->state_flags & PFSTATE_NOSYNC) {
1864		if (st->sync_state != PFSYNC_S_NONE)
1865			pfsync_q_del(st);
1866		PFSYNC_UNLOCK(sc);
1867		return;
1868	}
1869
1870	switch (st->sync_state) {
1871	case PFSYNC_S_UPD_C:
1872	case PFSYNC_S_IACK:
1873		pfsync_q_del(st);
1874	case PFSYNC_S_NONE:
1875		pfsync_q_ins(st, PFSYNC_S_UPD);
1876		pfsync_push(sc);
1877		break;
1878
1879	case PFSYNC_S_INS:
1880	case PFSYNC_S_UPD:
1881	case PFSYNC_S_DEL:
1882		/* we're already handling it */
1883		break;
1884
1885	default:
1886		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1887	}
1888
1889	PFSYNC_UNLOCK(sc);
1890}
1891
1892static void
1893pfsync_delete_state(struct pf_state *st)
1894{
1895	struct pfsync_softc *sc = V_pfsyncif;
1896
1897	PFSYNC_LOCK(sc);
1898	if (st->state_flags & PFSTATE_ACK)
1899		pfsync_undefer_state(st, 1);
1900	if (st->state_flags & PFSTATE_NOSYNC) {
1901		if (st->sync_state != PFSYNC_S_NONE)
1902			pfsync_q_del(st);
1903		PFSYNC_UNLOCK(sc);
1904		return;
1905	}
1906
1907	if (sc->sc_len == PFSYNC_MINPKT)
1908		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1909
1910	switch (st->sync_state) {
1911	case PFSYNC_S_INS:
1912		/* We never got to tell the world so just forget about it. */
1913		pfsync_q_del(st);
1914		break;
1915
1916	case PFSYNC_S_UPD_C:
1917	case PFSYNC_S_UPD:
1918	case PFSYNC_S_IACK:
1919		pfsync_q_del(st);
1920		/* FALLTHROUGH to putting it on the del list */
1921
1922	case PFSYNC_S_NONE:
1923		pfsync_q_ins(st, PFSYNC_S_DEL);
1924		break;
1925
1926	default:
1927		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1928	}
1929	PFSYNC_UNLOCK(sc);
1930}
1931
1932static void
1933pfsync_clear_states(u_int32_t creatorid, const char *ifname)
1934{
1935	struct pfsync_softc *sc = V_pfsyncif;
1936	struct {
1937		struct pfsync_subheader subh;
1938		struct pfsync_clr clr;
1939	} __packed r;
1940
1941	bzero(&r, sizeof(r));
1942
1943	r.subh.action = PFSYNC_ACT_CLR;
1944	r.subh.count = htons(1);
1945	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_CLR]++;
1946
1947	strlcpy(r.clr.ifname, ifname, sizeof(r.clr.ifname));
1948	r.clr.creatorid = creatorid;
1949
1950	PFSYNC_LOCK(sc);
1951	pfsync_send_plus(&r, sizeof(r));
1952	PFSYNC_UNLOCK(sc);
1953}
1954
1955static void
1956pfsync_q_ins(struct pf_state *st, int q)
1957{
1958	struct pfsync_softc *sc = V_pfsyncif;
1959	size_t nlen = pfsync_qs[q].len;
1960
1961	PFSYNC_LOCK_ASSERT(sc);
1962
1963	KASSERT(st->sync_state == PFSYNC_S_NONE,
1964		("%s: st->sync_state == PFSYNC_S_NONE", __func__));
1965	KASSERT(sc->sc_len >= PFSYNC_MINPKT, ("pfsync pkt len is too low %zu",
1966	    sc->sc_len));
1967
1968	if (TAILQ_EMPTY(&sc->sc_qs[q]))
1969		nlen += sizeof(struct pfsync_subheader);
1970
1971	if (sc->sc_len + nlen > sc->sc_ifp->if_mtu) {
1972		pfsync_sendout(1);
1973
1974		nlen = sizeof(struct pfsync_subheader) + pfsync_qs[q].len;
1975	}
1976
1977	sc->sc_len += nlen;
1978	TAILQ_INSERT_TAIL(&sc->sc_qs[q], st, sync_list);
1979	st->sync_state = q;
1980	pf_ref_state(st);
1981}
1982
1983static void
1984pfsync_q_del(struct pf_state *st)
1985{
1986	struct pfsync_softc *sc = V_pfsyncif;
1987	int q = st->sync_state;
1988
1989	PFSYNC_LOCK_ASSERT(sc);
1990	KASSERT(st->sync_state != PFSYNC_S_NONE,
1991		("%s: st->sync_state != PFSYNC_S_NONE", __func__));
1992
1993	sc->sc_len -= pfsync_qs[q].len;
1994	TAILQ_REMOVE(&sc->sc_qs[q], st, sync_list);
1995	st->sync_state = PFSYNC_S_NONE;
1996	pf_release_state(st);
1997
1998	if (TAILQ_EMPTY(&sc->sc_qs[q]))
1999		sc->sc_len -= sizeof(struct pfsync_subheader);
2000}
2001
2002static void
2003pfsync_bulk_start(void)
2004{
2005	struct pfsync_softc *sc = V_pfsyncif;
2006
2007	if (V_pf_status.debug >= PF_DEBUG_MISC)
2008		printf("pfsync: received bulk update request\n");
2009
2010	PFSYNC_BLOCK(sc);
2011
2012	sc->sc_ureq_received = time_uptime;
2013	sc->sc_bulk_hashid = 0;
2014	sc->sc_bulk_stateid = 0;
2015	pfsync_bulk_status(PFSYNC_BUS_START);
2016	callout_reset(&sc->sc_bulk_tmo, 1, pfsync_bulk_update, sc);
2017	PFSYNC_BUNLOCK(sc);
2018}
2019
2020static void
2021pfsync_bulk_update(void *arg)
2022{
2023	struct pfsync_softc *sc = arg;
2024	struct pf_state *s;
2025	int i, sent = 0;
2026
2027	PFSYNC_BLOCK_ASSERT(sc);
2028	CURVNET_SET(sc->sc_ifp->if_vnet);
2029
2030	/*
2031	 * Start with last state from previous invocation.
2032	 * It may had gone, in this case start from the
2033	 * hash slot.
2034	 */
2035	s = pf_find_state_byid(sc->sc_bulk_stateid, sc->sc_bulk_creatorid);
2036
2037	if (s != NULL)
2038		i = PF_IDHASH(s);
2039	else
2040		i = sc->sc_bulk_hashid;
2041
2042	for (; i <= V_pf_hashmask; i++) {
2043		struct pf_idhash *ih = &V_pf_idhash[i];
2044
2045		if (s != NULL)
2046			PF_HASHROW_ASSERT(ih);
2047		else {
2048			PF_HASHROW_LOCK(ih);
2049			s = LIST_FIRST(&ih->states);
2050		}
2051
2052		for (; s; s = LIST_NEXT(s, entry)) {
2053
2054			if (sent > 1 && (sc->sc_ifp->if_mtu - sc->sc_len) <
2055			    sizeof(struct pfsync_state)) {
2056				/* We've filled a packet. */
2057				sc->sc_bulk_hashid = i;
2058				sc->sc_bulk_stateid = s->id;
2059				sc->sc_bulk_creatorid = s->creatorid;
2060				PF_HASHROW_UNLOCK(ih);
2061				callout_reset(&sc->sc_bulk_tmo, 1,
2062				    pfsync_bulk_update, sc);
2063				goto full;
2064			}
2065
2066			if (s->sync_state == PFSYNC_S_NONE &&
2067			    s->timeout < PFTM_MAX &&
2068			    s->pfsync_time <= sc->sc_ureq_received) {
2069				PFSYNC_LOCK(sc);
2070				pfsync_update_state_req(s);
2071				PFSYNC_UNLOCK(sc);
2072				sent++;
2073			}
2074		}
2075		PF_HASHROW_UNLOCK(ih);
2076	}
2077
2078	/* We're done. */
2079	pfsync_bulk_status(PFSYNC_BUS_END);
2080
2081full:
2082	CURVNET_RESTORE();
2083}
2084
2085static void
2086pfsync_bulk_status(u_int8_t status)
2087{
2088	struct {
2089		struct pfsync_subheader subh;
2090		struct pfsync_bus bus;
2091	} __packed r;
2092
2093	struct pfsync_softc *sc = V_pfsyncif;
2094
2095	bzero(&r, sizeof(r));
2096
2097	r.subh.action = PFSYNC_ACT_BUS;
2098	r.subh.count = htons(1);
2099	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_BUS]++;
2100
2101	r.bus.creatorid = V_pf_status.hostid;
2102	r.bus.endtime = htonl(time_uptime - sc->sc_ureq_received);
2103	r.bus.status = status;
2104
2105	PFSYNC_LOCK(sc);
2106	pfsync_send_plus(&r, sizeof(r));
2107	PFSYNC_UNLOCK(sc);
2108}
2109
2110static void
2111pfsync_bulk_fail(void *arg)
2112{
2113	struct pfsync_softc *sc = arg;
2114
2115	CURVNET_SET(sc->sc_ifp->if_vnet);
2116
2117	PFSYNC_BLOCK_ASSERT(sc);
2118
2119	if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
2120		/* Try again */
2121		callout_reset(&sc->sc_bulkfail_tmo, 5 * hz,
2122		    pfsync_bulk_fail, V_pfsyncif);
2123		PFSYNC_LOCK(sc);
2124		pfsync_request_update(0, 0);
2125		PFSYNC_UNLOCK(sc);
2126	} else {
2127		/* Pretend like the transfer was ok. */
2128		sc->sc_ureq_sent = 0;
2129		sc->sc_bulk_tries = 0;
2130		PFSYNC_LOCK(sc);
2131		if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
2132			(*carp_demote_adj_p)(-V_pfsync_carp_adj,
2133			    "pfsync bulk fail");
2134		sc->sc_flags |= PFSYNCF_OK;
2135		PFSYNC_UNLOCK(sc);
2136		if (V_pf_status.debug >= PF_DEBUG_MISC)
2137			printf("pfsync: failed to receive bulk update\n");
2138	}
2139
2140	CURVNET_RESTORE();
2141}
2142
2143static void
2144pfsync_send_plus(void *plus, size_t pluslen)
2145{
2146	struct pfsync_softc *sc = V_pfsyncif;
2147
2148	PFSYNC_LOCK_ASSERT(sc);
2149
2150	if (sc->sc_len + pluslen > sc->sc_ifp->if_mtu)
2151		pfsync_sendout(1);
2152
2153	sc->sc_plus = plus;
2154	sc->sc_len += (sc->sc_pluslen = pluslen);
2155
2156	pfsync_sendout(1);
2157}
2158
2159static void
2160pfsync_timeout(void *arg)
2161{
2162	struct pfsync_softc *sc = arg;
2163
2164	CURVNET_SET(sc->sc_ifp->if_vnet);
2165	PFSYNC_LOCK(sc);
2166	pfsync_push(sc);
2167	PFSYNC_UNLOCK(sc);
2168	CURVNET_RESTORE();
2169}
2170
2171static void
2172pfsync_push(struct pfsync_softc *sc)
2173{
2174
2175	PFSYNC_LOCK_ASSERT(sc);
2176
2177	sc->sc_flags |= PFSYNCF_PUSH;
2178	swi_sched(V_pfsync_swi_cookie, 0);
2179}
2180
2181static void
2182pfsyncintr(void *arg)
2183{
2184	struct pfsync_softc *sc = arg;
2185	struct mbuf *m, *n;
2186
2187	CURVNET_SET(sc->sc_ifp->if_vnet);
2188
2189	PFSYNC_LOCK(sc);
2190	if ((sc->sc_flags & PFSYNCF_PUSH) && sc->sc_len > PFSYNC_MINPKT) {
2191		pfsync_sendout(0);
2192		sc->sc_flags &= ~PFSYNCF_PUSH;
2193	}
2194	_IF_DEQUEUE_ALL(&sc->sc_ifp->if_snd, m);
2195	PFSYNC_UNLOCK(sc);
2196
2197	for (; m != NULL; m = n) {
2198
2199		n = m->m_nextpkt;
2200		m->m_nextpkt = NULL;
2201
2202		/*
2203		 * We distinguish between a deferral packet and our
2204		 * own pfsync packet based on M_SKIP_FIREWALL
2205		 * flag. This is XXX.
2206		 */
2207		if (m->m_flags & M_SKIP_FIREWALL)
2208			ip_output(m, NULL, NULL, 0, NULL, NULL);
2209		else if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo,
2210		    NULL) == 0)
2211			V_pfsyncstats.pfsyncs_opackets++;
2212		else
2213			V_pfsyncstats.pfsyncs_oerrors++;
2214	}
2215	CURVNET_RESTORE();
2216}
2217
2218static int
2219pfsync_multicast_setup(struct pfsync_softc *sc, struct ifnet *ifp, void *mship)
2220{
2221	struct ip_moptions *imo = &sc->sc_imo;
2222	int error;
2223
2224	if (!(ifp->if_flags & IFF_MULTICAST))
2225		return (EADDRNOTAVAIL);
2226
2227	imo->imo_membership = (struct in_multi **)mship;
2228	imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
2229	imo->imo_multicast_vif = -1;
2230
2231	if ((error = in_joingroup(ifp, &sc->sc_sync_peer, NULL,
2232	    &imo->imo_membership[0])) != 0) {
2233		imo->imo_membership = NULL;
2234		return (error);
2235	}
2236	imo->imo_num_memberships++;
2237	imo->imo_multicast_ifp = ifp;
2238	imo->imo_multicast_ttl = PFSYNC_DFLTTL;
2239	imo->imo_multicast_loop = 0;
2240
2241	return (0);
2242}
2243
2244static void
2245pfsync_multicast_cleanup(struct pfsync_softc *sc)
2246{
2247	struct ip_moptions *imo = &sc->sc_imo;
2248
2249	in_leavegroup(imo->imo_membership[0], NULL);
2250	free(imo->imo_membership, M_PFSYNC);
2251	imo->imo_membership = NULL;
2252	imo->imo_multicast_ifp = NULL;
2253}
2254
2255#ifdef INET
2256extern  struct domain inetdomain;
2257static struct protosw in_pfsync_protosw = {
2258	.pr_type =		SOCK_RAW,
2259	.pr_domain =		&inetdomain,
2260	.pr_protocol =		IPPROTO_PFSYNC,
2261	.pr_flags =		PR_ATOMIC|PR_ADDR,
2262	.pr_input =		pfsync_input,
2263	.pr_output =		(pr_output_t *)rip_output,
2264	.pr_ctloutput =		rip_ctloutput,
2265	.pr_usrreqs =		&rip_usrreqs
2266};
2267#endif
2268
2269static int
2270pfsync_init()
2271{
2272	VNET_ITERATOR_DECL(vnet_iter);
2273	int error = 0;
2274
2275	VNET_LIST_RLOCK();
2276	VNET_FOREACH(vnet_iter) {
2277		CURVNET_SET(vnet_iter);
2278		V_pfsync_cloner = pfsync_cloner;
2279		V_pfsync_cloner_data = pfsync_cloner_data;
2280		V_pfsync_cloner.ifc_data = &V_pfsync_cloner_data;
2281		if_clone_attach(&V_pfsync_cloner);
2282		error = swi_add(NULL, "pfsync", pfsyncintr, V_pfsyncif,
2283		    SWI_NET, INTR_MPSAFE, &V_pfsync_swi_cookie);
2284		CURVNET_RESTORE();
2285		if (error)
2286			goto fail_locked;
2287	}
2288	VNET_LIST_RUNLOCK();
2289#ifdef INET
2290	error = pf_proto_register(PF_INET, &in_pfsync_protosw);
2291	if (error)
2292		goto fail;
2293	error = ipproto_register(IPPROTO_PFSYNC);
2294	if (error) {
2295		pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
2296		goto fail;
2297	}
2298#endif
2299	PF_RULES_WLOCK();
2300	pfsync_state_import_ptr = pfsync_state_import;
2301	pfsync_insert_state_ptr = pfsync_insert_state;
2302	pfsync_update_state_ptr = pfsync_update_state;
2303	pfsync_delete_state_ptr = pfsync_delete_state;
2304	pfsync_clear_states_ptr = pfsync_clear_states;
2305	pfsync_defer_ptr = pfsync_defer;
2306	PF_RULES_WUNLOCK();
2307
2308	return (0);
2309
2310fail:
2311	VNET_LIST_RLOCK();
2312fail_locked:
2313	VNET_FOREACH(vnet_iter) {
2314		CURVNET_SET(vnet_iter);
2315		if (V_pfsync_swi_cookie) {
2316			swi_remove(V_pfsync_swi_cookie);
2317			if_clone_detach(&V_pfsync_cloner);
2318		}
2319		CURVNET_RESTORE();
2320	}
2321	VNET_LIST_RUNLOCK();
2322
2323	return (error);
2324}
2325
2326static void
2327pfsync_uninit()
2328{
2329	VNET_ITERATOR_DECL(vnet_iter);
2330
2331	PF_RULES_WLOCK();
2332	pfsync_state_import_ptr = NULL;
2333	pfsync_insert_state_ptr = NULL;
2334	pfsync_update_state_ptr = NULL;
2335	pfsync_delete_state_ptr = NULL;
2336	pfsync_clear_states_ptr = NULL;
2337	pfsync_defer_ptr = NULL;
2338	PF_RULES_WUNLOCK();
2339
2340	ipproto_unregister(IPPROTO_PFSYNC);
2341	pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
2342	VNET_LIST_RLOCK();
2343	VNET_FOREACH(vnet_iter) {
2344		CURVNET_SET(vnet_iter);
2345		if_clone_detach(&V_pfsync_cloner);
2346		swi_remove(V_pfsync_swi_cookie);
2347		CURVNET_RESTORE();
2348	}
2349	VNET_LIST_RUNLOCK();
2350}
2351
2352static int
2353pfsync_modevent(module_t mod, int type, void *data)
2354{
2355	int error = 0;
2356
2357	switch (type) {
2358	case MOD_LOAD:
2359		error = pfsync_init();
2360		break;
2361	case MOD_QUIESCE:
2362		/*
2363		 * Module should not be unloaded due to race conditions.
2364		 */
2365		error = EBUSY;
2366		break;
2367	case MOD_UNLOAD:
2368		pfsync_uninit();
2369		break;
2370	default:
2371		error = EINVAL;
2372		break;
2373	}
2374
2375	return (error);
2376}
2377
2378static moduledata_t pfsync_mod = {
2379	"pfsync",
2380	pfsync_modevent,
2381	0
2382};
2383
2384#define PFSYNC_MODVER 1
2385
2386DECLARE_MODULE(pfsync, pfsync_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
2387MODULE_VERSION(pfsync, PFSYNC_MODVER);
2388MODULE_DEPEND(pfsync, pf, PF_MODVER, PF_MODVER, PF_MODVER);
2389