]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/pf/net/if_pfsync.c
MFV: r233550
[FreeBSD/FreeBSD.git] / sys / contrib / pf / net / if_pfsync.c
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  */
54
55 #ifdef __FreeBSD__
56 #include "opt_inet.h"
57 #include "opt_inet6.h"
58 #include "opt_pf.h"
59
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
62
63 #define NBPFILTER       1
64 #endif /* __FreeBSD__ */
65
66 #include <sys/param.h>
67 #include <sys/kernel.h>
68 #ifdef __FreeBSD__
69 #include <sys/bus.h>
70 #include <sys/interrupt.h>
71 #include <sys/priv.h>
72 #endif
73 #include <sys/proc.h>
74 #include <sys/systm.h>
75 #include <sys/time.h>
76 #include <sys/mbuf.h>
77 #include <sys/socket.h>
78 #ifdef __FreeBSD__
79 #include <sys/endian.h>
80 #include <sys/malloc.h>
81 #include <sys/module.h>
82 #include <sys/sockio.h>
83 #include <sys/taskqueue.h>
84 #include <sys/lock.h>
85 #include <sys/mutex.h>
86 #include <sys/protosw.h>
87 #else
88 #include <sys/ioctl.h>
89 #include <sys/timeout.h>
90 #endif
91 #include <sys/sysctl.h>
92 #ifndef __FreeBSD__
93 #include <sys/pool.h>
94 #endif
95
96 #include <net/if.h>
97 #ifdef __FreeBSD__
98 #include <net/if_clone.h>
99 #endif
100 #include <net/if_types.h>
101 #include <net/route.h>
102 #include <net/bpf.h>
103 #include <net/netisr.h>
104 #ifdef __FreeBSD__
105 #include <net/vnet.h>
106 #endif
107
108 #include <netinet/in.h>
109 #include <netinet/if_ether.h>
110 #include <netinet/tcp.h>
111 #include <netinet/tcp_seq.h>
112
113 #ifdef  INET
114 #include <netinet/in_systm.h>
115 #include <netinet/in_var.h>
116 #include <netinet/ip.h>
117 #include <netinet/ip_var.h>
118 #endif
119
120 #ifdef INET6
121 #include <netinet6/nd6.h>
122 #endif /* INET6 */
123
124 #ifdef __FreeBSD__
125 #include <netinet/ip_carp.h>
126 #else
127 #include "carp.h"
128 #if NCARP > 0
129 #include <netinet/ip_carp.h>
130 #endif
131 #endif
132
133 #include <net/pfvar.h>
134 #include <net/if_pfsync.h>
135
136 #ifndef __FreeBSD__
137 #include "bpfilter.h"
138 #include "pfsync.h"
139 #endif
140
141 #define PFSYNC_MINPKT ( \
142         sizeof(struct ip) + \
143         sizeof(struct pfsync_header) + \
144         sizeof(struct pfsync_subheader) + \
145         sizeof(struct pfsync_eof))
146
147 struct pfsync_pkt {
148         struct ip *ip;
149         struct in_addr src;
150         u_int8_t flags;
151 };
152
153 int     pfsync_input_hmac(struct mbuf *, int);
154
155 int     pfsync_upd_tcp(struct pf_state *, struct pfsync_state_peer *,
156             struct pfsync_state_peer *);
157
158 int     pfsync_in_clr(struct pfsync_pkt *, struct mbuf *, int, int);
159 int     pfsync_in_ins(struct pfsync_pkt *, struct mbuf *, int, int);
160 int     pfsync_in_iack(struct pfsync_pkt *, struct mbuf *, int, int);
161 int     pfsync_in_upd(struct pfsync_pkt *, struct mbuf *, int, int);
162 int     pfsync_in_upd_c(struct pfsync_pkt *, struct mbuf *, int, int);
163 int     pfsync_in_ureq(struct pfsync_pkt *, struct mbuf *, int, int);
164 int     pfsync_in_del(struct pfsync_pkt *, struct mbuf *, int, int);
165 int     pfsync_in_del_c(struct pfsync_pkt *, struct mbuf *, int, int);
166 int     pfsync_in_bus(struct pfsync_pkt *, struct mbuf *, int, int);
167 int     pfsync_in_tdb(struct pfsync_pkt *, struct mbuf *, int, int);
168 int     pfsync_in_eof(struct pfsync_pkt *, struct mbuf *, int, int);
169
170 int     pfsync_in_error(struct pfsync_pkt *, struct mbuf *, int, int);
171
172 int     (*pfsync_acts[])(struct pfsync_pkt *, struct mbuf *, int, int) = {
173         pfsync_in_clr,                  /* PFSYNC_ACT_CLR */
174         pfsync_in_ins,                  /* PFSYNC_ACT_INS */
175         pfsync_in_iack,                 /* PFSYNC_ACT_INS_ACK */
176         pfsync_in_upd,                  /* PFSYNC_ACT_UPD */
177         pfsync_in_upd_c,                /* PFSYNC_ACT_UPD_C */
178         pfsync_in_ureq,                 /* PFSYNC_ACT_UPD_REQ */
179         pfsync_in_del,                  /* PFSYNC_ACT_DEL */
180         pfsync_in_del_c,                /* PFSYNC_ACT_DEL_C */
181         pfsync_in_error,                /* PFSYNC_ACT_INS_F */
182         pfsync_in_error,                /* PFSYNC_ACT_DEL_F */
183         pfsync_in_bus,                  /* PFSYNC_ACT_BUS */
184         pfsync_in_tdb,                  /* PFSYNC_ACT_TDB */
185         pfsync_in_eof                   /* PFSYNC_ACT_EOF */
186 };
187
188 struct pfsync_q {
189         int             (*write)(struct pf_state *, struct mbuf *, int);
190         size_t          len;
191         u_int8_t        action;
192 };
193
194 /* we have one of these for every PFSYNC_S_ */
195 int     pfsync_out_state(struct pf_state *, struct mbuf *, int);
196 int     pfsync_out_iack(struct pf_state *, struct mbuf *, int);
197 int     pfsync_out_upd_c(struct pf_state *, struct mbuf *, int);
198 int     pfsync_out_del(struct pf_state *, struct mbuf *, int);
199
200 struct pfsync_q pfsync_qs[] = {
201         { pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_INS },
202         { pfsync_out_iack,  sizeof(struct pfsync_ins_ack), PFSYNC_ACT_INS_ACK },
203         { pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_UPD },
204         { pfsync_out_upd_c, sizeof(struct pfsync_upd_c),   PFSYNC_ACT_UPD_C },
205         { pfsync_out_del,   sizeof(struct pfsync_del_c),   PFSYNC_ACT_DEL_C }
206 };
207
208 void    pfsync_q_ins(struct pf_state *, int);
209 void    pfsync_q_del(struct pf_state *);
210
211 struct pfsync_upd_req_item {
212         TAILQ_ENTRY(pfsync_upd_req_item)        ur_entry;
213         struct pfsync_upd_req                   ur_msg;
214 };
215 TAILQ_HEAD(pfsync_upd_reqs, pfsync_upd_req_item);
216
217 struct pfsync_deferral {
218         TAILQ_ENTRY(pfsync_deferral)             pd_entry;
219         struct pf_state                         *pd_st;
220         struct mbuf                             *pd_m;
221 #ifdef __FreeBSD__
222         struct callout                           pd_tmo;
223 #else
224         struct timeout                           pd_tmo;
225 #endif
226 };
227 TAILQ_HEAD(pfsync_deferrals, pfsync_deferral);
228
229 #define PFSYNC_PLSIZE   MAX(sizeof(struct pfsync_upd_req_item), \
230                             sizeof(struct pfsync_deferral))
231
232 #ifdef notyet
233 int     pfsync_out_tdb(struct tdb *, struct mbuf *, int);
234 #endif
235
236 struct pfsync_softc {
237 #ifdef __FreeBSD__
238         struct ifnet            *sc_ifp;
239 #else
240         struct ifnet             sc_if;
241 #endif
242         struct ifnet            *sc_sync_if;
243
244 #ifdef __FreeBSD__
245         uma_zone_t               sc_pool;
246 #else
247         struct pool              sc_pool;
248 #endif
249
250         struct ip_moptions       sc_imo;
251
252         struct in_addr           sc_sync_peer;
253         u_int8_t                 sc_maxupdates;
254 #ifdef __FreeBSD__
255         int                      pfsync_sync_ok;
256 #endif
257
258         struct ip                sc_template;
259
260         struct pf_state_queue    sc_qs[PFSYNC_S_COUNT];
261         size_t                   sc_len;
262
263         struct pfsync_upd_reqs   sc_upd_req_list;
264
265         struct pfsync_deferrals  sc_deferrals;
266         u_int                    sc_deferred;
267
268         void                    *sc_plus;
269         size_t                   sc_pluslen;
270
271         u_int32_t                sc_ureq_sent;
272         int                      sc_bulk_tries;
273 #ifdef __FreeBSD__
274         struct callout           sc_bulkfail_tmo;
275 #else
276         struct timeout           sc_bulkfail_tmo;
277 #endif
278
279         u_int32_t                sc_ureq_received;
280         struct pf_state         *sc_bulk_next;
281         struct pf_state         *sc_bulk_last;
282 #ifdef __FreeBSD__
283         struct callout           sc_bulk_tmo;
284 #else
285         struct timeout           sc_bulk_tmo;
286 #endif
287
288         TAILQ_HEAD(, tdb)        sc_tdb_q;
289
290 #ifdef __FreeBSD__
291         struct callout           sc_tmo;
292 #else
293         struct timeout           sc_tmo;
294 #endif
295 };
296
297 #ifdef __FreeBSD__
298 static MALLOC_DEFINE(M_PFSYNC, "pfsync", "pfsync data");
299 static VNET_DEFINE(struct pfsync_softc  *, pfsyncif) = NULL;
300 #define V_pfsyncif              VNET(pfsyncif)
301 static VNET_DEFINE(void *, pfsync_swi_cookie) = NULL;
302 #define V_pfsync_swi_cookie     VNET(pfsync_swi_cookie)
303 static VNET_DEFINE(struct pfsyncstats, pfsyncstats);
304 #define V_pfsyncstats           VNET(pfsyncstats)
305 static VNET_DEFINE(int, pfsync_carp_adj) = CARP_MAXSKEW;
306 #define V_pfsync_carp_adj       VNET(pfsync_carp_adj)
307
308 static void     pfsyncintr(void *);
309 static int      pfsync_multicast_setup(struct pfsync_softc *);
310 static void     pfsync_multicast_cleanup(struct pfsync_softc *);
311 static int      pfsync_init(void);
312 static void     pfsync_uninit(void);
313 static void     pfsync_sendout1(int);
314
315 #define schednetisr(NETISR_PFSYNC)      swi_sched(V_pfsync_swi_cookie, 0)
316
317 SYSCTL_NODE(_net, OID_AUTO, pfsync, CTLFLAG_RW, 0, "PFSYNC");
318 SYSCTL_VNET_STRUCT(_net_pfsync, OID_AUTO, stats, CTLFLAG_RW,
319     &VNET_NAME(pfsyncstats), pfsyncstats,
320     "PFSYNC statistics (struct pfsyncstats, net/if_pfsync.h)");
321 SYSCTL_INT(_net_pfsync, OID_AUTO, carp_demotion_factor, CTLFLAG_RW,
322     &VNET_NAME(pfsync_carp_adj), 0, "pfsync's CARP demotion factor adjustment");
323 #else
324 struct pfsync_softc     *pfsyncif = NULL;
325 struct pfsyncstats       pfsyncstats;
326 #define V_pfsyncstats    pfsyncstats
327 #endif
328
329 void    pfsyncattach(int);
330 #ifdef __FreeBSD__
331 int     pfsync_clone_create(struct if_clone *, int, caddr_t);
332 void    pfsync_clone_destroy(struct ifnet *);
333 #else
334 int     pfsync_clone_create(struct if_clone *, int);
335 int     pfsync_clone_destroy(struct ifnet *);
336 #endif
337 int     pfsync_alloc_scrub_memory(struct pfsync_state_peer *,
338             struct pf_state_peer *);
339 void    pfsync_update_net_tdb(struct pfsync_tdb *);
340 int     pfsyncoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
341 #ifdef __FreeBSD__
342             struct route *);
343 #else
344             struct rtentry *);
345 #endif
346 int     pfsyncioctl(struct ifnet *, u_long, caddr_t);
347 void    pfsyncstart(struct ifnet *);
348
349 struct mbuf *pfsync_if_dequeue(struct ifnet *);
350
351 void    pfsync_deferred(struct pf_state *, int);
352 void    pfsync_undefer(struct pfsync_deferral *, int);
353 void    pfsync_defer_tmo(void *);
354
355 void    pfsync_request_update(u_int32_t, u_int64_t);
356 void    pfsync_update_state_req(struct pf_state *);
357
358 void    pfsync_drop(struct pfsync_softc *);
359 void    pfsync_sendout(void);
360 void    pfsync_send_plus(void *, size_t);
361 void    pfsync_timeout(void *);
362 void    pfsync_tdb_timeout(void *);
363
364 void    pfsync_bulk_start(void);
365 void    pfsync_bulk_status(u_int8_t);
366 void    pfsync_bulk_update(void *);
367 void    pfsync_bulk_fail(void *);
368
369 #ifdef __FreeBSD__
370 /* XXX: ugly */
371 #define betoh64         (unsigned long long)be64toh
372 #define timeout_del     callout_stop
373 #endif
374
375 #define PFSYNC_MAX_BULKTRIES    12
376 #ifndef __FreeBSD__
377 int     pfsync_sync_ok;
378 #endif
379
380 #ifdef __FreeBSD__
381 VNET_DEFINE(struct ifc_simple_data, pfsync_cloner_data);
382 VNET_DEFINE(struct if_clone, pfsync_cloner);
383 #define V_pfsync_cloner_data    VNET(pfsync_cloner_data)
384 #define V_pfsync_cloner         VNET(pfsync_cloner)
385 IFC_SIMPLE_DECLARE(pfsync, 1);
386 #else
387 struct if_clone pfsync_cloner =
388     IF_CLONE_INITIALIZER("pfsync", pfsync_clone_create, pfsync_clone_destroy);
389 #endif
390
391 void
392 pfsyncattach(int npfsync)
393 {
394         if_clone_attach(&pfsync_cloner);
395 }
396 int
397 #ifdef __FreeBSD__
398 pfsync_clone_create(struct if_clone *ifc, int unit, caddr_t param)
399 #else
400 pfsync_clone_create(struct if_clone *ifc, int unit)
401 #endif
402 {
403         struct pfsync_softc *sc;
404         struct ifnet *ifp;
405         int q;
406
407         if (unit != 0)
408                 return (EINVAL);
409
410 #ifdef __FreeBSD__
411         sc = malloc(sizeof(struct pfsync_softc), M_PFSYNC, M_WAITOK | M_ZERO);
412         sc->pfsync_sync_ok = 1;
413 #else
414         pfsync_sync_ok = 1;
415         sc = malloc(sizeof(*pfsyncif), M_DEVBUF, M_NOWAIT | M_ZERO);
416 #endif
417
418         for (q = 0; q < PFSYNC_S_COUNT; q++)
419                 TAILQ_INIT(&sc->sc_qs[q]);
420
421 #ifdef __FreeBSD__
422         sc->sc_pool = uma_zcreate("pfsync", PFSYNC_PLSIZE, NULL, NULL, NULL,
423             NULL, UMA_ALIGN_PTR, 0);
424 #else
425         pool_init(&sc->sc_pool, PFSYNC_PLSIZE, 0, 0, 0, "pfsync", NULL);
426 #endif
427         TAILQ_INIT(&sc->sc_upd_req_list);
428         TAILQ_INIT(&sc->sc_deferrals);
429         sc->sc_deferred = 0;
430
431         TAILQ_INIT(&sc->sc_tdb_q);
432
433         sc->sc_len = PFSYNC_MINPKT;
434         sc->sc_maxupdates = 128;
435
436 #ifndef __FreeBSD__
437         sc->sc_imo.imo_membership = (struct in_multi **)malloc(
438             (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_IPMOPTS,
439             M_WAITOK | M_ZERO);
440         sc->sc_imo.imo_max_memberships = IP_MIN_MEMBERSHIPS;
441 #endif
442
443 #ifdef __FreeBSD__
444         ifp = sc->sc_ifp = if_alloc(IFT_PFSYNC);
445         if (ifp == NULL) {
446                 uma_zdestroy(sc->sc_pool);
447                 free(sc, M_PFSYNC);
448                 return (ENOSPC);
449         }
450         if_initname(ifp, ifc->ifc_name, unit);
451 #else
452         ifp = &sc->sc_if;
453         snprintf(ifp->if_xname, sizeof ifp->if_xname, "pfsync%d", unit);
454 #endif
455         ifp->if_softc = sc;
456         ifp->if_ioctl = pfsyncioctl;
457         ifp->if_output = pfsyncoutput;
458         ifp->if_start = pfsyncstart;
459         ifp->if_type = IFT_PFSYNC;
460         ifp->if_snd.ifq_maxlen = ifqmaxlen;
461         ifp->if_hdrlen = sizeof(struct pfsync_header);
462         ifp->if_mtu = ETHERMTU;
463 #ifdef __FreeBSD__
464         callout_init(&sc->sc_tmo, CALLOUT_MPSAFE);
465         callout_init_mtx(&sc->sc_bulk_tmo, &pf_task_mtx, 0);
466         callout_init(&sc->sc_bulkfail_tmo, CALLOUT_MPSAFE);
467 #else
468         timeout_set(&sc->sc_tmo, pfsync_timeout, sc);
469         timeout_set(&sc->sc_bulk_tmo, pfsync_bulk_update, sc);
470         timeout_set(&sc->sc_bulkfail_tmo, pfsync_bulk_fail, sc);
471 #endif
472
473         if_attach(ifp);
474 #ifndef __FreeBSD__
475         if_alloc_sadl(ifp);
476
477 #if NCARP > 0
478         if_addgroup(ifp, "carp");
479 #endif
480 #endif
481
482 #if NBPFILTER > 0
483 #ifdef __FreeBSD__
484         bpfattach(ifp, DLT_PFSYNC, PFSYNC_HDRLEN);
485 #else
486         bpfattach(&sc->sc_if.if_bpf, ifp, DLT_PFSYNC, PFSYNC_HDRLEN);
487 #endif
488 #endif
489
490 #ifdef __FreeBSD__
491         V_pfsyncif = sc;
492 #else
493         pfsyncif = sc;
494 #endif
495
496         return (0);
497 }
498
499 #ifdef __FreeBSD__
500 void
501 #else
502 int
503 #endif
504 pfsync_clone_destroy(struct ifnet *ifp)
505 {
506         struct pfsync_softc *sc = ifp->if_softc;
507
508 #ifdef __FreeBSD__
509         PF_LOCK();
510 #endif
511         timeout_del(&sc->sc_bulkfail_tmo);
512         timeout_del(&sc->sc_bulk_tmo);
513         timeout_del(&sc->sc_tmo);
514 #ifdef __FreeBSD__
515         PF_UNLOCK();
516         if (!sc->pfsync_sync_ok && carp_demote_adj_p)
517                 (*carp_demote_adj_p)(-V_pfsync_carp_adj, "pfsync destroy");
518 #else
519 #if NCARP > 0
520         if (!pfsync_sync_ok)
521                 carp_group_demote_adj(&sc->sc_if, -1);
522 #endif
523 #endif
524 #if NBPFILTER > 0
525         bpfdetach(ifp);
526 #endif
527         if_detach(ifp);
528
529         pfsync_drop(sc);
530
531         while (sc->sc_deferred > 0)
532                 pfsync_undefer(TAILQ_FIRST(&sc->sc_deferrals), 0);
533
534 #ifdef __FreeBSD__
535         UMA_DESTROY(sc->sc_pool);
536 #else
537         pool_destroy(&sc->sc_pool);
538 #endif
539 #ifdef __FreeBSD__
540         if_free(ifp);
541         if (sc->sc_imo.imo_membership)
542                 pfsync_multicast_cleanup(sc);
543         free(sc, M_PFSYNC);
544 #else
545         free(sc->sc_imo.imo_membership, M_IPMOPTS);
546         free(sc, M_DEVBUF);
547 #endif
548
549 #ifdef __FreeBSD__
550         V_pfsyncif = NULL;
551 #else
552         pfsyncif = NULL;
553 #endif
554
555 #ifndef __FreeBSD__
556         return (0);
557 #endif
558 }
559
560 struct mbuf *
561 pfsync_if_dequeue(struct ifnet *ifp)
562 {
563         struct mbuf *m;
564 #ifndef __FreeBSD__
565         int s;
566 #endif
567
568 #ifdef __FreeBSD__
569         IF_LOCK(&ifp->if_snd);
570         _IF_DROP(&ifp->if_snd);
571         _IF_DEQUEUE(&ifp->if_snd, m);
572         IF_UNLOCK(&ifp->if_snd);
573 #else
574         s = splnet();
575         IF_DEQUEUE(&ifp->if_snd, m);
576         splx(s);
577 #endif
578
579         return (m);
580 }
581
582 /*
583  * Start output on the pfsync interface.
584  */
585 void
586 pfsyncstart(struct ifnet *ifp)
587 {
588         struct mbuf *m;
589
590         while ((m = pfsync_if_dequeue(ifp)) != NULL) {
591 #ifndef __FreeBSD__
592                 IF_DROP(&ifp->if_snd);
593 #endif
594                 m_freem(m);
595         }
596 }
597
598 int
599 pfsync_alloc_scrub_memory(struct pfsync_state_peer *s,
600     struct pf_state_peer *d)
601 {
602         if (s->scrub.scrub_flag && d->scrub == NULL) {
603 #ifdef __FreeBSD__
604                 d->scrub = pool_get(&V_pf_state_scrub_pl, PR_NOWAIT | PR_ZERO);
605 #else
606                 d->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT | PR_ZERO);
607 #endif
608                 if (d->scrub == NULL)
609                         return (ENOMEM);
610         }
611
612         return (0);
613 }
614
615 #ifndef __FreeBSD__
616 void
617 pfsync_state_export(struct pfsync_state *sp, struct pf_state *st)
618 {
619         bzero(sp, sizeof(struct pfsync_state));
620
621         /* copy from state key */
622         sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
623         sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
624         sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
625         sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
626         sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
627         sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
628         sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
629         sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
630         sp->proto = st->key[PF_SK_WIRE]->proto;
631         sp->af = st->key[PF_SK_WIRE]->af;
632
633         /* copy from state */
634         strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
635         bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));
636         sp->creation = htonl(time_uptime - st->creation);
637         sp->expire = pf_state_expires(st);
638         if (sp->expire <= time_second)
639                 sp->expire = htonl(0);
640         else
641                 sp->expire = htonl(sp->expire - time_second);
642
643         sp->direction = st->direction;
644         sp->log = st->log;
645         sp->timeout = st->timeout;
646         sp->state_flags = st->state_flags;
647         if (st->src_node)
648                 sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
649         if (st->nat_src_node)
650                 sp->sync_flags |= PFSYNC_FLAG_NATSRCNODE;
651
652         bcopy(&st->id, &sp->id, sizeof(sp->id));
653         sp->creatorid = st->creatorid;
654         pf_state_peer_hton(&st->src, &sp->src);
655         pf_state_peer_hton(&st->dst, &sp->dst);
656
657         if (st->rule.ptr == NULL)
658                 sp->rule = htonl(-1);
659         else
660                 sp->rule = htonl(st->rule.ptr->nr);
661         if (st->anchor.ptr == NULL)
662                 sp->anchor = htonl(-1);
663         else
664                 sp->anchor = htonl(st->anchor.ptr->nr);
665         if (st->nat_rule.ptr == NULL)
666                 sp->nat_rule = htonl(-1);
667         else
668                 sp->nat_rule = htonl(st->nat_rule.ptr->nr);
669
670         pf_state_counter_hton(st->packets[0], sp->packets[0]);
671         pf_state_counter_hton(st->packets[1], sp->packets[1]);
672         pf_state_counter_hton(st->bytes[0], sp->bytes[0]);
673         pf_state_counter_hton(st->bytes[1], sp->bytes[1]);
674
675 }
676 #endif
677
678 int
679 pfsync_state_import(struct pfsync_state *sp, u_int8_t flags)
680 {
681         struct pf_state *st = NULL;
682         struct pf_state_key *skw = NULL, *sks = NULL;
683         struct pf_rule *r = NULL;
684         struct pfi_kif  *kif;
685         int pool_flags;
686         int error;
687
688 #ifdef __FreeBSD__
689         PF_LOCK_ASSERT();
690
691         if (sp->creatorid == 0 && V_pf_status.debug >= PF_DEBUG_MISC) {
692 #else
693         if (sp->creatorid == 0 && pf_status.debug >= PF_DEBUG_MISC) {
694 #endif
695                 printf("pfsync_state_import: invalid creator id:"
696                     " %08x\n", ntohl(sp->creatorid));
697                 return (EINVAL);
698         }
699
700         if ((kif = pfi_kif_get(sp->ifname)) == NULL) {
701 #ifdef __FreeBSD__
702                 if (V_pf_status.debug >= PF_DEBUG_MISC)
703 #else
704                 if (pf_status.debug >= PF_DEBUG_MISC)
705 #endif
706                         printf("pfsync_state_import: "
707                             "unknown interface: %s\n", sp->ifname);
708                 if (flags & PFSYNC_SI_IOCTL)
709                         return (EINVAL);
710                 return (0);     /* skip this state */
711         }
712
713         /*
714          * If the ruleset checksums match or the state is coming from the ioctl,
715          * it's safe to associate the state with the rule of that number.
716          */
717         if (sp->rule != htonl(-1) && sp->anchor == htonl(-1) &&
718             (flags & (PFSYNC_SI_IOCTL | PFSYNC_SI_CKSUM)) && ntohl(sp->rule) <
719             pf_main_ruleset.rules[PF_RULESET_FILTER].active.rcount)
720                 r = pf_main_ruleset.rules[
721                     PF_RULESET_FILTER].active.ptr_array[ntohl(sp->rule)];
722         else
723 #ifdef __FreeBSD__
724                 r = &V_pf_default_rule;
725 #else
726                 r = &pf_default_rule;
727 #endif
728
729         if ((r->max_states && r->states_cur >= r->max_states))
730                 goto cleanup;
731
732 #ifdef __FreeBSD__
733         if (flags & PFSYNC_SI_IOCTL)
734                 pool_flags = PR_WAITOK | PR_ZERO;
735         else
736                 pool_flags = PR_NOWAIT | PR_ZERO;
737
738         if ((st = pool_get(&V_pf_state_pl, pool_flags)) == NULL)
739                 goto cleanup;
740 #else
741         if (flags & PFSYNC_SI_IOCTL)
742                 pool_flags = PR_WAITOK | PR_LIMITFAIL | PR_ZERO;
743         else
744                 pool_flags = PR_LIMITFAIL | PR_ZERO;
745
746         if ((st = pool_get(&pf_state_pl, pool_flags)) == NULL)
747                 goto cleanup;
748 #endif
749
750         if ((skw = pf_alloc_state_key(pool_flags)) == NULL)
751                 goto cleanup;
752
753         if (PF_ANEQ(&sp->key[PF_SK_WIRE].addr[0],
754             &sp->key[PF_SK_STACK].addr[0], sp->af) ||
755             PF_ANEQ(&sp->key[PF_SK_WIRE].addr[1],
756             &sp->key[PF_SK_STACK].addr[1], sp->af) ||
757             sp->key[PF_SK_WIRE].port[0] != sp->key[PF_SK_STACK].port[0] ||
758             sp->key[PF_SK_WIRE].port[1] != sp->key[PF_SK_STACK].port[1]) {
759                 if ((sks = pf_alloc_state_key(pool_flags)) == NULL)
760                         goto cleanup;
761         } else
762                 sks = skw;
763
764         /* allocate memory for scrub info */
765         if (pfsync_alloc_scrub_memory(&sp->src, &st->src) ||
766             pfsync_alloc_scrub_memory(&sp->dst, &st->dst))
767                 goto cleanup;
768
769         /* copy to state key(s) */
770         skw->addr[0] = sp->key[PF_SK_WIRE].addr[0];
771         skw->addr[1] = sp->key[PF_SK_WIRE].addr[1];
772         skw->port[0] = sp->key[PF_SK_WIRE].port[0];
773         skw->port[1] = sp->key[PF_SK_WIRE].port[1];
774         skw->proto = sp->proto;
775         skw->af = sp->af;
776         if (sks != skw) {
777                 sks->addr[0] = sp->key[PF_SK_STACK].addr[0];
778                 sks->addr[1] = sp->key[PF_SK_STACK].addr[1];
779                 sks->port[0] = sp->key[PF_SK_STACK].port[0];
780                 sks->port[1] = sp->key[PF_SK_STACK].port[1];
781                 sks->proto = sp->proto;
782                 sks->af = sp->af;
783         }
784
785         /* copy to state */
786         bcopy(&sp->rt_addr, &st->rt_addr, sizeof(st->rt_addr));
787         st->creation = time_uptime - ntohl(sp->creation);
788         st->expire = time_second;
789         if (sp->expire) {
790                 /* XXX No adaptive scaling. */
791                 st->expire -= r->timeout[sp->timeout] - ntohl(sp->expire);
792         }
793
794         st->expire = ntohl(sp->expire) + time_second;
795         st->direction = sp->direction;
796         st->log = sp->log;
797         st->timeout = sp->timeout;
798         st->state_flags = sp->state_flags;
799
800         bcopy(sp->id, &st->id, sizeof(st->id));
801         st->creatorid = sp->creatorid;
802         pf_state_peer_ntoh(&sp->src, &st->src);
803         pf_state_peer_ntoh(&sp->dst, &st->dst);
804
805         st->rule.ptr = r;
806         st->nat_rule.ptr = NULL;
807         st->anchor.ptr = NULL;
808         st->rt_kif = NULL;
809
810         st->pfsync_time = time_uptime;
811         st->sync_state = PFSYNC_S_NONE;
812
813         /* XXX when we have nat_rule/anchors, use STATE_INC_COUNTERS */
814         r->states_cur++;
815         r->states_tot++;
816
817         if (!ISSET(flags, PFSYNC_SI_IOCTL))
818                 SET(st->state_flags, PFSTATE_NOSYNC);
819
820         if ((error = pf_state_insert(kif, skw, sks, st)) != 0) {
821                 /* XXX when we have nat_rule/anchors, use STATE_DEC_COUNTERS */
822                 r->states_cur--;
823                 goto cleanup_state;
824         }
825
826         if (!ISSET(flags, PFSYNC_SI_IOCTL)) {
827                 CLR(st->state_flags, PFSTATE_NOSYNC);
828                 if (ISSET(st->state_flags, PFSTATE_ACK)) {
829                         pfsync_q_ins(st, PFSYNC_S_IACK);
830                         schednetisr(NETISR_PFSYNC);
831                 }
832         }
833         CLR(st->state_flags, PFSTATE_ACK);
834
835         return (0);
836
837 cleanup:
838         error = ENOMEM;
839         if (skw == sks)
840                 sks = NULL;
841 #ifdef __FreeBSD__
842         if (skw != NULL)
843                 pool_put(&V_pf_state_key_pl, skw);
844         if (sks != NULL)
845                 pool_put(&V_pf_state_key_pl, sks);
846 #else
847         if (skw != NULL)
848                 pool_put(&pf_state_key_pl, skw);
849         if (sks != NULL)
850                 pool_put(&pf_state_key_pl, sks);
851 #endif
852
853 cleanup_state:  /* pf_state_insert frees the state keys */
854         if (st) {
855 #ifdef __FreeBSD__
856                 if (st->dst.scrub)
857                         pool_put(&V_pf_state_scrub_pl, st->dst.scrub);
858                 if (st->src.scrub)
859                         pool_put(&V_pf_state_scrub_pl, st->src.scrub);
860                 pool_put(&V_pf_state_pl, st);
861 #else
862                 if (st->dst.scrub)
863                         pool_put(&pf_state_scrub_pl, st->dst.scrub);
864                 if (st->src.scrub)
865                         pool_put(&pf_state_scrub_pl, st->src.scrub);
866                 pool_put(&pf_state_pl, st);
867 #endif
868         }
869         return (error);
870 }
871
872 void
873 #ifdef __FreeBSD__
874 pfsync_input(struct mbuf *m, __unused int off)
875 #else
876 pfsync_input(struct mbuf *m, ...)
877 #endif
878 {
879 #ifdef __FreeBSD__
880         struct pfsync_softc *sc = V_pfsyncif;
881 #else
882         struct pfsync_softc *sc = pfsyncif;
883 #endif
884         struct pfsync_pkt pkt;
885         struct ip *ip = mtod(m, struct ip *);
886         struct pfsync_header *ph;
887         struct pfsync_subheader subh;
888
889         int offset;
890         int rv;
891
892         V_pfsyncstats.pfsyncs_ipackets++;
893
894         /* verify that we have a sync interface configured */
895 #ifdef __FreeBSD__
896         if (!sc || !sc->sc_sync_if || !V_pf_status.running)
897 #else
898         if (!sc || !sc->sc_sync_if || !pf_status.running)
899 #endif
900                 goto done;
901
902         /* verify that the packet came in on the right interface */
903         if (sc->sc_sync_if != m->m_pkthdr.rcvif) {
904                 V_pfsyncstats.pfsyncs_badif++;
905                 goto done;
906         }
907
908 #ifdef __FreeBSD__
909         sc->sc_ifp->if_ipackets++;
910         sc->sc_ifp->if_ibytes += m->m_pkthdr.len;
911 #else
912         sc->sc_if.if_ipackets++;
913         sc->sc_if.if_ibytes += m->m_pkthdr.len;
914 #endif
915         /* verify that the IP TTL is 255. */
916         if (ip->ip_ttl != PFSYNC_DFLTTL) {
917                 V_pfsyncstats.pfsyncs_badttl++;
918                 goto done;
919         }
920
921         offset = ip->ip_hl << 2;
922         if (m->m_pkthdr.len < offset + sizeof(*ph)) {
923                 V_pfsyncstats.pfsyncs_hdrops++;
924                 goto done;
925         }
926
927         if (offset + sizeof(*ph) > m->m_len) {
928                 if (m_pullup(m, offset + sizeof(*ph)) == NULL) {
929                         V_pfsyncstats.pfsyncs_hdrops++;
930                         return;
931                 }
932                 ip = mtod(m, struct ip *);
933         }
934         ph = (struct pfsync_header *)((char *)ip + offset);
935
936         /* verify the version */
937         if (ph->version != PFSYNC_VERSION) {
938                 V_pfsyncstats.pfsyncs_badver++;
939                 goto done;
940         }
941
942 #if 0
943         if (pfsync_input_hmac(m, offset) != 0) {
944                 /* XXX stats */
945                 goto done;
946         }
947 #endif
948
949         /* Cheaper to grab this now than having to mess with mbufs later */
950         pkt.ip = ip;
951         pkt.src = ip->ip_src;
952         pkt.flags = 0;
953
954 #ifdef __FreeBSD__
955         if (!bcmp(&ph->pfcksum, &V_pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
956 #else
957         if (!bcmp(&ph->pfcksum, &pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
958 #endif
959                 pkt.flags |= PFSYNC_SI_CKSUM;
960
961         offset += sizeof(*ph);
962         for (;;) {
963                 m_copydata(m, offset, sizeof(subh), (caddr_t)&subh);
964                 offset += sizeof(subh);
965
966                 if (subh.action >= PFSYNC_ACT_MAX) {
967                         V_pfsyncstats.pfsyncs_badact++;
968                         goto done;
969                 }
970
971                 rv = (*pfsync_acts[subh.action])(&pkt, m, offset,
972                     ntohs(subh.count));
973                 if (rv == -1)
974                         return;
975
976                 offset += rv;
977         }
978
979 done:
980         m_freem(m);
981 }
982
983 int
984 pfsync_in_clr(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
985 {
986         struct pfsync_clr *clr;
987         struct mbuf *mp;
988         int len = sizeof(*clr) * count;
989         int i, offp;
990
991         struct pf_state *st, *nexts;
992         struct pf_state_key *sk, *nextsk;
993         struct pf_state_item *si;
994         u_int32_t creatorid;
995         int s;
996
997         mp = m_pulldown(m, offset, len, &offp);
998         if (mp == NULL) {
999                 V_pfsyncstats.pfsyncs_badlen++;
1000                 return (-1);
1001         }
1002         clr = (struct pfsync_clr *)(mp->m_data + offp);
1003
1004         s = splsoftnet();
1005 #ifdef __FreeBSD__
1006         PF_LOCK();
1007 #endif
1008         for (i = 0; i < count; i++) {
1009                 creatorid = clr[i].creatorid;
1010
1011                 if (clr[i].ifname[0] == '\0') {
1012 #ifdef __FreeBSD__
1013                         for (st = RB_MIN(pf_state_tree_id, &V_tree_id);
1014                             st; st = nexts) {
1015                                 nexts = RB_NEXT(pf_state_tree_id, &V_tree_id, st);
1016 #else
1017                         for (st = RB_MIN(pf_state_tree_id, &tree_id);
1018                             st; st = nexts) {
1019                                 nexts = RB_NEXT(pf_state_tree_id, &tree_id, st);
1020 #endif
1021                                 if (st->creatorid == creatorid) {
1022                                         SET(st->state_flags, PFSTATE_NOSYNC);
1023                                         pf_unlink_state(st);
1024                                 }
1025                         }
1026                 } else {
1027                         if (pfi_kif_get(clr[i].ifname) == NULL)
1028                                 continue;
1029
1030                         /* XXX correct? */
1031 #ifdef __FreeBSD__
1032                         for (sk = RB_MIN(pf_state_tree, &V_pf_statetbl);
1033 #else
1034                         for (sk = RB_MIN(pf_state_tree, &pf_statetbl);
1035 #endif
1036                             sk; sk = nextsk) {
1037                                 nextsk = RB_NEXT(pf_state_tree,
1038 #ifdef __FreeBSD__
1039                                     &V_pf_statetbl, sk);
1040 #else
1041                                     &pf_statetbl, sk);
1042 #endif
1043                                 TAILQ_FOREACH(si, &sk->states, entry) {
1044                                         if (si->s->creatorid == creatorid) {
1045                                                 SET(si->s->state_flags,
1046                                                     PFSTATE_NOSYNC);
1047                                                 pf_unlink_state(si->s);
1048                                         }
1049                                 }
1050                         }
1051                 }
1052         }
1053 #ifdef __FreeBSD__
1054         PF_UNLOCK();
1055 #endif
1056         splx(s);
1057
1058         return (len);
1059 }
1060
1061 int
1062 pfsync_in_ins(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1063 {
1064         struct mbuf *mp;
1065         struct pfsync_state *sa, *sp;
1066         int len = sizeof(*sp) * count;
1067         int i, offp;
1068
1069         int s;
1070
1071         mp = m_pulldown(m, offset, len, &offp);
1072         if (mp == NULL) {
1073                 V_pfsyncstats.pfsyncs_badlen++;
1074                 return (-1);
1075         }
1076         sa = (struct pfsync_state *)(mp->m_data + offp);
1077
1078         s = splsoftnet();
1079 #ifdef __FreeBSD__
1080         PF_LOCK();
1081 #endif
1082         for (i = 0; i < count; i++) {
1083                 sp = &sa[i];
1084
1085                 /* check for invalid values */
1086                 if (sp->timeout >= PFTM_MAX ||
1087                     sp->src.state > PF_TCPS_PROXY_DST ||
1088                     sp->dst.state > PF_TCPS_PROXY_DST ||
1089                     sp->direction > PF_OUT ||
1090                     (sp->af != AF_INET && sp->af != AF_INET6)) {
1091 #ifdef __FreeBSD__
1092                         if (V_pf_status.debug >= PF_DEBUG_MISC) {
1093 #else
1094                         if (pf_status.debug >= PF_DEBUG_MISC) {
1095 #endif
1096                                 printf("pfsync_input: PFSYNC5_ACT_INS: "
1097                                     "invalid value\n");
1098                         }
1099                         V_pfsyncstats.pfsyncs_badval++;
1100                         continue;
1101                 }
1102
1103                 if (pfsync_state_import(sp, pkt->flags) == ENOMEM) {
1104                         /* drop out, but process the rest of the actions */
1105                         break;
1106                 }
1107         }
1108 #ifdef __FreeBSD__
1109         PF_UNLOCK();
1110 #endif
1111         splx(s);
1112
1113         return (len);
1114 }
1115
1116 int
1117 pfsync_in_iack(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1118 {
1119         struct pfsync_ins_ack *ia, *iaa;
1120         struct pf_state_cmp id_key;
1121         struct pf_state *st;
1122
1123         struct mbuf *mp;
1124         int len = count * sizeof(*ia);
1125         int offp, i;
1126         int s;
1127
1128         mp = m_pulldown(m, offset, len, &offp);
1129         if (mp == NULL) {
1130                 V_pfsyncstats.pfsyncs_badlen++;
1131                 return (-1);
1132         }
1133         iaa = (struct pfsync_ins_ack *)(mp->m_data + offp);
1134
1135         s = splsoftnet();
1136 #ifdef __FreeBSD__
1137         PF_LOCK();
1138 #endif
1139         for (i = 0; i < count; i++) {
1140                 ia = &iaa[i];
1141
1142                 bcopy(&ia->id, &id_key.id, sizeof(id_key.id));
1143                 id_key.creatorid = ia->creatorid;
1144
1145                 st = pf_find_state_byid(&id_key);
1146                 if (st == NULL)
1147                         continue;
1148
1149                 if (ISSET(st->state_flags, PFSTATE_ACK))
1150                         pfsync_deferred(st, 0);
1151         }
1152 #ifdef __FreeBSD__
1153         PF_UNLOCK();
1154 #endif
1155         splx(s);
1156         /*
1157          * XXX this is not yet implemented, but we know the size of the
1158          * message so we can skip it.
1159          */
1160
1161         return (count * sizeof(struct pfsync_ins_ack));
1162 }
1163
1164 int
1165 pfsync_upd_tcp(struct pf_state *st, struct pfsync_state_peer *src,
1166     struct pfsync_state_peer *dst)
1167 {
1168         int sfail = 0;
1169
1170         /*
1171          * The state should never go backwards except
1172          * for syn-proxy states.  Neither should the
1173          * sequence window slide backwards.
1174          */
1175         if (st->src.state > src->state &&
1176             (st->src.state < PF_TCPS_PROXY_SRC ||
1177             src->state >= PF_TCPS_PROXY_SRC))
1178                 sfail = 1;
1179         else if (SEQ_GT(st->src.seqlo, ntohl(src->seqlo)))
1180                 sfail = 3;
1181         else if (st->dst.state > dst->state) {
1182                 /* There might still be useful
1183                  * information about the src state here,
1184                  * so import that part of the update,
1185                  * then "fail" so we send the updated
1186                  * state back to the peer who is missing
1187                  * our what we know. */
1188                 pf_state_peer_ntoh(src, &st->src);
1189                 /* XXX do anything with timeouts? */
1190                 sfail = 7;
1191         } else if (st->dst.state >= TCPS_SYN_SENT &&
1192             SEQ_GT(st->dst.seqlo, ntohl(dst->seqlo)))
1193                 sfail = 4;
1194
1195         return (sfail);
1196 }
1197
1198 int
1199 pfsync_in_upd(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1200 {
1201         struct pfsync_state *sa, *sp;
1202         struct pf_state_cmp id_key;
1203         struct pf_state_key *sk;
1204         struct pf_state *st;
1205         int sfail;
1206
1207         struct mbuf *mp;
1208         int len = count * sizeof(*sp);
1209         int offp, i;
1210         int s;
1211
1212         mp = m_pulldown(m, offset, len, &offp);
1213         if (mp == NULL) {
1214                 V_pfsyncstats.pfsyncs_badlen++;
1215                 return (-1);
1216         }
1217         sa = (struct pfsync_state *)(mp->m_data + offp);
1218
1219         s = splsoftnet();
1220 #ifdef __FreeBSD__
1221         PF_LOCK();
1222 #endif
1223         for (i = 0; i < count; i++) {
1224                 sp = &sa[i];
1225
1226                 /* check for invalid values */
1227                 if (sp->timeout >= PFTM_MAX ||
1228                     sp->src.state > PF_TCPS_PROXY_DST ||
1229                     sp->dst.state > PF_TCPS_PROXY_DST) {
1230 #ifdef __FreeBSD__
1231                         if (V_pf_status.debug >= PF_DEBUG_MISC) {
1232 #else
1233                         if (pf_status.debug >= PF_DEBUG_MISC) {
1234 #endif
1235                                 printf("pfsync_input: PFSYNC_ACT_UPD: "
1236                                     "invalid value\n");
1237                         }
1238                         V_pfsyncstats.pfsyncs_badval++;
1239                         continue;
1240                 }
1241
1242                 bcopy(sp->id, &id_key.id, sizeof(id_key.id));
1243                 id_key.creatorid = sp->creatorid;
1244
1245                 st = pf_find_state_byid(&id_key);
1246                 if (st == NULL) {
1247                         /* insert the update */
1248                         if (pfsync_state_import(sp, 0))
1249                                 V_pfsyncstats.pfsyncs_badstate++;
1250                         continue;
1251                 }
1252
1253                 if (ISSET(st->state_flags, PFSTATE_ACK))
1254                         pfsync_deferred(st, 1);
1255
1256                 sk = st->key[PF_SK_WIRE];       /* XXX right one? */
1257                 sfail = 0;
1258                 if (sk->proto == IPPROTO_TCP)
1259                         sfail = pfsync_upd_tcp(st, &sp->src, &sp->dst);
1260                 else {
1261                         /*
1262                          * Non-TCP protocol state machine always go
1263                          * forwards
1264                          */
1265                         if (st->src.state > sp->src.state)
1266                                 sfail = 5;
1267                         else if (st->dst.state > sp->dst.state)
1268                                 sfail = 6;
1269                 }
1270
1271                 if (sfail) {
1272 #ifdef __FreeBSD__
1273                         if (V_pf_status.debug >= PF_DEBUG_MISC) {
1274 #else
1275                         if (pf_status.debug >= PF_DEBUG_MISC) {
1276 #endif
1277                                 printf("pfsync: %s stale update (%d)"
1278                                     " id: %016llx creatorid: %08x\n",
1279                                     (sfail < 7 ?  "ignoring" : "partial"),
1280                                     sfail, betoh64(st->id),
1281                                     ntohl(st->creatorid));
1282                         }
1283                         V_pfsyncstats.pfsyncs_stale++;
1284
1285                         pfsync_update_state(st);
1286                         schednetisr(NETISR_PFSYNC);
1287                         continue;
1288                 }
1289                 pfsync_alloc_scrub_memory(&sp->dst, &st->dst);
1290                 pf_state_peer_ntoh(&sp->src, &st->src);
1291                 pf_state_peer_ntoh(&sp->dst, &st->dst);
1292                 st->expire = ntohl(sp->expire) + time_second;
1293                 st->timeout = sp->timeout;
1294                 st->pfsync_time = time_uptime;
1295         }
1296 #ifdef __FreeBSD__
1297         PF_UNLOCK();
1298 #endif
1299         splx(s);
1300
1301         return (len);
1302 }
1303
1304 int
1305 pfsync_in_upd_c(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1306 {
1307         struct pfsync_upd_c *ua, *up;
1308         struct pf_state_key *sk;
1309         struct pf_state_cmp id_key;
1310         struct pf_state *st;
1311
1312         int len = count * sizeof(*up);
1313         int sfail;
1314
1315         struct mbuf *mp;
1316         int offp, i;
1317         int s;
1318
1319         mp = m_pulldown(m, offset, len, &offp);
1320         if (mp == NULL) {
1321                 V_pfsyncstats.pfsyncs_badlen++;
1322                 return (-1);
1323         }
1324         ua = (struct pfsync_upd_c *)(mp->m_data + offp);
1325
1326         s = splsoftnet();
1327 #ifdef __FreeBSD__
1328         PF_LOCK();
1329 #endif
1330         for (i = 0; i < count; i++) {
1331                 up = &ua[i];
1332
1333                 /* check for invalid values */
1334                 if (up->timeout >= PFTM_MAX ||
1335                     up->src.state > PF_TCPS_PROXY_DST ||
1336                     up->dst.state > PF_TCPS_PROXY_DST) {
1337 #ifdef __FreeBSD__
1338                         if (V_pf_status.debug >= PF_DEBUG_MISC) {
1339 #else
1340                         if (pf_status.debug >= PF_DEBUG_MISC) {
1341 #endif
1342                                 printf("pfsync_input: "
1343                                     "PFSYNC_ACT_UPD_C: "
1344                                     "invalid value\n");
1345                         }
1346                         V_pfsyncstats.pfsyncs_badval++;
1347                         continue;
1348                 }
1349
1350                 bcopy(&up->id, &id_key.id, sizeof(id_key.id));
1351                 id_key.creatorid = up->creatorid;
1352
1353                 st = pf_find_state_byid(&id_key);
1354                 if (st == NULL) {
1355                         /* We don't have this state. Ask for it. */
1356                         pfsync_request_update(id_key.creatorid, id_key.id);
1357                         continue;
1358                 }
1359
1360                 if (ISSET(st->state_flags, PFSTATE_ACK))
1361                         pfsync_deferred(st, 1);
1362
1363                 sk = st->key[PF_SK_WIRE]; /* XXX right one? */
1364                 sfail = 0;
1365                 if (sk->proto == IPPROTO_TCP)
1366                         sfail = pfsync_upd_tcp(st, &up->src, &up->dst);
1367                 else {
1368                         /*
1369                          * Non-TCP protocol state machine always go forwards
1370                          */
1371                         if (st->src.state > up->src.state)
1372                                 sfail = 5;
1373                         else if (st->dst.state > up->dst.state)
1374                                 sfail = 6;
1375                 }
1376
1377                 if (sfail) {
1378 #ifdef __FreeBSD__
1379                         if (V_pf_status.debug >= PF_DEBUG_MISC) {
1380 #else
1381                         if (pf_status.debug >= PF_DEBUG_MISC) {
1382 #endif
1383                                 printf("pfsync: ignoring stale update "
1384                                     "(%d) id: %016llx "
1385                                     "creatorid: %08x\n", sfail,
1386                                     betoh64(st->id),
1387                                     ntohl(st->creatorid));
1388                         }
1389                         V_pfsyncstats.pfsyncs_stale++;
1390
1391                         pfsync_update_state(st);
1392                         schednetisr(NETISR_PFSYNC);
1393                         continue;
1394                 }
1395                 pfsync_alloc_scrub_memory(&up->dst, &st->dst);
1396                 pf_state_peer_ntoh(&up->src, &st->src);
1397                 pf_state_peer_ntoh(&up->dst, &st->dst);
1398                 st->expire = ntohl(up->expire) + time_second;
1399                 st->timeout = up->timeout;
1400                 st->pfsync_time = time_uptime;
1401         }
1402 #ifdef __FreeBSD__
1403         PF_UNLOCK();
1404 #endif
1405         splx(s);
1406
1407         return (len);
1408 }
1409
1410 int
1411 pfsync_in_ureq(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1412 {
1413         struct pfsync_upd_req *ur, *ura;
1414         struct mbuf *mp;
1415         int len = count * sizeof(*ur);
1416         int i, offp;
1417
1418         struct pf_state_cmp id_key;
1419         struct pf_state *st;
1420
1421         mp = m_pulldown(m, offset, len, &offp);
1422         if (mp == NULL) {
1423                 V_pfsyncstats.pfsyncs_badlen++;
1424                 return (-1);
1425         }
1426         ura = (struct pfsync_upd_req *)(mp->m_data + offp);
1427
1428 #ifdef __FreeBSD__
1429         PF_LOCK();
1430 #endif
1431         for (i = 0; i < count; i++) {
1432                 ur = &ura[i];
1433
1434                 bcopy(&ur->id, &id_key.id, sizeof(id_key.id));
1435                 id_key.creatorid = ur->creatorid;
1436
1437                 if (id_key.id == 0 && id_key.creatorid == 0)
1438                         pfsync_bulk_start();
1439                 else {
1440                         st = pf_find_state_byid(&id_key);
1441                         if (st == NULL) {
1442                                 V_pfsyncstats.pfsyncs_badstate++;
1443                                 continue;
1444                         }
1445                         if (ISSET(st->state_flags, PFSTATE_NOSYNC))
1446                                 continue;
1447
1448                         pfsync_update_state_req(st);
1449                 }
1450         }
1451 #ifdef __FreeBSD__
1452         PF_UNLOCK();
1453 #endif
1454
1455         return (len);
1456 }
1457
1458 int
1459 pfsync_in_del(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1460 {
1461         struct mbuf *mp;
1462         struct pfsync_state *sa, *sp;
1463         struct pf_state_cmp id_key;
1464         struct pf_state *st;
1465         int len = count * sizeof(*sp);
1466         int offp, i;
1467         int s;
1468
1469         mp = m_pulldown(m, offset, len, &offp);
1470         if (mp == NULL) {
1471                 V_pfsyncstats.pfsyncs_badlen++;
1472                 return (-1);
1473         }
1474         sa = (struct pfsync_state *)(mp->m_data + offp);
1475
1476         s = splsoftnet();
1477 #ifdef __FreeBSD__
1478         PF_LOCK();
1479 #endif
1480         for (i = 0; i < count; i++) {
1481                 sp = &sa[i];
1482
1483                 bcopy(sp->id, &id_key.id, sizeof(id_key.id));
1484                 id_key.creatorid = sp->creatorid;
1485
1486                 st = pf_find_state_byid(&id_key);
1487                 if (st == NULL) {
1488                         V_pfsyncstats.pfsyncs_badstate++;
1489                         continue;
1490                 }
1491                 SET(st->state_flags, PFSTATE_NOSYNC);
1492                 pf_unlink_state(st);
1493         }
1494 #ifdef __FreeBSD__
1495         PF_UNLOCK();
1496 #endif
1497         splx(s);
1498
1499         return (len);
1500 }
1501
1502 int
1503 pfsync_in_del_c(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1504 {
1505         struct mbuf *mp;
1506         struct pfsync_del_c *sa, *sp;
1507         struct pf_state_cmp id_key;
1508         struct pf_state *st;
1509         int len = count * sizeof(*sp);
1510         int offp, i;
1511         int s;
1512
1513         mp = m_pulldown(m, offset, len, &offp);
1514         if (mp == NULL) {
1515                 V_pfsyncstats.pfsyncs_badlen++;
1516                 return (-1);
1517         }
1518         sa = (struct pfsync_del_c *)(mp->m_data + offp);
1519
1520         s = splsoftnet();
1521 #ifdef __FreeBSD__
1522         PF_LOCK();
1523 #endif
1524         for (i = 0; i < count; i++) {
1525                 sp = &sa[i];
1526
1527                 bcopy(&sp->id, &id_key.id, sizeof(id_key.id));
1528                 id_key.creatorid = sp->creatorid;
1529
1530                 st = pf_find_state_byid(&id_key);
1531                 if (st == NULL) {
1532                         V_pfsyncstats.pfsyncs_badstate++;
1533                         continue;
1534                 }
1535
1536                 SET(st->state_flags, PFSTATE_NOSYNC);
1537                 pf_unlink_state(st);
1538         }
1539 #ifdef __FreeBSD__
1540         PF_UNLOCK();
1541 #endif
1542         splx(s);
1543
1544         return (len);
1545 }
1546
1547 int
1548 pfsync_in_bus(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1549 {
1550 #ifdef __FreeBSD__
1551         struct pfsync_softc *sc = V_pfsyncif;
1552 #else
1553         struct pfsync_softc *sc = pfsyncif;
1554 #endif
1555         struct pfsync_bus *bus;
1556         struct mbuf *mp;
1557         int len = count * sizeof(*bus);
1558         int offp;
1559
1560         /* If we're not waiting for a bulk update, who cares. */
1561         if (sc->sc_ureq_sent == 0)
1562                 return (len);
1563
1564         mp = m_pulldown(m, offset, len, &offp);
1565         if (mp == NULL) {
1566                 V_pfsyncstats.pfsyncs_badlen++;
1567                 return (-1);
1568         }
1569         bus = (struct pfsync_bus *)(mp->m_data + offp);
1570
1571         switch (bus->status) {
1572         case PFSYNC_BUS_START:
1573 #ifdef __FreeBSD__
1574                 callout_reset(&sc->sc_bulkfail_tmo, 4 * hz +
1575                     V_pf_pool_limits[PF_LIMIT_STATES].limit /
1576                     ((sc->sc_ifp->if_mtu - PFSYNC_MINPKT) /
1577                     sizeof(struct pfsync_state)),
1578                     pfsync_bulk_fail, V_pfsyncif);
1579 #else
1580                 timeout_add(&sc->sc_bulkfail_tmo, 4 * hz +
1581                     pf_pool_limits[PF_LIMIT_STATES].limit /
1582                     ((sc->sc_if.if_mtu - PFSYNC_MINPKT) /
1583                     sizeof(struct pfsync_state)));
1584 #endif
1585 #ifdef __FreeBSD__
1586                 if (V_pf_status.debug >= PF_DEBUG_MISC)
1587 #else
1588                 if (pf_status.debug >= PF_DEBUG_MISC)
1589 #endif
1590                         printf("pfsync: received bulk update start\n");
1591                 break;
1592
1593         case PFSYNC_BUS_END:
1594                 if (time_uptime - ntohl(bus->endtime) >=
1595                     sc->sc_ureq_sent) {
1596                         /* that's it, we're happy */
1597                         sc->sc_ureq_sent = 0;
1598                         sc->sc_bulk_tries = 0;
1599                         timeout_del(&sc->sc_bulkfail_tmo);
1600 #ifdef __FreeBSD__
1601                         if (!sc->pfsync_sync_ok && carp_demote_adj_p)
1602                                 (*carp_demote_adj_p)(-V_pfsync_carp_adj,
1603                                     "pfsync bulk done");
1604                         sc->pfsync_sync_ok = 1;
1605 #else
1606 #if NCARP > 0
1607                         if (!pfsync_sync_ok)
1608                                 carp_group_demote_adj(&sc->sc_if, -1);
1609 #endif
1610                         pfsync_sync_ok = 1;
1611 #endif
1612 #ifdef __FreeBSD__
1613                         if (V_pf_status.debug >= PF_DEBUG_MISC)
1614 #else
1615                         if (pf_status.debug >= PF_DEBUG_MISC)
1616 #endif
1617                                 printf("pfsync: received valid "
1618                                     "bulk update end\n");
1619                 } else {
1620 #ifdef __FreeBSD__
1621                         if (V_pf_status.debug >= PF_DEBUG_MISC)
1622 #else
1623                         if (pf_status.debug >= PF_DEBUG_MISC)
1624 #endif
1625                                 printf("pfsync: received invalid "
1626                                     "bulk update end: bad timestamp\n");
1627                 }
1628                 break;
1629         }
1630
1631         return (len);
1632 }
1633
1634 int
1635 pfsync_in_tdb(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1636 {
1637         int len = count * sizeof(struct pfsync_tdb);
1638
1639 #if defined(IPSEC)
1640         struct pfsync_tdb *tp;
1641         struct mbuf *mp;
1642         int offp;
1643         int i;
1644         int s;
1645
1646         mp = m_pulldown(m, offset, len, &offp);
1647         if (mp == NULL) {
1648                 V_pfsyncstats.pfsyncs_badlen++;
1649                 return (-1);
1650         }
1651         tp = (struct pfsync_tdb *)(mp->m_data + offp);
1652
1653         s = splsoftnet();
1654 #ifdef __FreeBSD__
1655         PF_LOCK();
1656 #endif
1657         for (i = 0; i < count; i++)
1658                 pfsync_update_net_tdb(&tp[i]);
1659 #ifdef __FreeBSD__
1660         PF_UNLOCK();
1661 #endif
1662         splx(s);
1663 #endif
1664
1665         return (len);
1666 }
1667
1668 #if defined(IPSEC)
1669 /* Update an in-kernel tdb. Silently fail if no tdb is found. */
1670 void
1671 pfsync_update_net_tdb(struct pfsync_tdb *pt)
1672 {
1673         struct tdb              *tdb;
1674         int                      s;
1675
1676         /* check for invalid values */
1677         if (ntohl(pt->spi) <= SPI_RESERVED_MAX ||
1678             (pt->dst.sa.sa_family != AF_INET &&
1679              pt->dst.sa.sa_family != AF_INET6))
1680                 goto bad;
1681
1682         s = spltdb();
1683         tdb = gettdb(pt->spi, &pt->dst, pt->sproto);
1684         if (tdb) {
1685                 pt->rpl = ntohl(pt->rpl);
1686                 pt->cur_bytes = betoh64(pt->cur_bytes);
1687
1688                 /* Neither replay nor byte counter should ever decrease. */
1689                 if (pt->rpl < tdb->tdb_rpl ||
1690                     pt->cur_bytes < tdb->tdb_cur_bytes) {
1691                         splx(s);
1692                         goto bad;
1693                 }
1694
1695                 tdb->tdb_rpl = pt->rpl;
1696                 tdb->tdb_cur_bytes = pt->cur_bytes;
1697         }
1698         splx(s);
1699         return;
1700
1701 bad:
1702 #ifdef __FreeBSD__
1703         if (V_pf_status.debug >= PF_DEBUG_MISC)
1704 #else
1705         if (pf_status.debug >= PF_DEBUG_MISC)
1706 #endif
1707                 printf("pfsync_insert: PFSYNC_ACT_TDB_UPD: "
1708                     "invalid value\n");
1709         V_pfsyncstats.pfsyncs_badstate++;
1710         return;
1711 }
1712 #endif
1713
1714
1715 int
1716 pfsync_in_eof(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1717 {
1718         /* check if we are at the right place in the packet */
1719         if (offset != m->m_pkthdr.len - sizeof(struct pfsync_eof))
1720                 V_pfsyncstats.pfsyncs_badact++;
1721
1722         /* we're done. free and let the caller return */
1723         m_freem(m);
1724         return (-1);
1725 }
1726
1727 int
1728 pfsync_in_error(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1729 {
1730         V_pfsyncstats.pfsyncs_badact++;
1731
1732         m_freem(m);
1733         return (-1);
1734 }
1735
1736 int
1737 pfsyncoutput(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst,
1738 #ifdef __FreeBSD__
1739         struct route *rt)
1740 #else
1741         struct rtentry *rt)
1742 #endif
1743 {
1744         m_freem(m);
1745         return (0);
1746 }
1747
1748 /* ARGSUSED */
1749 int
1750 pfsyncioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1751 {
1752 #ifndef __FreeBSD__
1753         struct proc *p = curproc;
1754 #endif
1755         struct pfsync_softc *sc = ifp->if_softc;
1756         struct ifreq *ifr = (struct ifreq *)data;
1757         struct ip_moptions *imo = &sc->sc_imo;
1758         struct pfsyncreq pfsyncr;
1759         struct ifnet    *sifp;
1760         struct ip *ip;
1761         int s, error;
1762
1763         switch (cmd) {
1764 #if 0
1765         case SIOCSIFADDR:
1766         case SIOCAIFADDR:
1767         case SIOCSIFDSTADDR:
1768 #endif
1769         case SIOCSIFFLAGS:
1770 #ifdef __FreeBSD__
1771                 if (ifp->if_flags & IFF_UP)
1772                         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1773                 else
1774                         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1775 #else
1776                 if (ifp->if_flags & IFF_UP)
1777                         ifp->if_flags |= IFF_RUNNING;
1778                 else
1779                         ifp->if_flags &= ~IFF_RUNNING;
1780 #endif
1781                 break;
1782         case SIOCSIFMTU:
1783                 if (!sc->sc_sync_if ||
1784                     ifr->ifr_mtu <= PFSYNC_MINPKT ||
1785                     ifr->ifr_mtu > sc->sc_sync_if->if_mtu)
1786                         return (EINVAL);
1787                 if (ifr->ifr_mtu < ifp->if_mtu) {
1788                         s = splnet();
1789 #ifdef __FreeBSD__
1790                         PF_LOCK();
1791 #endif
1792                         pfsync_sendout();
1793 #ifdef __FreeBSD__
1794                         PF_UNLOCK();
1795 #endif
1796                         splx(s);
1797                 }
1798                 ifp->if_mtu = ifr->ifr_mtu;
1799                 break;
1800         case SIOCGETPFSYNC:
1801                 bzero(&pfsyncr, sizeof(pfsyncr));
1802                 if (sc->sc_sync_if) {
1803                         strlcpy(pfsyncr.pfsyncr_syncdev,
1804                             sc->sc_sync_if->if_xname, IFNAMSIZ);
1805                 }
1806                 pfsyncr.pfsyncr_syncpeer = sc->sc_sync_peer;
1807                 pfsyncr.pfsyncr_maxupdates = sc->sc_maxupdates;
1808                 return (copyout(&pfsyncr, ifr->ifr_data, sizeof(pfsyncr)));
1809
1810         case SIOCSETPFSYNC:
1811 #ifdef __FreeBSD__
1812                 if ((error = priv_check(curthread, PRIV_NETINET_PF)) != 0)
1813 #else
1814                 if ((error = suser(p, p->p_acflag)) != 0)
1815 #endif
1816                         return (error);
1817                 if ((error = copyin(ifr->ifr_data, &pfsyncr, sizeof(pfsyncr))))
1818                         return (error);
1819
1820 #ifdef __FreeBSD__
1821                 PF_LOCK();
1822 #endif
1823                 if (pfsyncr.pfsyncr_syncpeer.s_addr == 0)
1824 #ifdef __FreeBSD__
1825                         sc->sc_sync_peer.s_addr = htonl(INADDR_PFSYNC_GROUP);
1826 #else
1827                         sc->sc_sync_peer.s_addr = INADDR_PFSYNC_GROUP;
1828 #endif
1829                 else
1830                         sc->sc_sync_peer.s_addr =
1831                             pfsyncr.pfsyncr_syncpeer.s_addr;
1832
1833                 if (pfsyncr.pfsyncr_maxupdates > 255)
1834 #ifdef __FreeBSD__
1835                 {
1836                         PF_UNLOCK();
1837 #endif
1838                         return (EINVAL);
1839 #ifdef __FreeBSD__
1840                 }
1841 #endif
1842                 sc->sc_maxupdates = pfsyncr.pfsyncr_maxupdates;
1843
1844                 if (pfsyncr.pfsyncr_syncdev[0] == 0) {
1845                         sc->sc_sync_if = NULL;
1846 #ifdef __FreeBSD__
1847                         PF_UNLOCK();
1848                         if (imo->imo_membership)
1849                                 pfsync_multicast_cleanup(sc);
1850 #else
1851                         if (imo->imo_num_memberships > 0) {
1852                                 in_delmulti(imo->imo_membership[
1853                                     --imo->imo_num_memberships]);
1854                                 imo->imo_multicast_ifp = NULL;
1855                         }
1856 #endif
1857                         break;
1858                 }
1859
1860 #ifdef __FreeBSD__
1861                 PF_UNLOCK();
1862 #endif
1863                 if ((sifp = ifunit(pfsyncr.pfsyncr_syncdev)) == NULL)
1864                         return (EINVAL);
1865
1866 #ifdef __FreeBSD__
1867                 PF_LOCK();
1868 #endif
1869                 s = splnet();
1870 #ifdef __FreeBSD__
1871                 if (sifp->if_mtu < sc->sc_ifp->if_mtu ||
1872 #else
1873                 if (sifp->if_mtu < sc->sc_if.if_mtu ||
1874 #endif
1875                     (sc->sc_sync_if != NULL &&
1876                     sifp->if_mtu < sc->sc_sync_if->if_mtu) ||
1877                     sifp->if_mtu < MCLBYTES - sizeof(struct ip))
1878                         pfsync_sendout();
1879                 sc->sc_sync_if = sifp;
1880
1881 #ifdef __FreeBSD__
1882                 if (imo->imo_membership) {
1883                         PF_UNLOCK();
1884                         pfsync_multicast_cleanup(sc);
1885                         PF_LOCK();
1886                 }
1887 #else
1888                 if (imo->imo_num_memberships > 0) {
1889                         in_delmulti(imo->imo_membership[--imo->imo_num_memberships]);
1890                         imo->imo_multicast_ifp = NULL;
1891                 }
1892 #endif
1893
1894 #ifdef __FreeBSD__
1895                 if (sc->sc_sync_if &&
1896                     sc->sc_sync_peer.s_addr == htonl(INADDR_PFSYNC_GROUP)) {
1897                         PF_UNLOCK();
1898                         error = pfsync_multicast_setup(sc);
1899                         if (error)
1900                                 return (error);
1901                         PF_LOCK();
1902                 }
1903 #else
1904                 if (sc->sc_sync_if &&
1905                     sc->sc_sync_peer.s_addr == INADDR_PFSYNC_GROUP) {
1906                         struct in_addr addr;
1907
1908                         if (!(sc->sc_sync_if->if_flags & IFF_MULTICAST)) {
1909                                 sc->sc_sync_if = NULL;
1910                                 splx(s);
1911                                 return (EADDRNOTAVAIL);
1912                         }
1913
1914                         addr.s_addr = INADDR_PFSYNC_GROUP;
1915
1916                         if ((imo->imo_membership[0] =
1917                             in_addmulti(&addr, sc->sc_sync_if)) == NULL) {
1918                                 sc->sc_sync_if = NULL;
1919                                 splx(s);
1920                                 return (ENOBUFS);
1921                         }
1922                         imo->imo_num_memberships++;
1923                         imo->imo_multicast_ifp = sc->sc_sync_if;
1924                         imo->imo_multicast_ttl = PFSYNC_DFLTTL;
1925                         imo->imo_multicast_loop = 0;
1926                 }
1927 #endif  /* !__FreeBSD__ */
1928
1929                 ip = &sc->sc_template;
1930                 bzero(ip, sizeof(*ip));
1931                 ip->ip_v = IPVERSION;
1932                 ip->ip_hl = sizeof(sc->sc_template) >> 2;
1933                 ip->ip_tos = IPTOS_LOWDELAY;
1934                 /* len and id are set later */
1935 #ifdef __FreeBSD__
1936                 ip->ip_off = IP_DF;
1937 #else
1938                 ip->ip_off = htons(IP_DF);
1939 #endif
1940                 ip->ip_ttl = PFSYNC_DFLTTL;
1941                 ip->ip_p = IPPROTO_PFSYNC;
1942                 ip->ip_src.s_addr = INADDR_ANY;
1943                 ip->ip_dst.s_addr = sc->sc_sync_peer.s_addr;
1944
1945                 if (sc->sc_sync_if) {
1946                         /* Request a full state table update. */
1947                         sc->sc_ureq_sent = time_uptime;
1948 #ifdef __FreeBSD__
1949                         if (sc->pfsync_sync_ok && carp_demote_adj_p)
1950                                 (*carp_demote_adj_p)(V_pfsync_carp_adj,
1951                                     "pfsync bulk start");
1952                         sc->pfsync_sync_ok = 0;
1953 #else
1954 #if NCARP > 0
1955                         if (pfsync_sync_ok)
1956                                 carp_group_demote_adj(&sc->sc_if, 1);
1957 #endif
1958                         pfsync_sync_ok = 0;
1959 #endif
1960 #ifdef __FreeBSD__
1961                         if (V_pf_status.debug >= PF_DEBUG_MISC)
1962 #else
1963                         if (pf_status.debug >= PF_DEBUG_MISC)
1964 #endif
1965                                 printf("pfsync: requesting bulk update\n");
1966 #ifdef __FreeBSD__
1967                         callout_reset(&sc->sc_bulkfail_tmo, 5 * hz,
1968                             pfsync_bulk_fail, V_pfsyncif);
1969 #else
1970                         timeout_add_sec(&sc->sc_bulkfail_tmo, 5);
1971 #endif
1972                         pfsync_request_update(0, 0);
1973                 }
1974 #ifdef __FreeBSD__
1975                 PF_UNLOCK();
1976 #endif
1977                 splx(s);
1978
1979                 break;
1980
1981         default:
1982                 return (ENOTTY);
1983         }
1984
1985         return (0);
1986 }
1987
1988 int
1989 pfsync_out_state(struct pf_state *st, struct mbuf *m, int offset)
1990 {
1991         struct pfsync_state *sp = (struct pfsync_state *)(m->m_data + offset);
1992
1993         pfsync_state_export(sp, st);
1994
1995         return (sizeof(*sp));
1996 }
1997
1998 int
1999 pfsync_out_iack(struct pf_state *st, struct mbuf *m, int offset)
2000 {
2001         struct pfsync_ins_ack *iack =
2002             (struct pfsync_ins_ack *)(m->m_data + offset);
2003
2004         iack->id = st->id;
2005         iack->creatorid = st->creatorid;
2006
2007         return (sizeof(*iack));
2008 }
2009
2010 int
2011 pfsync_out_upd_c(struct pf_state *st, struct mbuf *m, int offset)
2012 {
2013         struct pfsync_upd_c *up = (struct pfsync_upd_c *)(m->m_data + offset);
2014
2015         bzero(up, sizeof(*up));
2016         up->id = st->id;
2017         pf_state_peer_hton(&st->src, &up->src);
2018         pf_state_peer_hton(&st->dst, &up->dst);
2019         up->creatorid = st->creatorid;
2020
2021         up->expire = pf_state_expires(st);
2022         if (up->expire <= time_second)
2023                 up->expire = htonl(0);
2024         else
2025                 up->expire = htonl(up->expire - time_second);
2026         up->timeout = st->timeout;
2027
2028         return (sizeof(*up));
2029 }
2030
2031 int
2032 pfsync_out_del(struct pf_state *st, struct mbuf *m, int offset)
2033 {
2034         struct pfsync_del_c *dp = (struct pfsync_del_c *)(m->m_data + offset);
2035
2036         dp->id = st->id;
2037         dp->creatorid = st->creatorid;
2038
2039         SET(st->state_flags, PFSTATE_NOSYNC);
2040
2041         return (sizeof(*dp));
2042 }
2043
2044 void
2045 pfsync_drop(struct pfsync_softc *sc)
2046 {
2047         struct pf_state *st;
2048         struct pfsync_upd_req_item *ur;
2049 #ifdef notyet
2050         struct tdb *t;
2051 #endif
2052         int q;
2053
2054         for (q = 0; q < PFSYNC_S_COUNT; q++) {
2055                 if (TAILQ_EMPTY(&sc->sc_qs[q]))
2056                         continue;
2057
2058                 TAILQ_FOREACH(st, &sc->sc_qs[q], sync_list) {
2059 #ifdef PFSYNC_DEBUG
2060 #ifdef __FreeBSD__
2061                         KASSERT(st->sync_state == q,
2062                                 ("%s: st->sync_state == q",
2063                                         __FUNCTION__));
2064 #else
2065                         KASSERT(st->sync_state == q);
2066 #endif
2067 #endif
2068                         st->sync_state = PFSYNC_S_NONE;
2069                 }
2070                 TAILQ_INIT(&sc->sc_qs[q]);
2071         }
2072
2073         while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
2074                 TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
2075                 pool_put(&sc->sc_pool, ur);
2076         }
2077
2078         sc->sc_plus = NULL;
2079
2080 #ifdef notyet
2081         if (!TAILQ_EMPTY(&sc->sc_tdb_q)) {
2082                 TAILQ_FOREACH(t, &sc->sc_tdb_q, tdb_sync_entry)
2083                         CLR(t->tdb_flags, TDBF_PFSYNC);
2084
2085                 TAILQ_INIT(&sc->sc_tdb_q);
2086         }
2087 #endif
2088
2089         sc->sc_len = PFSYNC_MINPKT;
2090 }
2091
2092 #ifdef __FreeBSD__
2093 void pfsync_sendout()
2094 {
2095         pfsync_sendout1(1);
2096 }
2097
2098 static void
2099 pfsync_sendout1(int schedswi)
2100 {
2101         struct pfsync_softc *sc = V_pfsyncif;
2102 #else
2103 void
2104 pfsync_sendout(void)
2105 {
2106         struct pfsync_softc *sc = pfsyncif;
2107 #endif
2108 #if NBPFILTER > 0
2109 #ifdef __FreeBSD__
2110         struct ifnet *ifp = sc->sc_ifp;
2111 #else
2112         struct ifnet *ifp = &sc->sc_if;
2113 #endif
2114 #endif
2115         struct mbuf *m;
2116         struct ip *ip;
2117         struct pfsync_header *ph;
2118         struct pfsync_subheader *subh;
2119         struct pf_state *st;
2120         struct pfsync_upd_req_item *ur;
2121 #ifdef notyet
2122         struct tdb *t;
2123 #endif
2124         int offset;
2125         int q, count = 0;
2126
2127 #ifdef __FreeBSD__
2128         PF_LOCK_ASSERT();
2129 #else
2130         splassert(IPL_NET);
2131 #endif
2132
2133         if (sc == NULL || sc->sc_len == PFSYNC_MINPKT)
2134                 return;
2135
2136 #if NBPFILTER > 0
2137         if (ifp->if_bpf == NULL && sc->sc_sync_if == NULL) {
2138 #else
2139         if (sc->sc_sync_if == NULL) {
2140 #endif
2141                 pfsync_drop(sc);
2142                 return;
2143         }
2144
2145 #ifdef __FreeBSD__
2146         m = m_get2(M_NOWAIT, MT_DATA, M_PKTHDR, max_linkhdr + sc->sc_len);
2147         if (m == NULL) {
2148                 sc->sc_ifp->if_oerrors++;
2149                 V_pfsyncstats.pfsyncs_onomem++;
2150                 return;
2151         }
2152 #else
2153         MGETHDR(m, M_DONTWAIT, MT_DATA);
2154         if (m == NULL) {
2155                 sc->sc_if.if_oerrors++;
2156                 pfsyncstats.pfsyncs_onomem++;
2157                 pfsync_drop(sc);
2158                 return;
2159         }
2160
2161         if (max_linkhdr + sc->sc_len > MHLEN) {
2162                 MCLGETI(m, M_DONTWAIT, NULL, max_linkhdr + sc->sc_len);
2163                 if (!ISSET(m->m_flags, M_EXT)) {
2164                         m_free(m);
2165                         sc->sc_if.if_oerrors++;
2166                         pfsyncstats.pfsyncs_onomem++;
2167                         pfsync_drop(sc);
2168                         return;
2169                 }
2170         }
2171 #endif
2172         m->m_data += max_linkhdr;
2173         m->m_len = m->m_pkthdr.len = sc->sc_len;
2174
2175         /* build the ip header */
2176         ip = (struct ip *)m->m_data;
2177         bcopy(&sc->sc_template, ip, sizeof(*ip));
2178         offset = sizeof(*ip);
2179
2180 #ifdef __FreeBSD__
2181         ip->ip_len = m->m_pkthdr.len;
2182 #else
2183         ip->ip_len = htons(m->m_pkthdr.len);
2184 #endif
2185         ip->ip_id = htons(ip_randomid());
2186
2187         /* build the pfsync header */
2188         ph = (struct pfsync_header *)(m->m_data + offset);
2189         bzero(ph, sizeof(*ph));
2190         offset += sizeof(*ph);
2191
2192         ph->version = PFSYNC_VERSION;
2193         ph->len = htons(sc->sc_len - sizeof(*ip));
2194 #ifdef __FreeBSD__
2195         bcopy(V_pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
2196 #else
2197         bcopy(pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
2198 #endif
2199
2200         /* walk the queues */
2201         for (q = 0; q < PFSYNC_S_COUNT; q++) {
2202                 if (TAILQ_EMPTY(&sc->sc_qs[q]))
2203                         continue;
2204
2205                 subh = (struct pfsync_subheader *)(m->m_data + offset);
2206                 offset += sizeof(*subh);
2207
2208                 count = 0;
2209                 TAILQ_FOREACH(st, &sc->sc_qs[q], sync_list) {
2210 #ifdef PFSYNC_DEBUG
2211 #ifdef __FreeBSD__
2212                         KASSERT(st->sync_state == q,
2213                                 ("%s: st->sync_state == q",
2214                                         __FUNCTION__));
2215 #else
2216                         KASSERT(st->sync_state == q);
2217 #endif
2218 #endif
2219
2220                         offset += pfsync_qs[q].write(st, m, offset);
2221                         st->sync_state = PFSYNC_S_NONE;
2222                         count++;
2223                 }
2224                 TAILQ_INIT(&sc->sc_qs[q]);
2225
2226                 bzero(subh, sizeof(*subh));
2227                 subh->action = pfsync_qs[q].action;
2228                 subh->count = htons(count);
2229         }
2230
2231         if (!TAILQ_EMPTY(&sc->sc_upd_req_list)) {
2232                 subh = (struct pfsync_subheader *)(m->m_data + offset);
2233                 offset += sizeof(*subh);
2234
2235                 count = 0;
2236                 while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
2237                         TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
2238
2239                         bcopy(&ur->ur_msg, m->m_data + offset,
2240                             sizeof(ur->ur_msg));
2241                         offset += sizeof(ur->ur_msg);
2242
2243                         pool_put(&sc->sc_pool, ur);
2244
2245                         count++;
2246                 }
2247
2248                 bzero(subh, sizeof(*subh));
2249                 subh->action = PFSYNC_ACT_UPD_REQ;
2250                 subh->count = htons(count);
2251         }
2252
2253         /* has someone built a custom region for us to add? */
2254         if (sc->sc_plus != NULL) {
2255                 bcopy(sc->sc_plus, m->m_data + offset, sc->sc_pluslen);
2256                 offset += sc->sc_pluslen;
2257
2258                 sc->sc_plus = NULL;
2259         }
2260
2261 #ifdef notyet
2262         if (!TAILQ_EMPTY(&sc->sc_tdb_q)) {
2263                 subh = (struct pfsync_subheader *)(m->m_data + offset);
2264                 offset += sizeof(*subh);
2265
2266                 count = 0;
2267                 TAILQ_FOREACH(t, &sc->sc_tdb_q, tdb_sync_entry) {
2268                         offset += pfsync_out_tdb(t, m, offset);
2269                         CLR(t->tdb_flags, TDBF_PFSYNC);
2270
2271                         count++;
2272                 }
2273                 TAILQ_INIT(&sc->sc_tdb_q);
2274
2275                 bzero(subh, sizeof(*subh));
2276                 subh->action = PFSYNC_ACT_TDB;
2277                 subh->count = htons(count);
2278         }
2279 #endif
2280
2281         subh = (struct pfsync_subheader *)(m->m_data + offset);
2282         offset += sizeof(*subh);
2283
2284         bzero(subh, sizeof(*subh));
2285         subh->action = PFSYNC_ACT_EOF;
2286         subh->count = htons(1);
2287
2288         /* XXX write checksum in EOF here */
2289
2290         /* we're done, let's put it on the wire */
2291 #if NBPFILTER > 0
2292         if (ifp->if_bpf) {
2293                 m->m_data += sizeof(*ip);
2294                 m->m_len = m->m_pkthdr.len = sc->sc_len - sizeof(*ip);
2295 #ifdef __FreeBSD__
2296                 BPF_MTAP(ifp, m);
2297 #else
2298                 bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
2299 #endif
2300                 m->m_data -= sizeof(*ip);
2301                 m->m_len = m->m_pkthdr.len = sc->sc_len;
2302         }
2303
2304         if (sc->sc_sync_if == NULL) {
2305                 sc->sc_len = PFSYNC_MINPKT;
2306                 m_freem(m);
2307                 return;
2308         }
2309 #endif
2310
2311 #ifdef __FreeBSD__
2312         sc->sc_ifp->if_opackets++;
2313         sc->sc_ifp->if_obytes += m->m_pkthdr.len;
2314         sc->sc_len = PFSYNC_MINPKT;
2315
2316         if (!_IF_QFULL(&sc->sc_ifp->if_snd))
2317                 _IF_ENQUEUE(&sc->sc_ifp->if_snd, m);
2318         else {
2319                 m_freem(m);
2320                 sc->sc_ifp->if_snd.ifq_drops++;
2321         }
2322         if (schedswi)
2323                 swi_sched(V_pfsync_swi_cookie, 0);
2324 #else
2325         sc->sc_if.if_opackets++;
2326         sc->sc_if.if_obytes += m->m_pkthdr.len;
2327
2328         if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo, NULL) == 0)
2329                 pfsyncstats.pfsyncs_opackets++;
2330         else
2331                 pfsyncstats.pfsyncs_oerrors++;
2332
2333         /* start again */
2334         sc->sc_len = PFSYNC_MINPKT;
2335 #endif
2336 }
2337
2338 void
2339 pfsync_insert_state(struct pf_state *st)
2340 {
2341 #ifdef __FreeBSD__
2342         struct pfsync_softc *sc = V_pfsyncif;
2343 #else
2344         struct pfsync_softc *sc = pfsyncif;
2345 #endif
2346
2347 #ifdef __FreeBSD__
2348         PF_LOCK_ASSERT();
2349 #else
2350         splassert(IPL_SOFTNET);
2351 #endif
2352
2353         if (ISSET(st->rule.ptr->rule_flag, PFRULE_NOSYNC) ||
2354             st->key[PF_SK_WIRE]->proto == IPPROTO_PFSYNC) {
2355                 SET(st->state_flags, PFSTATE_NOSYNC);
2356                 return;
2357         }
2358
2359         if (sc == NULL || ISSET(st->state_flags, PFSTATE_NOSYNC))
2360                 return;
2361
2362 #ifdef PFSYNC_DEBUG
2363 #ifdef __FreeBSD__
2364         KASSERT(st->sync_state == PFSYNC_S_NONE,
2365                 ("%s: st->sync_state == PFSYNC_S_NONE", __FUNCTION__));
2366 #else
2367         KASSERT(st->sync_state == PFSYNC_S_NONE);
2368 #endif
2369 #endif
2370
2371         if (sc->sc_len == PFSYNC_MINPKT)
2372 #ifdef __FreeBSD__
2373                 callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout,
2374                     V_pfsyncif);
2375 #else
2376                 timeout_add_sec(&sc->sc_tmo, 1);
2377 #endif
2378
2379         pfsync_q_ins(st, PFSYNC_S_INS);
2380
2381         if (ISSET(st->state_flags, PFSTATE_ACK))
2382                 schednetisr(NETISR_PFSYNC);
2383         else
2384                 st->sync_updates = 0;
2385 }
2386
2387 int defer = 10;
2388
2389 int
2390 pfsync_defer(struct pf_state *st, struct mbuf *m)
2391 {
2392 #ifdef __FreeBSD__
2393         struct pfsync_softc *sc = V_pfsyncif;
2394 #else
2395         struct pfsync_softc *sc = pfsyncif;
2396 #endif
2397         struct pfsync_deferral *pd;
2398
2399 #ifdef __FreeBSD__
2400         PF_LOCK_ASSERT();
2401 #else
2402         splassert(IPL_SOFTNET);
2403 #endif
2404
2405         if (sc->sc_deferred >= 128)
2406                 pfsync_undefer(TAILQ_FIRST(&sc->sc_deferrals), 0);
2407
2408         pd = pool_get(&sc->sc_pool, M_NOWAIT);
2409         if (pd == NULL)
2410                 return (0);
2411         sc->sc_deferred++;
2412
2413 #ifdef __FreeBSD__
2414         m->m_flags |= M_SKIP_FIREWALL;
2415 #else
2416         m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
2417 #endif
2418         SET(st->state_flags, PFSTATE_ACK);
2419
2420         pd->pd_st = st;
2421         pd->pd_m = m;
2422
2423         TAILQ_INSERT_TAIL(&sc->sc_deferrals, pd, pd_entry);
2424 #ifdef __FreeBSD__
2425         callout_init(&pd->pd_tmo, CALLOUT_MPSAFE);
2426         callout_reset(&pd->pd_tmo, defer, pfsync_defer_tmo,
2427                 pd);
2428 #else
2429         timeout_set(&pd->pd_tmo, pfsync_defer_tmo, pd);
2430         timeout_add(&pd->pd_tmo, defer);
2431 #endif
2432
2433         return (1);
2434 }
2435
2436 void
2437 pfsync_undefer(struct pfsync_deferral *pd, int drop)
2438 {
2439 #ifdef __FreeBSD__
2440         struct pfsync_softc *sc = V_pfsyncif;
2441 #else
2442         struct pfsync_softc *sc = pfsyncif;
2443 #endif
2444         int s;
2445
2446 #ifdef __FreeBSD__
2447         PF_LOCK_ASSERT();
2448 #else
2449         splassert(IPL_SOFTNET);
2450 #endif
2451
2452         TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
2453         sc->sc_deferred--;
2454
2455         CLR(pd->pd_st->state_flags, PFSTATE_ACK);
2456         timeout_del(&pd->pd_tmo); /* bah */
2457         if (drop)
2458                 m_freem(pd->pd_m);
2459         else {
2460                 s = splnet();
2461 #ifdef __FreeBSD__
2462                 /* XXX: use pf_defered?! */
2463                 PF_UNLOCK();
2464 #endif
2465                 ip_output(pd->pd_m, (void *)NULL, (void *)NULL, 0,
2466                     (void *)NULL, (void *)NULL);
2467 #ifdef __FreeBSD__
2468                 PF_LOCK();
2469 #endif
2470                 splx(s);
2471         }
2472
2473         pool_put(&sc->sc_pool, pd);
2474 }
2475
2476 void
2477 pfsync_defer_tmo(void *arg)
2478 {
2479 #if defined(__FreeBSD__) && defined(VIMAGE)
2480         struct pfsync_deferral *pd = arg;
2481 #endif
2482         int s;
2483
2484         s = splsoftnet();
2485 #ifdef __FreeBSD__
2486         CURVNET_SET(pd->pd_m->m_pkthdr.rcvif->if_vnet); /* XXX */
2487         PF_LOCK();
2488 #endif
2489         pfsync_undefer(arg, 0);
2490 #ifdef __FreeBSD__
2491         PF_UNLOCK();
2492         CURVNET_RESTORE();
2493 #endif
2494         splx(s);
2495 }
2496
2497 void
2498 pfsync_deferred(struct pf_state *st, int drop)
2499 {
2500 #ifdef __FreeBSD__
2501         struct pfsync_softc *sc = V_pfsyncif;
2502 #else
2503         struct pfsync_softc *sc = pfsyncif;
2504 #endif
2505         struct pfsync_deferral *pd;
2506
2507         TAILQ_FOREACH(pd, &sc->sc_deferrals, pd_entry) {
2508                  if (pd->pd_st == st) {
2509                         pfsync_undefer(pd, drop);
2510                         return;
2511                 }
2512         }
2513
2514         panic("pfsync_send_deferred: unable to find deferred state");
2515 }
2516
2517 u_int pfsync_upds = 0;
2518
2519 void
2520 pfsync_update_state(struct pf_state *st)
2521 {
2522 #ifdef __FreeBSD__
2523         struct pfsync_softc *sc = V_pfsyncif;
2524 #else
2525         struct pfsync_softc *sc = pfsyncif;
2526 #endif
2527         int sync = 0;
2528
2529 #ifdef __FreeBSD__
2530         PF_LOCK_ASSERT();
2531 #else
2532         splassert(IPL_SOFTNET);
2533 #endif
2534
2535         if (sc == NULL)
2536                 return;
2537
2538         if (ISSET(st->state_flags, PFSTATE_ACK))
2539                 pfsync_deferred(st, 0);
2540         if (ISSET(st->state_flags, PFSTATE_NOSYNC)) {
2541                 if (st->sync_state != PFSYNC_S_NONE)
2542                         pfsync_q_del(st);
2543                 return;
2544         }
2545
2546         if (sc->sc_len == PFSYNC_MINPKT)
2547 #ifdef __FreeBSD__
2548                 callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout,
2549                     V_pfsyncif);
2550 #else
2551                 timeout_add_sec(&sc->sc_tmo, 1);
2552 #endif
2553
2554         switch (st->sync_state) {
2555         case PFSYNC_S_UPD_C:
2556         case PFSYNC_S_UPD:
2557         case PFSYNC_S_INS:
2558                 /* we're already handling it */
2559
2560                 if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP) {
2561                         st->sync_updates++;
2562                         if (st->sync_updates >= sc->sc_maxupdates)
2563                                 sync = 1;
2564                 }
2565                 break;
2566
2567         case PFSYNC_S_IACK:
2568                 pfsync_q_del(st);
2569         case PFSYNC_S_NONE:
2570                 pfsync_q_ins(st, PFSYNC_S_UPD_C);
2571                 st->sync_updates = 0;
2572                 break;
2573
2574         default:
2575                 panic("pfsync_update_state: unexpected sync state %d",
2576                     st->sync_state);
2577         }
2578
2579         if (sync || (time_uptime - st->pfsync_time) < 2) {
2580                 pfsync_upds++;
2581                 schednetisr(NETISR_PFSYNC);
2582         }
2583 }
2584
2585 void
2586 pfsync_request_update(u_int32_t creatorid, u_int64_t id)
2587 {
2588 #ifdef __FreeBSD__
2589         struct pfsync_softc *sc = V_pfsyncif;
2590 #else
2591         struct pfsync_softc *sc = pfsyncif;
2592 #endif
2593         struct pfsync_upd_req_item *item;
2594         size_t nlen = sizeof(struct pfsync_upd_req);
2595         int s;
2596
2597         PF_LOCK_ASSERT();
2598
2599         /*
2600          * this code does nothing to prevent multiple update requests for the
2601          * same state being generated.
2602          */
2603
2604         item = pool_get(&sc->sc_pool, PR_NOWAIT);
2605         if (item == NULL) {
2606                 /* XXX stats */
2607                 return;
2608         }
2609
2610         item->ur_msg.id = id;
2611         item->ur_msg.creatorid = creatorid;
2612
2613         if (TAILQ_EMPTY(&sc->sc_upd_req_list))
2614                 nlen += sizeof(struct pfsync_subheader);
2615
2616 #ifdef __FreeBSD__
2617         if (sc->sc_len + nlen > sc->sc_ifp->if_mtu) {
2618 #else
2619         if (sc->sc_len + nlen > sc->sc_if.if_mtu) {
2620 #endif
2621                 s = splnet();
2622                 pfsync_sendout();
2623                 splx(s);
2624
2625                 nlen = sizeof(struct pfsync_subheader) +
2626                     sizeof(struct pfsync_upd_req);
2627         }
2628
2629         TAILQ_INSERT_TAIL(&sc->sc_upd_req_list, item, ur_entry);
2630         sc->sc_len += nlen;
2631
2632         schednetisr(NETISR_PFSYNC);
2633 }
2634
2635 void
2636 pfsync_update_state_req(struct pf_state *st)
2637 {
2638 #ifdef __FreeBSD__
2639         struct pfsync_softc *sc = V_pfsyncif;
2640 #else
2641         struct pfsync_softc *sc = pfsyncif;
2642 #endif
2643
2644         PF_LOCK_ASSERT();
2645
2646         if (sc == NULL)
2647                 panic("pfsync_update_state_req: nonexistant instance");
2648
2649         if (ISSET(st->state_flags, PFSTATE_NOSYNC)) {
2650                 if (st->sync_state != PFSYNC_S_NONE)
2651                         pfsync_q_del(st);
2652                 return;
2653         }
2654
2655         switch (st->sync_state) {
2656         case PFSYNC_S_UPD_C:
2657         case PFSYNC_S_IACK:
2658                 pfsync_q_del(st);
2659         case PFSYNC_S_NONE:
2660                 pfsync_q_ins(st, PFSYNC_S_UPD);
2661                 schednetisr(NETISR_PFSYNC);
2662                 return;
2663
2664         case PFSYNC_S_INS:
2665         case PFSYNC_S_UPD:
2666         case PFSYNC_S_DEL:
2667                 /* we're already handling it */
2668                 return;
2669
2670         default:
2671                 panic("pfsync_update_state_req: unexpected sync state %d",
2672                     st->sync_state);
2673         }
2674 }
2675
2676 void
2677 pfsync_delete_state(struct pf_state *st)
2678 {
2679 #ifdef __FreeBSD__
2680         struct pfsync_softc *sc = V_pfsyncif;
2681 #else
2682         struct pfsync_softc *sc = pfsyncif;
2683 #endif
2684
2685 #ifdef __FreeBSD__
2686         PF_LOCK_ASSERT();
2687 #else
2688         splassert(IPL_SOFTNET);
2689 #endif
2690
2691         if (sc == NULL)
2692                 return;
2693
2694         if (ISSET(st->state_flags, PFSTATE_ACK))
2695                 pfsync_deferred(st, 1);
2696         if (ISSET(st->state_flags, PFSTATE_NOSYNC)) {
2697                 if (st->sync_state != PFSYNC_S_NONE)
2698                         pfsync_q_del(st);
2699                 return;
2700         }
2701
2702         if (sc->sc_len == PFSYNC_MINPKT)
2703 #ifdef __FreeBSD__
2704                 callout_reset(&sc->sc_tmo, 1 * hz, pfsync_timeout,
2705                     V_pfsyncif);
2706 #else
2707                 timeout_add_sec(&sc->sc_tmo, 1);
2708 #endif
2709
2710         switch (st->sync_state) {
2711         case PFSYNC_S_INS:
2712                 /* we never got to tell the world so just forget about it */
2713                 pfsync_q_del(st);
2714                 return;
2715
2716         case PFSYNC_S_UPD_C:
2717         case PFSYNC_S_UPD:
2718         case PFSYNC_S_IACK:
2719                 pfsync_q_del(st);
2720                 /* FALLTHROUGH to putting it on the del list */
2721
2722         case PFSYNC_S_NONE:
2723                 pfsync_q_ins(st, PFSYNC_S_DEL);
2724                 return;
2725
2726         default:
2727                 panic("pfsync_delete_state: unexpected sync state %d",
2728                     st->sync_state);
2729         }
2730 }
2731
2732 void
2733 pfsync_clear_states(u_int32_t creatorid, const char *ifname)
2734 {
2735         struct {
2736                 struct pfsync_subheader subh;
2737                 struct pfsync_clr clr;
2738         } __packed r;
2739
2740 #ifdef __FreeBSD__
2741         struct pfsync_softc *sc = V_pfsyncif;
2742 #else
2743         struct pfsync_softc *sc = pfsyncif;
2744 #endif
2745
2746 #ifdef __FreeBSD__
2747         PF_LOCK_ASSERT();
2748 #else
2749         splassert(IPL_SOFTNET);
2750 #endif
2751
2752         if (sc == NULL)
2753                 return;
2754
2755         bzero(&r, sizeof(r));
2756
2757         r.subh.action = PFSYNC_ACT_CLR;
2758         r.subh.count = htons(1);
2759
2760         strlcpy(r.clr.ifname, ifname, sizeof(r.clr.ifname));
2761         r.clr.creatorid = creatorid;
2762
2763         pfsync_send_plus(&r, sizeof(r));
2764 }
2765
2766 void
2767 pfsync_q_ins(struct pf_state *st, int q)
2768 {
2769 #ifdef __FreeBSD__
2770         struct pfsync_softc *sc = V_pfsyncif;
2771 #else
2772         struct pfsync_softc *sc = pfsyncif;
2773 #endif
2774         size_t nlen = pfsync_qs[q].len;
2775         int s;
2776
2777         PF_LOCK_ASSERT();
2778
2779 #ifdef __FreeBSD__
2780         KASSERT(st->sync_state == PFSYNC_S_NONE,
2781                 ("%s: st->sync_state == PFSYNC_S_NONE", __FUNCTION__));
2782 #else
2783         KASSERT(st->sync_state == PFSYNC_S_NONE);
2784 #endif
2785
2786 #if 1 || defined(PFSYNC_DEBUG)
2787         if (sc->sc_len < PFSYNC_MINPKT)
2788 #ifdef __FreeBSD__
2789                 panic("pfsync pkt len is too low %zu", sc->sc_len);
2790 #else
2791                 panic("pfsync pkt len is too low %d", sc->sc_len);
2792 #endif
2793 #endif
2794         if (TAILQ_EMPTY(&sc->sc_qs[q]))
2795                 nlen += sizeof(struct pfsync_subheader);
2796
2797 #ifdef __FreeBSD__
2798         if (sc->sc_len + nlen > sc->sc_ifp->if_mtu) {
2799 #else
2800         if (sc->sc_len + nlen > sc->sc_if.if_mtu) {
2801 #endif
2802                 s = splnet();
2803                 pfsync_sendout();
2804                 splx(s);
2805
2806                 nlen = sizeof(struct pfsync_subheader) + pfsync_qs[q].len;
2807         }
2808
2809         sc->sc_len += nlen;
2810         TAILQ_INSERT_TAIL(&sc->sc_qs[q], st, sync_list);
2811         st->sync_state = q;
2812 }
2813
2814 void
2815 pfsync_q_del(struct pf_state *st)
2816 {
2817 #ifdef __FreeBSD__
2818         struct pfsync_softc *sc = V_pfsyncif;
2819 #else
2820         struct pfsync_softc *sc = pfsyncif;
2821 #endif
2822         int q = st->sync_state;
2823
2824 #ifdef __FreeBSD__
2825         KASSERT(st->sync_state != PFSYNC_S_NONE,
2826                 ("%s: st->sync_state != PFSYNC_S_NONE", __FUNCTION__));
2827 #else
2828         KASSERT(st->sync_state != PFSYNC_S_NONE);
2829 #endif
2830
2831         sc->sc_len -= pfsync_qs[q].len;
2832         TAILQ_REMOVE(&sc->sc_qs[q], st, sync_list);
2833         st->sync_state = PFSYNC_S_NONE;
2834
2835         if (TAILQ_EMPTY(&sc->sc_qs[q]))
2836                 sc->sc_len -= sizeof(struct pfsync_subheader);
2837 }
2838
2839 #ifdef notyet
2840 void
2841 pfsync_update_tdb(struct tdb *t, int output)
2842 {
2843 #ifdef __FreeBSD__
2844         struct pfsync_softc *sc = V_pfsyncif;
2845 #else
2846         struct pfsync_softc *sc = pfsyncif;
2847 #endif
2848         size_t nlen = sizeof(struct pfsync_tdb);
2849         int s;
2850
2851         if (sc == NULL)
2852                 return;
2853
2854         if (!ISSET(t->tdb_flags, TDBF_PFSYNC)) {
2855                 if (TAILQ_EMPTY(&sc->sc_tdb_q))
2856                         nlen += sizeof(struct pfsync_subheader);
2857
2858                 if (sc->sc_len + nlen > sc->sc_if.if_mtu) {
2859                         s = splnet();
2860                         PF_LOCK();
2861                         pfsync_sendout();
2862                         PF_UNLOCK();
2863                         splx(s);
2864
2865                         nlen = sizeof(struct pfsync_subheader) +
2866                             sizeof(struct pfsync_tdb);
2867                 }
2868
2869                 sc->sc_len += nlen;
2870                 TAILQ_INSERT_TAIL(&sc->sc_tdb_q, t, tdb_sync_entry);
2871                 SET(t->tdb_flags, TDBF_PFSYNC);
2872                 t->tdb_updates = 0;
2873         } else {
2874                 if (++t->tdb_updates >= sc->sc_maxupdates)
2875                         schednetisr(NETISR_PFSYNC);
2876         }
2877
2878         if (output)
2879                 SET(t->tdb_flags, TDBF_PFSYNC_RPL);
2880         else
2881                 CLR(t->tdb_flags, TDBF_PFSYNC_RPL);
2882 }
2883
2884 void
2885 pfsync_delete_tdb(struct tdb *t)
2886 {
2887 #ifdef __FreeBSD__
2888         struct pfsync_softc *sc = V_pfsyncif;
2889 #else
2890         struct pfsync_softc *sc = pfsyncif;
2891 #endif
2892
2893         if (sc == NULL || !ISSET(t->tdb_flags, TDBF_PFSYNC))
2894                 return;
2895
2896         sc->sc_len -= sizeof(struct pfsync_tdb);
2897         TAILQ_REMOVE(&sc->sc_tdb_q, t, tdb_sync_entry);
2898         CLR(t->tdb_flags, TDBF_PFSYNC);
2899
2900         if (TAILQ_EMPTY(&sc->sc_tdb_q))
2901                 sc->sc_len -= sizeof(struct pfsync_subheader);
2902 }
2903
2904 int
2905 pfsync_out_tdb(struct tdb *t, struct mbuf *m, int offset)
2906 {
2907         struct pfsync_tdb *ut = (struct pfsync_tdb *)(m->m_data + offset);
2908
2909         bzero(ut, sizeof(*ut));
2910         ut->spi = t->tdb_spi;
2911         bcopy(&t->tdb_dst, &ut->dst, sizeof(ut->dst));
2912         /*
2913          * When a failover happens, the master's rpl is probably above
2914          * what we see here (we may be up to a second late), so
2915          * increase it a bit for outbound tdbs to manage most such
2916          * situations.
2917          *
2918          * For now, just add an offset that is likely to be larger
2919          * than the number of packets we can see in one second. The RFC
2920          * just says the next packet must have a higher seq value.
2921          *
2922          * XXX What is a good algorithm for this? We could use
2923          * a rate-determined increase, but to know it, we would have
2924          * to extend struct tdb.
2925          * XXX pt->rpl can wrap over MAXINT, but if so the real tdb
2926          * will soon be replaced anyway. For now, just don't handle
2927          * this edge case.
2928          */
2929 #define RPL_INCR 16384
2930         ut->rpl = htonl(t->tdb_rpl + (ISSET(t->tdb_flags, TDBF_PFSYNC_RPL) ?
2931             RPL_INCR : 0));
2932         ut->cur_bytes = htobe64(t->tdb_cur_bytes);
2933         ut->sproto = t->tdb_sproto;
2934
2935         return (sizeof(*ut));
2936 }
2937 #endif
2938
2939 void
2940 pfsync_bulk_start(void)
2941 {
2942 #ifdef __FreeBSD__
2943         struct pfsync_softc *sc = V_pfsyncif;
2944 #else
2945         struct pfsync_softc *sc = pfsyncif;
2946 #endif
2947
2948 #ifdef __FreeBSD__
2949         if (V_pf_status.debug >= PF_DEBUG_MISC)
2950 #else
2951         if (pf_status.debug >= PF_DEBUG_MISC)
2952 #endif
2953                 printf("pfsync: received bulk update request\n");
2954
2955 #ifdef __FreeBSD__
2956         PF_LOCK_ASSERT();
2957         if (TAILQ_EMPTY(&V_state_list))
2958 #else
2959         if (TAILQ_EMPTY(&state_list))
2960 #endif
2961                 pfsync_bulk_status(PFSYNC_BUS_END);
2962         else {
2963                 sc->sc_ureq_received = time_uptime;
2964                 if (sc->sc_bulk_next == NULL)
2965 #ifdef __FreeBSD__
2966                         sc->sc_bulk_next = TAILQ_FIRST(&V_state_list);
2967 #else
2968                         sc->sc_bulk_next = TAILQ_FIRST(&state_list);
2969 #endif
2970                 sc->sc_bulk_last = sc->sc_bulk_next;
2971
2972                 pfsync_bulk_status(PFSYNC_BUS_START);
2973                 callout_reset(&sc->sc_bulk_tmo, 1, pfsync_bulk_update, sc);
2974         }
2975 }
2976
2977 void
2978 pfsync_bulk_update(void *arg)
2979 {
2980         struct pfsync_softc *sc = arg;
2981         struct pf_state *st = sc->sc_bulk_next;
2982         int i = 0;
2983         int s;
2984
2985         PF_LOCK_ASSERT();
2986
2987         s = splsoftnet();
2988 #ifdef __FreeBSD__
2989         CURVNET_SET(sc->sc_ifp->if_vnet);
2990 #endif
2991         for (;;) {
2992                 if (st->sync_state == PFSYNC_S_NONE &&
2993                     st->timeout < PFTM_MAX &&
2994                     st->pfsync_time <= sc->sc_ureq_received) {
2995                         pfsync_update_state_req(st);
2996                         i++;
2997                 }
2998
2999                 st = TAILQ_NEXT(st, entry_list);
3000                 if (st == NULL)
3001 #ifdef __FreeBSD__
3002                         st = TAILQ_FIRST(&V_state_list);
3003 #else
3004                         st = TAILQ_FIRST(&state_list);
3005 #endif
3006
3007                 if (st == sc->sc_bulk_last) {
3008                         /* we're done */
3009                         sc->sc_bulk_next = NULL;
3010                         sc->sc_bulk_last = NULL;
3011                         pfsync_bulk_status(PFSYNC_BUS_END);
3012                         break;
3013                 }
3014
3015 #ifdef __FreeBSD__
3016                 if (i > 1 && (sc->sc_ifp->if_mtu - sc->sc_len) <
3017 #else
3018                 if (i > 1 && (sc->sc_if.if_mtu - sc->sc_len) <
3019 #endif
3020                     sizeof(struct pfsync_state)) {
3021                         /* we've filled a packet */
3022                         sc->sc_bulk_next = st;
3023 #ifdef __FreeBSD__
3024                         callout_reset(&sc->sc_bulk_tmo, 1,
3025                             pfsync_bulk_update, sc);
3026 #else
3027                         timeout_add(&sc->sc_bulk_tmo, 1);
3028 #endif
3029                         break;
3030                 }
3031         }
3032
3033 #ifdef __FreeBSD__
3034         CURVNET_RESTORE();
3035 #endif
3036         splx(s);
3037 }
3038
3039 void
3040 pfsync_bulk_status(u_int8_t status)
3041 {
3042         struct {
3043                 struct pfsync_subheader subh;
3044                 struct pfsync_bus bus;
3045         } __packed r;
3046
3047 #ifdef __FreeBSD__
3048         struct pfsync_softc *sc = V_pfsyncif;
3049 #else
3050         struct pfsync_softc *sc = pfsyncif;
3051 #endif
3052
3053         PF_LOCK_ASSERT();
3054
3055         bzero(&r, sizeof(r));
3056
3057         r.subh.action = PFSYNC_ACT_BUS;
3058         r.subh.count = htons(1);
3059
3060 #ifdef __FreeBSD__
3061         r.bus.creatorid = V_pf_status.hostid;
3062 #else
3063         r.bus.creatorid = pf_status.hostid;
3064 #endif
3065         r.bus.endtime = htonl(time_uptime - sc->sc_ureq_received);
3066         r.bus.status = status;
3067
3068         pfsync_send_plus(&r, sizeof(r));
3069 }
3070
3071 void
3072 pfsync_bulk_fail(void *arg)
3073 {
3074         struct pfsync_softc *sc = arg;
3075
3076 #ifdef __FreeBSD__
3077         CURVNET_SET(sc->sc_ifp->if_vnet);
3078 #endif
3079
3080         if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
3081                 /* Try again */
3082 #ifdef __FreeBSD__
3083                 callout_reset(&sc->sc_bulkfail_tmo, 5 * hz,
3084                     pfsync_bulk_fail, V_pfsyncif);
3085 #else
3086                 timeout_add_sec(&sc->sc_bulkfail_tmo, 5);
3087 #endif
3088                 PF_LOCK();
3089                 pfsync_request_update(0, 0);
3090                 PF_UNLOCK();
3091         } else {
3092                 /* Pretend like the transfer was ok */
3093                 sc->sc_ureq_sent = 0;
3094                 sc->sc_bulk_tries = 0;
3095 #ifdef __FreeBSD__
3096                 if (!sc->pfsync_sync_ok && carp_demote_adj_p)
3097                         (*carp_demote_adj_p)(-V_pfsync_carp_adj,
3098                             "pfsync bulk fail");
3099                 sc->pfsync_sync_ok = 1;
3100 #else
3101 #if NCARP > 0
3102                 if (!pfsync_sync_ok)
3103                         carp_group_demote_adj(&sc->sc_if, -1);
3104 #endif
3105                 pfsync_sync_ok = 1;
3106 #endif
3107 #ifdef __FreeBSD__
3108                 if (V_pf_status.debug >= PF_DEBUG_MISC)
3109 #else
3110                 if (pf_status.debug >= PF_DEBUG_MISC)
3111 #endif
3112                         printf("pfsync: failed to receive bulk update\n");
3113         }
3114
3115 #ifdef __FreeBSD__
3116         CURVNET_RESTORE();
3117 #endif
3118 }
3119
3120 void
3121 pfsync_send_plus(void *plus, size_t pluslen)
3122 {
3123 #ifdef __FreeBSD__
3124         struct pfsync_softc *sc = V_pfsyncif;
3125 #else
3126         struct pfsync_softc *sc = pfsyncif;
3127 #endif
3128         int s;
3129
3130         PF_LOCK_ASSERT();
3131
3132 #ifdef __FreeBSD__
3133         if (sc->sc_len + pluslen > sc->sc_ifp->if_mtu) {
3134 #else
3135         if (sc->sc_len + pluslen > sc->sc_if.if_mtu) {
3136 #endif
3137                 s = splnet();
3138                 pfsync_sendout();
3139                 splx(s);
3140         }
3141
3142         sc->sc_plus = plus;
3143         sc->sc_len += (sc->sc_pluslen = pluslen);
3144
3145         s = splnet();
3146         pfsync_sendout();
3147         splx(s);
3148 }
3149
3150 int
3151 pfsync_up(void)
3152 {
3153 #ifdef __FreeBSD__
3154         struct pfsync_softc *sc = V_pfsyncif;
3155 #else
3156         struct pfsync_softc *sc = pfsyncif;
3157 #endif
3158
3159 #ifdef __FreeBSD__
3160         if (sc == NULL || !ISSET(sc->sc_ifp->if_flags, IFF_DRV_RUNNING))
3161 #else
3162         if (sc == NULL || !ISSET(sc->sc_if.if_flags, IFF_RUNNING))
3163 #endif
3164                 return (0);
3165
3166         return (1);
3167 }
3168
3169 int
3170 pfsync_state_in_use(struct pf_state *st)
3171 {
3172 #ifdef __FreeBSD__
3173         struct pfsync_softc *sc = V_pfsyncif;
3174 #else
3175         struct pfsync_softc *sc = pfsyncif;
3176 #endif
3177
3178         if (sc == NULL)
3179                 return (0);
3180
3181         if (st->sync_state != PFSYNC_S_NONE ||
3182             st == sc->sc_bulk_next ||
3183             st == sc->sc_bulk_last)
3184                 return (1);
3185
3186         return (0);
3187 }
3188
3189 u_int pfsync_ints;
3190 u_int pfsync_tmos;
3191
3192 void
3193 pfsync_timeout(void *arg)
3194 {
3195 #if defined(__FreeBSD__) && defined(VIMAGE)
3196         struct pfsync_softc *sc = arg;
3197 #endif
3198         int s;
3199
3200 #ifdef __FreeBSD__
3201         CURVNET_SET(sc->sc_ifp->if_vnet);
3202 #endif
3203
3204         pfsync_tmos++;
3205
3206         s = splnet();
3207 #ifdef __FreeBSD__
3208         PF_LOCK();
3209 #endif
3210         pfsync_sendout();
3211 #ifdef __FreeBSD__
3212         PF_UNLOCK();
3213 #endif
3214         splx(s);
3215
3216 #ifdef __FreeBSD__
3217         CURVNET_RESTORE();
3218 #endif
3219 }
3220
3221 /* this is a softnet/netisr handler */
3222 void
3223 #ifdef __FreeBSD__
3224 pfsyncintr(void *arg)
3225 {
3226         struct pfsync_softc *sc = arg;
3227         struct mbuf *m, *n;
3228
3229         CURVNET_SET(sc->sc_ifp->if_vnet);
3230         pfsync_ints++;
3231
3232         PF_LOCK();
3233         if (sc->sc_len > PFSYNC_MINPKT)
3234                 pfsync_sendout1(0);
3235         _IF_DEQUEUE_ALL(&sc->sc_ifp->if_snd, m);
3236         PF_UNLOCK();
3237
3238         for (; m != NULL; m = n) {
3239
3240                 n = m->m_nextpkt;
3241                 m->m_nextpkt = NULL;
3242                 if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo, NULL)
3243                     == 0)
3244                         V_pfsyncstats.pfsyncs_opackets++;
3245                 else
3246                         V_pfsyncstats.pfsyncs_oerrors++;
3247         }
3248         CURVNET_RESTORE();
3249 }
3250 #else
3251 pfsyncintr(void)
3252 {
3253         int s;
3254
3255         pfsync_ints++;
3256
3257         s = splnet();
3258         pfsync_sendout();
3259         splx(s);
3260 }
3261 #endif
3262
3263 int
3264 pfsync_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
3265     size_t newlen)
3266 {
3267
3268 #ifdef notyet
3269         /* All sysctl names at this level are terminal. */
3270         if (namelen != 1)
3271                 return (ENOTDIR);
3272
3273         switch (name[0]) {
3274         case PFSYNCCTL_STATS:
3275                 if (newp != NULL)
3276                         return (EPERM);
3277                 return (sysctl_struct(oldp, oldlenp, newp, newlen,
3278                     &V_pfsyncstats, sizeof(V_pfsyncstats)));
3279         }
3280 #endif
3281         return (ENOPROTOOPT);
3282 }
3283
3284 #ifdef __FreeBSD__
3285 static int
3286 pfsync_multicast_setup(struct pfsync_softc *sc)
3287 {
3288         struct ip_moptions *imo = &sc->sc_imo;
3289         int error;
3290
3291         if (!(sc->sc_sync_if->if_flags & IFF_MULTICAST)) {
3292                 sc->sc_sync_if = NULL;
3293                 return (EADDRNOTAVAIL);
3294         }
3295
3296         imo->imo_membership = (struct in_multi **)malloc(
3297             (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_PFSYNC,
3298             M_WAITOK | M_ZERO);
3299         imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
3300         imo->imo_multicast_vif = -1;
3301
3302         if ((error = in_joingroup(sc->sc_sync_if, &sc->sc_sync_peer, NULL,
3303             &imo->imo_membership[0])) != 0) {
3304                 free(imo->imo_membership, M_PFSYNC);
3305                 return (error);
3306         }
3307         imo->imo_num_memberships++;
3308         imo->imo_multicast_ifp = sc->sc_sync_if;
3309         imo->imo_multicast_ttl = PFSYNC_DFLTTL;
3310         imo->imo_multicast_loop = 0;
3311
3312         return (0);
3313 }
3314
3315 static void
3316 pfsync_multicast_cleanup(struct pfsync_softc *sc)
3317 {
3318         struct ip_moptions *imo = &sc->sc_imo;
3319
3320         in_leavegroup(imo->imo_membership[0], NULL);
3321         free(imo->imo_membership, M_PFSYNC);
3322         imo->imo_membership = NULL;
3323         imo->imo_multicast_ifp = NULL;
3324 }
3325
3326 #ifdef INET
3327 extern  struct domain inetdomain;
3328 static struct protosw in_pfsync_protosw = {
3329         .pr_type =              SOCK_RAW,
3330         .pr_domain =            &inetdomain,
3331         .pr_protocol =          IPPROTO_PFSYNC,
3332         .pr_flags =             PR_ATOMIC|PR_ADDR,
3333         .pr_input =             pfsync_input,
3334         .pr_output =            (pr_output_t *)rip_output,
3335         .pr_ctloutput =         rip_ctloutput,
3336         .pr_usrreqs =           &rip_usrreqs
3337 };
3338 #endif
3339
3340 static int
3341 pfsync_init()
3342 {
3343         VNET_ITERATOR_DECL(vnet_iter);
3344         int error = 0;
3345
3346         VNET_LIST_RLOCK();
3347         VNET_FOREACH(vnet_iter) {
3348                 CURVNET_SET(vnet_iter);
3349                 V_pfsync_cloner = pfsync_cloner;
3350                 V_pfsync_cloner_data = pfsync_cloner_data;
3351                 V_pfsync_cloner.ifc_data = &V_pfsync_cloner_data;
3352                 if_clone_attach(&V_pfsync_cloner);
3353                 error = swi_add(NULL, "pfsync", pfsyncintr, V_pfsyncif,
3354                     SWI_NET, INTR_MPSAFE, &V_pfsync_swi_cookie);
3355                 CURVNET_RESTORE();
3356                 if (error)
3357                         goto fail_locked;
3358         }
3359         VNET_LIST_RUNLOCK();
3360 #ifdef INET
3361         error = pf_proto_register(PF_INET, &in_pfsync_protosw);
3362         if (error)
3363                 goto fail;
3364         error = ipproto_register(IPPROTO_PFSYNC);
3365         if (error) {
3366                 pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
3367                 goto fail;
3368         }
3369 #endif
3370         PF_LOCK();
3371         pfsync_state_import_ptr = pfsync_state_import;
3372         pfsync_up_ptr = pfsync_up;
3373         pfsync_insert_state_ptr = pfsync_insert_state;
3374         pfsync_update_state_ptr = pfsync_update_state;
3375         pfsync_delete_state_ptr = pfsync_delete_state;
3376         pfsync_clear_states_ptr = pfsync_clear_states;
3377         pfsync_state_in_use_ptr = pfsync_state_in_use;
3378         pfsync_defer_ptr = pfsync_defer;
3379         PF_UNLOCK();
3380
3381         return (0);
3382
3383 fail:
3384         VNET_LIST_RLOCK();
3385 fail_locked:
3386         VNET_FOREACH(vnet_iter) {
3387                 CURVNET_SET(vnet_iter);
3388                 if (V_pfsync_swi_cookie) {
3389                         swi_remove(V_pfsync_swi_cookie);
3390                         if_clone_detach(&V_pfsync_cloner);
3391                 }
3392                 CURVNET_RESTORE();
3393         }
3394         VNET_LIST_RUNLOCK();
3395
3396         return (error);
3397 }
3398
3399 static void
3400 pfsync_uninit()
3401 {
3402         VNET_ITERATOR_DECL(vnet_iter);
3403
3404         PF_LOCK();
3405         pfsync_state_import_ptr = NULL;
3406         pfsync_up_ptr = NULL;
3407         pfsync_insert_state_ptr = NULL;
3408         pfsync_update_state_ptr = NULL;
3409         pfsync_delete_state_ptr = NULL;
3410         pfsync_clear_states_ptr = NULL;
3411         pfsync_state_in_use_ptr = NULL;
3412         pfsync_defer_ptr = NULL;
3413         PF_UNLOCK();
3414
3415         ipproto_unregister(IPPROTO_PFSYNC);
3416         pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
3417         VNET_LIST_RLOCK();
3418         VNET_FOREACH(vnet_iter) {
3419                 CURVNET_SET(vnet_iter);
3420                 swi_remove(V_pfsync_swi_cookie);
3421                 if_clone_detach(&V_pfsync_cloner);
3422                 CURVNET_RESTORE();
3423         }
3424         VNET_LIST_RUNLOCK();
3425 }
3426
3427 static int
3428 pfsync_modevent(module_t mod, int type, void *data)
3429 {
3430         int error = 0;
3431
3432         switch (type) {
3433         case MOD_LOAD:
3434                 error = pfsync_init();
3435                 break;
3436         case MOD_QUIESCE:
3437                 /*
3438                  * Module should not be unloaded due to race conditions.
3439                  */
3440                 error = EPERM;
3441                 break;
3442         case MOD_UNLOAD:
3443                 pfsync_uninit();
3444                 break;
3445         default:
3446                 error = EINVAL;
3447                 break;
3448         }
3449
3450         return (error);
3451 }
3452
3453 static moduledata_t pfsync_mod = {
3454         "pfsync",
3455         pfsync_modevent,
3456         0
3457 };
3458
3459 #define PFSYNC_MODVER 1
3460
3461 DECLARE_MODULE(pfsync, pfsync_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
3462 MODULE_VERSION(pfsync, PFSYNC_MODVER);
3463 MODULE_DEPEND(pfsync, pf, PF_MODVER, PF_MODVER, PF_MODVER);
3464 #endif /* __FreeBSD__ */