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