if_pfsync.c revision 241913
1/*	$OpenBSD: if_pfsync.c,v 1.110 2009/02/24 05:39:19 dlg Exp $	*/
2
3/*
4 * Copyright (c) 2002 Michael Shalayeff
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
20 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
24 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
25 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26 * THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/*
30 * Copyright (c) 2009 David Gwynne <dlg@openbsd.org>
31 *
32 * Permission to use, copy, modify, and distribute this software for any
33 * purpose with or without fee is hereby granted, provided that the above
34 * copyright notice and this permission notice appear in all copies.
35 *
36 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
37 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
38 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
39 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
40 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
41 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
42 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
43 */
44
45/*
46 * Revisions picked from OpenBSD after revision 1.110 import:
47 * 1.118, 1.124, 1.148, 1.149, 1.151, 1.171 - fixes to bulk updates
48 * 1.120, 1.175 - use monotonic time_uptime
49 * 1.122 - reduce number of updates for non-TCP sessions
50 * 1.128 - cleanups
51 * 1.146 - bzero() mbuf before sparsely filling it with data
52 * 1.170 - SIOCSIFMTU checks
53 * 1.126, 1.142 - deferred packets processing
54 * 1.173 - correct expire time processing
55 */
56
57#include <sys/cdefs.h>
58__FBSDID("$FreeBSD: head/sys/netpfil/pf/if_pfsync.c 241913 2012-10-22 21:09:03Z glebius $");
59
60#include "opt_inet.h"
61#include "opt_inet6.h"
62#include "opt_pf.h"
63
64#include <sys/param.h>
65#include <sys/bus.h>
66#include <sys/endian.h>
67#include <sys/interrupt.h>
68#include <sys/kernel.h>
69#include <sys/lock.h>
70#include <sys/mbuf.h>
71#include <sys/module.h>
72#include <sys/mutex.h>
73#include <sys/priv.h>
74#include <sys/protosw.h>
75#include <sys/socket.h>
76#include <sys/sockio.h>
77#include <sys/sysctl.h>
78
79#include <net/bpf.h>
80#include <net/if.h>
81#include <net/if_clone.h>
82#include <net/if_types.h>
83#include <net/pfvar.h>
84#include <net/if_pfsync.h>
85
86#include <netinet/if_ether.h>
87#include <netinet/in.h>
88#include <netinet/in_var.h>
89#include <netinet/ip.h>
90#include <netinet/ip_carp.h>
91#include <netinet/ip_var.h>
92#include <netinet/tcp.h>
93#include <netinet/tcp_fsm.h>
94#include <netinet/tcp_seq.h>
95
96#define PFSYNC_MINPKT ( \
97	sizeof(struct ip) + \
98	sizeof(struct pfsync_header) + \
99	sizeof(struct pfsync_subheader) + \
100	sizeof(struct pfsync_eof))
101
102struct pfsync_pkt {
103	struct ip *ip;
104	struct in_addr src;
105	u_int8_t flags;
106};
107
108static int	pfsync_upd_tcp(struct pf_state *, struct pfsync_state_peer *,
109		    struct pfsync_state_peer *);
110static int	pfsync_in_clr(struct pfsync_pkt *, struct mbuf *, int, int);
111static int	pfsync_in_ins(struct pfsync_pkt *, struct mbuf *, int, int);
112static int	pfsync_in_iack(struct pfsync_pkt *, struct mbuf *, int, int);
113static int	pfsync_in_upd(struct pfsync_pkt *, struct mbuf *, int, int);
114static int	pfsync_in_upd_c(struct pfsync_pkt *, struct mbuf *, int, int);
115static int	pfsync_in_ureq(struct pfsync_pkt *, struct mbuf *, int, int);
116static int	pfsync_in_del(struct pfsync_pkt *, struct mbuf *, int, int);
117static int	pfsync_in_del_c(struct pfsync_pkt *, struct mbuf *, int, int);
118static int	pfsync_in_bus(struct pfsync_pkt *, struct mbuf *, int, int);
119static int	pfsync_in_tdb(struct pfsync_pkt *, struct mbuf *, int, int);
120static int	pfsync_in_eof(struct pfsync_pkt *, struct mbuf *, int, int);
121static int	pfsync_in_error(struct pfsync_pkt *, struct mbuf *, int, int);
122
123static int (*pfsync_acts[])(struct pfsync_pkt *, struct mbuf *, int, int) = {
124	pfsync_in_clr,			/* PFSYNC_ACT_CLR */
125	pfsync_in_ins,			/* PFSYNC_ACT_INS */
126	pfsync_in_iack,			/* PFSYNC_ACT_INS_ACK */
127	pfsync_in_upd,			/* PFSYNC_ACT_UPD */
128	pfsync_in_upd_c,		/* PFSYNC_ACT_UPD_C */
129	pfsync_in_ureq,			/* PFSYNC_ACT_UPD_REQ */
130	pfsync_in_del,			/* PFSYNC_ACT_DEL */
131	pfsync_in_del_c,		/* PFSYNC_ACT_DEL_C */
132	pfsync_in_error,		/* PFSYNC_ACT_INS_F */
133	pfsync_in_error,		/* PFSYNC_ACT_DEL_F */
134	pfsync_in_bus,			/* PFSYNC_ACT_BUS */
135	pfsync_in_tdb,			/* PFSYNC_ACT_TDB */
136	pfsync_in_eof			/* PFSYNC_ACT_EOF */
137};
138
139struct pfsync_q {
140	void		(*write)(struct pf_state *, void *);
141	size_t		len;
142	u_int8_t	action;
143};
144
145/* we have one of these for every PFSYNC_S_ */
146static void	pfsync_out_state(struct pf_state *, void *);
147static void	pfsync_out_iack(struct pf_state *, void *);
148static void	pfsync_out_upd_c(struct pf_state *, void *);
149static void	pfsync_out_del(struct pf_state *, void *);
150
151static struct pfsync_q pfsync_qs[] = {
152	{ pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_INS },
153	{ pfsync_out_iack,  sizeof(struct pfsync_ins_ack), PFSYNC_ACT_INS_ACK },
154	{ pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_UPD },
155	{ pfsync_out_upd_c, sizeof(struct pfsync_upd_c),   PFSYNC_ACT_UPD_C },
156	{ pfsync_out_del,   sizeof(struct pfsync_del_c),   PFSYNC_ACT_DEL_C }
157};
158
159static void	pfsync_q_ins(struct pf_state *, int);
160static void	pfsync_q_del(struct pf_state *);
161
162static void	pfsync_update_state(struct pf_state *);
163
164struct pfsync_upd_req_item {
165	TAILQ_ENTRY(pfsync_upd_req_item)	ur_entry;
166	struct pfsync_upd_req			ur_msg;
167};
168
169struct pfsync_deferral {
170	struct pfsync_softc		*pd_sc;
171	TAILQ_ENTRY(pfsync_deferral)	pd_entry;
172	u_int				pd_refs;
173	struct callout			pd_tmo;
174
175	struct pf_state			*pd_st;
176	struct mbuf			*pd_m;
177};
178
179struct pfsync_softc {
180	/* Configuration */
181	struct ifnet		*sc_ifp;
182	struct ifnet		*sc_sync_if;
183	struct ip_moptions	sc_imo;
184	struct in_addr		sc_sync_peer;
185	uint32_t		sc_flags;
186#define	PFSYNCF_OK		0x00000001
187#define	PFSYNCF_DEFER		0x00000002
188#define	PFSYNCF_PUSH		0x00000004
189	uint8_t			sc_maxupdates;
190	struct ip		sc_template;
191	struct callout		sc_tmo;
192	struct mtx		sc_mtx;
193
194	/* Queued data */
195	size_t			sc_len;
196	TAILQ_HEAD(, pf_state)			sc_qs[PFSYNC_S_COUNT];
197	TAILQ_HEAD(, pfsync_upd_req_item)	sc_upd_req_list;
198	TAILQ_HEAD(, pfsync_deferral)		sc_deferrals;
199	u_int			sc_deferred;
200	void			*sc_plus;
201	size_t			sc_pluslen;
202
203	/* Bulk update info */
204	struct mtx		sc_bulk_mtx;
205	uint32_t		sc_ureq_sent;
206	int			sc_bulk_tries;
207	uint32_t		sc_ureq_received;
208	int			sc_bulk_hashid;
209	uint64_t		sc_bulk_stateid;
210	uint32_t		sc_bulk_creatorid;
211	struct callout		sc_bulk_tmo;
212	struct callout		sc_bulkfail_tmo;
213};
214
215#define	PFSYNC_LOCK(sc)		mtx_lock(&(sc)->sc_mtx)
216#define	PFSYNC_UNLOCK(sc)	mtx_unlock(&(sc)->sc_mtx)
217#define	PFSYNC_LOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_mtx, MA_OWNED)
218
219#define	PFSYNC_BLOCK(sc)	mtx_lock(&(sc)->sc_bulk_mtx)
220#define	PFSYNC_BUNLOCK(sc)	mtx_unlock(&(sc)->sc_bulk_mtx)
221#define	PFSYNC_BLOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_bulk_mtx, MA_OWNED)
222
223static const char pfsyncname[] = "pfsync";
224static MALLOC_DEFINE(M_PFSYNC, pfsyncname, "pfsync(4) data");
225static VNET_DEFINE(struct pfsync_softc	*, pfsyncif) = NULL;
226#define	V_pfsyncif		VNET(pfsyncif)
227static VNET_DEFINE(void *, pfsync_swi_cookie) = NULL;
228#define	V_pfsync_swi_cookie	VNET(pfsync_swi_cookie)
229static VNET_DEFINE(struct pfsyncstats, pfsyncstats);
230#define	V_pfsyncstats		VNET(pfsyncstats)
231static VNET_DEFINE(int, pfsync_carp_adj) = CARP_MAXSKEW;
232#define	V_pfsync_carp_adj	VNET(pfsync_carp_adj)
233
234static void	pfsync_timeout(void *);
235static void	pfsync_push(struct pfsync_softc *);
236static void	pfsyncintr(void *);
237static int	pfsync_multicast_setup(struct pfsync_softc *, struct ifnet *,
238		    void *);
239static void	pfsync_multicast_cleanup(struct pfsync_softc *);
240static void	pfsync_pointers_init(void);
241static void	pfsync_pointers_uninit(void);
242static int	pfsync_init(void);
243static void	pfsync_uninit(void);
244
245SYSCTL_NODE(_net, OID_AUTO, pfsync, CTLFLAG_RW, 0, "PFSYNC");
246SYSCTL_VNET_STRUCT(_net_pfsync, OID_AUTO, stats, CTLFLAG_RW,
247    &VNET_NAME(pfsyncstats), pfsyncstats,
248    "PFSYNC statistics (struct pfsyncstats, net/if_pfsync.h)");
249SYSCTL_INT(_net_pfsync, OID_AUTO, carp_demotion_factor, CTLFLAG_RW,
250    &VNET_NAME(pfsync_carp_adj), 0, "pfsync's CARP demotion factor adjustment");
251
252static int	pfsync_clone_create(struct if_clone *, int, caddr_t);
253static void	pfsync_clone_destroy(struct ifnet *);
254static int	pfsync_alloc_scrub_memory(struct pfsync_state_peer *,
255		    struct pf_state_peer *);
256static int	pfsyncoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
257		    struct route *);
258static int	pfsyncioctl(struct ifnet *, u_long, caddr_t);
259
260static int	pfsync_defer(struct pf_state *, struct mbuf *);
261static void	pfsync_undefer(struct pfsync_deferral *, int);
262static void	pfsync_undefer_state(struct pf_state *, int);
263static void	pfsync_defer_tmo(void *);
264
265static void	pfsync_request_update(u_int32_t, u_int64_t);
266static void	pfsync_update_state_req(struct pf_state *);
267
268static void	pfsync_drop(struct pfsync_softc *);
269static void	pfsync_sendout(int);
270static void	pfsync_send_plus(void *, size_t);
271
272static void	pfsync_bulk_start(void);
273static void	pfsync_bulk_status(u_int8_t);
274static void	pfsync_bulk_update(void *);
275static void	pfsync_bulk_fail(void *);
276
277#ifdef IPSEC
278static void	pfsync_update_net_tdb(struct pfsync_tdb *);
279#endif
280
281#define PFSYNC_MAX_BULKTRIES	12
282
283VNET_DEFINE(struct if_clone *, pfsync_cloner);
284#define	V_pfsync_cloner	VNET(pfsync_cloner)
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, pfsyncname, 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, pfsyncname, 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			PFSYNC_UNLOCK(sc);
1273			pfsync_pointers_init();
1274		} else {
1275			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1276			PFSYNC_UNLOCK(sc);
1277			pfsync_pointers_uninit();
1278		}
1279		break;
1280	case SIOCSIFMTU:
1281		if (!sc->sc_sync_if ||
1282		    ifr->ifr_mtu <= PFSYNC_MINPKT ||
1283		    ifr->ifr_mtu > sc->sc_sync_if->if_mtu)
1284			return (EINVAL);
1285		if (ifr->ifr_mtu < ifp->if_mtu) {
1286			PFSYNC_LOCK(sc);
1287			if (sc->sc_len > PFSYNC_MINPKT)
1288				pfsync_sendout(1);
1289			PFSYNC_UNLOCK(sc);
1290		}
1291		ifp->if_mtu = ifr->ifr_mtu;
1292		break;
1293	case SIOCGETPFSYNC:
1294		bzero(&pfsyncr, sizeof(pfsyncr));
1295		PFSYNC_LOCK(sc);
1296		if (sc->sc_sync_if) {
1297			strlcpy(pfsyncr.pfsyncr_syncdev,
1298			    sc->sc_sync_if->if_xname, IFNAMSIZ);
1299		}
1300		pfsyncr.pfsyncr_syncpeer = sc->sc_sync_peer;
1301		pfsyncr.pfsyncr_maxupdates = sc->sc_maxupdates;
1302		pfsyncr.pfsyncr_defer = (PFSYNCF_DEFER ==
1303		    (sc->sc_flags & PFSYNCF_DEFER));
1304		PFSYNC_UNLOCK(sc);
1305		return (copyout(&pfsyncr, ifr->ifr_data, sizeof(pfsyncr)));
1306
1307	case SIOCSETPFSYNC:
1308	    {
1309		struct ip_moptions *imo = &sc->sc_imo;
1310		struct ifnet *sifp;
1311		struct ip *ip;
1312		void *mship = NULL;
1313
1314		if ((error = priv_check(curthread, PRIV_NETINET_PF)) != 0)
1315			return (error);
1316		if ((error = copyin(ifr->ifr_data, &pfsyncr, sizeof(pfsyncr))))
1317			return (error);
1318
1319		if (pfsyncr.pfsyncr_maxupdates > 255)
1320			return (EINVAL);
1321
1322		if (pfsyncr.pfsyncr_syncdev[0] == 0)
1323			sifp = NULL;
1324		else if ((sifp = ifunit_ref(pfsyncr.pfsyncr_syncdev)) == NULL)
1325			return (EINVAL);
1326
1327		if (pfsyncr.pfsyncr_syncpeer.s_addr == 0 && sifp != NULL)
1328			mship = malloc((sizeof(struct in_multi *) *
1329			    IP_MIN_MEMBERSHIPS), M_PFSYNC, M_WAITOK | M_ZERO);
1330
1331		PFSYNC_LOCK(sc);
1332		if (pfsyncr.pfsyncr_syncpeer.s_addr == 0)
1333			sc->sc_sync_peer.s_addr = htonl(INADDR_PFSYNC_GROUP);
1334		else
1335			sc->sc_sync_peer.s_addr =
1336			    pfsyncr.pfsyncr_syncpeer.s_addr;
1337
1338		sc->sc_maxupdates = pfsyncr.pfsyncr_maxupdates;
1339		if (pfsyncr.pfsyncr_defer) {
1340			sc->sc_flags |= PFSYNCF_DEFER;
1341			pfsync_defer_ptr = pfsync_defer;
1342		} else {
1343			sc->sc_flags &= ~PFSYNCF_DEFER;
1344			pfsync_defer_ptr = NULL;
1345		}
1346
1347		if (sifp == NULL) {
1348			if (sc->sc_sync_if)
1349				if_rele(sc->sc_sync_if);
1350			sc->sc_sync_if = NULL;
1351			if (imo->imo_membership)
1352				pfsync_multicast_cleanup(sc);
1353			PFSYNC_UNLOCK(sc);
1354			break;
1355		}
1356
1357		if (sc->sc_len > PFSYNC_MINPKT &&
1358		    (sifp->if_mtu < sc->sc_ifp->if_mtu ||
1359		    (sc->sc_sync_if != NULL &&
1360		    sifp->if_mtu < sc->sc_sync_if->if_mtu) ||
1361		    sifp->if_mtu < MCLBYTES - sizeof(struct ip)))
1362			pfsync_sendout(1);
1363
1364		if (imo->imo_membership)
1365			pfsync_multicast_cleanup(sc);
1366
1367		if (sc->sc_sync_peer.s_addr == htonl(INADDR_PFSYNC_GROUP)) {
1368			error = pfsync_multicast_setup(sc, sifp, mship);
1369			if (error) {
1370				if_rele(sifp);
1371				free(mship, M_PFSYNC);
1372				return (error);
1373			}
1374		}
1375		if (sc->sc_sync_if)
1376			if_rele(sc->sc_sync_if);
1377		sc->sc_sync_if = sifp;
1378
1379		ip = &sc->sc_template;
1380		bzero(ip, sizeof(*ip));
1381		ip->ip_v = IPVERSION;
1382		ip->ip_hl = sizeof(sc->sc_template) >> 2;
1383		ip->ip_tos = IPTOS_LOWDELAY;
1384		/* len and id are set later. */
1385		ip->ip_off = htons(IP_DF);
1386		ip->ip_ttl = PFSYNC_DFLTTL;
1387		ip->ip_p = IPPROTO_PFSYNC;
1388		ip->ip_src.s_addr = INADDR_ANY;
1389		ip->ip_dst.s_addr = sc->sc_sync_peer.s_addr;
1390
1391		/* Request a full state table update. */
1392		if ((sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
1393			(*carp_demote_adj_p)(V_pfsync_carp_adj,
1394			    "pfsync bulk start");
1395		sc->sc_flags &= ~PFSYNCF_OK;
1396		if (V_pf_status.debug >= PF_DEBUG_MISC)
1397			printf("pfsync: requesting bulk update\n");
1398		pfsync_request_update(0, 0);
1399		PFSYNC_UNLOCK(sc);
1400		PFSYNC_BLOCK(sc);
1401		sc->sc_ureq_sent = time_uptime;
1402		callout_reset(&sc->sc_bulkfail_tmo, 5 * hz, pfsync_bulk_fail,
1403		    sc);
1404		PFSYNC_BUNLOCK(sc);
1405
1406		break;
1407	    }
1408	default:
1409		return (ENOTTY);
1410	}
1411
1412	return (0);
1413}
1414
1415static void
1416pfsync_out_state(struct pf_state *st, void *buf)
1417{
1418	struct pfsync_state *sp = buf;
1419
1420	pfsync_state_export(sp, st);
1421}
1422
1423static void
1424pfsync_out_iack(struct pf_state *st, void *buf)
1425{
1426	struct pfsync_ins_ack *iack = buf;
1427
1428	iack->id = st->id;
1429	iack->creatorid = st->creatorid;
1430}
1431
1432static void
1433pfsync_out_upd_c(struct pf_state *st, void *buf)
1434{
1435	struct pfsync_upd_c *up = buf;
1436
1437	bzero(up, sizeof(*up));
1438	up->id = st->id;
1439	pf_state_peer_hton(&st->src, &up->src);
1440	pf_state_peer_hton(&st->dst, &up->dst);
1441	up->creatorid = st->creatorid;
1442	up->timeout = st->timeout;
1443}
1444
1445static void
1446pfsync_out_del(struct pf_state *st, void *buf)
1447{
1448	struct pfsync_del_c *dp = buf;
1449
1450	dp->id = st->id;
1451	dp->creatorid = st->creatorid;
1452	st->state_flags |= PFSTATE_NOSYNC;
1453}
1454
1455static void
1456pfsync_drop(struct pfsync_softc *sc)
1457{
1458	struct pf_state *st, *next;
1459	struct pfsync_upd_req_item *ur;
1460	int q;
1461
1462	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1463		if (TAILQ_EMPTY(&sc->sc_qs[q]))
1464			continue;
1465
1466		TAILQ_FOREACH_SAFE(st, &sc->sc_qs[q], sync_list, next) {
1467			KASSERT(st->sync_state == q,
1468				("%s: st->sync_state == q",
1469					__func__));
1470			st->sync_state = PFSYNC_S_NONE;
1471			pf_release_state(st);
1472		}
1473		TAILQ_INIT(&sc->sc_qs[q]);
1474	}
1475
1476	while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
1477		TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
1478		free(ur, M_PFSYNC);
1479	}
1480
1481	sc->sc_plus = NULL;
1482	sc->sc_len = PFSYNC_MINPKT;
1483}
1484
1485static void
1486pfsync_sendout(int schedswi)
1487{
1488	struct pfsync_softc *sc = V_pfsyncif;
1489	struct ifnet *ifp = sc->sc_ifp;
1490	struct mbuf *m;
1491	struct ip *ip;
1492	struct pfsync_header *ph;
1493	struct pfsync_subheader *subh;
1494	struct pf_state *st;
1495	struct pfsync_upd_req_item *ur;
1496	int offset;
1497	int q, count = 0;
1498
1499	KASSERT(sc != NULL, ("%s: null sc", __func__));
1500	KASSERT(sc->sc_len > PFSYNC_MINPKT,
1501	    ("%s: sc_len %zu", __func__, sc->sc_len));
1502	PFSYNC_LOCK_ASSERT(sc);
1503
1504	if (ifp->if_bpf == NULL && sc->sc_sync_if == NULL) {
1505		pfsync_drop(sc);
1506		return;
1507	}
1508
1509	m = m_get2(M_NOWAIT, MT_DATA, M_PKTHDR, max_linkhdr + sc->sc_len);
1510	if (m == NULL) {
1511		sc->sc_ifp->if_oerrors++;
1512		V_pfsyncstats.pfsyncs_onomem++;
1513		return;
1514	}
1515	m->m_data += max_linkhdr;
1516	m->m_len = m->m_pkthdr.len = sc->sc_len;
1517
1518	/* build the ip header */
1519	ip = (struct ip *)m->m_data;
1520	bcopy(&sc->sc_template, ip, sizeof(*ip));
1521	offset = sizeof(*ip);
1522
1523	ip->ip_len = htons(m->m_pkthdr.len);
1524	ip->ip_id = htons(ip_randomid());
1525
1526	/* build the pfsync header */
1527	ph = (struct pfsync_header *)(m->m_data + offset);
1528	bzero(ph, sizeof(*ph));
1529	offset += sizeof(*ph);
1530
1531	ph->version = PFSYNC_VERSION;
1532	ph->len = htons(sc->sc_len - sizeof(*ip));
1533	bcopy(V_pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
1534
1535	/* walk the queues */
1536	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1537		if (TAILQ_EMPTY(&sc->sc_qs[q]))
1538			continue;
1539
1540		subh = (struct pfsync_subheader *)(m->m_data + offset);
1541		offset += sizeof(*subh);
1542
1543		count = 0;
1544		TAILQ_FOREACH(st, &sc->sc_qs[q], sync_list) {
1545			KASSERT(st->sync_state == q,
1546				("%s: st->sync_state == q",
1547					__func__));
1548			/*
1549			 * XXXGL: some of write methods do unlocked reads
1550			 * of state data :(
1551			 */
1552			pfsync_qs[q].write(st, m->m_data + offset);
1553			offset += pfsync_qs[q].len;
1554			st->sync_state = PFSYNC_S_NONE;
1555			pf_release_state(st);
1556			count++;
1557		}
1558		TAILQ_INIT(&sc->sc_qs[q]);
1559
1560		bzero(subh, sizeof(*subh));
1561		subh->action = pfsync_qs[q].action;
1562		subh->count = htons(count);
1563		V_pfsyncstats.pfsyncs_oacts[pfsync_qs[q].action] += count;
1564	}
1565
1566	if (!TAILQ_EMPTY(&sc->sc_upd_req_list)) {
1567		subh = (struct pfsync_subheader *)(m->m_data + offset);
1568		offset += sizeof(*subh);
1569
1570		count = 0;
1571		while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
1572			TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
1573
1574			bcopy(&ur->ur_msg, m->m_data + offset,
1575			    sizeof(ur->ur_msg));
1576			offset += sizeof(ur->ur_msg);
1577			free(ur, M_PFSYNC);
1578			count++;
1579		}
1580
1581		bzero(subh, sizeof(*subh));
1582		subh->action = PFSYNC_ACT_UPD_REQ;
1583		subh->count = htons(count);
1584		V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_UPD_REQ] += count;
1585	}
1586
1587	/* has someone built a custom region for us to add? */
1588	if (sc->sc_plus != NULL) {
1589		bcopy(sc->sc_plus, m->m_data + offset, sc->sc_pluslen);
1590		offset += sc->sc_pluslen;
1591
1592		sc->sc_plus = NULL;
1593	}
1594
1595	subh = (struct pfsync_subheader *)(m->m_data + offset);
1596	offset += sizeof(*subh);
1597
1598	bzero(subh, sizeof(*subh));
1599	subh->action = PFSYNC_ACT_EOF;
1600	subh->count = htons(1);
1601	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_EOF]++;
1602
1603	/* XXX write checksum in EOF here */
1604
1605	/* we're done, let's put it on the wire */
1606	if (ifp->if_bpf) {
1607		m->m_data += sizeof(*ip);
1608		m->m_len = m->m_pkthdr.len = sc->sc_len - sizeof(*ip);
1609		BPF_MTAP(ifp, m);
1610		m->m_data -= sizeof(*ip);
1611		m->m_len = m->m_pkthdr.len = sc->sc_len;
1612	}
1613
1614	if (sc->sc_sync_if == NULL) {
1615		sc->sc_len = PFSYNC_MINPKT;
1616		m_freem(m);
1617		return;
1618	}
1619
1620	sc->sc_ifp->if_opackets++;
1621	sc->sc_ifp->if_obytes += m->m_pkthdr.len;
1622	sc->sc_len = PFSYNC_MINPKT;
1623
1624	if (!_IF_QFULL(&sc->sc_ifp->if_snd))
1625		_IF_ENQUEUE(&sc->sc_ifp->if_snd, m);
1626	else {
1627		m_freem(m);
1628		sc->sc_ifp->if_snd.ifq_drops++;
1629	}
1630	if (schedswi)
1631		swi_sched(V_pfsync_swi_cookie, 0);
1632}
1633
1634static void
1635pfsync_insert_state(struct pf_state *st)
1636{
1637	struct pfsync_softc *sc = V_pfsyncif;
1638
1639	if (st->state_flags & PFSTATE_NOSYNC)
1640		return;
1641
1642	if ((st->rule.ptr->rule_flag & PFRULE_NOSYNC) ||
1643	    st->key[PF_SK_WIRE]->proto == IPPROTO_PFSYNC) {
1644		st->state_flags |= PFSTATE_NOSYNC;
1645		return;
1646	}
1647
1648	KASSERT(st->sync_state == PFSYNC_S_NONE,
1649		("%s: st->sync_state == PFSYNC_S_NONE", __func__));
1650
1651	PFSYNC_LOCK(sc);
1652	if (sc->sc_len == PFSYNC_MINPKT)
1653		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1654
1655	pfsync_q_ins(st, PFSYNC_S_INS);
1656	PFSYNC_UNLOCK(sc);
1657
1658	st->sync_updates = 0;
1659}
1660
1661static int
1662pfsync_defer(struct pf_state *st, struct mbuf *m)
1663{
1664	struct pfsync_softc *sc = V_pfsyncif;
1665	struct pfsync_deferral *pd;
1666
1667	if (m->m_flags & (M_BCAST|M_MCAST))
1668		return (0);
1669
1670	PFSYNC_LOCK(sc);
1671
1672	if (sc == NULL || !(sc->sc_ifp->if_flags & IFF_DRV_RUNNING) ||
1673	    !(sc->sc_flags & PFSYNCF_DEFER)) {
1674		PFSYNC_UNLOCK(sc);
1675		return (0);
1676	}
1677
1678	 if (sc->sc_deferred >= 128)
1679		pfsync_undefer(TAILQ_FIRST(&sc->sc_deferrals), 0);
1680
1681	pd = malloc(sizeof(*pd), M_PFSYNC, M_NOWAIT);
1682	if (pd == NULL)
1683		return (0);
1684	sc->sc_deferred++;
1685
1686	m->m_flags |= M_SKIP_FIREWALL;
1687	st->state_flags |= PFSTATE_ACK;
1688
1689	pd->pd_sc = sc;
1690	pd->pd_refs = 0;
1691	pd->pd_st = st;
1692	pf_ref_state(st);
1693	pd->pd_m = m;
1694
1695	TAILQ_INSERT_TAIL(&sc->sc_deferrals, pd, pd_entry);
1696	callout_init_mtx(&pd->pd_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1697	callout_reset(&pd->pd_tmo, 10, pfsync_defer_tmo, pd);
1698
1699	pfsync_push(sc);
1700
1701	return (1);
1702}
1703
1704static void
1705pfsync_undefer(struct pfsync_deferral *pd, int drop)
1706{
1707	struct pfsync_softc *sc = pd->pd_sc;
1708	struct mbuf *m = pd->pd_m;
1709	struct pf_state *st = pd->pd_st;
1710
1711	PFSYNC_LOCK_ASSERT(sc);
1712
1713	TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
1714	sc->sc_deferred--;
1715	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
1716	free(pd, M_PFSYNC);
1717	pf_release_state(st);
1718
1719	if (drop)
1720		m_freem(m);
1721	else {
1722		_IF_ENQUEUE(&sc->sc_ifp->if_snd, m);
1723		pfsync_push(sc);
1724	}
1725}
1726
1727static void
1728pfsync_defer_tmo(void *arg)
1729{
1730	struct pfsync_deferral *pd = arg;
1731	struct pfsync_softc *sc = pd->pd_sc;
1732	struct mbuf *m = pd->pd_m;
1733	struct pf_state *st = pd->pd_st;
1734
1735	PFSYNC_LOCK_ASSERT(sc);
1736
1737	CURVNET_SET(m->m_pkthdr.rcvif->if_vnet);
1738
1739	TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
1740	sc->sc_deferred--;
1741	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
1742	if (pd->pd_refs == 0)
1743		free(pd, M_PFSYNC);
1744	PFSYNC_UNLOCK(sc);
1745
1746	ip_output(m, NULL, NULL, 0, NULL, NULL);
1747
1748	pf_release_state(st);
1749
1750	CURVNET_RESTORE();
1751}
1752
1753static void
1754pfsync_undefer_state(struct pf_state *st, int drop)
1755{
1756	struct pfsync_softc *sc = V_pfsyncif;
1757	struct pfsync_deferral *pd;
1758
1759	PFSYNC_LOCK_ASSERT(sc);
1760
1761	TAILQ_FOREACH(pd, &sc->sc_deferrals, pd_entry) {
1762		 if (pd->pd_st == st) {
1763			if (callout_stop(&pd->pd_tmo))
1764				pfsync_undefer(pd, drop);
1765			return;
1766		}
1767	}
1768
1769	panic("%s: unable to find deferred state", __func__);
1770}
1771
1772static void
1773pfsync_update_state(struct pf_state *st)
1774{
1775	struct pfsync_softc *sc = V_pfsyncif;
1776	int sync = 0;
1777
1778	PF_STATE_LOCK_ASSERT(st);
1779	PFSYNC_LOCK(sc);
1780
1781	if (st->state_flags & PFSTATE_ACK)
1782		pfsync_undefer_state(st, 0);
1783	if (st->state_flags & PFSTATE_NOSYNC) {
1784		if (st->sync_state != PFSYNC_S_NONE)
1785			pfsync_q_del(st);
1786		PFSYNC_UNLOCK(sc);
1787		return;
1788	}
1789
1790	if (sc->sc_len == PFSYNC_MINPKT)
1791		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1792
1793	switch (st->sync_state) {
1794	case PFSYNC_S_UPD_C:
1795	case PFSYNC_S_UPD:
1796	case PFSYNC_S_INS:
1797		/* we're already handling it */
1798
1799		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP) {
1800			st->sync_updates++;
1801			if (st->sync_updates >= sc->sc_maxupdates)
1802				sync = 1;
1803		}
1804		break;
1805
1806	case PFSYNC_S_IACK:
1807		pfsync_q_del(st);
1808	case PFSYNC_S_NONE:
1809		pfsync_q_ins(st, PFSYNC_S_UPD_C);
1810		st->sync_updates = 0;
1811		break;
1812
1813	default:
1814		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1815	}
1816
1817	if (sync || (time_uptime - st->pfsync_time) < 2)
1818		pfsync_push(sc);
1819
1820	PFSYNC_UNLOCK(sc);
1821}
1822
1823static void
1824pfsync_request_update(u_int32_t creatorid, u_int64_t id)
1825{
1826	struct pfsync_softc *sc = V_pfsyncif;
1827	struct pfsync_upd_req_item *item;
1828	size_t nlen = sizeof(struct pfsync_upd_req);
1829
1830	PFSYNC_LOCK_ASSERT(sc);
1831
1832	/*
1833	 * This code does a bit to prevent multiple update requests for the
1834	 * same state being generated. It searches current subheader queue,
1835	 * but it doesn't lookup into queue of already packed datagrams.
1836	 */
1837	TAILQ_FOREACH(item, &sc->sc_upd_req_list, ur_entry)
1838		if (item->ur_msg.id == id &&
1839		    item->ur_msg.creatorid == creatorid)
1840			return;
1841
1842	item = malloc(sizeof(*item), M_PFSYNC, M_NOWAIT);
1843	if (item == NULL)
1844		return; /* XXX stats */
1845
1846	item->ur_msg.id = id;
1847	item->ur_msg.creatorid = creatorid;
1848
1849	if (TAILQ_EMPTY(&sc->sc_upd_req_list))
1850		nlen += sizeof(struct pfsync_subheader);
1851
1852	if (sc->sc_len + nlen > sc->sc_ifp->if_mtu) {
1853		pfsync_sendout(1);
1854
1855		nlen = sizeof(struct pfsync_subheader) +
1856		    sizeof(struct pfsync_upd_req);
1857	}
1858
1859	TAILQ_INSERT_TAIL(&sc->sc_upd_req_list, item, ur_entry);
1860	sc->sc_len += nlen;
1861}
1862
1863static void
1864pfsync_update_state_req(struct pf_state *st)
1865{
1866	struct pfsync_softc *sc = V_pfsyncif;
1867
1868	PF_STATE_LOCK_ASSERT(st);
1869	PFSYNC_LOCK(sc);
1870
1871	if (st->state_flags & PFSTATE_NOSYNC) {
1872		if (st->sync_state != PFSYNC_S_NONE)
1873			pfsync_q_del(st);
1874		PFSYNC_UNLOCK(sc);
1875		return;
1876	}
1877
1878	switch (st->sync_state) {
1879	case PFSYNC_S_UPD_C:
1880	case PFSYNC_S_IACK:
1881		pfsync_q_del(st);
1882	case PFSYNC_S_NONE:
1883		pfsync_q_ins(st, PFSYNC_S_UPD);
1884		pfsync_push(sc);
1885		break;
1886
1887	case PFSYNC_S_INS:
1888	case PFSYNC_S_UPD:
1889	case PFSYNC_S_DEL:
1890		/* we're already handling it */
1891		break;
1892
1893	default:
1894		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1895	}
1896
1897	PFSYNC_UNLOCK(sc);
1898}
1899
1900static void
1901pfsync_delete_state(struct pf_state *st)
1902{
1903	struct pfsync_softc *sc = V_pfsyncif;
1904
1905	PFSYNC_LOCK(sc);
1906	if (st->state_flags & PFSTATE_ACK)
1907		pfsync_undefer_state(st, 1);
1908	if (st->state_flags & PFSTATE_NOSYNC) {
1909		if (st->sync_state != PFSYNC_S_NONE)
1910			pfsync_q_del(st);
1911		PFSYNC_UNLOCK(sc);
1912		return;
1913	}
1914
1915	if (sc->sc_len == PFSYNC_MINPKT)
1916		callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout, V_pfsyncif);
1917
1918	switch (st->sync_state) {
1919	case PFSYNC_S_INS:
1920		/* We never got to tell the world so just forget about it. */
1921		pfsync_q_del(st);
1922		break;
1923
1924	case PFSYNC_S_UPD_C:
1925	case PFSYNC_S_UPD:
1926	case PFSYNC_S_IACK:
1927		pfsync_q_del(st);
1928		/* FALLTHROUGH to putting it on the del list */
1929
1930	case PFSYNC_S_NONE:
1931		pfsync_q_ins(st, PFSYNC_S_DEL);
1932		break;
1933
1934	default:
1935		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1936	}
1937	PFSYNC_UNLOCK(sc);
1938}
1939
1940static void
1941pfsync_clear_states(u_int32_t creatorid, const char *ifname)
1942{
1943	struct pfsync_softc *sc = V_pfsyncif;
1944	struct {
1945		struct pfsync_subheader subh;
1946		struct pfsync_clr clr;
1947	} __packed r;
1948
1949	bzero(&r, sizeof(r));
1950
1951	r.subh.action = PFSYNC_ACT_CLR;
1952	r.subh.count = htons(1);
1953	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_CLR]++;
1954
1955	strlcpy(r.clr.ifname, ifname, sizeof(r.clr.ifname));
1956	r.clr.creatorid = creatorid;
1957
1958	PFSYNC_LOCK(sc);
1959	pfsync_send_plus(&r, sizeof(r));
1960	PFSYNC_UNLOCK(sc);
1961}
1962
1963static void
1964pfsync_q_ins(struct pf_state *st, int q)
1965{
1966	struct pfsync_softc *sc = V_pfsyncif;
1967	size_t nlen = pfsync_qs[q].len;
1968
1969	PFSYNC_LOCK_ASSERT(sc);
1970
1971	KASSERT(st->sync_state == PFSYNC_S_NONE,
1972		("%s: st->sync_state == PFSYNC_S_NONE", __func__));
1973	KASSERT(sc->sc_len >= PFSYNC_MINPKT, ("pfsync pkt len is too low %zu",
1974	    sc->sc_len));
1975
1976	if (TAILQ_EMPTY(&sc->sc_qs[q]))
1977		nlen += sizeof(struct pfsync_subheader);
1978
1979	if (sc->sc_len + nlen > sc->sc_ifp->if_mtu) {
1980		pfsync_sendout(1);
1981
1982		nlen = sizeof(struct pfsync_subheader) + pfsync_qs[q].len;
1983	}
1984
1985	sc->sc_len += nlen;
1986	TAILQ_INSERT_TAIL(&sc->sc_qs[q], st, sync_list);
1987	st->sync_state = q;
1988	pf_ref_state(st);
1989}
1990
1991static void
1992pfsync_q_del(struct pf_state *st)
1993{
1994	struct pfsync_softc *sc = V_pfsyncif;
1995	int q = st->sync_state;
1996
1997	PFSYNC_LOCK_ASSERT(sc);
1998	KASSERT(st->sync_state != PFSYNC_S_NONE,
1999		("%s: st->sync_state != PFSYNC_S_NONE", __func__));
2000
2001	sc->sc_len -= pfsync_qs[q].len;
2002	TAILQ_REMOVE(&sc->sc_qs[q], st, sync_list);
2003	st->sync_state = PFSYNC_S_NONE;
2004	pf_release_state(st);
2005
2006	if (TAILQ_EMPTY(&sc->sc_qs[q]))
2007		sc->sc_len -= sizeof(struct pfsync_subheader);
2008}
2009
2010static void
2011pfsync_bulk_start(void)
2012{
2013	struct pfsync_softc *sc = V_pfsyncif;
2014
2015	if (V_pf_status.debug >= PF_DEBUG_MISC)
2016		printf("pfsync: received bulk update request\n");
2017
2018	PFSYNC_BLOCK(sc);
2019
2020	sc->sc_ureq_received = time_uptime;
2021	sc->sc_bulk_hashid = 0;
2022	sc->sc_bulk_stateid = 0;
2023	pfsync_bulk_status(PFSYNC_BUS_START);
2024	callout_reset(&sc->sc_bulk_tmo, 1, pfsync_bulk_update, sc);
2025	PFSYNC_BUNLOCK(sc);
2026}
2027
2028static void
2029pfsync_bulk_update(void *arg)
2030{
2031	struct pfsync_softc *sc = arg;
2032	struct pf_state *s;
2033	int i, sent = 0;
2034
2035	PFSYNC_BLOCK_ASSERT(sc);
2036	CURVNET_SET(sc->sc_ifp->if_vnet);
2037
2038	/*
2039	 * Start with last state from previous invocation.
2040	 * It may had gone, in this case start from the
2041	 * hash slot.
2042	 */
2043	s = pf_find_state_byid(sc->sc_bulk_stateid, sc->sc_bulk_creatorid);
2044
2045	if (s != NULL)
2046		i = PF_IDHASH(s);
2047	else
2048		i = sc->sc_bulk_hashid;
2049
2050	for (; i <= V_pf_hashmask; i++) {
2051		struct pf_idhash *ih = &V_pf_idhash[i];
2052
2053		if (s != NULL)
2054			PF_HASHROW_ASSERT(ih);
2055		else {
2056			PF_HASHROW_LOCK(ih);
2057			s = LIST_FIRST(&ih->states);
2058		}
2059
2060		for (; s; s = LIST_NEXT(s, entry)) {
2061
2062			if (sent > 1 && (sc->sc_ifp->if_mtu - sc->sc_len) <
2063			    sizeof(struct pfsync_state)) {
2064				/* We've filled a packet. */
2065				sc->sc_bulk_hashid = i;
2066				sc->sc_bulk_stateid = s->id;
2067				sc->sc_bulk_creatorid = s->creatorid;
2068				PF_HASHROW_UNLOCK(ih);
2069				callout_reset(&sc->sc_bulk_tmo, 1,
2070				    pfsync_bulk_update, sc);
2071				goto full;
2072			}
2073
2074			if (s->sync_state == PFSYNC_S_NONE &&
2075			    s->timeout < PFTM_MAX &&
2076			    s->pfsync_time <= sc->sc_ureq_received) {
2077				PFSYNC_LOCK(sc);
2078				pfsync_update_state_req(s);
2079				PFSYNC_UNLOCK(sc);
2080				sent++;
2081			}
2082		}
2083		PF_HASHROW_UNLOCK(ih);
2084	}
2085
2086	/* We're done. */
2087	pfsync_bulk_status(PFSYNC_BUS_END);
2088
2089full:
2090	CURVNET_RESTORE();
2091}
2092
2093static void
2094pfsync_bulk_status(u_int8_t status)
2095{
2096	struct {
2097		struct pfsync_subheader subh;
2098		struct pfsync_bus bus;
2099	} __packed r;
2100
2101	struct pfsync_softc *sc = V_pfsyncif;
2102
2103	bzero(&r, sizeof(r));
2104
2105	r.subh.action = PFSYNC_ACT_BUS;
2106	r.subh.count = htons(1);
2107	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_BUS]++;
2108
2109	r.bus.creatorid = V_pf_status.hostid;
2110	r.bus.endtime = htonl(time_uptime - sc->sc_ureq_received);
2111	r.bus.status = status;
2112
2113	PFSYNC_LOCK(sc);
2114	pfsync_send_plus(&r, sizeof(r));
2115	PFSYNC_UNLOCK(sc);
2116}
2117
2118static void
2119pfsync_bulk_fail(void *arg)
2120{
2121	struct pfsync_softc *sc = arg;
2122
2123	CURVNET_SET(sc->sc_ifp->if_vnet);
2124
2125	PFSYNC_BLOCK_ASSERT(sc);
2126
2127	if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
2128		/* Try again */
2129		callout_reset(&sc->sc_bulkfail_tmo, 5 * hz,
2130		    pfsync_bulk_fail, V_pfsyncif);
2131		PFSYNC_LOCK(sc);
2132		pfsync_request_update(0, 0);
2133		PFSYNC_UNLOCK(sc);
2134	} else {
2135		/* Pretend like the transfer was ok. */
2136		sc->sc_ureq_sent = 0;
2137		sc->sc_bulk_tries = 0;
2138		PFSYNC_LOCK(sc);
2139		if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
2140			(*carp_demote_adj_p)(-V_pfsync_carp_adj,
2141			    "pfsync bulk fail");
2142		sc->sc_flags |= PFSYNCF_OK;
2143		PFSYNC_UNLOCK(sc);
2144		if (V_pf_status.debug >= PF_DEBUG_MISC)
2145			printf("pfsync: failed to receive bulk update\n");
2146	}
2147
2148	CURVNET_RESTORE();
2149}
2150
2151static void
2152pfsync_send_plus(void *plus, size_t pluslen)
2153{
2154	struct pfsync_softc *sc = V_pfsyncif;
2155
2156	PFSYNC_LOCK_ASSERT(sc);
2157
2158	if (sc->sc_len + pluslen > sc->sc_ifp->if_mtu)
2159		pfsync_sendout(1);
2160
2161	sc->sc_plus = plus;
2162	sc->sc_len += (sc->sc_pluslen = pluslen);
2163
2164	pfsync_sendout(1);
2165}
2166
2167static void
2168pfsync_timeout(void *arg)
2169{
2170	struct pfsync_softc *sc = arg;
2171
2172	CURVNET_SET(sc->sc_ifp->if_vnet);
2173	PFSYNC_LOCK(sc);
2174	pfsync_push(sc);
2175	PFSYNC_UNLOCK(sc);
2176	CURVNET_RESTORE();
2177}
2178
2179static void
2180pfsync_push(struct pfsync_softc *sc)
2181{
2182
2183	PFSYNC_LOCK_ASSERT(sc);
2184
2185	sc->sc_flags |= PFSYNCF_PUSH;
2186	swi_sched(V_pfsync_swi_cookie, 0);
2187}
2188
2189static void
2190pfsyncintr(void *arg)
2191{
2192	struct pfsync_softc *sc = arg;
2193	struct mbuf *m, *n;
2194
2195	CURVNET_SET(sc->sc_ifp->if_vnet);
2196
2197	PFSYNC_LOCK(sc);
2198	if ((sc->sc_flags & PFSYNCF_PUSH) && sc->sc_len > PFSYNC_MINPKT) {
2199		pfsync_sendout(0);
2200		sc->sc_flags &= ~PFSYNCF_PUSH;
2201	}
2202	_IF_DEQUEUE_ALL(&sc->sc_ifp->if_snd, m);
2203	PFSYNC_UNLOCK(sc);
2204
2205	for (; m != NULL; m = n) {
2206
2207		n = m->m_nextpkt;
2208		m->m_nextpkt = NULL;
2209
2210		/*
2211		 * We distinguish between a deferral packet and our
2212		 * own pfsync packet based on M_SKIP_FIREWALL
2213		 * flag. This is XXX.
2214		 */
2215		if (m->m_flags & M_SKIP_FIREWALL)
2216			ip_output(m, NULL, NULL, 0, NULL, NULL);
2217		else if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo,
2218		    NULL) == 0)
2219			V_pfsyncstats.pfsyncs_opackets++;
2220		else
2221			V_pfsyncstats.pfsyncs_oerrors++;
2222	}
2223	CURVNET_RESTORE();
2224}
2225
2226static int
2227pfsync_multicast_setup(struct pfsync_softc *sc, struct ifnet *ifp, void *mship)
2228{
2229	struct ip_moptions *imo = &sc->sc_imo;
2230	int error;
2231
2232	if (!(ifp->if_flags & IFF_MULTICAST))
2233		return (EADDRNOTAVAIL);
2234
2235	imo->imo_membership = (struct in_multi **)mship;
2236	imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
2237	imo->imo_multicast_vif = -1;
2238
2239	if ((error = in_joingroup(ifp, &sc->sc_sync_peer, NULL,
2240	    &imo->imo_membership[0])) != 0) {
2241		imo->imo_membership = NULL;
2242		return (error);
2243	}
2244	imo->imo_num_memberships++;
2245	imo->imo_multicast_ifp = ifp;
2246	imo->imo_multicast_ttl = PFSYNC_DFLTTL;
2247	imo->imo_multicast_loop = 0;
2248
2249	return (0);
2250}
2251
2252static void
2253pfsync_multicast_cleanup(struct pfsync_softc *sc)
2254{
2255	struct ip_moptions *imo = &sc->sc_imo;
2256
2257	in_leavegroup(imo->imo_membership[0], NULL);
2258	free(imo->imo_membership, M_PFSYNC);
2259	imo->imo_membership = NULL;
2260	imo->imo_multicast_ifp = NULL;
2261}
2262
2263#ifdef INET
2264extern  struct domain inetdomain;
2265static struct protosw in_pfsync_protosw = {
2266	.pr_type =		SOCK_RAW,
2267	.pr_domain =		&inetdomain,
2268	.pr_protocol =		IPPROTO_PFSYNC,
2269	.pr_flags =		PR_ATOMIC|PR_ADDR,
2270	.pr_input =		pfsync_input,
2271	.pr_output =		(pr_output_t *)rip_output,
2272	.pr_ctloutput =		rip_ctloutput,
2273	.pr_usrreqs =		&rip_usrreqs
2274};
2275#endif
2276
2277static void
2278pfsync_pointers_init()
2279{
2280
2281	PF_RULES_WLOCK();
2282	pfsync_state_import_ptr = pfsync_state_import;
2283	pfsync_insert_state_ptr = pfsync_insert_state;
2284	pfsync_update_state_ptr = pfsync_update_state;
2285	pfsync_delete_state_ptr = pfsync_delete_state;
2286	pfsync_clear_states_ptr = pfsync_clear_states;
2287	pfsync_defer_ptr = pfsync_defer;
2288	PF_RULES_WUNLOCK();
2289}
2290
2291static void
2292pfsync_pointers_uninit()
2293{
2294
2295	PF_RULES_WLOCK();
2296	pfsync_state_import_ptr = NULL;
2297	pfsync_insert_state_ptr = NULL;
2298	pfsync_update_state_ptr = NULL;
2299	pfsync_delete_state_ptr = NULL;
2300	pfsync_clear_states_ptr = NULL;
2301	pfsync_defer_ptr = NULL;
2302	PF_RULES_WUNLOCK();
2303}
2304
2305static int
2306pfsync_init()
2307{
2308	VNET_ITERATOR_DECL(vnet_iter);
2309	int error = 0;
2310
2311	VNET_LIST_RLOCK();
2312	VNET_FOREACH(vnet_iter) {
2313		CURVNET_SET(vnet_iter);
2314		V_pfsync_cloner = if_clone_simple(pfsyncname,
2315		    pfsync_clone_create, pfsync_clone_destroy, 1);
2316		error = swi_add(NULL, pfsyncname, pfsyncintr, V_pfsyncif,
2317		    SWI_NET, INTR_MPSAFE, &V_pfsync_swi_cookie);
2318		CURVNET_RESTORE();
2319		if (error)
2320			goto fail_locked;
2321	}
2322	VNET_LIST_RUNLOCK();
2323#ifdef INET
2324	error = pf_proto_register(PF_INET, &in_pfsync_protosw);
2325	if (error)
2326		goto fail;
2327	error = ipproto_register(IPPROTO_PFSYNC);
2328	if (error) {
2329		pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
2330		goto fail;
2331	}
2332#endif
2333	pfsync_pointers_init();
2334
2335	return (0);
2336
2337fail:
2338	VNET_LIST_RLOCK();
2339fail_locked:
2340	VNET_FOREACH(vnet_iter) {
2341		CURVNET_SET(vnet_iter);
2342		if (V_pfsync_swi_cookie) {
2343			swi_remove(V_pfsync_swi_cookie);
2344			if_clone_detach(V_pfsync_cloner);
2345		}
2346		CURVNET_RESTORE();
2347	}
2348	VNET_LIST_RUNLOCK();
2349
2350	return (error);
2351}
2352
2353static void
2354pfsync_uninit()
2355{
2356	VNET_ITERATOR_DECL(vnet_iter);
2357
2358	pfsync_pointers_uninit();
2359
2360	ipproto_unregister(IPPROTO_PFSYNC);
2361	pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
2362	VNET_LIST_RLOCK();
2363	VNET_FOREACH(vnet_iter) {
2364		CURVNET_SET(vnet_iter);
2365		if_clone_detach(V_pfsync_cloner);
2366		swi_remove(V_pfsync_swi_cookie);
2367		CURVNET_RESTORE();
2368	}
2369	VNET_LIST_RUNLOCK();
2370}
2371
2372static int
2373pfsync_modevent(module_t mod, int type, void *data)
2374{
2375	int error = 0;
2376
2377	switch (type) {
2378	case MOD_LOAD:
2379		error = pfsync_init();
2380		break;
2381	case MOD_QUIESCE:
2382		/*
2383		 * Module should not be unloaded due to race conditions.
2384		 */
2385		error = EBUSY;
2386		break;
2387	case MOD_UNLOAD:
2388		pfsync_uninit();
2389		break;
2390	default:
2391		error = EINVAL;
2392		break;
2393	}
2394
2395	return (error);
2396}
2397
2398static moduledata_t pfsync_mod = {
2399	pfsyncname,
2400	pfsync_modevent,
2401	0
2402};
2403
2404#define PFSYNC_MODVER 1
2405
2406DECLARE_MODULE(pfsync, pfsync_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
2407MODULE_VERSION(pfsync, PFSYNC_MODVER);
2408MODULE_DEPEND(pfsync, pf, PF_MODVER, PF_MODVER, PF_MODVER);
2409