if_pfsync.c revision 240233
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/contrib/pf/net/if_pfsync.c 240233 2012-09-08 06:41:54Z 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	int		(*write)(struct pf_state *, struct mbuf *, int);
141	size_t		len;
142	u_int8_t	action;
143};
144
145/* we have one of these for every PFSYNC_S_ */
146static int	pfsync_out_state(struct pf_state *, struct mbuf *, int);
147static int	pfsync_out_iack(struct pf_state *, struct mbuf *, int);
148static int	pfsync_out_upd_c(struct pf_state *, struct mbuf *, int);
149static int	pfsync_out_del(struct pf_state *, struct mbuf *, int);
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 int
1412pfsync_out_state(struct pf_state *st, struct mbuf *m, int offset)
1413{
1414	struct pfsync_state *sp = (struct pfsync_state *)(m->m_data + offset);
1415
1416	pfsync_state_export(sp, st);
1417
1418	return (sizeof(*sp));
1419}
1420
1421static int
1422pfsync_out_iack(struct pf_state *st, struct mbuf *m, int offset)
1423{
1424	struct pfsync_ins_ack *iack =
1425	    (struct pfsync_ins_ack *)(m->m_data + offset);
1426
1427	iack->id = st->id;
1428	iack->creatorid = st->creatorid;
1429
1430	return (sizeof(*iack));
1431}
1432
1433static int
1434pfsync_out_upd_c(struct pf_state *st, struct mbuf *m, int offset)
1435{
1436	struct pfsync_upd_c *up = (struct pfsync_upd_c *)(m->m_data + offset);
1437
1438	bzero(up, sizeof(*up));
1439	up->id = st->id;
1440	pf_state_peer_hton(&st->src, &up->src);
1441	pf_state_peer_hton(&st->dst, &up->dst);
1442	up->creatorid = st->creatorid;
1443	up->timeout = st->timeout;
1444
1445	return (sizeof(*up));
1446}
1447
1448static int
1449pfsync_out_del(struct pf_state *st, struct mbuf *m, int offset)
1450{
1451	struct pfsync_del_c *dp = (struct pfsync_del_c *)(m->m_data + offset);
1452
1453	dp->id = st->id;
1454	dp->creatorid = st->creatorid;
1455
1456	st->state_flags |= PFSTATE_NOSYNC;
1457
1458	return (sizeof(*dp));
1459}
1460
1461static void
1462pfsync_drop(struct pfsync_softc *sc)
1463{
1464	struct pf_state *st, *next;
1465	struct pfsync_upd_req_item *ur;
1466	int q;
1467
1468	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1469		if (TAILQ_EMPTY(&sc->sc_qs[q]))
1470			continue;
1471
1472		TAILQ_FOREACH_SAFE(st, &sc->sc_qs[q], sync_list, next) {
1473			KASSERT(st->sync_state == q,
1474				("%s: st->sync_state == q",
1475					__func__));
1476			st->sync_state = PFSYNC_S_NONE;
1477			pf_release_state(st);
1478		}
1479		TAILQ_INIT(&sc->sc_qs[q]);
1480	}
1481
1482	while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
1483		TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
1484		free(ur, M_PFSYNC);
1485	}
1486
1487	sc->sc_plus = NULL;
1488	sc->sc_len = PFSYNC_MINPKT;
1489}
1490
1491static void
1492pfsync_sendout(int schedswi)
1493{
1494	struct pfsync_softc *sc = V_pfsyncif;
1495	struct ifnet *ifp = sc->sc_ifp;
1496	struct mbuf *m;
1497	struct ip *ip;
1498	struct pfsync_header *ph;
1499	struct pfsync_subheader *subh;
1500	struct pf_state *st, *next;
1501	struct pfsync_upd_req_item *ur;
1502	int offset;
1503	int q, count = 0;
1504
1505	KASSERT(sc != NULL, ("%s: null sc", __func__));
1506	KASSERT(sc->sc_len > PFSYNC_MINPKT,
1507	    ("%s: sc_len %zu", __func__, sc->sc_len));
1508	PFSYNC_LOCK_ASSERT(sc);
1509
1510	if (ifp->if_bpf == NULL && sc->sc_sync_if == NULL) {
1511		pfsync_drop(sc);
1512		return;
1513	}
1514
1515	m = m_get2(M_NOWAIT, MT_DATA, M_PKTHDR, max_linkhdr + sc->sc_len);
1516	if (m == NULL) {
1517		sc->sc_ifp->if_oerrors++;
1518		V_pfsyncstats.pfsyncs_onomem++;
1519		return;
1520	}
1521	m->m_data += max_linkhdr;
1522	m->m_len = m->m_pkthdr.len = sc->sc_len;
1523
1524	/* build the ip header */
1525	ip = (struct ip *)m->m_data;
1526	bcopy(&sc->sc_template, ip, sizeof(*ip));
1527	offset = sizeof(*ip);
1528
1529	ip->ip_len = m->m_pkthdr.len;
1530	ip->ip_id = htons(ip_randomid());
1531
1532	/* build the pfsync header */
1533	ph = (struct pfsync_header *)(m->m_data + offset);
1534	bzero(ph, sizeof(*ph));
1535	offset += sizeof(*ph);
1536
1537	ph->version = PFSYNC_VERSION;
1538	ph->len = htons(sc->sc_len - sizeof(*ip));
1539	bcopy(V_pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
1540
1541	/* walk the queues */
1542	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1543		if (TAILQ_EMPTY(&sc->sc_qs[q]))
1544			continue;
1545
1546		subh = (struct pfsync_subheader *)(m->m_data + offset);
1547		offset += sizeof(*subh);
1548
1549		count = 0;
1550		TAILQ_FOREACH_SAFE(st, &sc->sc_qs[q], sync_list, next) {
1551			KASSERT(st->sync_state == q,
1552				("%s: st->sync_state == q",
1553					__func__));
1554			/*
1555			 * XXXGL: some of write methods do unlocked reads
1556			 * of state data :(
1557			 */
1558			offset += pfsync_qs[q].write(st, m, offset);
1559			st->sync_state = PFSYNC_S_NONE;
1560			pf_release_state(st);
1561			count++;
1562		}
1563		TAILQ_INIT(&sc->sc_qs[q]);
1564
1565		bzero(subh, sizeof(*subh));
1566		subh->action = pfsync_qs[q].action;
1567		subh->count = htons(count);
1568		V_pfsyncstats.pfsyncs_oacts[pfsync_qs[q].action] += count;
1569	}
1570
1571	if (!TAILQ_EMPTY(&sc->sc_upd_req_list)) {
1572		subh = (struct pfsync_subheader *)(m->m_data + offset);
1573		offset += sizeof(*subh);
1574
1575		count = 0;
1576		while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
1577			TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
1578
1579			bcopy(&ur->ur_msg, m->m_data + offset,
1580			    sizeof(ur->ur_msg));
1581			offset += sizeof(ur->ur_msg);
1582			free(ur, M_PFSYNC);
1583			count++;
1584		}
1585
1586		bzero(subh, sizeof(*subh));
1587		subh->action = PFSYNC_ACT_UPD_REQ;
1588		subh->count = htons(count);
1589		V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_UPD_REQ] += count;
1590	}
1591
1592	/* has someone built a custom region for us to add? */
1593	if (sc->sc_plus != NULL) {
1594		bcopy(sc->sc_plus, m->m_data + offset, sc->sc_pluslen);
1595		offset += sc->sc_pluslen;
1596
1597		sc->sc_plus = NULL;
1598	}
1599
1600	subh = (struct pfsync_subheader *)(m->m_data + offset);
1601	offset += sizeof(*subh);
1602
1603	bzero(subh, sizeof(*subh));
1604	subh->action = PFSYNC_ACT_EOF;
1605	subh->count = htons(1);
1606	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_EOF]++;
1607
1608	/* XXX write checksum in EOF here */
1609
1610	/* we're done, let's put it on the wire */
1611	if (ifp->if_bpf) {
1612		m->m_data += sizeof(*ip);
1613		m->m_len = m->m_pkthdr.len = sc->sc_len - sizeof(*ip);
1614		BPF_MTAP(ifp, m);
1615		m->m_data -= sizeof(*ip);
1616		m->m_len = m->m_pkthdr.len = sc->sc_len;
1617	}
1618
1619	if (sc->sc_sync_if == NULL) {
1620		sc->sc_len = PFSYNC_MINPKT;
1621		m_freem(m);
1622		return;
1623	}
1624
1625	sc->sc_ifp->if_opackets++;
1626	sc->sc_ifp->if_obytes += m->m_pkthdr.len;
1627	sc->sc_len = PFSYNC_MINPKT;
1628
1629	if (!_IF_QFULL(&sc->sc_ifp->if_snd))
1630		_IF_ENQUEUE(&sc->sc_ifp->if_snd, m);
1631	else {
1632		m_freem(m);
1633		sc->sc_ifp->if_snd.ifq_drops++;
1634	}
1635	if (schedswi)
1636		swi_sched(V_pfsync_swi_cookie, 0);
1637}
1638
1639static void
1640pfsync_insert_state(struct pf_state *st)
1641{
1642	struct pfsync_softc *sc = V_pfsyncif;
1643
1644	if (st->state_flags & PFSTATE_NOSYNC)
1645		return;
1646
1647	if ((st->rule.ptr->rule_flag & PFRULE_NOSYNC) ||
1648	    st->key[PF_SK_WIRE]->proto == IPPROTO_PFSYNC) {
1649		st->state_flags |= PFSTATE_NOSYNC;
1650		return;
1651	}
1652
1653	KASSERT(st->sync_state == PFSYNC_S_NONE,
1654		("%s: st->sync_state == PFSYNC_S_NONE", __func__));
1655
1656	PFSYNC_LOCK(sc);
1657	if (sc->sc_len == PFSYNC_MINPKT)
1658		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1659
1660	pfsync_q_ins(st, PFSYNC_S_INS);
1661	PFSYNC_UNLOCK(sc);
1662
1663	st->sync_updates = 0;
1664}
1665
1666static int
1667pfsync_defer(struct pf_state *st, struct mbuf *m)
1668{
1669	struct pfsync_softc *sc = V_pfsyncif;
1670	struct pfsync_deferral *pd;
1671
1672	if (m->m_flags & (M_BCAST|M_MCAST))
1673		return (0);
1674
1675	PFSYNC_LOCK(sc);
1676
1677	if (sc == NULL || !(sc->sc_ifp->if_flags & IFF_DRV_RUNNING) ||
1678	    !(sc->sc_flags & PFSYNCF_DEFER)) {
1679		PFSYNC_UNLOCK(sc);
1680		return (0);
1681	}
1682
1683	 if (sc->sc_deferred >= 128)
1684		pfsync_undefer(TAILQ_FIRST(&sc->sc_deferrals), 0);
1685
1686	pd = malloc(sizeof(*pd), M_PFSYNC, M_NOWAIT);
1687	if (pd == NULL)
1688		return (0);
1689	sc->sc_deferred++;
1690
1691	m->m_flags |= M_SKIP_FIREWALL;
1692	st->state_flags |= PFSTATE_ACK;
1693
1694	pd->pd_sc = sc;
1695	pd->pd_refs = 0;
1696	pd->pd_st = st;
1697	pf_ref_state(st);
1698	pd->pd_m = m;
1699
1700	TAILQ_INSERT_TAIL(&sc->sc_deferrals, pd, pd_entry);
1701	callout_init_mtx(&pd->pd_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1702	callout_reset(&pd->pd_tmo, 10, pfsync_defer_tmo, pd);
1703
1704	pfsync_push(sc);
1705
1706	return (1);
1707}
1708
1709static void
1710pfsync_undefer(struct pfsync_deferral *pd, int drop)
1711{
1712	struct pfsync_softc *sc = pd->pd_sc;
1713	struct mbuf *m = pd->pd_m;
1714	struct pf_state *st = pd->pd_st;
1715
1716	PFSYNC_LOCK_ASSERT(sc);
1717
1718	TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
1719	sc->sc_deferred--;
1720	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
1721	free(pd, M_PFSYNC);
1722	pf_release_state(st);
1723
1724	if (drop)
1725		m_freem(m);
1726	else {
1727		_IF_ENQUEUE(&sc->sc_ifp->if_snd, m);
1728		pfsync_push(sc);
1729	}
1730}
1731
1732static void
1733pfsync_defer_tmo(void *arg)
1734{
1735	struct pfsync_deferral *pd = arg;
1736	struct pfsync_softc *sc = pd->pd_sc;
1737	struct mbuf *m = pd->pd_m;
1738	struct pf_state *st = pd->pd_st;
1739
1740	PFSYNC_LOCK_ASSERT(sc);
1741
1742	CURVNET_SET(m->m_pkthdr.rcvif->if_vnet);
1743
1744	TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
1745	sc->sc_deferred--;
1746	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
1747	if (pd->pd_refs == 0)
1748		free(pd, M_PFSYNC);
1749	PFSYNC_UNLOCK(sc);
1750
1751	ip_output(m, NULL, NULL, 0, NULL, NULL);
1752
1753	pf_release_state(st);
1754
1755	CURVNET_RESTORE();
1756}
1757
1758static void
1759pfsync_undefer_state(struct pf_state *st, int drop)
1760{
1761	struct pfsync_softc *sc = V_pfsyncif;
1762	struct pfsync_deferral *pd;
1763
1764	PFSYNC_LOCK_ASSERT(sc);
1765
1766	TAILQ_FOREACH(pd, &sc->sc_deferrals, pd_entry) {
1767		 if (pd->pd_st == st) {
1768			if (callout_stop(&pd->pd_tmo))
1769				pfsync_undefer(pd, drop);
1770			return;
1771		}
1772	}
1773
1774	panic("%s: unable to find deferred state", __func__);
1775}
1776
1777static void
1778pfsync_update_state(struct pf_state *st)
1779{
1780	struct pfsync_softc *sc = V_pfsyncif;
1781	int sync = 0;
1782
1783	PF_STATE_LOCK_ASSERT(st);
1784	PFSYNC_LOCK(sc);
1785
1786	if (st->state_flags & PFSTATE_ACK)
1787		pfsync_undefer_state(st, 0);
1788	if (st->state_flags & PFSTATE_NOSYNC) {
1789		if (st->sync_state != PFSYNC_S_NONE)
1790			pfsync_q_del(st);
1791		PFSYNC_UNLOCK(sc);
1792		return;
1793	}
1794
1795	if (sc->sc_len == PFSYNC_MINPKT)
1796		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1797
1798	switch (st->sync_state) {
1799	case PFSYNC_S_UPD_C:
1800	case PFSYNC_S_UPD:
1801	case PFSYNC_S_INS:
1802		/* we're already handling it */
1803
1804		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP) {
1805			st->sync_updates++;
1806			if (st->sync_updates >= sc->sc_maxupdates)
1807				sync = 1;
1808		}
1809		break;
1810
1811	case PFSYNC_S_IACK:
1812		pfsync_q_del(st);
1813	case PFSYNC_S_NONE:
1814		pfsync_q_ins(st, PFSYNC_S_UPD_C);
1815		st->sync_updates = 0;
1816		break;
1817
1818	default:
1819		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1820	}
1821
1822	if (sync || (time_uptime - st->pfsync_time) < 2)
1823		pfsync_push(sc);
1824
1825	PFSYNC_UNLOCK(sc);
1826}
1827
1828static void
1829pfsync_request_update(u_int32_t creatorid, u_int64_t id)
1830{
1831	struct pfsync_softc *sc = V_pfsyncif;
1832	struct pfsync_upd_req_item *item;
1833	size_t nlen = sizeof(struct pfsync_upd_req);
1834
1835	PFSYNC_LOCK_ASSERT(sc);
1836
1837	/*
1838	 * This code does nothing to prevent multiple update requests for the
1839	 * same state being generated.
1840	 */
1841	item = malloc(sizeof(*item), M_PFSYNC, M_NOWAIT);
1842	if (item == NULL)
1843		return; /* XXX stats */
1844
1845	item->ur_msg.id = id;
1846	item->ur_msg.creatorid = creatorid;
1847
1848	if (TAILQ_EMPTY(&sc->sc_upd_req_list))
1849		nlen += sizeof(struct pfsync_subheader);
1850
1851	if (sc->sc_len + nlen > sc->sc_ifp->if_mtu) {
1852		pfsync_sendout(1);
1853
1854		nlen = sizeof(struct pfsync_subheader) +
1855		    sizeof(struct pfsync_upd_req);
1856	}
1857
1858	TAILQ_INSERT_TAIL(&sc->sc_upd_req_list, item, ur_entry);
1859	sc->sc_len += nlen;
1860
1861	pfsync_push(sc);
1862}
1863
1864static void
1865pfsync_update_state_req(struct pf_state *st)
1866{
1867	struct pfsync_softc *sc = V_pfsyncif;
1868
1869	PF_STATE_LOCK_ASSERT(st);
1870	PFSYNC_LOCK(sc);
1871
1872	if (st->state_flags & PFSTATE_NOSYNC) {
1873		if (st->sync_state != PFSYNC_S_NONE)
1874			pfsync_q_del(st);
1875		PFSYNC_UNLOCK(sc);
1876		return;
1877	}
1878
1879	switch (st->sync_state) {
1880	case PFSYNC_S_UPD_C:
1881	case PFSYNC_S_IACK:
1882		pfsync_q_del(st);
1883	case PFSYNC_S_NONE:
1884		pfsync_q_ins(st, PFSYNC_S_UPD);
1885		pfsync_push(sc);
1886		break;
1887
1888	case PFSYNC_S_INS:
1889	case PFSYNC_S_UPD:
1890	case PFSYNC_S_DEL:
1891		/* we're already handling it */
1892		break;
1893
1894	default:
1895		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1896	}
1897
1898	PFSYNC_UNLOCK(sc);
1899}
1900
1901static void
1902pfsync_delete_state(struct pf_state *st)
1903{
1904	struct pfsync_softc *sc = V_pfsyncif;
1905
1906	PFSYNC_LOCK(sc);
1907	if (st->state_flags & PFSTATE_ACK)
1908		pfsync_undefer_state(st, 1);
1909	if (st->state_flags & PFSTATE_NOSYNC) {
1910		if (st->sync_state != PFSYNC_S_NONE)
1911			pfsync_q_del(st);
1912		PFSYNC_UNLOCK(sc);
1913		return;
1914	}
1915
1916	if (sc->sc_len == PFSYNC_MINPKT)
1917		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1918
1919	switch (st->sync_state) {
1920	case PFSYNC_S_INS:
1921		/* We never got to tell the world so just forget about it. */
1922		pfsync_q_del(st);
1923		break;
1924
1925	case PFSYNC_S_UPD_C:
1926	case PFSYNC_S_UPD:
1927	case PFSYNC_S_IACK:
1928		pfsync_q_del(st);
1929		/* FALLTHROUGH to putting it on the del list */
1930
1931	case PFSYNC_S_NONE:
1932		pfsync_q_ins(st, PFSYNC_S_DEL);
1933		break;
1934
1935	default:
1936		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1937	}
1938	PFSYNC_UNLOCK(sc);
1939}
1940
1941static void
1942pfsync_clear_states(u_int32_t creatorid, const char *ifname)
1943{
1944	struct pfsync_softc *sc = V_pfsyncif;
1945	struct {
1946		struct pfsync_subheader subh;
1947		struct pfsync_clr clr;
1948	} __packed r;
1949
1950	bzero(&r, sizeof(r));
1951
1952	r.subh.action = PFSYNC_ACT_CLR;
1953	r.subh.count = htons(1);
1954	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_CLR]++;
1955
1956	strlcpy(r.clr.ifname, ifname, sizeof(r.clr.ifname));
1957	r.clr.creatorid = creatorid;
1958
1959	PFSYNC_LOCK(sc);
1960	pfsync_send_plus(&r, sizeof(r));
1961	PFSYNC_UNLOCK(sc);
1962}
1963
1964static void
1965pfsync_q_ins(struct pf_state *st, int q)
1966{
1967	struct pfsync_softc *sc = V_pfsyncif;
1968	size_t nlen = pfsync_qs[q].len;
1969
1970	PFSYNC_LOCK_ASSERT(sc);
1971
1972	KASSERT(st->sync_state == PFSYNC_S_NONE,
1973		("%s: st->sync_state == PFSYNC_S_NONE", __func__));
1974	KASSERT(sc->sc_len >= PFSYNC_MINPKT, ("pfsync pkt len is too low %zu",
1975	    sc->sc_len));
1976
1977	if (TAILQ_EMPTY(&sc->sc_qs[q]))
1978		nlen += sizeof(struct pfsync_subheader);
1979
1980	if (sc->sc_len + nlen > sc->sc_ifp->if_mtu) {
1981		pfsync_sendout(1);
1982
1983		nlen = sizeof(struct pfsync_subheader) + pfsync_qs[q].len;
1984	}
1985
1986	sc->sc_len += nlen;
1987	TAILQ_INSERT_TAIL(&sc->sc_qs[q], st, sync_list);
1988	st->sync_state = q;
1989	pf_ref_state(st);
1990}
1991
1992static void
1993pfsync_q_del(struct pf_state *st)
1994{
1995	struct pfsync_softc *sc = V_pfsyncif;
1996	int q = st->sync_state;
1997
1998	PFSYNC_LOCK_ASSERT(sc);
1999	KASSERT(st->sync_state != PFSYNC_S_NONE,
2000		("%s: st->sync_state != PFSYNC_S_NONE", __func__));
2001
2002	sc->sc_len -= pfsync_qs[q].len;
2003	TAILQ_REMOVE(&sc->sc_qs[q], st, sync_list);
2004	st->sync_state = PFSYNC_S_NONE;
2005	pf_release_state(st);
2006
2007	if (TAILQ_EMPTY(&sc->sc_qs[q]))
2008		sc->sc_len -= sizeof(struct pfsync_subheader);
2009}
2010
2011static void
2012pfsync_bulk_start(void)
2013{
2014	struct pfsync_softc *sc = V_pfsyncif;
2015
2016	if (V_pf_status.debug >= PF_DEBUG_MISC)
2017		printf("pfsync: received bulk update request\n");
2018
2019	PFSYNC_BLOCK(sc);
2020
2021	sc->sc_ureq_received = time_uptime;
2022	sc->sc_bulk_hashid = 0;
2023	sc->sc_bulk_stateid = 0;
2024	pfsync_bulk_status(PFSYNC_BUS_START);
2025	callout_reset(&sc->sc_bulk_tmo, 1, pfsync_bulk_update, sc);
2026	PFSYNC_BUNLOCK(sc);
2027}
2028
2029static void
2030pfsync_bulk_update(void *arg)
2031{
2032	struct pfsync_softc *sc = arg;
2033	struct pf_state *s;
2034	int i, sent = 0;
2035
2036	PFSYNC_BLOCK_ASSERT(sc);
2037	CURVNET_SET(sc->sc_ifp->if_vnet);
2038
2039	/*
2040	 * Start with last state from previous invocation.
2041	 * It may had gone, in this case start from the
2042	 * hash slot.
2043	 */
2044	s = pf_find_state_byid(sc->sc_bulk_stateid, sc->sc_bulk_creatorid);
2045
2046	if (s != NULL)
2047		i = PF_IDHASH(s);
2048	else
2049		i = sc->sc_bulk_hashid;
2050
2051	for (; i <= V_pf_hashmask; i++) {
2052		struct pf_idhash *ih = &V_pf_idhash[i];
2053
2054		if (s != NULL)
2055			PF_HASHROW_ASSERT(ih);
2056		else {
2057			PF_HASHROW_LOCK(ih);
2058			s = LIST_FIRST(&ih->states);
2059		}
2060
2061		for (; s; s = LIST_NEXT(s, entry)) {
2062
2063			if (sent > 1 && (sc->sc_ifp->if_mtu - sc->sc_len) <
2064			    sizeof(struct pfsync_state)) {
2065				/* We've filled a packet. */
2066				sc->sc_bulk_hashid = i;
2067				sc->sc_bulk_stateid = s->id;
2068				sc->sc_bulk_creatorid = s->creatorid;
2069				PF_HASHROW_UNLOCK(ih);
2070				callout_reset(&sc->sc_bulk_tmo, 1,
2071				    pfsync_bulk_update, sc);
2072				goto full;
2073			}
2074
2075			if (s->sync_state == PFSYNC_S_NONE &&
2076			    s->timeout < PFTM_MAX &&
2077			    s->pfsync_time <= sc->sc_ureq_received) {
2078				PFSYNC_LOCK(sc);
2079				pfsync_update_state_req(s);
2080				PFSYNC_UNLOCK(sc);
2081				sent++;
2082			}
2083		}
2084		PF_HASHROW_UNLOCK(ih);
2085	}
2086
2087	/* We're done. */
2088	pfsync_bulk_status(PFSYNC_BUS_END);
2089
2090full:
2091	CURVNET_RESTORE();
2092}
2093
2094static void
2095pfsync_bulk_status(u_int8_t status)
2096{
2097	struct {
2098		struct pfsync_subheader subh;
2099		struct pfsync_bus bus;
2100	} __packed r;
2101
2102	struct pfsync_softc *sc = V_pfsyncif;
2103
2104	bzero(&r, sizeof(r));
2105
2106	r.subh.action = PFSYNC_ACT_BUS;
2107	r.subh.count = htons(1);
2108	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_BUS]++;
2109
2110	r.bus.creatorid = V_pf_status.hostid;
2111	r.bus.endtime = htonl(time_uptime - sc->sc_ureq_received);
2112	r.bus.status = status;
2113
2114	PFSYNC_LOCK(sc);
2115	pfsync_send_plus(&r, sizeof(r));
2116	PFSYNC_UNLOCK(sc);
2117}
2118
2119static void
2120pfsync_bulk_fail(void *arg)
2121{
2122	struct pfsync_softc *sc = arg;
2123
2124	CURVNET_SET(sc->sc_ifp->if_vnet);
2125
2126	PFSYNC_BLOCK_ASSERT(sc);
2127
2128	if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
2129		/* Try again */
2130		callout_reset(&sc->sc_bulkfail_tmo, 5 * hz,
2131		    pfsync_bulk_fail, V_pfsyncif);
2132		PFSYNC_LOCK(sc);
2133		pfsync_request_update(0, 0);
2134		PFSYNC_UNLOCK(sc);
2135	} else {
2136		/* Pretend like the transfer was ok. */
2137		sc->sc_ureq_sent = 0;
2138		sc->sc_bulk_tries = 0;
2139		PFSYNC_LOCK(sc);
2140		if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
2141			(*carp_demote_adj_p)(-V_pfsync_carp_adj,
2142			    "pfsync bulk fail");
2143		sc->sc_flags |= PFSYNCF_OK;
2144		PFSYNC_UNLOCK(sc);
2145		if (V_pf_status.debug >= PF_DEBUG_MISC)
2146			printf("pfsync: failed to receive bulk update\n");
2147	}
2148
2149	CURVNET_RESTORE();
2150}
2151
2152static void
2153pfsync_send_plus(void *plus, size_t pluslen)
2154{
2155	struct pfsync_softc *sc = V_pfsyncif;
2156
2157	PFSYNC_LOCK_ASSERT(sc);
2158
2159	if (sc->sc_len + pluslen > sc->sc_ifp->if_mtu)
2160		pfsync_sendout(1);
2161
2162	sc->sc_plus = plus;
2163	sc->sc_len += (sc->sc_pluslen = pluslen);
2164
2165	pfsync_sendout(1);
2166}
2167
2168static void
2169pfsync_timeout(void *arg)
2170{
2171	struct pfsync_softc *sc = arg;
2172
2173	CURVNET_SET(sc->sc_ifp->if_vnet);
2174	PFSYNC_LOCK(sc);
2175	pfsync_push(sc);
2176	PFSYNC_UNLOCK(sc);
2177	CURVNET_RESTORE();
2178}
2179
2180static void
2181pfsync_push(struct pfsync_softc *sc)
2182{
2183
2184	PFSYNC_LOCK_ASSERT(sc);
2185
2186	sc->sc_flags |= PFSYNCF_PUSH;
2187	swi_sched(V_pfsync_swi_cookie, 0);
2188}
2189
2190static void
2191pfsyncintr(void *arg)
2192{
2193	struct pfsync_softc *sc = arg;
2194	struct mbuf *m, *n;
2195
2196	CURVNET_SET(sc->sc_ifp->if_vnet);
2197
2198	PFSYNC_LOCK(sc);
2199	if ((sc->sc_flags & PFSYNCF_PUSH) && sc->sc_len > PFSYNC_MINPKT) {
2200		pfsync_sendout(0);
2201		sc->sc_flags &= ~PFSYNCF_PUSH;
2202	}
2203	_IF_DEQUEUE_ALL(&sc->sc_ifp->if_snd, m);
2204	PFSYNC_UNLOCK(sc);
2205
2206	for (; m != NULL; m = n) {
2207
2208		n = m->m_nextpkt;
2209		m->m_nextpkt = NULL;
2210
2211		/*
2212		 * We distinguish between a deferral packet and our
2213		 * own pfsync packet based on M_SKIP_FIREWALL
2214		 * flag. This is XXX.
2215		 */
2216		if (m->m_flags & M_SKIP_FIREWALL)
2217			ip_output(m, NULL, NULL, 0, NULL, NULL);
2218		else if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo,
2219		    NULL) == 0)
2220			V_pfsyncstats.pfsyncs_opackets++;
2221		else
2222			V_pfsyncstats.pfsyncs_oerrors++;
2223	}
2224	CURVNET_RESTORE();
2225}
2226
2227static int
2228pfsync_multicast_setup(struct pfsync_softc *sc, struct ifnet *ifp, void *mship)
2229{
2230	struct ip_moptions *imo = &sc->sc_imo;
2231	int error;
2232
2233	if (!(ifp->if_flags & IFF_MULTICAST))
2234		return (EADDRNOTAVAIL);
2235
2236	imo->imo_membership = (struct in_multi **)mship;
2237	imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
2238	imo->imo_multicast_vif = -1;
2239
2240	if ((error = in_joingroup(ifp, &sc->sc_sync_peer, NULL,
2241	    &imo->imo_membership[0])) != 0) {
2242		imo->imo_membership = NULL;
2243		return (error);
2244	}
2245	imo->imo_num_memberships++;
2246	imo->imo_multicast_ifp = ifp;
2247	imo->imo_multicast_ttl = PFSYNC_DFLTTL;
2248	imo->imo_multicast_loop = 0;
2249
2250	return (0);
2251}
2252
2253static void
2254pfsync_multicast_cleanup(struct pfsync_softc *sc)
2255{
2256	struct ip_moptions *imo = &sc->sc_imo;
2257
2258	in_leavegroup(imo->imo_membership[0], NULL);
2259	free(imo->imo_membership, M_PFSYNC);
2260	imo->imo_membership = NULL;
2261	imo->imo_multicast_ifp = NULL;
2262}
2263
2264#ifdef INET
2265extern  struct domain inetdomain;
2266static struct protosw in_pfsync_protosw = {
2267	.pr_type =		SOCK_RAW,
2268	.pr_domain =		&inetdomain,
2269	.pr_protocol =		IPPROTO_PFSYNC,
2270	.pr_flags =		PR_ATOMIC|PR_ADDR,
2271	.pr_input =		pfsync_input,
2272	.pr_output =		(pr_output_t *)rip_output,
2273	.pr_ctloutput =		rip_ctloutput,
2274	.pr_usrreqs =		&rip_usrreqs
2275};
2276#endif
2277
2278static int
2279pfsync_init()
2280{
2281	VNET_ITERATOR_DECL(vnet_iter);
2282	int error = 0;
2283
2284	VNET_LIST_RLOCK();
2285	VNET_FOREACH(vnet_iter) {
2286		CURVNET_SET(vnet_iter);
2287		V_pfsync_cloner = pfsync_cloner;
2288		V_pfsync_cloner_data = pfsync_cloner_data;
2289		V_pfsync_cloner.ifc_data = &V_pfsync_cloner_data;
2290		if_clone_attach(&V_pfsync_cloner);
2291		error = swi_add(NULL, "pfsync", pfsyncintr, V_pfsyncif,
2292		    SWI_NET, INTR_MPSAFE, &V_pfsync_swi_cookie);
2293		CURVNET_RESTORE();
2294		if (error)
2295			goto fail_locked;
2296	}
2297	VNET_LIST_RUNLOCK();
2298#ifdef INET
2299	error = pf_proto_register(PF_INET, &in_pfsync_protosw);
2300	if (error)
2301		goto fail;
2302	error = ipproto_register(IPPROTO_PFSYNC);
2303	if (error) {
2304		pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
2305		goto fail;
2306	}
2307#endif
2308	PF_RULES_WLOCK();
2309	pfsync_state_import_ptr = pfsync_state_import;
2310	pfsync_insert_state_ptr = pfsync_insert_state;
2311	pfsync_update_state_ptr = pfsync_update_state;
2312	pfsync_delete_state_ptr = pfsync_delete_state;
2313	pfsync_clear_states_ptr = pfsync_clear_states;
2314	pfsync_defer_ptr = pfsync_defer;
2315	PF_RULES_WUNLOCK();
2316
2317	return (0);
2318
2319fail:
2320	VNET_LIST_RLOCK();
2321fail_locked:
2322	VNET_FOREACH(vnet_iter) {
2323		CURVNET_SET(vnet_iter);
2324		if (V_pfsync_swi_cookie) {
2325			swi_remove(V_pfsync_swi_cookie);
2326			if_clone_detach(&V_pfsync_cloner);
2327		}
2328		CURVNET_RESTORE();
2329	}
2330	VNET_LIST_RUNLOCK();
2331
2332	return (error);
2333}
2334
2335static void
2336pfsync_uninit()
2337{
2338	VNET_ITERATOR_DECL(vnet_iter);
2339
2340	PF_RULES_WLOCK();
2341	pfsync_state_import_ptr = NULL;
2342	pfsync_insert_state_ptr = NULL;
2343	pfsync_update_state_ptr = NULL;
2344	pfsync_delete_state_ptr = NULL;
2345	pfsync_clear_states_ptr = NULL;
2346	pfsync_defer_ptr = NULL;
2347	PF_RULES_WUNLOCK();
2348
2349	ipproto_unregister(IPPROTO_PFSYNC);
2350	pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
2351	VNET_LIST_RLOCK();
2352	VNET_FOREACH(vnet_iter) {
2353		CURVNET_SET(vnet_iter);
2354		if_clone_detach(&V_pfsync_cloner);
2355		swi_remove(V_pfsync_swi_cookie);
2356		CURVNET_RESTORE();
2357	}
2358	VNET_LIST_RUNLOCK();
2359}
2360
2361static int
2362pfsync_modevent(module_t mod, int type, void *data)
2363{
2364	int error = 0;
2365
2366	switch (type) {
2367	case MOD_LOAD:
2368		error = pfsync_init();
2369		break;
2370	case MOD_QUIESCE:
2371		/*
2372		 * Module should not be unloaded due to race conditions.
2373		 */
2374		error = EPERM;
2375		break;
2376	case MOD_UNLOAD:
2377		pfsync_uninit();
2378		break;
2379	default:
2380		error = EINVAL;
2381		break;
2382	}
2383
2384	return (error);
2385}
2386
2387static moduledata_t pfsync_mod = {
2388	"pfsync",
2389	pfsync_modevent,
2390	0
2391};
2392
2393#define PFSYNC_MODVER 1
2394
2395DECLARE_MODULE(pfsync, pfsync_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
2396MODULE_VERSION(pfsync, PFSYNC_MODVER);
2397MODULE_DEPEND(pfsync, pf, PF_MODVER, PF_MODVER, PF_MODVER);
2398