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